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 | FECore/fecore_type.cpp | .cpp | 1,781 | 49 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "fecore_type.h"
#include <assert.h>
int fecore_data_size(FEDataType type)
{
switch (type)
{
case FE_INVALID_TYPE: return 0; break;
case FE_DOUBLE: return fecoreType<double>::size(); break;
case FE_VEC2D : return fecoreType<vec2d >::size(); break;
case FE_VEC3D : return fecoreType<vec3d >::size(); break;
case FE_MAT3D : return fecoreType<mat3d >::size(); break;
case FE_MAT3DS: return fecoreType<mat3ds>::size(); break;
default:
assert(false);
}
return 0;
};
| C++ |
3D | febiosoftware/FEBio | FECore/FELinearConstraint.h | .h | 3,331 | 115 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FEBoundaryCondition.h"
#include "FECoreClass.h"
#include <vector>
//-----------------------------------------------------------------------------
//! linear constraint
class FECORE_API FELinearConstraintDOF : public FECoreClass
{
public:
FELinearConstraintDOF(FEModel* fem);
public:
int node; // node number
int dof; // degree of freedom
double val; // coefficient value (ignored for parent dof)
private:
FELinearConstraintDOF(const FELinearConstraintDOF&) : FECoreClass(nullptr) {}
void operator = (const FELinearConstraintDOF&) {}
DECLARE_FECORE_CLASS();
FECORE_BASE_CLASS(FELinearConstraintDOF);
};
class FECORE_API FELinearConstraint : public FEBoundaryCondition
{
public:
typedef std::vector<FELinearConstraintDOF*>::iterator dof_iterator;
public:
// constructors
FELinearConstraint();
FELinearConstraint(FEModel* pfem);
FELinearConstraint(const FELinearConstraint& LC);
~FELinearConstraint();
void Clear();
// copy data
void CopyFrom(FEBoundaryCondition* pbc) override;
// serialization
void Serialize(DumpStream& ar) override;
// initialize the linear constraint
bool Init() override;
// make the constraint active
void Activate() override;
void Deactivate() override;
// set the parent degree of freedom
void SetParentDof(int dof, int node);
void SetParentNode(int node);
void SetParentDof(int dof);
// get the parent dof
int GetParentDof() const;
int GetParentNode() const;
// add a child degree of freedom
void AddChildDof(int dof, int node, double v);
void AddChildDof(FELinearConstraintDOF* dof);
// set the linear constraint offset
void SetOffset(double d) { m_off = d; }
// return offset
double GetOffset() const;
// get the child DOF
const FELinearConstraintDOF& GetChildDof(int n) const;
size_t Size() const;
dof_iterator begin();
protected:
FELinearConstraintDOF* m_parentDof; // parent degree of freedom
std::vector<FELinearConstraintDOF*> m_childDof; // list of child dofs
double m_off; // offset value
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FECoreTask.cpp | .cpp | 1,577 | 41 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FECoreTask.h"
//-----------------------------------------------------------------------------
FECoreTask::FECoreTask(FEModel* fem) : FECoreBase(fem)
{
}
//-----------------------------------------------------------------------------
FECoreTask::~FECoreTask(void)
{
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEDomainParameter.cpp | .cpp | 1,607 | 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.*/
#include "stdafx.h"
#include "FEDomainParameter.h"
FEDomainParameter::FEDomainParameter(const std::string& name) : m_name(name)
{
}
FEDomainParameter::~FEDomainParameter()
{
}
void FEDomainParameter::setName(const std::string& name)
{
m_name = name;
}
const std::string& FEDomainParameter::name() const
{
return m_name;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FaceDataRecord.h | .h | 2,293 | 64 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FECoreBase.h"
#include "DataRecord.h"
class FESurface;
class FESurfaceElement;
//-----------------------------------------------------------------------------
//! This is the base class for a face data value.
class FECORE_API FELogFaceData : public FELogData
{
FECORE_SUPER_CLASS(FELOGFACEDATA_ID)
FECORE_BASE_CLASS(FELogFaceData)
public:
FELogFaceData(FEModel* fem);
virtual ~FELogFaceData();
virtual double value(FESurfaceElement& el) = 0;
};
//-----------------------------------------------------------------------------
//! This class records surface data
class FECORE_API FaceDataRecord : public DataRecord
{
public:
FaceDataRecord(FEModel* pfem);
double Evaluate(int item, int ndata) override;
bool Initialize() override;
void SetData(const char* sz) override;
void SelectAllItems() override;
int Size() const override;
void SetItemList(FEItemList* itemList, const std::vector<int>& selection) override;
private:
FESurface* m_surface;
vector<FELogFaceData*> m_Data;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/ElementDataRecord.h | .h | 1,969 | 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 "FECoreBase.h"
#include "DataRecord.h"
#include "FELogElemData.h"
class FEElement;
class FEElementSet;
class FECORE_API ElementDataRecord : public DataRecord
{
struct ELEMREF
{
int ndom;
int nid;
};
public:
ElementDataRecord(FEModel* pfem);
double Evaluate(int item, int ndata) override;
void SetData(const char* sz) override;
void SelectAllItems() override;
int Size() const override;
void SetElementSet(FEElementSet* pg);
void SetItemList(FEItemList* itemList, const vector<int>& selection) override;
using DataRecord::SetItemList;
protected:
void BuildELT();
protected:
vector<ELEMREF> m_ELT;
int m_offset;
vector<FELogElemData*> m_Data;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FECore.h | .h | 1,751 | 46 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "fecore_api.h"
//-----------------------------------------------------------------------------
//! The FECore namespace encapsulates all classes that belong to the FECore library
namespace FECore
{
// retrieve version numbers
FECORE_API void get_version(int& version, int& subversion);
// retrieve version number string
FECORE_API const char* get_version_string();
// initialize the module
FECORE_API void InitModule();
} // namespace FECore
| Unknown |
3D | febiosoftware/FEBio | FECore/FEDataMathGenerator.cpp | .cpp | 2,838 | 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 "FEDataMathGenerator.h"
#include "FENodeDataMap.h"
#include "MathObject.h"
#include "MObjBuilder.h"
#include "FEMesh.h"
using namespace std;
BEGIN_FECORE_CLASS(FEDataMathGenerator, FENodeDataGenerator)
ADD_PARAMETER(m_math, "math");
END_FECORE_CLASS();
FEDataMathGenerator::FEDataMathGenerator(FEModel* fem) : FENodeDataGenerator(fem)
{
}
// set the math expression
void FEDataMathGenerator::setExpression(const std::string& math)
{
m_math = math;
}
bool FEDataMathGenerator::Init()
{
string tmp = m_math;
// split the math string at ','
vector<string> strings;
size_t pos = 0;
while ((pos = tmp.find(',')) != string::npos)
{
string t = tmp.substr(0, pos);
strings.push_back(t);
tmp.erase(0, pos + 1);
}
strings.push_back(tmp);
if ((strings.size() == 0) || (strings.size() > 3)) return false;
for (size_t i = 0; i < strings.size(); ++i)
{
MSimpleExpression val;
MVariable* var_x = val.AddVariable("X");
MVariable* var_y = val.AddVariable("Y");
MVariable* var_z = val.AddVariable("Z");
if (val.Create(strings[i]) == false) return false;
m_val.push_back(val);
}
return true;
}
FEDataMap* FEDataMathGenerator::Generate()
{
assert(m_nodeSet);
if (m_nodeSet == nullptr) return nullptr;
FENodeDataMap* map = new FENodeDataMap(FE_DOUBLE);
map->Create(m_nodeSet);
int N = m_nodeSet->Size();
for (int i=0; i<N; ++i)
{
FENode* node = m_nodeSet->Node(i);
vec3d r = node->m_r0;
vector<double> p{ r.x, r.y, r.z };
double v = m_val[0].value_s(p);
map->setValue(i, v);
}
return map;
}
| C++ |
3D | febiosoftware/FEBio | FECore/version.h | .h | 2,005 | 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
//-----------------------------------------------------------------------------
// This file defines the SDK versioning. It follows the versioning of FEBio, but
// will only be modified if the SDK is no longer compatible with older versions
// of FEBio. In that case, plugins need to be recompiled to be usable with the
// newer version of FEBio.
#define FE_SDK_MAJOR_VERSION 4
#define FE_SDK_SUB_VERSION 11
#define FE_SDK_SUBSUB_VERSION 0
//-----------------------------------------------------------------------------
// This macro needs to be exported by all plugins in the GetSDKVersion() function.
#define FE_SDK_VERSION ((FE_SDK_MAJOR_VERSION << 16) | (FE_SDK_SUB_VERSION << 8) | (FE_SDK_SUBSUB_VERSION))
| Unknown |
3D | febiosoftware/FEBio | FECore/expint_Ei.h | .h | 1,375 | 30 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "fecore_api.h"
FECORE_API double expint_Ei(double x);
| Unknown |
3D | febiosoftware/FEBio | FECore/FELogNodeData.h | .h | 1,616 | 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) 2025 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "FELogData.h"
class FENode;
//! This is the base class for a node data value.
class FECORE_API FELogNodeData : public FELogData
{
FECORE_SUPER_CLASS(FELOGNODEDATA_ID)
FECORE_BASE_CLASS(FELogNodeData)
public:
FELogNodeData(FEModel* fem);
virtual ~FELogNodeData();
virtual double value(const FENode& node) = 0;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FEModelLoad.h | .h | 2,466 | 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 "FEStepComponent.h"
#include "FEGlobalVector.h"
#include <FECore/FEDofList.h>
//-----------------------------------------------------------------------------
class FELinearSystem;
//-----------------------------------------------------------------------------
//! This class is the base class for all classes that affect the state of the model
//! and contribute directly to the residual and the global stiffness matrix. This
//! includes most boundary loads, body loads, contact, etc.
class FECORE_API FEModelLoad : public FEStepComponent
{
FECORE_SUPER_CLASS(FELOAD_ID)
FECORE_BASE_CLASS(FEModelLoad)
public:
//! constructor
FEModelLoad(FEModel* pfem);
const FEDofList& GetDofList() const;
void Serialize(DumpStream& ar) override;
virtual void PrepStep();
virtual Matrix_Type PreferredMatrixType();
public:
// all classes derived from this base class must implement
// the following functions.
//! evaluate the contribution to the external load vector
virtual void LoadVector(FEGlobalVector& R);
//! evaluate the contribution to the global stiffness matrix
virtual void StiffnessMatrix(FELinearSystem& LS);
protected:
FEDofList m_dof;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FENormalProjection.cpp | .cpp | 6,715 | 219 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FENormalProjection.h"
#include "FEMesh.h"
//-----------------------------------------------------------------------------
FENormalProjection::FENormalProjection(FESurface& s) : m_surf(s)
{
m_tol = 0.0;
m_rad = 0.0;
}
//-----------------------------------------------------------------------------
void FENormalProjection::Init()
{
m_OT.Attach(&m_surf);
m_OT.Init(m_tol);
}
//-----------------------------------------------------------------------------
//! This function finds the element which is intersected by the ray (r,n).
//! It returns a pointer to the element, as well as the isoparametric coordinates
//! of the intersection point. It searches for the closest patch based on
//! algebraic value of the gap function
//!
FESurfaceElement* FENormalProjection::Project(vec3d r, vec3d n, double rs[2])
{
// let's find all the candidate surface elements
set<int>selist;
m_OT.FindCandidateSurfaceElements(r, n, selist, m_rad);
// now that we found candidate surface elements, lets see if we can find
// those that intersect the ray, then pick the closest intersection
set<int>::iterator it;
bool found = false;
double rsl[2], gl, g = 0;
FESurfaceElement* pei = 0;
for (it=selist.begin(); it!=selist.end(); ++it) {
// get the surface element
int j = *it;
// project the node on the element
FESurfaceElement* pe = &m_surf.Element(j);
if (pe->isActive())
{
if (m_surf.Intersect(*pe, r, n, rsl, gl, m_tol)) {
if ((!found) && (gl > -m_rad)) {
found = true;
g = gl;
rs[0] = rsl[0];
rs[1] = rsl[1];
pei = pe;
}
else if ((gl < g) && (gl > -m_rad)) {
g = gl;
rs[0] = rsl[0];
rs[1] = rsl[1];
pei = pe;
}
}
}
}
if (found) return pei;
// we did not find a surface
return 0;
}
//-----------------------------------------------------------------------------
//! This function finds the element which is intersected by the ray (r,n).
//! It returns a pointer to the element, as well as the isoparametric coordinates
//! of the intersection point. It searches for the closest patch based on
//! the absolute value of the gap function
//!
FESurfaceElement* FENormalProjection::Project2(vec3d r, vec3d n, double rs[2])
{
// let's find all the candidate surface elements
set<int>selist;
m_OT.FindCandidateSurfaceElements(r, n, selist, m_rad);
// now that we found candidate surface elements, lets see if we can find
// those that intersect the ray, then pick the closest intersection
set<int>::iterator it;
bool found = false;
double rsl[2], gl, g = 0;
FESurfaceElement* pei = 0;
for (it=selist.begin(); it!=selist.end(); ++it) {
// get the surface element
int j = *it;
FESurfaceElement* pe = &m_surf.Element(j);
// project the node on the element
if (m_surf.Intersect(*pe, r, n, rsl, gl, m_tol)) {
if ((!found) && (fabs(gl) < m_rad)) {
found = true;
g = gl;
rs[0] = rsl[0];
rs[1] = rsl[1];
pei = pe;
} else if ((fabs(gl) < m_rad) && (fabs(gl) < fabs(g))) {
g = gl;
rs[0] = rsl[0];
rs[1] = rsl[1];
pei = pe;
}
}
}
if (found) return pei;
// we did not find a surface
return 0;
}
//-----------------------------------------------------------------------------
//! This function finds the element which is intersected by the ray (r,n).
//! It returns a pointer to the element, as well as the isoparametric coordinates
//! of the intersection point.
//!
FESurfaceElement* FENormalProjection::Project3(const vec3d& r, const vec3d& n, double rs[2], int* pei)
{
// let's find all the candidate surface elements
set<int>selist;
m_OT.FindCandidateSurfaceElements(r, n, selist, m_rad);
double g, gmax = -1e99, r2[2] = {rs[0], rs[1]};
int imin = -1;
FESurfaceElement* pme = 0;
// loop over all surface element
set<int>::iterator it;
for (it = selist.begin(); it != selist.end(); ++it)
{
FESurfaceElement& el = m_surf.Element(*it);
// see if the ray intersects this element
if (m_surf.Intersect(el, r, n, r2, g, m_tol))
{
// see if this is the best intersection found so far
// TODO: should I put a limit on how small g can
// be to be considered a valid intersection?
// if (g < gmin)
if (g > gmax)
{
// keep results
pme = ⪙
// gmin = g;
gmax = g;
imin = *it;
rs[0] = r2[0];
rs[1] = r2[1];
}
}
}
if (pei) *pei = imin;
// return the intersected element (or zero if none)
return pme;
}
//-----------------------------------------------------------------------------
vec3d FENormalProjection::Project(const vec3d& x, const vec3d& N)
{
double rs[2];
FESurfaceElement* pe = FENormalProjection::Project3(x, N, rs);
if (pe)
{
FEMesh& mesh = *m_surf.GetMesh();
vec3d r[FEElement::MAX_NODES];
for (int i=0; i<pe->Nodes(); ++i) r[i] = mesh.Node(pe->m_node[i]).m_rt;
vec3d q = pe->eval(r, rs[0], rs[1]);
return q;
}
else return x;
}
//-----------------------------------------------------------------------------
vec3d FENormalProjection::Project2(const vec3d& x, const vec3d& N)
{
double rs[2];
FESurfaceElement* pe = FENormalProjection::Project3(x, N, rs);
if (pe == nullptr) pe = FENormalProjection::Project3(x, -N, rs);
if (pe)
{
FEMesh& mesh = *m_surf.GetMesh();
vec3d r[FEElement::MAX_NODES];
for (int i = 0; i<pe->Nodes(); ++i) r[i] = mesh.Node(pe->m_node[i]).m_rt;
vec3d q = pe->eval(r, rs[0], rs[1]);
return q;
}
else return x;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEPlotDataStore.h | .h | 2,588 | 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.*/
#pragma once
#include "fecore_api.h"
#include <vector>
#include <string>
class DumpStream;
class FECORE_API FEPlotVariable
{
public:
FEPlotVariable();
FEPlotVariable(const FEPlotVariable& pv);
void operator = (const FEPlotVariable& pv);
FEPlotVariable(const std::string& var, std::vector<int>& item, const char* szdom = "");
void Serialize(DumpStream& ar);
const std::string& Name() const { return m_svar; }
const std::string& DomainName() const { return m_sdom; }
public:
std::string m_svar; //!< name of output variable
std::string m_sdom; //!< (optional) name of domain
std::vector<int> m_item; //!< (optional) list of items
};
class FECORE_API FEPlotDataStore
{
public:
FEPlotDataStore();
FEPlotDataStore(const FEPlotDataStore&);
void operator = (const FEPlotDataStore&);
void AddPlotVariable(const char* szvar, std::vector<int>& item, const char* szdom = "");
int GetPlotCompression() const;
void SetPlotCompression(int n);
void SetPlotFileType(const std::string& fileType);
std::string GetPlotFileType();
void Serialize(DumpStream& ar);
int PlotVariables() const { return (int)m_plot.size(); }
FEPlotVariable& GetPlotVariable(int n) { return m_plot[n]; }
private:
std::string m_splot_type;
std::vector<FEPlotVariable> m_plot;
int m_nplot_compression;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FEBroydenStrategy.cpp | .cpp | 8,294 | 304 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FEBroydenStrategy.h"
#include "LinearSolver.h"
#include "FEException.h"
#include "FENewtonSolver.h"
#include "log.h"
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FEBroydenStrategy, FENewtonStrategy)
ADD_PARAMETER(m_maxups, "max_ups");
ADD_PARAMETER(m_max_buf_size, FE_RANGE_GREATER_OR_EQUAL(0), "max_buffer_size");
ADD_PARAMETER(m_cycle_buffer, "cycle_buffer");
ADD_PARAMETER(m_cmax, FE_RANGE_GREATER_OR_EQUAL(0.0), "cmax");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! constructor
FEBroydenStrategy::FEBroydenStrategy(FEModel* fem) : FENewtonStrategy(fem)
{
m_neq = 0;
m_plinsolve = nullptr;
}
//-----------------------------------------------------------------------------
//! Initialization
bool FEBroydenStrategy::Init()
{
if (m_pns == nullptr) return false;
if (m_max_buf_size <= 0) m_max_buf_size = m_maxups;
int neq = m_pns->m_neq;
// allocate storage for Broyden update vectors
m_R.resize(m_max_buf_size, neq);
m_D.resize(m_max_buf_size, neq);
m_rho.resize(m_max_buf_size);
m_q.resize(neq, 0.0);
m_neq = neq;
m_nups = 0;
m_plinsolve = m_pns->GetLinearSolver();
m_bnewStep = true;
return true;
}
//! Presolve update
void FEBroydenStrategy::PreSolveUpdate()
{
m_bnewStep = true;
}
//-----------------------------------------------------------------------------
//! perform a quasi-Newton udpate
bool FEBroydenStrategy::Update(double s, vector<double>& ui, vector<double>& R0, vector<double>& R1)
{
// for full-Newton, we skip QN update
if (m_maxups == 0) return false;
// make sure we didn't reach max updates
if (m_nups >= m_maxups - 1)
{
feLogWarning("Max nr of iterations reached.\nStiffness matrix will now be reformed.");
return false;
}
// calculate q1
m_q.assign(m_neq, 0.0);
if (m_plinsolve->BackSolve(m_q, R1) == false)
throw LinearSolverFailed();
// only update when allowed
if ((m_nups < m_max_buf_size) || (m_cycle_buffer == true))
{
// since the number of updates can be larger than buffer size we need to clamp
int nups = (m_nups >= m_max_buf_size ? m_max_buf_size - 1 : m_nups);
// get the "0" buffer index
int n0 = (m_nups >= m_max_buf_size ? (m_nups + 1) % m_max_buf_size : 0);
int n1 = (m_nups >= m_max_buf_size ? (m_nups) % m_max_buf_size : m_nups);
// loop over update vectors
for (int j = 0; j<nups; ++j)
{
int n = (n0 + j) % m_max_buf_size;
double w = 0.0;
for (int i = 0; i<m_neq; ++i) w += (m_D[n][i] * m_q[i]);
double g = m_rho[n] * w;
for (int i = 0; i<m_neq; ++i) m_q[i] += g*(m_D[n][i] - m_R[n][i]);
}
// form and store the next update vector
double rhoi = 0.0;
for (int i = 0; i<m_neq; ++i)
{
double ri = m_q[i] - ui[i];
double di = -s*ui[i];
m_R[n1][i] = ri;
m_D[n1][i] = di;
rhoi += di*ri;
}
m_rho[n1] = 1.0 / (rhoi);
}
m_nups++;
return true;
}
//-----------------------------------------------------------------------------
//! solve the equations
void FEBroydenStrategy::SolveEquations(vector<double>& x, vector<double>& b)
{
// loop over update vectors
if (m_nups == 0)
{
if (m_plinsolve->BackSolve(x, b) == false)
throw LinearSolverFailed();
m_bnewStep = false;
}
else
{
// since the number of updates can be larger than buffer size we need to clamp
int nups = (m_nups > m_max_buf_size ? m_max_buf_size : m_nups);
// get the first and last buffer index
int n0 = 0;
int n1 = nups - 1;
if ((m_nups > m_max_buf_size) && (m_cycle_buffer == true))
{
n0 = m_nups % m_max_buf_size;
n1 = (m_nups - 1) % m_max_buf_size;
}
if (m_bnewStep)
{
m_q = x;
if (m_plinsolve->BackSolve(m_q, b) == false)
throw LinearSolverFailed();
for (int j = 0; j<nups - 1; ++j)
{
int n = (n0 + j) % m_max_buf_size;
double w = 0.0;
for (int i = 0; i<m_neq; ++i) w += (m_D[n][i] * m_q[i]);
double g = m_rho[n] * w;
for (int i = 0; i<m_neq; ++i) m_q[i] += g*(m_D[n][i] - m_R[n][i]);
}
m_bnewStep = false;
}
// calculate solution
double rho = 0.0;
for (int i = 0; i<m_neq; ++i) rho += m_D[n1][i] * m_q[i];
rho *= m_rho[n1];
for (int i = 0; i<m_neq; ++i)
{
x[i] = m_q[i] + rho*(m_D[n1][i] - m_R[n1][i]);
}
}
}
/*
//-----------------------------------------------------------------------------
//! perform a quasi-Newton udpate
bool FEBroydenStrategy::Update(double s, vector<double>& ui, vector<double>& R0, vector<double>& R1)
{
// calculate q1
// TODO: q is not initialized. Don't the iterative solvers use this as an initial guess?
// TODO: Can I use ui as an initial guess for q?
vector<double> q(m_neq);
if (m_plinsolve->BackSolve(q, R1) == false)
throw LinearSolverFailed();
// only update when allowed
if ((m_nups < m_max_buf_size) || (m_cycle_buffer == true))
{
// since the number of updates can be larger than buffer size we need to clamp
int nups = (m_nups >= m_max_buf_size ? m_max_buf_size - 1: m_nups);
// get the "0" buffer index
int n0 = (m_nups >= m_max_buf_size ? (m_nups + 1) % m_max_buf_size : 0);
int n1 = (m_nups >= m_max_buf_size ? (m_nups ) % m_max_buf_size : m_nups);
// loop over update vectors
for (int j=0; j<nups; ++j)
{
int n = (n0 + j) % m_max_buf_size;
double w = 0.0;
for (int i=0; i<m_neq; ++i) w += (m_D[n][i]*q[i]);
double g = m_rho[n]*w;
for (int i=0; i<m_neq; ++i) q[i] += g*(m_D[n][i] - m_R[n][i]);
}
// form and store the next update vector
double rhoi = 0.0;
for (int i=0; i<m_neq; ++i)
{
double ri = q[i] - ui[i];
double di = -s*ui[i];
m_R[n1][i] = ri;
m_D[n1][i] = di;
rhoi += di*ri;
}
m_rho[n1] = 1.0 / (rhoi);
}
m_nups++;
return true;
}
//-----------------------------------------------------------------------------
//! solve the equations
void FEBroydenStrategy::SolveEquations(vector<double>& x, vector<double>& b)
{
// loop over update vectors
if (m_nups == 0)
{
if (m_plinsolve->BackSolve(x, b) == false)
throw LinearSolverFailed();
}
else
{
// calculate q1
vector<double> q(m_neq);
if (m_plinsolve->BackSolve(q, b) == false)
throw LinearSolverFailed();
// since the number of updates can be larger than buffer size we need to clamp
int nups = (m_nups > m_max_buf_size ? m_max_buf_size : m_nups);
// get the first and last buffer index
int n0 = 0;
int n1 = nups - 1;
if ((m_nups > m_max_buf_size) && (m_cycle_buffer == true))
{
n0 = m_nups % m_max_buf_size;
n1 = (m_nups - 1) % m_max_buf_size;
}
for (int j=0; j<nups-1; ++j)
{
int n = (n0 + j) % m_max_buf_size;
double w = 0.0;
for (int i=0; i<m_neq; ++i) w += (m_D[n][i]*q[i]);
double g = m_rho[n]*w;
for (int i=0; i<m_neq; ++i) q[i] += g*(m_D[n][i] - m_R[n][i]);
}
// calculate solution
double rho = 0.0;
for (int i=0; i<m_neq; ++i) rho += m_D[n1][i]*q[i];
rho *= m_rho[n1];
for (int i=0; i<m_neq; ++i)
{
x[i] = q[i] + rho*(m_D[n1][i] - m_R[n1][i]);
}
}
}
*/
| C++ |
3D | febiosoftware/FEBio | FECore/MMatrix.cpp | .cpp | 8,815 | 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 "MMatrix.h"
using namespace std;
//-----------------------------------------------------------------------------
MMatrix::MMatrix() : MItem(MMATRIX)
{
m_nrow = 0; m_ncol = 0;
}
//-----------------------------------------------------------------------------
MMatrix::~MMatrix()
{
for (int i=0;i<m_nrow; ++i)
for (int j=0; j<m_ncol; ++j) delete m_d[i][j];
m_d.clear();
m_nrow = 0;
m_ncol = 0;
}
//-----------------------------------------------------------------------------
void MMatrix::Create(int nrow, int ncol)
{
m_d.clear();
m_d.assign(nrow, vector<MItem*>(ncol));
m_nrow = nrow;
m_ncol = ncol;
}
//-----------------------------------------------------------------------------
MItem* MMatrix::copy() const
{
MMatrix* pm = new MMatrix();
MMatrix& m = *pm;
const MMatrix& a = (*this);
m.Create(m_nrow, m_ncol);
for (int i=0; i<m_nrow; ++i)
for (int j=0; j<m_ncol; ++j) m[i][j] = a[i][j]->copy();
return pm;
}
//-----------------------------------------------------------------------------
MMatrix* operator + (const MMatrix& A, const MMatrix& B)
{
if ((A.rows() != B.rows()) || (A.columns() != B.columns())) throw InvalidOperation();
MMatrix& C = *(new MMatrix());
int N = A.rows();
int M = A.columns();
C.Create(A.rows(), A.columns());
for (int i=0; i<N; ++i)
{
for (int j=0; j<M; ++j)
{
MITEM aij = MITEM(A[i][j]->copy());
MITEM bij = MITEM(B[i][j]->copy());
C[i][j] = (aij + bij).copy();
}
}
return &C;
}
//-----------------------------------------------------------------------------
MMatrix* operator - (const MMatrix& A, const MMatrix& B)
{
if ((A.rows() != B.rows()) || (A.columns() != B.columns())) throw InvalidOperation();
MMatrix& C = *(new MMatrix());
int N = A.rows();
int M = A.columns();
C.Create(A.rows(), A.columns());
for (int i=0; i<N; ++i)
{
for (int j=0; j<M; ++j)
{
MITEM aij = MITEM(A[i][j]->copy());
MITEM bij = MITEM(B[i][j]->copy());
C[i][j] = (aij - bij).copy();
}
}
return &C;
}
//-----------------------------------------------------------------------------
MMatrix* operator * (const MMatrix& A, const MMatrix& B)
{
int RA = A.rows();
int CA = A.columns();
if (B.rows() != CA) throw InvalidOperation();
int CB = B.columns();
MMatrix& C = *(new MMatrix());
C.Create(RA, CB);
for (int i=0; i<RA; ++i)
{
for (int j=0; j<CB; ++j)
{
MITEM ai0 = A[i][0]->copy();
MITEM b0j = B[0][j]->copy();
MITEM cij = ai0*b0j;
for (int k=1; k<CA; ++k)
{
MITEM aik = A[i][k]->copy();
MITEM bkj = B[k][j]->copy();
cij = cij + aik*bkj;
}
C[i][j] = cij.copy();
}
}
return (&C);
}
//-----------------------------------------------------------------------------
MMatrix* operator * (const MMatrix& A, const MITEM& n)
{
if (n == 1.0) return static_cast<MMatrix*>(A.copy());
MMatrix& C = *(new MMatrix());
int N = A.rows();
int M = A.columns();
C.Create(A.rows(), A.columns());
for (int i=0; i<N; ++i)
{
for (int j=0; j<M; ++j)
{
MITEM aij(A[i][j]->copy());
MITEM f(n.copy());
C[i][j] = (f*aij).copy();
}
}
return &C;
}
//-----------------------------------------------------------------------------
MMatrix* operator / (const MMatrix& A, const MITEM& n)
{
if (n == 1.0) return static_cast<MMatrix*>(A.copy());
MMatrix& C = *(new MMatrix());
int N = A.rows();
int M = A.columns();
C.Create(A.rows(), A.columns());
for (int i=0; i<N; ++i)
{
for (int j=0; j<M; ++j)
{
MITEM aij(A[i][j]->copy());
MITEM f(n.copy());
C[i][j] = (aij/f).copy();
}
}
return &C;
}
//-----------------------------------------------------------------------------
MItem* matrix_transpose(const MMatrix& A)
{
MMatrix& B = *(new MMatrix());
B.Create(A.columns(), A.rows());
for (int i=0; i<B.rows(); ++i)
for (int j=0; j<B.columns(); ++j)
{
B[i][j] = A[j][i]->copy();
}
return &B;
}
//-----------------------------------------------------------------------------
MItem* matrix_trace(const MMatrix& A)
{
if (A.rows() != A.columns()) throw InvalidOperation();
MITEM t = A[0][0]->copy();
for (int i=1; i<A.rows(); ++i)
{
MITEM aii = A[i][i]->copy();
t = t + aii;
}
return t.copy();
}
//-----------------------------------------------------------------------------
MItem* matrix_determinant(const MMatrix& A)
{
// make sure the matrix is square
if (A.rows() != A.columns()) throw InvalidOperation();
if (A.rows() == 1) return A(0,0)->copy();
if (A.rows() == 2)
{
MITEM D = MITEM(A(0,0))*MITEM(A(1,1)) - MITEM(A(0,1))*MITEM(A(1,0));
return D.copy();
}
if (A.rows() == 3)
{
MITEM D(0.0);
D = D + MITEM(A(0,0))*MITEM(A(1,1))*MITEM(A(2,2));
D = D + MITEM(A(0,1))*MITEM(A(1,2))*MITEM(A(2,0));
D = D + MITEM(A(0,2))*MITEM(A(1,0))*MITEM(A(2,1));
D = D - MITEM(A(0,2))*MITEM(A(1,1))*MITEM(A(2,0));
D = D - MITEM(A(0,1))*MITEM(A(1,0))*MITEM(A(2,2));
D = D - MITEM(A(0,0))*MITEM(A(1,2))*MITEM(A(2,1));
return D.copy();
}
throw InvalidOperation();
return 0;
}
//-----------------------------------------------------------------------------
MItem* matrix_contract(const MMatrix& A, const MMatrix& B)
{
if ((A.rows() != B.rows())||(A.columns() != B.columns())) throw InvalidOperation();
MITEM s(0.0);
for (int i=0; i<A.rows(); ++i)
for (int j=0; j<A.columns(); ++j)
{
MITEM aij = A[i][j]->copy();
MITEM bij = B[i][j]->copy();
s = s + aij*bij;
}
return s.copy();
}
//-----------------------------------------------------------------------------
MMatrix* matrix_identity(int n)
{
MMatrix& m = *(new MMatrix());
m.Create(n, n);
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
{
m[i][j] = new MConstant((i==j?1.0:0.0));
}
return &m;
}
//-----------------------------------------------------------------------------
//! Calculate the inverse of a matrix
MItem* matrix_inverse(const MMatrix& m)
{
// make sure it is a square matrix
int nrows = m.rows();
int ncols = m.columns();
if (nrows != ncols) throw InvalidOperation();
// calculate the inverse, but we can only handle matrix up to order 3 for now
if (nrows == 1)
{
MMatrix* pmi = new MMatrix;
MMatrix& mi = *pmi;
mi.Create(1,1);
MITEM mij(m[0][0]->copy());
mi[0][0] = (MITEM(1.0) / mij).copy();
return pmi;
}
else if (nrows == 2)
{
MITEM m00(m[0][0]->copy());
MITEM m01(m[0][1]->copy());
MITEM m10(m[1][0]->copy());
MITEM m11(m[1][1]->copy());
MITEM D(matrix_determinant(m));
if (D == 0.0) throw DivisionByZero();
MMatrix mi;
mi.Create(2,2);
mi[0][0] = m11.copy();
mi[1][1] = m00.copy();
mi[0][1] = (-m01).copy();
mi[1][0] = (-m10).copy();
MMatrix& Mi = *(mi/D);
return &Mi;
}
else if (nrows == 3)
{
MITEM m00(m[0][0]->copy());
MITEM m01(m[0][1]->copy());
MITEM m02(m[0][2]->copy());
MITEM m10(m[1][0]->copy());
MITEM m11(m[1][1]->copy());
MITEM m12(m[1][2]->copy());
MITEM m20(m[2][0]->copy());
MITEM m21(m[2][1]->copy());
MITEM m22(m[2][2]->copy());
MITEM D(matrix_determinant(m));
if (D == 0.0) throw DivisionByZero();
MMatrix mi;
mi.Create(3,3);
mi[0][0] = (m11*m22 - m21*m12).copy();
mi[1][0] = (m12*m20 - m10*m22).copy();
mi[2][0] = (m10*m21 - m20*m11).copy();
mi[0][1] = (m21*m02 - m01*m22).copy();
mi[1][1] = (m00*m22 - m20*m02).copy();
mi[2][1] = (m20*m01 - m00*m21).copy();
mi[0][2] = (m01*m12 - m11*m02).copy();
mi[1][2] = (m10*m02 - m00*m12).copy();
mi[2][2] = (m00*m11 - m10*m01).copy();
MMatrix& Mi = *(mi/D);
return &Mi;
}
else throw InvalidOperation();
// we should not get here
assert(false);
return 0;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FENewtonStrategy.h | .h | 3,016 | 87 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <vector>
#include "fecore_api.h"
#include "fecore_enum.h"
#include "FECoreBase.h"
//-----------------------------------------------------------------------------
class FENewtonSolver;
class SparseMatrix;
class LinearSolver;
//-----------------------------------------------------------------------------
//! A Base class for newton-type solution strategies
class FECORE_API FENewtonStrategy : public FECoreBase
{
FECORE_SUPER_CLASS(FENEWTONSTRATEGY_ID)
FECORE_BASE_CLASS(FENewtonStrategy)
public:
FENewtonStrategy(FEModel* fem);
virtual ~FENewtonStrategy();
void SetNewtonSolver(FENewtonSolver* solver);
void Serialize(DumpStream& ar) override;
//! reset data for new run
virtual void Reset();
public:
//! initialize the linear system
virtual SparseMatrix* CreateSparseMatrix(Matrix_Type mtype);
//! Presolve update
virtual void PreSolveUpdate() {}
//! perform a Newton udpate (returning false will force a matrix reformations)
virtual bool Update(double s, std::vector<double>& ui, std::vector<double>& R0, std::vector<double>& R1) = 0;
//! solve the equations
virtual void SolveEquations(std::vector<double>& x, std::vector<double>& b) = 0;
//! reform the stiffness matrix
virtual bool ReformStiffness();
//! calculate the residual
virtual bool Residual(std::vector<double>& R, bool binit);
public:
int m_maxups; //!< max nr of QN iters permitted between stiffness reformations
int m_max_buf_size; //!< max buffer size for update vector storage
bool m_cycle_buffer; //!< recycle the buffer when updates is larger than buffer size
double m_cmax; //!< maximum value for the condition number
int m_nups; //!< nr of stiffness updates
protected:
FENewtonSolver* m_pns;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FESPRProjection.h | .h | 2,093 | 57 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include <vector>
#include "fecore_api.h"
#include <FECore/matrix.h>
#include <FECore/FENodeElemList.h>
class FESolidDomain;
//-------------------------------------------------------------------------------------------------
//! This class implements the super-convergent-patch recovery method which projects integration point
//! data to the finite element nodes.
class FECORE_API FESPRProjection
{
public:
FESPRProjection(FESolidDomain& dom, int interpolationOrder = -1);
void Project(const std::vector< std::vector<double> >& d, std::vector<double>& o);
private:
void Init();
protected:
FESolidDomain& m_dom; //!< reference to the solid domain
FENodeElemList NEL;
std::vector<matrix> m_Ai;
std::vector<int> m_valence;
int m_p; //!< interpolation order (set to -1 for default rules)
};
| Unknown |
3D | febiosoftware/FEBio | FECore/MathObject.h | .h | 4,067 | 120 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "MItem.h"
#include <vector>
#include "fecore_api.h"
//-----------------------------------------------------------------------------
typedef std::vector<MVariable*> MVarList;
//-----------------------------------------------------------------------------
// This class defines the base class for all math objects
// It also stores a list of all the variables
class FECORE_API MathObject
{
public:
MathObject();
MathObject(const MathObject& mo);
void operator = (const MathObject& mo);
virtual ~MathObject();
int Dim() { return (int)m_Var.size(); }
MVariable* AddVariable(const std::string& var, double initVal = 0.0);
void AddVariables(const std::vector<std::string>& varList);
void AddVariable(MVariable* pv);
MVariable* FindVariable(const std::string& s);
int Variables() const { return (int)m_Var.size(); }
MVariable* Variable(int i) { return m_Var[i]; }
const MVariable* Variable(int i) const { return m_Var[i]; }
virtual void Clear();
virtual MathObject* copy() = 0;
protected:
MVarList m_Var; // list of variables
};
//-----------------------------------------------------------------------------
// This class defines a simple epxression that can be evaluated by
// setting the values of the variables.
class FECORE_API MSimpleExpression : public MathObject
{
public:
MSimpleExpression() {}
MSimpleExpression(const MSimpleExpression& mo);
void operator = (const MSimpleExpression& mo);
void SetExpression(MITEM& e) { m_item = e; }
MITEM& GetExpression() { return m_item; }
const MITEM& GetExpression() const { return m_item; }
// Create a simple expression object from a string
bool Create(const std::string& expr, bool autoVars = false);
// copy the expression
MathObject* copy() { return new MSimpleExpression(*this); }
// These functions are not thread safe since variable values can be overridden by different threads
// In multithreaded applications, use the thread safe functions below.
double value() const { return value(m_item.ItemPtr()); }
// combines Create and value. Not efficient usage!
double value(const std::string& s);
// This is a thread safe function to evaluate the expression
// The values of the variables are passed as an argument. This function
// does not call MVariable->value, but uses these passed values insteads.
// Make sure that the var array has the same size as the variable array of the expression
double value_s(const std::vector<double>& var) const
{
assert(var.size() == m_Var.size());
return value(m_item.ItemPtr(), var);
}
int Items();
bool IsValid() const;
protected:
double value(const MItem* pi) const;
double value(const MItem* pi, const std::vector<double>& var) const;
protected:
void fixVariableRefs(MItem* pi);
protected:
MITEM m_item;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/JFNKStrategy.h | .h | 2,513 | 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 "FENewtonStrategy.h"
#include "SparseMatrix.h"
class JFNKMatrix;
//-----------------------------------------------------------------------------
// Implements a Jacobian-Free Newton-Krylov strategy
class JFNKStrategy : public FENewtonStrategy
{
public:
JFNKStrategy(FEModel* fem);
//! New initialization method
bool Init() override;
//! initialize the linear system
SparseMatrix* CreateSparseMatrix(Matrix_Type mtype) override;
//! perform a BFGS udpate
bool Update(double s, vector<double>& ui, vector<double>& R0, vector<double>& R1) override;
//! solve the equations
void SolveEquations(vector<double>& x, vector<double>& b) override;
//! Overide reform stiffness because we don't want to do any reformations
bool ReformStiffness() override;
//! override so we can store a copy of the residual before we add Fd
bool Residual(std::vector<double>& R, bool binit) override;
private:
double m_jfnk_eps; //!< JFNK epsilon
public:
// keep a pointer to the linear solver
LinearSolver* m_plinsolve; //!< pointer to linear solver
int m_neq; //!< number of equations
bool m_bprecondition; //!< the solver requires preconditioning
JFNKMatrix* m_A;
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FECore/units.h | .h | 3,724 | 110 | /*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.*/
#pragma once
// units are defined as strings that use the following
// characters to represent the physical quantities that
// define the SI base units.
// (Note that the symbols for time and temperature differ
// from the conventional SI dimension symbols)
//
// L = length
// M = mass
// t = time
// T = temperature
// l = electric current
// n = substance
//
// In addition, the following symbols for derived units are also defined:
//
// F = force
// P = pressure
// E = energy
// W = power
// d = angles in degrees
// r = angles in radians
//
// or use one of these predefined constants
#define UNIT_NONE ""
#define UNIT_LENGTH "L"
#define UNIT_MASS "M"
#define UNIT_TIME "t"
#define UNIT_TEMPERATURE "T"
#define UNIT_CURRENT "I"
#define UNIT_SUBSTANCE "n"
#define UNIT_FORCE "F"
#define UNIT_MOMENT "F.L"
#define UNIT_PRESSURE "P"
#define UNIT_ENERGY "E"
#define UNIT_POWER "W"
#define UNIT_VOLTAGE "V"
#define UNIT_CONCENTRATION "c"
#define UNIT_RELATIVE_TEMPERATURE "R"
#define UNIT_DEGREE "d"
#define UNIT_RADIAN "r"
#define UNIT_ACCELERATION "L/t^2"
#define UNIT_ANGULAR_MOMENTUM "E.t"
#define UNIT_ANGULAR_VELOCITY "r/t"
#define UNIT_AREA "L^2"
#define UNIT_COUPLE_VISCOSITY "F.t/r"
#define UNIT_CURRENT_CONDUCTIVITY "I/V.L^2"
#define UNIT_CURRENT_DENSITY "I/L^2"
#define UNIT_DENSITY "M/L^3"
#define UNIT_DENSITY_RATE "M/L^3.t"
#define UNIT_DIFFUSIVITY "L^2/t"
#define UNIT_ENERGY_AREAL_DENSITY "E/L^2"
#define UNIT_ENERGY_DENSITY "E/L^3"
#define UNIT_ENERGY_FLUX "W/L^2"
#define UNIT_FARADAY_CONSTANT "I.t/n"
#define UNIT_FILTRATION "L^2/F.t"
#define UNIT_FLOW_CAPACITANCE "L^5/F"
#define UNIT_FLOW_RATE "L^3/t"
#define UNIT_FLOW_RESISTANCE "F.t/L^3"
#define UNIT_GAS_CONSTANT "E/n.T"
#define UNIT_GRADIENT "1/L"
#define UNIT_LINEAR_MOMENTUM "F.t"
#define UNIT_MASS_FLOW_RATE "M/t"
#define UNIT_MOLAR_AREAL_CONCENTRATION "n/L^2"
#define UNIT_MOLAR_FLUX "n/L^2.t"
#define UNIT_MOLAR_MASS "M/n"
#define UNIT_MOLAR_VOLUME "L^3/n"
#define UNIT_PERMEABILITY "L^4/F.t"
#define UNIT_POWER_DENSITY "W/L^3"
#define UNIT_RECIPROCAL_LENGTH "1/L"
#define UNIT_RECIPROCAL_TIME "1/t"
#define UNIT_ROTATIONAL_VISCOSITY "P.t/r"
#define UNIT_SPECIFIC_ENERGY "E/M"
#define UNIT_SPECIFIC_ENTROPY "E/M.T"
#define UNIT_SPECIFIC_FORCE "F/M"
#define UNIT_SPECIFIC_MOMENT "F.L/M"
#define UNIT_STIFFNESS "F/L"
#define UNIT_THERMAL_CONDUCTIVITY "W/L.T"
#define UNIT_VELOCITY "L/t"
#define UNIT_VISCOSITY "P.t"
#define UNIT_VOLUME "L^3"
| Unknown |
3D | febiosoftware/FEBio | FECore/DumpMemStream.h | .h | 2,402 | 64 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "DumpStream.h"
//-----------------------------------------------------------------------------
//! The dump stream allows a class to record its internal state to a memory object
//! so that it can be restored later.
//! This can be used for storing the FEModel state during running restarts
class FECORE_API DumpMemStream : public DumpStream
{
public:
DumpMemStream(FEModel& fem);
~DumpMemStream();
public: // overloaded from base class
size_t write(const void* pd, size_t size, size_t count);
size_t read(void* pd, size_t size, size_t count);
void clear();
void Open(bool bsave, bool bshallow);
size_t size() const { return m_nsize; }
size_t reserved() const { return m_nreserved; }
bool EndOfStream() const;
protected:
void grow_buffer(size_t l);
void set_position(size_t l);
private:
char* m_pb; //!< pointer to buffer
char* m_pd; //!< position to insert a new value
size_t m_nsize; //!< size of stream
size_t m_nreserved; //!< size of reserved buffer
size_t m_growsize; //!< size to grow the buffer
size_t m_growcounter; //!< number of times we had to grow the buffer
};
| Unknown |
3D | febiosoftware/FEBio | FECore/Timer.h | .h | 3,755 | 133 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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_api.h"
class FEModel;
//! This class implements a simple timer.
//! The start function starts the timer, the stop
//! function stops it and the GetTime function returns the time elapsed between
//! the call to start and stop
class FECORE_API Timer
{
struct Imp;
public:
//! constructor
Timer();
~Timer();
//! Start the timer
void start();
//! Stop the timer
void stop();
//! pause the timer
void pause();
//! continue
void unpause();
void reset();
//! Get the elapsed time
void GetTime(int& nhour, int& nmin, int& nsec);
//! Get the time in seconds
double GetTime();
//! Get the exclusive time (i.e. time when not paused)
double GetExclusiveTime();
//! return the time as a text string
void time_str(char* sz);
//! check the elapsed time
double peek();
//! see if the timer is running
bool isRunning() const;
public:
static void time_str(double fsec, char* sz);
static void GetTime(double fsec, int& nhour, int& nmin, int& nsec);
static Timer* activeTimer();
private:
Imp* m; //!< local timing data (using PIMPL ididom)
};
//-----------------------------------------------------------------------------
class FEModel;
//-----------------------------------------------------------------------------
// Timer IDs
enum TimerID {
Timer_Init,
Timer_Update,
Timer_LinSol_Factor,
Timer_LinSol_Backsolve,
Timer_Reform,
Timer_Residual,
Timer_Stiffness,
Timer_QNUpdate,
Timer_Serialize,
Timer_ModelSolve,
Timer_Callback,
Timer_USER1,
Timer_USER2,
Timer_USER3,
Timer_USER4,
TIMER_COUNT // leave this at the end so that it equals the nr. of timers we need
};
//-----------------------------------------------------------------------------
// This is helper class that can be used to ensure that a timer is stopped when
// the function that is being timed exits. That way, the Timer::stop member does not
// have to be called at every exit point of a function.
// In addition, it will also check if the timer is already running (e.g. from a function
// higher in the call stack) in which case it will track the timer.
class FECORE_API TimerTracker
{
public:
TimerTracker(FEModel* fem, int timerId);
TimerTracker(Timer* timer)
{
if (timer && !timer->isRunning()) { m_timer = timer; timer->start(); }
else m_timer = nullptr;
}
~TimerTracker() { if (m_timer) m_timer->stop(); }
private:
Timer* m_timer;
};
#define TRACK_TIME(timerId) TimerTracker _trackTimer(GetFEModel(), timerId);
| Unknown |
3D | febiosoftware/FEBio | FECore/FEFacetSet.cpp | .cpp | 4,242 | 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 "FEFacetSet.h"
#include "FEMesh.h"
#include "DumpStream.h"
#include "FESurface.h"
//-----------------------------------------------------------------------------
void FEFacetSet::FACET::Serialize(DumpStream& ar)
{
ar & node;
ar & ntype;
}
//-----------------------------------------------------------------------------
FEFacetSet::FEFacetSet(FEModel* fem) : FEItemList(fem, FEItemList::FE_ELEMENT_SET)
{
m_surface = nullptr;
}
//-----------------------------------------------------------------------------
void FEFacetSet::SetSurface(FESurface* surf) { m_surface = surf; }
FESurface* FEFacetSet::GetSurface() { return m_surface; }
void FEFacetSet::Clear()
{
m_Face.clear();
}
//-----------------------------------------------------------------------------
int FEFacetSet::Faces() const { return (int)m_Face.size(); }
//-----------------------------------------------------------------------------
void FEFacetSet::Create(int n)
{
m_Face.resize(n);
}
//-----------------------------------------------------------------------------
// create from a surface
void FEFacetSet::Create(const FESurface& surf)
{
int NE = surf.Elements();
m_Face.resize(NE);
for (int i = 0; i < NE; ++i)
{
const FESurfaceElement& el = surf.Element(i);
FACET& face = m_Face[i];
switch (el.Shape())
{
case ET_TRI3 : face.ntype = 3; break;
case ET_QUAD4: face.ntype = 4; break;
case ET_TRI6 : face.ntype = 6; break;
case ET_TRI7 : face.ntype = 7; break;
case ET_QUAD8: face.ntype = 8; break;
default:
assert(false);
}
for (int j = 0; j < el.Nodes(); ++j)
{
face.node[j] = el.m_node[j];
}
}
}
//-----------------------------------------------------------------------------
FEFacetSet::FACET& FEFacetSet::Face(int i)
{
return m_Face[i];
}
//-----------------------------------------------------------------------------
const FEFacetSet::FACET& FEFacetSet::Face(int i) const
{
return m_Face[i];
}
//-----------------------------------------------------------------------------
void FEFacetSet::Add(FEFacetSet* pf)
{
m_Face.insert(m_Face.end(), pf->m_Face.begin(), pf->m_Face.end());
}
//-----------------------------------------------------------------------------
FENodeList FEFacetSet::GetNodeList() const
{
FEMesh* mesh = GetMesh();
FENodeList set(mesh);
vector<int> tag(mesh->Nodes(), 0);
for (int i = 0; i<Faces(); ++i)
{
const FACET& el = m_Face[i];
int ne = el.ntype;
for (int j = 0; j<ne; ++j)
{
if (tag[el.node[j]] == 0)
{
set.Add(el.node[j]);
tag[el.node[j]] = 1;
}
}
}
return set;
}
//-----------------------------------------------------------------------------
void FEFacetSet::Serialize(DumpStream& ar)
{
FEItemList::Serialize(ar);
if (ar.IsShallow()) return;
ar & m_Face;
}
void FEFacetSet::SaveClass(DumpStream& ar, FEFacetSet* p) {}
FEFacetSet* FEFacetSet::LoadClass(DumpStream& ar, FEFacetSet* p)
{
p = new FEFacetSet(&ar.GetFEModel());
return p;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEModelParam.cpp | .cpp | 6,185 | 290 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FEModelParam.h"
#include "MObjBuilder.h"
#include "FEDataArray.h"
#include "DumpStream.h"
#include "FEConstValueVec3.h"
//---------------------------------------------------------------------------------------
FEModelParam::FEModelParam()
{
m_scl = 1.0;
m_dom = 0;
}
FEModelParam::~FEModelParam()
{
}
// serialization
void FEModelParam::Serialize(DumpStream& ar)
{
ar & m_scl;
if (ar.IsShallow() == false)
{
ar & m_dom;
}
}
//---------------------------------------------------------------------------------------
FEParamDouble::FEParamDouble()
{
m_val = fecore_new<FEScalarValuator>("const", nullptr);
}
FEParamDouble::~FEParamDouble()
{
delete m_val;
}
FEParamDouble::FEParamDouble(const FEParamDouble& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
// set the value
void FEParamDouble::operator = (double v)
{
FEConstValue* val = fecore_new<FEConstValue>("const", nullptr);
*val->constValue() = v;
setValuator(val);
}
void FEParamDouble::operator = (const FEParamDouble& p)
{
if (m_val) delete m_val;
m_val = p.m_val->copy();
m_scl = p.m_scl;
// m_dom = p.m_dom;
}
// set the valuator
void FEParamDouble::setValuator(FEScalarValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
// get the valuator
FEScalarValuator* FEParamDouble::valuator()
{
return m_val;
}
// is this a const value
bool FEParamDouble::isConst() const { return m_val->isConst(); };
// get the const value (returns 0 if param is not const)
double& FEParamDouble::constValue() { assert(isConst()); return *m_val->constValue(); }
double FEParamDouble::constValue() const { assert(isConst()); return *m_val->constValue(); }
void FEParamDouble::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
bool FEParamDouble::Init()
{
return (m_val ? m_val->Init() : true);
}
//---------------------------------------------------------------------------------------
FEParamVec3::FEParamVec3()
{
m_val = fecore_new<FEVec3dValuator>("vector", nullptr);
}
FEParamVec3::~FEParamVec3()
{
delete m_val;
}
FEParamVec3::FEParamVec3(const FEParamVec3& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
bool FEParamVec3::Init()
{
return (m_val ? m_val->Init() : true);
}
// set the value
void FEParamVec3::operator = (const vec3d& v)
{
FEConstValueVec3* val = fecore_new<FEConstValueVec3>("vector", nullptr);
val->value() = v;
setValuator(val);
}
void FEParamVec3::operator = (const FEParamVec3& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
// m_dom = p.m_dom;
}
// set the valuator
void FEParamVec3::setValuator(FEVec3dValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
FEVec3dValuator* FEParamVec3::valuator()
{
return m_val;
}
void FEParamVec3::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
//==========================================================================
FEParamMat3d::FEParamMat3d()
{
m_val = fecore_new<FEMat3dValuator>("const", nullptr);
}
FEParamMat3d::~FEParamMat3d()
{
delete m_val;
}
FEParamMat3d::FEParamMat3d(const FEParamMat3d& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
// set the value
void FEParamMat3d::operator = (const mat3d& v)
{
FEConstValueMat3d* val = fecore_new<FEConstValueMat3d>("const", nullptr);
val->value() = v;
setValuator(val);
}
void FEParamMat3d::operator = (const FEParamMat3d& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
// m_dom = p.m_dom;
}
bool FEParamMat3d::Init()
{
return (m_val ? m_val->Init() : true);
}
// set the valuator
void FEParamMat3d::setValuator(FEMat3dValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
// get the valuator
FEMat3dValuator* FEParamMat3d::valuator()
{
return m_val;
}
void FEParamMat3d::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
//==========================================================================
FEParamMat3ds::FEParamMat3ds()
{
m_val = fecore_new<FEMat3dsValuator>("const", nullptr);
}
FEParamMat3ds::~FEParamMat3ds()
{
delete m_val;
}
FEParamMat3ds::FEParamMat3ds(const FEParamMat3ds& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
m_dom = p.m_dom;
}
// set the value
void FEParamMat3ds::operator = (const mat3ds& v)
{
FEConstValueMat3ds* val = fecore_new<FEConstValueMat3ds>("const", nullptr);
val->value() = v;
setValuator(val);
}
void FEParamMat3ds::operator = (const FEParamMat3ds& p)
{
m_val = p.m_val->copy();
m_scl = p.m_scl;
// m_dom = p.m_dom;
}
// set the valuator
void FEParamMat3ds::setValuator(FEMat3dsValuator* val)
{
if (m_val) delete m_val;
m_val = val;
if (val) val->SetModelParam(this);
}
FEMat3dsValuator* FEParamMat3ds::valuator()
{
return m_val;
}
void FEParamMat3ds::Serialize(DumpStream& ar)
{
FEModelParam::Serialize(ar);
ar & m_val;
}
| C++ |
3D | febiosoftware/FEBio | FECore/BSpline.h | .h | 2,632 | 79 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "fecore_api.h"
#include "vec2d.h"
#include <vector>
class FECORE_API BSpline
{
struct Impl;
public:
// constructor
BSpline();
// copy constructor
BSpline(const BSpline& bs);
// destructor
~BSpline();
// assignment operator
void operator = (const BSpline& bs);
public:
// spline function evaluations
double eval(double x, int korder, const std::vector<double>& xknot,
int ncoef, const std::vector<double>& coeff) const;
double eval(double x) const;
double eval_nderiv(double x, int n) const;
double eval_deriv(double x) const;
double eval_deriv2(double x) const;
public:
// spline fitting
std::vector<double> blending_functions(double x) const;
bool fit(int korder, int ncoef, const std::vector<vec2d>& p);
public:
// initializations
// use given points p as control points
bool init(int korder, const std::vector<vec2d>& p);
// use given points p as interpolation points
bool init_interpolation(int korder, const std::vector<vec2d>& p);
// perform spline approximation over points p, using ncoef coefficients
bool init_approximation(int korder, int ncoef, const std::vector<vec2d>& p);
bool m_deriv; //!< flag indicating derivative status
private:
Impl* im;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FEPeriodicLinearConstraint.cpp | .cpp | 7,473 | 284 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FEPeriodicLinearConstraint.h"
#include "FELinearConstraintManager.h"
#include "FELinearConstraint.h"
#include "FEModel.h"
#include "FESurface.h"
FEPeriodicLinearConstraint::FEPeriodicLinearConstraint(FEModel* fem) : FEStepComponent(fem), m_exclude(fem)
{
m_refNode = -1;
}
FEPeriodicLinearConstraint::~FEPeriodicLinearConstraint()
{
}
void FEPeriodicLinearConstraint::AddNodeSetPair(const FENodeList& ms, const FENodeList& ss, bool push_back)
{
NodeSetPair sp;
sp.secondary = ms;
sp.primary = ss;
if (push_back) m_set.push_back(sp); else m_set.insert(m_set.begin(), sp);
}
// helper function for finding the closest node
int closestNode(FEMesh& mesh, const FENodeList& set, const vec3d& r);
// helper function for adding the linear constraints
void addLinearConstraint(FEModel& fem, int parent, int child, int nodeA, int nodeB);
// This function generates a linear constraint set based on the definition
// of three surface pairs.
bool FEPeriodicLinearConstraint::GenerateConstraints(FEModel* fem)
{
// get the model's mesh
FEMesh& mesh = GetMesh();
// make sure there is a list of sets
if (m_set.empty()) return true;
// make sure we have three sets
if (m_set.size() != 3) return false;
// tag all nodes to identify what they are (edge, face, corner)
int N = mesh.Nodes();
vector<int> tag(N, 0);
for (size_t i=0; i<m_set.size(); ++i)
{
FENodeList& ms = m_set[i].secondary;
FENodeList& ss = m_set[i].primary;
for (int j=0; j<(int)ms.Size(); ++j) tag[ms[j]]++;
for (int j=0; j<(int)ss.Size(); ++j) tag[ss[j]]++;
}
// flip signs on primary
for (size_t i = 0; i<m_set.size(); ++i)
{
FENodeList& ss = m_set[i].primary;
for (int j = 0; j<(int)ss.Size(); ++j)
{
int ntag = tag[ss[j]];
if (ntag > 0) tag[ss[j]] = -ntag;
}
}
// At this point, the following should hold
// primary nodes: tag < 0, secondary nodes: tag > 0, interior nodes: tag = 0
// only one secondary node should have a value of 3. We make this the reference node
int refNode = -1;
for (int i=0; i<N; ++i)
{
if (tag[i] == 3)
{
assert(refNode == -1);
refNode = i;
}
}
assert(refNode != -1);
if (refNode == -1) return false;
// get the position of the reference node
vec3d rm = mesh.Node(refNode).m_r0;
// create the linear constraints for the surface nodes that don't belong to an edge (i.e. tag = 1)
for (size_t n = 0; n<m_set.size(); ++n)
{
FENodeList& ms = m_set[n].secondary;
FENodeList& ss = m_set[n].primary;
// find the corresponding reference node on the primary surface
int mref = closestNode(mesh, ss, rm);
// make sure this is a corner node
assert(tag[ss[mref]] == -3);
// repeat for all primary nodes
for (int i=0; i<(int)ss.Size(); ++i)
{
assert(tag[ss[i]] < 0);
if (tag[ss[i]] == -1)
{
// get the primary node position
vec3d& rs = ss.Node(i)->m_r0;
// find the closest secondary node
int m = closestNode(mesh, ms, rs);
assert(tag[ms[m]] == 1);
// add the linear constraints
addLinearConstraint(*fem, ss[i], ms[m], ss[mref], refNode);
}
}
}
// extract all 12 edges
vector<FENodeList> surf;
for (int i=0; i<(int)m_set.size(); ++i)
{
surf.push_back(m_set[i].secondary);
surf.push_back(m_set[i].primary);
}
vector<FENodeList> secondaryEdges;
vector<FENodeList> primaryEdges;
for (int i=0; i<surf.size(); ++i)
{
FENodeList& s0 = surf[i];
for (int j=i+1; j<surf.size(); ++j)
{
FENodeList& s1 = surf[j];
vector<int> tmp(N, 0);
for (int k=0; k<s0.Size(); ++k) tmp[s0[k]]++;
for (int k=0; k<s1.Size(); ++k) tmp[s1[k]]++;
FENodeList edge(&mesh);
for (int k=0; k<N; ++k)
{
if (tmp[k] == 2) edge.Add(k);
}
if (edge.Size() != 0)
{
// see if this is a secondary edge or not
// we assume it's a secondary edge if it connects to the refnode
bool bsecondary = false;
for (int k=0; k<edge.Size(); ++k)
{
if (edge[k] == refNode)
{
bsecondary = true;
break;
}
}
if (bsecondary)
secondaryEdges.push_back(edge);
else
primaryEdges.push_back(edge);
}
}
}
// since it is assumed the geometry is a cube, the following must hold
assert(secondaryEdges.size() == 3);
assert(primaryEdges.size() == 9);
// find the secondary edge vectors
vec3d Em[3];
for (int i=0; i<3; ++i)
{
FENodeList& edge = secondaryEdges[i];
// get the edge vector
Em[i] = edge.Node(0)->m_r0 - edge.Node(1)->m_r0; assert(edge[0] != edge[1]);
Em[i].unit();
}
// setup linear constraints for edges
for (int n = 0; n< primaryEdges.size(); ++n)
{
FENodeList& edge = primaryEdges[n];
// get the edge vector
vec3d E = edge.Node(0)->m_r0 - edge.Node(1)->m_r0; assert(edge[0] != edge[1]); E.unit();
// find the corresponding secondary edge
bool bfound = true;
for (int m=0; m<3; ++m)
{
if (fabs(E*Em[m]) > 0.9999)
{
FENodeList& medge = secondaryEdges[m];
int mref = closestNode(mesh, edge, rm);
for (int i=0; i<(int)edge.Size(); ++i)
{
assert(tag[edge[i]] < 0);
if (tag[edge[i]] == -2)
{
vec3d ri = edge.Node(i)->m_r0;
int k = closestNode(mesh, medge, ri);
addLinearConstraint(*fem, edge[i], medge[k], edge[mref], refNode);
}
}
bfound = true;
break;
}
}
assert(bfound);
}
return true;
}
int closestNode(FEMesh& mesh, const FENodeList& set, const vec3d& r)
{
int nmin = -1;
double Dmin = 0.0;
for (int i = 0; i<(int)set.Size(); ++i)
{
vec3d& ri = mesh.Node(set[i]).m_r0;
double D = (r - ri)*(r - ri);
if ((D < Dmin) || (nmin == -1))
{
Dmin = D;
nmin = i;
}
}
return nmin;
}
// helper function for adding the linear constraints
void addLinearConstraint(FEModel& fem, int parent, int child, int nodeA, int nodeB)
{
// get the linear constraint manager
FELinearConstraintManager& LCM = fem.GetLinearConstraintManager();
// do one constraint for x, y, z
for (int j = 0; j<3; ++j)
{
FELinearConstraint* lc = fecore_alloc(FELinearConstraint, &fem);
lc->SetParentDof(j, parent);
lc->AddChildDof(j, child, 1.0);
lc->AddChildDof(j, nodeA, 1.0);
lc->AddChildDof(j, nodeB, -1.0);
LCM.AddLinearConstraint(lc);
}
}
| C++ |
3D | febiosoftware/FEBio | FECore/MObj2String.h | .h | 2,193 | 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 "MathObject.h"
#include <string>
// this class converts a MathObject to a string
class FECORE_API MObj2String
{
public:
std::string Convert(const MathObject& o);
protected:
std::string Convert(const MItem* pi);
std::string Constant (const MConstant* pc);
std::string Fraction (const MFraction* pc);
std::string NamedCt (const MNamedCt* pc);
std::string Variable (const MVarRef* pv);
std::string OpNeg (const MNeg* po);
std::string OpAdd (const MAdd* po);
std::string OpSub (const MSub* po);
std::string OpMul (const MMul* po);
std::string OpDiv (const MDiv* po);
std::string OpPow (const MPow* po);
std::string OpEqual (const MEquation* po);
std::string OpFnc1D (const MFunc1D* po);
std::string OpFnc2D (const MFunc2D* po);
std::string OpFncND (const MFuncND* po);
std::string OpSFnc (const MSFuncND* po);
};
| Unknown |
3D | febiosoftware/FEBio | FECore/tens6d.h | .h | 4,144 | 107 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "tensor_base.h"
//-----------------------------------------------------------------------------
// Tensor classes defined in this file
class tens6ds;
class tens6d;
//-----------------------------------------------------------------------------
// traits for these classes defining the number of components
template <> class tensor_traits<tens6ds>{public: enum { NNZ = 55}; };
template <> class tensor_traits<tens6d >{public: enum { NNZ = 729}; };
//-----------------------------------------------------------------------------
//! Class for 6th order tensors. This class assumes the following symmetries:
// - full (minor) symmetry in the first three legs
// - full (minor) symmetry in the last three legs
// - major symmetry (A[i,j,k;l,m,n] = A[l,m,n;i,j,k])
//
// This tensor is effectively stored as an upper-triangular 10x10 matrix
// using column major ordering.
//
// / 0 1 3 6 10 15 21 28 37 46 \ / A00 A01 A02 ... A09 \
// | 2 4 7 11 16 22 29 38 47 | | A11 A12 ... A19 |
// | 5 8 12 17 23 30 39 48 | | A22 ... A18 |
// | 9 13 18 24 31 40 49 | | . |
// | 14 19 25 32 41 50 | | . |
// A = | 20 26 33 42 51 | = | . |
// | 27 34 43 52 | | |
// | 35 44 53 | | |
// | 45 54 | | |
// \ 55 / \ A99 /
//
// where A[I,J] = A[i,j,k;l,m,n] using the following convention
//
// I/J | i/l j/m k/n
// --------+-------------------
// 0 | 0 0 0
// 1 | 0 0 1
// 2 | 0 0 2
// 3 | 0 1 1
// 4 | 0 1 2
// 5 | 0 2 2
// 6 | 1 1 1
// 7 | 1 1 2
// 8 | 1 2 2
// 9 | 2 2 2
//
class tens6ds : public tensor_base<tens6ds>
{
public:
// constructors
tens6ds(){}
public:
// access operator
double operator () (int i, int j, int k, int l, int m, int n);
};
void calculate_e2O(tens6ds& e, double K[3][3], double Ri[3], double Rj[3] );
//-----------------------------------------------------------------------------
// class for general 6-th order tensors. No assumed symmetries
class tens6d : public tensor_base<tens6d>
{
public:
// default constructor
tens6d() {}
// access operators
double operator () (int i, int j, int k, int l, int m, int n) const;
double& operator () (int i, int j, int k, int l, int m, int n);
};
// The following file contains the actual definition of the class functions
#include "tens6d.hpp"
#include "tens6ds.hpp"
| Unknown |
3D | febiosoftware/FEBio | FECore/vector.h | .h | 3,672 | 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.*/
#pragma once
#include <math.h>
#include <memory.h>
#include <vector>
#include <algorithm>
#include "vec3d.h"
#include "fecore_api.h"
class FEMesh;
class FEDofList;
double FECORE_API operator*(const std::vector<double>& a, const std::vector<double>& b);
std::vector<double> FECORE_API operator - (std::vector<double>& a, std::vector<double>& b);
template<typename T> void zero(std::vector<T>& a) { std::fill(a.begin(), a.end(), T(0)); }
template<> inline void zero<vec3d>(std::vector<vec3d>& a) { std::fill(a.begin(), a.end(), vec3d(0,0,0)); }
template<typename T> void assign(std::vector<T>& a, const T& v) { std::fill(a.begin(), a.end(), v); }
void FECORE_API operator+=(std::vector<double>& a, const std::vector<double>& b);
void FECORE_API operator-=(std::vector<double>& a, const std::vector<double>& b);
void FECORE_API operator*=(std::vector<double>& a, double b);
std::vector<double> FECORE_API operator+(const std::vector<double>& a, const std::vector<double>& b);
std::vector<double> FECORE_API operator*(const std::vector<double>& a, double g);
std::vector<double> FECORE_API operator - (const std::vector<double>& a);
// copy vector and scale
void FECORE_API vcopys(std::vector<double>& a, const std::vector<double>& b, double s);
// add scaled vector
void FECORE_API vadds(std::vector<double>& a, const std::vector<double>& b, double s);
void FECORE_API vsubs(std::vector<double>& a, const std::vector<double>& b, double s);
// vector subtraction: a = l - r
void FECORE_API vsub(std::vector<double>& a, const std::vector<double>& l, const std::vector<double>& r);
// scale each component of a vector
void FECORE_API vscale(std::vector<double>& a, const std::vector<double>& s);
// gather operation (copy mesh data to vector)
void FECORE_API gather(std::vector<double>& v, FEMesh& mesh, int ndof);
void FECORE_API gather(std::vector<double>& v, FEMesh& mesh, const std::vector<int>& dof);
// scatter operation (copy vector data to mesh)
void FECORE_API scatter(std::vector<double>& v, FEMesh& mesh, int ndof);
void FECORE_API scatter3(std::vector<double>& v, FEMesh& mesh, int ndof1, int ndof2, int ndof3);
void FECORE_API scatter(std::vector<double>& v, FEMesh& mesh, const FEDofList& dofs);
// calculate l2 norm of vector
double FECORE_API l2_norm(const std::vector<double>& v);
double FECORE_API l2_sqrnorm(const std::vector<double>& v);
double l2_norm(double* x, int n);
| Unknown |
3D | febiosoftware/FEBio | FECore/FESurfaceMap.h | .h | 3,662 | 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.*/
#pragma once
#include <vector>
#include <string>
#include <assert.h>
#include "FEDataMap.h"
//-----------------------------------------------------------------------------
class FESurface;
class FEFacetSet;
class DumpStream;
//-----------------------------------------------------------------------------
typedef int FEFacetIndex;
//-----------------------------------------------------------------------------
// TODO: Perhaps I should rename this FESurfaceData
// and then define FESurfaceMap as a tool for evaluating data across a surface (i.e. via shape functions)
class FECORE_API FESurfaceMap : public FEDataMap
{
public:
//! default constructor
FESurfaceMap();
FESurfaceMap(FEDataType dataType);
//! copy constructor
FESurfaceMap(const FESurfaceMap& map);
//! assignment operator
FESurfaceMap& operator = (const FESurfaceMap& map);
//! Create a surface data map for this surface
bool Create(const FEFacetSet* ps, double val = 0.0, Storage_Fmt fmt = FMT_MULT);
//! serialization
void Serialize(DumpStream& ar) override;
const FEFacetSet* GetFacetSet() const { return m_surf; }
int MaxNodes() const { return m_maxFaceNodes; }
// return the item list associated with this map
FEItemList* GetItemList() override;
int StorageFormat() const;
public: // from FEDataMap
double value(const FEMaterialPoint& pt) override;
vec3d valueVec3d(const FEMaterialPoint& mp) override;
mat3d valueMat3d(const FEMaterialPoint& mp) override;
mat3ds valueMat3ds(const FEMaterialPoint& mp) override;
public:
template <typename T> T value(int nface, int node)
{
return get<T>(nface*m_maxFaceNodes + node);
}
template <typename T> void setValue(int nface, int node, const T& v)
{
set<T>(nface*m_maxFaceNodes + node, v);
}
void setValue(int n, double v) override;
void setValue(int n, const vec2d& v) override;
void setValue(int n, const vec3d& v) override;
void setValue(int n, const mat3d& v) override;
void setValue(int n, const mat3ds& v) override;
void fillValue(double v) override;
void fillValue(const vec2d& v) override;
void fillValue(const vec3d& v) override;
void fillValue(const mat3d& v) override;
void fillValue(const mat3ds& v) override;
private:
const FEFacetSet* m_surf; // the surface for which this data set is defined
int m_format; // the storage format
int m_maxFaceNodes; // number of nodes for each face
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FEPointFunction.cpp | .cpp | 6,634 | 223 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FEPointFunction.h"
#include "DumpStream.h"
#include "log.h"
#include "BSpline.h"
#ifndef min
#define min(a,b) ((a)<(b)?(a):(b))
#endif
//-----------------------------------------------------------------------------
BEGIN_FECORE_CLASS(FEPointFunction, FEFunction1D)
ADD_PARAMETER(m_int, "interpolate", 0, "linear\0step\0smooth\0cubic spline\0control points\0approximation\0smooth-step\0C2-smooth\0");
ADD_PARAMETER(m_ext, "extend" , 0, "constant\0extrapolate\0repeat\0repeat offset\0");
ADD_PARAMETER(m_bln, "log")->SetFlags(FE_PARAM_HIDDEN);
ADD_PARAMETER(m_points, "points");
END_FECORE_CLASS();
//-----------------------------------------------------------------------------
//! default constructor
FEPointFunction::FEPointFunction(FEModel* fem) : FEFunction1D(fem)
{
m_int = PointCurve::LINEAR;
m_ext = PointCurve::CONSTANT;
m_bln = false;
}
//-----------------------------------------------------------------------------
FEPointFunction::~FEPointFunction()
{
}
//-----------------------------------------------------------------------------
//! Clears the loadcurve data
bool FEPointFunction::Init()
{
m_fnc.SetInterpolator(m_int);
m_fnc.SetExtendMode(m_ext);
m_fnc.SetPoints(m_points);
if (m_fnc.Update() == false) return false;
return FEFunction1D::Init();
}
//-----------------------------------------------------------------------------
//! Clears the loadcurve data
void FEPointFunction::Clear()
{
m_fnc.Clear();
}
//-----------------------------------------------------------------------------
//! return nr of points
int FEPointFunction::Points() const
{
return (int) m_points.size();
}
//-----------------------------------------------------------------------------
//! set the points
void FEPointFunction::SetPoints(const std::vector<vec2d>& pts)
{
m_points = pts;
}
//-----------------------------------------------------------------------------
// Sets the time and data value of point i
// This function assumes that the load curve data has already been created
//
void FEPointFunction::SetPoint(int i, double x, double y)
{
m_fnc.SetPoint(i, x, y);
}
//-----------------------------------------------------------------------------
//! Set the type of interpolation
void FEPointFunction::SetInterpolation(int fnc) { m_int = fnc; }
//-----------------------------------------------------------------------------
//! Set the extend mode
void FEPointFunction::SetExtendMode(int mode) { m_ext = mode; }
//-----------------------------------------------------------------------------
//! returns point i
LOADPOINT FEPointFunction::LoadPoint(int i) const
{
const vec2d& p = m_points[i];
LOADPOINT lp;
lp.time = p.x();
lp.value = p.y();
return lp;
}
//-----------------------------------------------------------------------------
//! This function adds a datapoint to the loadcurve. The datapoint is inserted
//! at the appropriate place by examining the time parameter.
void FEPointFunction::Add(double x, double y)
{
// find the place to insert the data point
int n = 0;
int nsize = m_points.size();
while ((n<nsize) && (m_points[n].x() < x)) ++n;
// insert loadpoint
m_points.insert(m_points.begin() + n, vec2d(x, y));
}
//-----------------------------------------------------------------------------
void FEPointFunction::Scale(double s)
{
for (int i = 0; i < Points(); ++i)
{
m_points[i].y() *= s;
}
}
//-----------------------------------------------------------------------------
double FEPointFunction::value(double time) const
{
if (m_bln) time = (time > 0) ? log(time) : m_points[0].x();
return m_fnc.value(time);
}
//-----------------------------------------------------------------------------
void FEPointFunction::Serialize(DumpStream& ar)
{
FEFunction1D::Serialize(ar);
if (ar.IsShallow()) return;
if (ar.IsSaving())
{
ar << m_int << m_ext;
ar << m_points;
}
else
{
ar >> m_int >> m_ext;
ar >> m_points;
m_fnc.Clear();
m_fnc.SetInterpolator(m_int);
m_fnc.SetExtendMode(m_ext);
m_fnc.SetPoints(m_points);
m_fnc.Update();
}
}
//-----------------------------------------------------------------------------
double FEPointFunction::derive(double time) const
{
if (m_bln) time = (time > 0) ? log(time) : m_points[0].x();
return m_fnc.derive(time);
}
//-----------------------------------------------------------------------------
double FEPointFunction::deriv2(double time) const
{
if (m_bln) time = (time > 0) ? log(time) : m_points[0].x();
return m_fnc.deriv2(time);
}
double FEPointFunction::integrate(double a, double b) const
{
return m_fnc.integrate(a, b);
}
//-----------------------------------------------------------------------------
FEFunction1D* FEPointFunction::copy()
{
FEPointFunction* f = new FEPointFunction(GetFEModel());
f->m_int = m_int;
f->m_ext = m_ext;
f->m_points = m_points;
f->m_fnc = m_fnc;
return f;
}
//-----------------------------------------------------------------------------
void FEPointFunction::CopyFrom(const FEPointFunction& f)
{
m_int = f.m_int;
m_ext = f.m_ext;
m_points = f.m_points;
m_fnc = f.m_fnc;
}
//-----------------------------------------------------------------------------
void FEPointFunction::CopyFrom(const PointCurve& f)
{
m_int = f.GetInterpolator();
m_ext = f.GetExtendMode();
m_points = f.GetPoints();
m_fnc = f;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEModel.h | .h | 12,177 | 475 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "DOFS.h"
#include "FEMesh.h"
#include "FETimeInfo.h"
#include "FEStepComponent.h"
#include "Callback.h"
#include "FECoreKernel.h"
#include "DataStore.h"
#include "FEDataValue.h"
#include <string>
//-----------------------------------------------------------------------------
// forward declarations
class FELoadController;
class FEMaterial;
class FEModelLoad;
class FEBoundaryCondition;
class FEInitialCondition;
class FENLConstraint;
class FESurfacePairConstraint;
class FEAnalysis;
class FEGlobalData;
class FEGlobalMatrix;
class FELinearConstraintManager;
class FEDataArray;
class FEMeshAdaptor;
class Timer;
class FEPlotDataStore;
class FEMeshDataGenerator;
//-----------------------------------------------------------------------------
// struct that breaks down memory usage of FEModel
struct FEMODEL_MEMORY_STATS {
size_t StiffnessMatrix;
size_t Mesh;
size_t LinearSolver;
size_t NonLinSolver;
};
//-----------------------------------------------------------------------------
// helper class for managing global (user-defined) variables.
class FEGlobalVariable
{
public:
double v;
string name;
};
//! The FEModel class stores all the data for the finite element model, including
//! geometry, analysis steps, boundary and loading conditions, contact interfaces
//! and so on.
//!
class FECORE_API FEModel : public FECoreBase, public CallbackHandler
{
FECORE_SUPER_CLASS(FEMODEL_ID)
public:
enum {MAX_STRING = 256};
public:
FEModel(void);
virtual ~FEModel(void);
// Initialization
virtual bool Init() override;
//! Resets data structures
virtual bool Reset();
// solve the model
virtual bool Solve();
// copy the model data
virtual void CopyFrom(FEModel& fem);
// clear all model data
virtual void Clear();
// model activation
virtual void Activate();
// TODO: temporary construction. Need to see if I can just use Activate().
// This is called after remeshed
virtual void Reactivate();
//! Call this function whenever the geometry of the model has changed.
virtual void Update();
//! will return true if the model solved succussfully
bool IsSolved() const;
public: // reverse control solver interface
bool RCI_Init();
bool RCI_Restart();
bool RCI_Rewind();
bool RCI_Advance();
bool RCI_Finish();
bool RCI_ClearRewindStack();
public:
// get the FE mesh
FEMesh& GetMesh();
// get the linear constraint manager
FELinearConstraintManager& GetLinearConstraintManager();
//! Validate BC's
bool InitBCs();
//! Initialize the mesh
virtual bool InitMesh();
//! mesh validation
void ValidateMesh();
//! Initialize shells
virtual bool InitShells();
//! Build the matrix profile for this model
virtual void BuildMatrixProfile(FEGlobalMatrix& G, bool breset);
// call this function to set the mesh's update flag
void SetMeshUpdateFlag(bool b);
public: // --- Load controller functions ----
//! Add a load controller to the model
void AddLoadController(FELoadController* plc);
//! replace a load controller
void ReplaceLoadController(int n, FELoadController* plc);
//! get a load controller
FELoadController* GetLoadController(int i);
//! get the number of load controllers
int LoadControllers() const;
//! Attach a load controller to a parameter
void AttachLoadController(FEParam* p, int lc);
void AttachLoadController(FEParam* p, FELoadController* plc);
//! Detach a load controller from a parameter
bool DetachLoadController(FEParam* p);
//! return the number of load-controlled parameters
int LoadParams() const;
//! return a load-controlled parameter
FEParam* GetLoadParam(int n);
//! Get a load controller for a parameter (returns null if the param is not under load control)
FELoadController* GetLoadController(FEParam* p);
//! initialization of load controllers
bool InitLoadControllers();
public: // --- mesh data generators ---
//! Add a mesh data generator to the model
void AddMeshDataGenerator(FEMeshDataGenerator* pmd);
//! get a mesh data generator
FEMeshDataGenerator* GetMeshDataGenerator(int i);
//! get the number of mesh data generators
int MeshDataGenerators() const;
//! initialize mesh data generators
bool InitMeshDataGenerators();
public: // --- Material functions ---
//! Add a material to the model
void AddMaterial(FEMaterial* pm);
//! get the number of materials
int Materials();
//! return a pointer to a material
FEMaterial* GetMaterial(int i);
//! find a material based on its index
FEMaterial* FindMaterial(int nid);
//! find a material based on its name
FEMaterial* FindMaterial(const std::string& matName);
//! material initialization
bool InitMaterials();
//! material validation
bool ValidateMaterials();
public:
// Boundary conditions
int BoundaryConditions() const;
FEBoundaryCondition* BoundaryCondition(int i);
void AddBoundaryCondition(FEBoundaryCondition* bc);
void ClearBoundaryConditions();
// initial conditions
int InitialConditions();
FEInitialCondition* InitialCondition(int i);
void AddInitialCondition(FEInitialCondition* pbc);
public: // --- Analysis steps functions ---
//! retrieve the number of steps
int Steps() const;
//! clear the steps
void ClearSteps();
//! Add an analysis step
void AddStep(FEAnalysis* pstep);
//! Get a particular step
FEAnalysis* GetStep(int i);
//! Get the current step
FEAnalysis* GetCurrentStep();
const FEAnalysis* GetCurrentStep() const;
//! Set the current step index
int GetCurrentStepIndex() const;
//! Set the current step
void SetCurrentStep(FEAnalysis* pstep);
//! Set the current step index
void SetCurrentStepIndex(int n);
//! Get the current time
FETimeInfo& GetTime();
//! Get the start time
double GetStartTime() const;
//! Set the start time
void SetStartTime(double t);
//! Get the current time
double GetCurrentTime() const;
//! Set the current time
void SetCurrentTime(double t);
//! set the current time step
void SetCurrentTimeStep(double dt);
//! initialize steps
bool InitSteps();
public: // --- Contact interface functions ---
//! return number of surface pair constraints
int SurfacePairConstraints();
//! retrive a surface pair interaction
FESurfacePairConstraint* SurfacePairConstraint(int i);
//! Add a surface pair constraint
void AddSurfacePairConstraint(FESurfacePairConstraint* pci);
//! Initializes contact data
bool InitContact();
public: // --- Nonlinear constraints functions ---
//! return number of nonlinear constraints
int NonlinearConstraints();
//! retrieve a nonlinear constraint
FENLConstraint* NonlinearConstraint(int i);
//! add a nonlinear constraint
void AddNonlinearConstraint(FENLConstraint* pnlc);
//! Initialize constraint data
bool InitConstraints();
public: // --- Model Loads ----
//! return the number of model loads
int ModelLoads();
//! retrieve a model load
FEModelLoad* ModelLoad(int i);
//! Add a model load
void AddModelLoad(FEModelLoad* pml);
//! initialize model loads
bool InitModelLoads();
public: // --- Mesh adaptors ---
//! return number of mesh adaptors
int MeshAdaptors();
//! retrieve a mesh adaptors
FEMeshAdaptor* MeshAdaptor(int i);
//! add a mesh adaptor
void AddMeshAdaptor(FEMeshAdaptor* meshAdaptor);
//! initialize mesh adaptors
bool InitMeshAdaptors();
public: // --- parameter functions ---
//! evaluate all load controllers at some time
void EvaluateLoadControllers(double time);
// evaluate all mesh data
void EvaluateDataGenerators(double time);
//! evaluate all load parameters
virtual bool EvaluateLoadParameters();
//! Find a model parameter
FEParam* FindParameter(const ParamString& s) override;
//! return a reference to the named parameter
FEParamValue GetParameterValue(const ParamString& param) override;
//! return the parameter string for a parameter
std::string GetParamString(FEParam* p);
//! Find property
//! Note: Can't call this FindProperty, since this is already defined in base class
FECoreBase* FindComponent(const ParamString& prop);
//! Set the print parameters flag
void SetPrintParametersFlag(bool b);
//! Get the print parameter flag
bool GetPrintParametersFlag() const;
//! return a data value object
FEDataValue GetDataValue(const ParamString& s);
public: // --- Miscellaneous routines ---
//! call the callback function
//! This function returns fals if the run is to be aborted
bool DoCallback(unsigned int nevent);
//! I'd like to place the list of DOFS inside the model.
//! As a first step, all classes that have access to the model
//! should get the DOFS from this function
DOFS& GetDOFS();
//! Get the index of a DOF
int GetDOFIndex(const char* sz) const;
int GetDOFIndex(const char* szvar, int n) const;
//! serialize data for restarts
void Serialize(DumpStream& ar) override;
//! This is called to serialize geometry.
//! Derived classes can override this
virtual void SerializeGeometry(DumpStream& ar);
//! set the active module
void SetActiveModule(const std::string& moduleName);
//! get the module name
string GetModuleName() const;
public:
//! Log a message
void Logf(int ntag, const char* msg, ...);
void BlockLog();
void UnBlockLog();
bool LogBlocked() const;
void SetVerboseMode(bool b);
public:
// Derived classes can use this to implement the actual logging mechanism
virtual void Log(int ntag, const char* msg);
public: // Global data
void AddGlobalData(FEGlobalData* psd);
FEGlobalData* GetGlobalData(int i);
FEGlobalData* FindGlobalData(const char* szname);
int FindGlobalDataIndex(const char* szname) const;
int GlobalDataItems();
// get/set global data
void SetGlobalConstant(const string& s, double v);
double GetGlobalConstant(const string& s);
int GlobalVariables() const;
void AddGlobalVariable(const string& s, double v);
const FEGlobalVariable& GetGlobalVariable(int n);
public: // Data retrieval
// get nodal dof data
bool GetNodeData(int dof, vector<double>& data);
//! return the data store
DataStore& GetDataStore();
//! return plot data
FEPlotDataStore& GetPlotDataStore();
const FEPlotDataStore& GetPlotDataStore() const;
public:
// decide whether to collect timings
void CollectTimings(bool b);
// return if this model has timing collection on
bool CollectTimings() const;
// reset all the timers
void ResetAllTimers();
// return total number of timers
int Timers();
// return a timer by index
Timer* GetTimer(int i);
// get the number of calls to Update()
int UpdateCounter() const;
// this can be used to change the update counter
void IncrementUpdateCounter();
public:
void SetUnits(const char* szunits);
const char* GetUnits() const;
protected:
FEParamValue GetMeshParameter(const ParamString& paramString);
private:
class Implementation;
Implementation* m_imp;
DECLARE_FECORE_CLASS();
};
FECORE_API FECoreBase* CopyFEBioClass(FECoreBase* pc, FEModel* fem);
| Unknown |
3D | febiosoftware/FEBio | FECore/FEFullNewtonStrategy.h | .h | 1,974 | 53 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "matrix.h"
#include "vector.h"
#include "LinearSolver.h"
#include "FENewtonStrategy.h"
//-----------------------------------------------------------------------------
class FECORE_API FEFullNewtonStrategy : public FENewtonStrategy
{
public:
//! constructor
FEFullNewtonStrategy(FEModel* fem);
//! New initialization method
bool Init() override;
//! perform a BFGS udpate
bool Update(double s, vector<double>& ui, vector<double>& R0, vector<double>& R1) override;
//! solve the equations
void SolveEquations(vector<double>& x, vector<double>& b) override;
public:
// keep a pointer to the linear solver
LinearSolver* m_plinsolve; //!< pointer to linear solver
};
| Unknown |
3D | febiosoftware/FEBio | FECore/fecore_api.h | .h | 1,521 | 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 fecore_EXPORTS
#define FECORE_API __declspec(dllexport)
#else
#define FECORE_API __declspec(dllimport)
#endif
#else
#define FECORE_API
#endif
#else
#define FECORE_API
#endif
| Unknown |
3D | febiosoftware/FEBio | FECore/FEGlobalData.h | .h | 1,713 | 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
#include "FEModelComponent.h"
//-----------------------------------------------------------------------------
//! This class can be used to define global model data and will be placed in the
//! global date section of the FEModel class
class FECORE_API FEGlobalData : public FEModelComponent
{
FECORE_SUPER_CLASS(FEGLOBALDATA_ID)
FECORE_BASE_CLASS(FEGlobalData)
public:
//! constructor
FEGlobalData(FEModel* fem);
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FENodeSet.cpp | .cpp | 3,021 | 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 "FENodeSet.h"
#include "FEMesh.h"
#include "DumpStream.h"
#include "FEModel.h"
//=============================================================================
// FENodeSet
//-----------------------------------------------------------------------------
FENodeSet::FENodeSet(FEModel* fem) : FEItemList(fem, FEItemList::FE_ELEMENT_SET), m_Node(&fem->GetMesh())
{
SetMesh(&fem->GetMesh());
}
//-----------------------------------------------------------------------------
void FENodeSet::Add(int id)
{
m_Node.Add(id);
}
//-----------------------------------------------------------------------------
void FENodeSet::Add(const std::vector<int>& ns)
{
m_Node.Add(ns);
}
//-----------------------------------------------------------------------------
void FENodeSet::Add(const FENodeList& ns)
{
m_Node.Add(ns);
}
//-----------------------------------------------------------------------------
void FENodeSet::Clear()
{
m_Node.Clear();
}
//-----------------------------------------------------------------------------
FENode* FENodeSet::Node(int i)
{
FEMesh* mesh = GetMesh();
return (mesh ? &mesh->Node(m_Node[i]) : nullptr);
}
//-----------------------------------------------------------------------------
const FENode* FENodeSet::Node(int i) const
{
FEMesh* mesh = GetMesh();
return (mesh ? &mesh->Node(m_Node[i]) : nullptr);
}
//-----------------------------------------------------------------------------
void FENodeSet::Serialize(DumpStream& ar)
{
FEItemList::Serialize(ar);
if (ar.IsShallow()) return;
ar & m_Node;
}
void FENodeSet::SaveClass(DumpStream& ar, FENodeSet* p)
{
}
FENodeSet* FENodeSet::LoadClass(DumpStream& ar, FENodeSet* p)
{
p = new FENodeSet(&ar.GetFEModel());
return p;
}
| C++ |
3D | febiosoftware/FEBio | FECore/MObj2String.cpp | .cpp | 8,865 | 279 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "MObj2String.h"
#include <sstream>
using namespace std;
//-----------------------------------------------------------------------------
// Convert a math object to a string
string MObj2String::Convert(const MathObject& o)
{
const MathObject* po = &o;
if (dynamic_cast<const MSimpleExpression*>(po))
{
const MSimpleExpression* pe = dynamic_cast<const MSimpleExpression*>(po);
const MITEM& i = pe->GetExpression();
return Convert(i.ItemPtr());
}
assert(false);
return "";
}
//-----------------------------------------------------------------------------
// Convert a math item to string
string MObj2String::Convert(const MItem* pi)
{
switch(pi->Type())
{
case MCONST : return Constant (dynamic_cast<const MConstant*> (pi));
case MFRAC : return Fraction (dynamic_cast<const MFraction*> (pi));
case MNAMED : return NamedCt (dynamic_cast<const MNamedCt* > (pi));
case MVAR : return Variable (dynamic_cast<const MVarRef* > (pi));
case MNEG : return OpNeg (dynamic_cast<const MNeg* > (pi));
case MADD : return OpAdd (dynamic_cast<const MAdd* > (pi));
case MSUB : return OpSub (dynamic_cast<const MSub* > (pi));
case MMUL : return OpMul (dynamic_cast<const MMul* > (pi));
case MDIV : return OpDiv (dynamic_cast<const MDiv* > (pi));
case MPOW : return OpPow (dynamic_cast<const MPow* > (pi));
case MEQUATION: return OpEqual (dynamic_cast<const MEquation*> (pi));
case MF1D : return OpFnc1D (dynamic_cast<const MFunc1D* > (pi));
case MF2D : return OpFnc2D (dynamic_cast<const MFunc2D* > (pi));
case MFND : return OpFncND (dynamic_cast<const MFuncND* > (pi));
case MSFNC : return OpSFnc (dynamic_cast<const MSFuncND* > (pi));
}
assert(false);
return "";
}
//-----------------------------------------------------------------------------
// convert a constant to a string
string MObj2String::Constant(const MConstant *pc)
{
stringstream ss;
ss << pc->value();
return ss.str();
}
//-----------------------------------------------------------------------------
// convert a fraction to a string
string MObj2String::Fraction(const MFraction *pc)
{
FRACTION a = pc->fraction();
stringstream ss;
ss << a.n << "/" << a.d;
return ss.str();
}
//-----------------------------------------------------------------------------
// convert a constant to a string
string MObj2String::NamedCt(const MNamedCt *pc)
{
return pc->Name();
}
//-----------------------------------------------------------------------------
// convert a variable to a string
string MObj2String::Variable(const MVarRef* pv)
{
const MVariable* pvar = pv->GetVariable();
return string(pvar->Name());
}
//-----------------------------------------------------------------------------
string MObj2String::OpNeg(const MNeg* po)
{
const MItem* pi = po->Item();
string s = Convert(pi);
#ifndef NDEBUG
s = "-[" + s + "]";
#else
if (is_add(pi) || is_sub(pi) || is_neg(pi)) s = "-(" + s + ")"; else s = "-" + s;
#endif
return s;
}
//-----------------------------------------------------------------------------
string MObj2String::OpAdd(const MAdd* po)
{
string s;
const MItem* pl = po->LeftItem ();
const MItem* pr = po->RightItem();
string sl = Convert(pl);
string sr = Convert(pr);
#ifndef NDEBUG
if (is_binary(pl)) s = "(" + sl + ")"; else s = sl;
s += '+';
if (is_binary(pr)) s += "(" + sr + ")"; else s += sr;
#else
if (is_neg(pl)) s = '(' + sl + ')'; else s = sl;
s += '+';
if (is_neg(pr)) s += '(' + sr + ')'; else s += sr;
#endif
return s;
}
//-----------------------------------------------------------------------------
string MObj2String::OpSub(const MSub* po)
{
string s;
const MItem* pl = po->LeftItem ();
const MItem* pr = po->RightItem();
string sl = Convert(pl);
string sr = Convert(pr);
#ifndef NDEBUG
if (is_binary(pl)) s = "(" + sl + ")"; else s = sl;
s += '-';
if (is_binary(pr)) s += "(" + sr + ")"; else s += sr;
#else
if (is_neg(pl)) s = '(' + sl + ')'; else s = sl;
s += '-';
if (is_add(pr) || is_sub(pr) || is_neg(pr)) s += '(' + sr + ')'; else s += sr;
#endif
return s;
}
//-----------------------------------------------------------------------------
string MObj2String::OpMul(const MMul* po)
{
string s;
const MItem* pl = po->LeftItem ();
const MItem* pr = po->RightItem();
string sl = Convert(pl);
string sr = Convert(pr);
#ifndef NDEBUG
if (is_binary(pl)) s = "(" + sl + ")"; else s = sl;
s += '*';
if (is_binary(pr)) s += "(" + sr + ")"; else s += sr;
#else
if (is_add(pl) || is_sub(pl) || is_neg(pl) || is_div(pl)) s = '(' + sl + ')'; else s = sl;
s += '*';
if (is_add(pr) || is_sub(pr) || is_neg(pr) || is_div(pr)) s += '(' + sr + ')'; else s += sr;
#endif
return s;
}
//-----------------------------------------------------------------------------
string MObj2String::OpDiv(const MDiv* po)
{
string s;
const MItem* pl = po->LeftItem ();
const MItem* pr = po->RightItem();
string sl = Convert(pl);
string sr = Convert(pr);
#ifndef NDEBUG
if (is_binary(pl)) s = "(" + sl + ")"; else s = sl;
s += '/';
if (is_binary(pr)) s += "(" + sr + ")"; else s += sr;
#else
if (is_add(pl) || is_sub(pl) || is_neg(pl) || is_mul(pl) || is_div(pl) || is_pow(pr)) s = '(' + sl + ')'; else s = sl;
s += '/';
if (is_add(pr) || is_sub(pr) || is_neg(pr) || is_mul(pr) || is_div(pr)) s += '(' + sr + ')'; else s += sr;
#endif
return s;
}
//-----------------------------------------------------------------------------
string MObj2String::OpPow(const MPow* po)
{
string s;
const MItem* pl = po->LeftItem ();
const MItem* pr = po->RightItem();
string sl = Convert(pl);
string sr = Convert(pr);
#ifndef NDEBUG
if (is_binary(pl)) s = "(" + sl + ")"; else s = sl;
s += '^';
if (is_binary(pr)) s += "(" + sr + ")"; else s += sr;
#else
if (is_add(pl) || is_sub(pl) || is_neg(pl) || is_pow(pl) || is_mul(pl) || is_div(pl)) s = '(' + sl + ')'; else s = sl;
s += '^';
if (is_add(pr) || is_sub(pr) || is_neg(pr) || is_pow(pr) || is_mul(pr) || is_div(pr)) s += '(' + sr + ')'; else s += sr;
#endif
return s;
}
//-----------------------------------------------------------------------------
string MObj2String::OpEqual(const MEquation* po)
{
string s;
const MItem* pl = po->LeftItem ();
const MItem* pr = po->RightItem();
string sl = Convert(pl);
string sr = Convert(pr);
#ifndef NDEBUG
if (is_binary(pl)) s = "(" + sl + ")"; else s = sl;
s += '=';
if (is_binary(pr)) s += "(" + sr + ")"; else s += sr;
#else
s += '=';
#endif
return s;
}
//-----------------------------------------------------------------------------
string MObj2String::OpFnc1D(const MFunc1D *po)
{
return string(po->Name() + "(" + Convert(po->Item()) + ")");
}
//-----------------------------------------------------------------------------
string MObj2String::OpFnc2D(const MFunc2D *po)
{
return string(po->Name() + "(" + Convert(po->LeftItem()) + "," + Convert(po->RightItem()) + ")");
}
//-----------------------------------------------------------------------------
string MObj2String::OpFncND(const MFuncND *po)
{
int N = po->Params();
string s = po->Name() + "(";
for (int i=0; i<N; ++i)
{
const MItem* pi = po->Param(i);
s += Convert(pi);
if (i != N-1) s += ",";
}
return s + ")";
}
//-----------------------------------------------------------------------------
string MObj2String::OpSFnc(const MSFuncND *po)
{
int N = po->Params();
string s = po->Name() + "(";
for (int i=0; i<N; ++i)
{
const MItem* pi = po->Param(i);
s += Convert(pi);
if (i != N-1) s += ",";
}
return s + ")";
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEElement.cpp | .cpp | 17,465 | 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 "FEElement.h"
#include "DumpStream.h"
#include <math.h>
//-----------------------------------------------------------------------------
FEElementState::FEElementState(const FEElementState& s)
{
m_data.resize( s.m_data.size() );
for (size_t i=0; i<m_data.size(); ++i)
{
if (s.m_data[i]) m_data[i] = s.m_data[i]->Copy(); else m_data[i] = 0;
}
}
FEElementState& FEElementState::operator = (const FEElementState& s)
{
Clear();
m_data.resize( s.m_data.size() );
for (size_t i=0; i<m_data.size(); ++i)
{
if (s.m_data[i]) m_data[i] = s.m_data[i]->Copy(); else m_data[i] = 0;
}
return (*this);
}
//-----------------------------------------------------------------------------
//! clear material point data
void FEElement::ClearData()
{
int nint = GaussPoints();
for (int i=0; i<nint; ++i)
{
FEMaterialPoint* mp = GetMaterialPoint(i);
delete mp;
m_State[i] = nullptr;
}
}
//-----------------------------------------------------------------------------
double FEElement::Evaluate(double* fn, int n)
{
double* Hn = H(n);
double f = 0;
const int N = Nodes();
for (int i=0; i<N; ++i) f += Hn[i]*fn[i];
return f;
}
double FEElement::Evaluate(int order, double* fn, int n)
{
double* Hn = H(order, n);
double f = 0;
const int N = ShapeFunctions(order);
for (int i = 0; i<N; ++i) f += Hn[i] * fn[i];
return f;
}
double FEElement::Evaluate(vector<double>& fn, int n)
{
double* Hn = H(n);
double f = 0;
const int N = Nodes();
for (int i=0; i<N; ++i) f += Hn[i]*fn[i];
return f;
}
vec2d FEElement::Evaluate(vec2d* vn, int n)
{
double* Hn = H(n);
vec2d v(0,0);
const int N = Nodes();
for (int i=0; i<N; ++i) v += vn[i]*Hn[i];
return v;
}
vec3d FEElement::Evaluate(vec3d* vn, int n)
{
double* Hn = H(n);
vec3d v;
const int N = Nodes();
for (int i=0; i<N; ++i) v += vn[i]*Hn[i];
return v;
}
//-----------------------------------------------------------------------------
double FEElement::Evaluate(double* fn, int order, int n)
{
double* Hn = H(order, n);
double f = 0;
const int N = ShapeFunctions(order);
for (int i = 0; i<N; ++i) f += Hn[i] * fn[i];
return f;
}
double* FEElement::H(int order, int n)
{
if (order == -1) return m_pT->m_H[n];
else return m_pT->m_Hp[order][n];
}
int FEElement::ShapeFunctions(int order)
{
return (order == -1 ? Nodes() : m_pT->ShapeFunctions(order));
}
//-----------------------------------------------------------------------------
bool FEElement::HasNode(int n) const
{
int l = Nodes();
for (int i = 0; i<l; ++i)
if (m_node[i] == n) return true;
return false;
}
//-----------------------------------------------------------------------------
int FEElement::FindNode(int n) const
{
int l = Nodes();
for (int i = 0; i<l; ++i)
if (m_node[i] == n) return i;
return -1;
}
//-----------------------------------------------------------------------------
FEElement::FEElement() : m_pT(0)
{
static int n = 1;
m_nID = n++;
m_lm = -1;
m_val = 0.0;
m_lid = -1;
m_part = nullptr;
m_status = ACTIVE;
}
//! get the element ID
int FEElement::GetID() const { return m_nID; }
//! set the element ID
void FEElement::SetID(int n) { m_nID = n; }
//! Get the element's material ID
int FEElement::GetMatID() const { return m_mat; }
//! Set the element's material ID
void FEElement::SetMatID(int id) { m_mat = id; }
//-----------------------------------------------------------------------------
void FEElement::SetTraits(FEElementTraits* ptraits)
{
m_pT = ptraits;
m_node.resize(Nodes());
m_lnode.resize(Nodes());
m_State.Create(GaussPoints());
}
//! serialize
void FEElement::Serialize(DumpStream& ar)
{
if (ar.IsShallow()) return;
if (ar.IsSaving())
{
int type = Type();
ar << type;
ar << m_nID << m_lid << m_mat;
ar << m_node;
ar << m_lnode;
ar << m_lm << m_val;
ar << m_status;
}
else
{
int ntype;
ar >> ntype; SetType(ntype);
ar >> m_nID >> m_lid >> m_mat;
ar >> m_node;
ar >> m_lnode;
ar >> m_lm >> m_val;
ar >> m_status;
}
}
//! return the nodes of the face
int FEElement::GetFace(int nface, int* nf) const
{
int nn = -1;
const int* en = &(m_node[0]);
switch (Shape())
{
case ET_HEX8:
nn = 4;
switch (nface)
{
case 0: nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[5]; nf[3] = en[4]; break;
case 1: nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[6]; nf[3] = en[5]; break;
case 2: nf[0] = en[2]; nf[1] = en[3]; nf[2] = en[7]; nf[3] = en[6]; break;
case 3: nf[0] = en[3]; nf[1] = en[0]; nf[2] = en[4]; nf[3] = en[7]; break;
case 4: nf[0] = en[0]; nf[1] = en[3]; nf[2] = en[2]; nf[3] = en[1]; break;
case 5: nf[0] = en[4]; nf[1] = en[5]; nf[2] = en[6]; nf[3] = en[7]; break;
}
break;
case ET_PENTA6:
switch (nface)
{
case 0: nn = 4; nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[4]; nf[3] = en[3]; break;
case 1: nn = 4; nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[5]; nf[3] = en[4]; break;
case 2: nn = 4; nf[0] = en[0]; nf[1] = en[3]; nf[2] = en[5]; nf[3] = en[2]; break;
case 3: nn = 3; nf[0] = en[0]; nf[1] = en[2]; nf[2] = en[1]; nf[3] = en[1]; break;
case 4: nn = 3; nf[0] = en[3]; nf[1] = en[4]; nf[2] = en[5]; nf[3] = en[5]; break;
}
break;
case ET_PENTA15:
switch (nface)
{
case 0: nn = 8; nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[4]; nf[3] = en[3]; nf[4] = en[6]; nf[5] = en[13]; nf[6] = en[9]; nf[7] = en[12]; break;
case 1: nn = 8; nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[5]; nf[3] = en[4]; nf[4] = en[7]; nf[5] = en[14]; nf[6] = en[10]; nf[7] = en[13]; break;
case 2: nn = 8; nf[0] = en[0]; nf[1] = en[3]; nf[2] = en[5]; nf[3] = en[2]; nf[4] = en[12]; nf[5] = en[11]; nf[6] = en[14]; nf[7] = en[8]; break;
case 3: nn = 6; nf[0] = en[0]; nf[1] = en[2]; nf[2] = en[1]; nf[3] = en[8]; nf[4] = en[7]; nf[5] = en[6]; break;
case 4: nn = 6; nf[0] = en[3]; nf[1] = en[4]; nf[2] = en[5]; nf[3] = en[9]; nf[4] = en[10]; nf[5] = en[11]; break;
}
break;
case ET_PYRA5:
switch (nface)
{
case 0: nn = 3; nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[4]; break;
case 1: nn = 3; nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[4]; break;
case 2: nn = 3; nf[0] = en[2]; nf[1] = en[3]; nf[2] = en[4]; break;
case 3: nn = 3; nf[0] = en[3]; nf[1] = en[0]; nf[2] = en[4]; break;
case 4: nn = 4; nf[0] = en[3]; nf[1] = en[2]; nf[2] = en[1]; nf[3] = en[0]; break;
}
break;
case ET_TET4:
case ET_TET5:
nn = 3;
switch (nface)
{
case 0: nf[0] = en[0]; nf[1] = en[1]; nf[2] = nf[3] = en[3]; break;
case 1: nf[0] = en[1]; nf[1] = en[2]; nf[2] = nf[3] = en[3]; break;
case 2: nf[0] = en[2]; nf[1] = en[0]; nf[2] = nf[3] = en[3]; break;
case 3: nf[0] = en[2]; nf[1] = en[1]; nf[2] = nf[3] = en[0]; break;
}
break;
case ET_TET10:
nn = 6;
switch (nface)
{
case 0: nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[3]; nf[3] = en[4]; nf[4] = en[8]; nf[5] = en[7]; break;
case 1: nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[3]; nf[3] = en[5]; nf[4] = en[9]; nf[5] = en[8]; break;
case 2: nf[0] = en[2]; nf[1] = en[0]; nf[2] = en[3]; nf[3] = en[6]; nf[4] = en[7]; nf[5] = en[9]; break;
case 3: nf[0] = en[2]; nf[1] = en[1]; nf[2] = en[0]; nf[3] = en[5]; nf[4] = en[4]; nf[5] = en[6]; break;
}
break;
case ET_TET15:
nn = 7;
switch (nface)
{
case 0: nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[3]; nf[3] = en[4]; nf[4] = en[8]; nf[5] = en[7]; nf[6] = en[11]; break;
case 1: nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[3]; nf[3] = en[5]; nf[4] = en[9]; nf[5] = en[8]; nf[6] = en[12]; break;
case 2: nf[0] = en[2]; nf[1] = en[0]; nf[2] = en[3]; nf[3] = en[6]; nf[4] = en[7]; nf[5] = en[9]; nf[6] = en[13]; break;
case 3: nf[0] = en[2]; nf[1] = en[1]; nf[2] = en[0]; nf[3] = en[5]; nf[4] = en[4]; nf[5] = en[6]; nf[6] = en[10]; break;
}
break;
case ET_TET20:
nn = 10;
switch (nface)
{
case 0: nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[3]; nf[3] = en[4]; nf[4] = en[5]; nf[5] = en[12]; nf[6] = en[13]; nf[7] = en[10]; nf[8] = en[11]; nf[9] = en[16]; break;
case 1: nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[3]; nf[3] = en[6]; nf[4] = en[7]; nf[5] = en[14]; nf[6] = en[15]; nf[7] = en[13]; nf[8] = en[14]; nf[9] = en[17]; break;
case 2: nf[0] = en[2]; nf[1] = en[0]; nf[2] = en[3]; nf[3] = en[9]; nf[4] = en[8]; nf[5] = en[10]; nf[6] = en[11]; nf[7] = en[14]; nf[8] = en[15]; nf[9] = en[18]; break;
case 3: nf[0] = en[2]; nf[1] = en[1]; nf[2] = en[0]; nf[3] = en[7]; nf[4] = en[6]; nf[5] = en[5]; nf[6] = en[4]; nf[7] = en[10]; nf[8] = en[8]; nf[9] = en[19]; break;
}
break;
case ET_HEX20:
nn = 8;
switch (nface)
{
case 0: nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[5]; nf[3] = en[4]; nf[4] = en[8]; nf[5] = en[17]; nf[6] = en[12]; nf[7] = en[16]; break;
case 1: nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[6]; nf[3] = en[5]; nf[4] = en[9]; nf[5] = en[18]; nf[6] = en[13]; nf[7] = en[17]; break;
case 2: nf[0] = en[2]; nf[1] = en[3]; nf[2] = en[7]; nf[3] = en[6]; nf[4] = en[10]; nf[5] = en[19]; nf[6] = en[14]; nf[7] = en[18]; break;
case 3: nf[0] = en[3]; nf[1] = en[0]; nf[2] = en[4]; nf[3] = en[7]; nf[4] = en[11]; nf[5] = en[16]; nf[6] = en[15]; nf[7] = en[19]; break;
case 4: nf[0] = en[0]; nf[1] = en[3]; nf[2] = en[2]; nf[3] = en[1]; nf[4] = en[11]; nf[5] = en[10]; nf[6] = en[9]; nf[7] = en[8]; break;
case 5: nf[0] = en[4]; nf[1] = en[5]; nf[2] = en[6]; nf[3] = en[7]; nf[4] = en[12]; nf[5] = en[13]; nf[6] = en[14]; nf[7] = en[15]; break;
}
break;
case ET_HEX27:
nn = 9;
switch (nface)
{
case 0: nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[5]; nf[3] = en[4]; nf[4] = en[8]; nf[5] = en[17]; nf[6] = en[12]; nf[7] = en[16]; nf[8] = en[20]; break;
case 1: nf[0] = en[1]; nf[1] = en[2]; nf[2] = en[6]; nf[3] = en[5]; nf[4] = en[9]; nf[5] = en[18]; nf[6] = en[13]; nf[7] = en[17]; nf[8] = en[21]; break;
case 2: nf[0] = en[2]; nf[1] = en[3]; nf[2] = en[7]; nf[3] = en[6]; nf[4] = en[10]; nf[5] = en[19]; nf[6] = en[14]; nf[7] = en[18]; nf[8] = en[22]; break;
case 3: nf[0] = en[3]; nf[1] = en[0]; nf[2] = en[4]; nf[3] = en[7]; nf[4] = en[11]; nf[5] = en[16]; nf[6] = en[15]; nf[7] = en[19]; nf[8] = en[23]; break;
case 4: nf[0] = en[0]; nf[1] = en[3]; nf[2] = en[2]; nf[3] = en[1]; nf[4] = en[11]; nf[5] = en[10]; nf[6] = en[9]; nf[7] = en[8]; nf[8] = en[24]; break;
case 5: nf[0] = en[4]; nf[1] = en[5]; nf[2] = en[6]; nf[3] = en[7]; nf[4] = en[12]; nf[5] = en[13]; nf[6] = en[14]; nf[7] = en[15]; nf[8] = en[25]; break;
}
break;
case ET_QUAD4:
nn = 4;
nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[2]; nf[3] = en[3];
break;
case ET_QUAD8:
nn = 8;
nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[2]; nf[3] = en[3]; nf[4] = en[4]; nf[5] = en[5]; nf[6] = en[6]; nf[7] = en[7];
break;
case ET_QUAD9:
nn = 9;
nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[2]; nf[3] = en[3]; nf[4] = en[4]; nf[5] = en[5]; nf[6] = en[6]; nf[7] = en[7]; nf[8] = en[8];
break;
case ET_TRI3:
nn = 3;
nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[2];
break;
case ET_TRI6:
nn = 6;
nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[2]; nf[3] = en[3]; nf[4] = en[4]; nf[5] = en[5];
break;
case ET_TRI7:
nn = 7;
nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[2]; nf[3] = en[3]; nf[4] = en[4]; nf[5] = en[5]; nf[6] = en[6];
break;
case ET_TRI10:
nn = 7;
nf[0] = en[0]; nf[1] = en[1]; nf[2] = en[2]; nf[3] = en[3]; nf[4] = en[4]; nf[5] = en[5]; nf[6] = en[6]; nf[7] = en[7]; nf[8] = en[8]; nf[9] = en[9];
break;
}
return nn;
}
//=================================================================================================
// FETrussElement
//=================================================================================================
//-----------------------------------------------------------------------------
FETrussElement::FETrussElement()
{
m_a0 = 0.0;
m_lam = 1.0;
m_tau = 0.0;
m_L0 = 0.0;
}
FETrussElement::FETrussElement(const FETrussElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
// truss data
m_a0 = el.m_a0;
m_L0 = el.m_L0;
m_lam = el.m_lam;
m_tau = el.m_tau;
}
FETrussElement& FETrussElement::operator = (const FETrussElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
// copy truss data
m_a0 = el.m_a0;
m_L0 = el.m_L0;
m_lam = el.m_lam;
m_tau = el.m_tau;
return (*this);
}
//-----------------------------------------------------------------------------
void FETrussElement::Serialize(DumpStream& ar)
{
FEElement::Serialize(ar);
if (ar.IsShallow() == false)
{
ar & m_a0 & m_L0 & m_lam & m_tau;
}
}
//-----------------------------------------------------------------------------
FEDiscreteElement::FEDiscreteElement(const FEDiscreteElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
}
FEDiscreteElement& FEDiscreteElement::operator =(const FEDiscreteElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
return (*this);
}
//-----------------------------------------------------------------------------
FEElement2D::FEElement2D(const FEElement2D& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
}
FEElement2D& FEElement2D::operator = (const FEElement2D& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
return (*this);
}
//-----------------------------------------------------------------------------
FELineElement::FELineElement()
{
m_lid = -1;
}
FELineElement::FELineElement(const FELineElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy data
m_lid = el.m_lid;
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
}
FELineElement& FELineElement::operator = (const FELineElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy data
m_lid = el.m_lid;
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
return (*this);
}
void FELineElement::SetTraits(FEElementTraits* pt)
{
m_pT = pt;
m_node.resize(Nodes());
m_lnode.resize(Nodes());
m_State.Create(GaussPoints());
}
//=============================================================================
FEBeamElement::FEBeamElement()
{
m_lid = -1;
m_L0 = 0.0;
}
FEBeamElement::FEBeamElement(const FEBeamElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy data
m_lid = el.m_lid;
m_L0 = el.m_L0;
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
}
FEBeamElement& FEBeamElement::operator = (const FEBeamElement& el)
{
// set the traits of the element
if (el.m_pT) { SetTraits(el.m_pT); m_State = el.m_State; }
// copy data
m_lid = el.m_lid;
m_L0 = el.m_L0;
// copy base class data
m_mat = el.m_mat;
m_nID = el.m_nID;
m_lid = el.m_lid;
m_node = el.m_node;
m_lnode = el.m_lnode;
m_lm = el.m_lm;
m_val = el.m_val;
return (*this);
}
| C++ |
3D | febiosoftware/FEBio | FECore/FECoreFactory.cpp | .cpp | 2,517 | 74 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FECoreFactory.h"
#include "FECoreBase.h"
#include "log.h"
#include <assert.h>
//-----------------------------------------------------------------------------
//! constructor
FECoreFactory::FECoreFactory(SUPER_CLASS_ID scid, const char* szclass, const char* szbase, const char* szalias, int nspec) : m_scid(scid)
{
m_szclass = szclass;
m_szalias = szalias;
m_szbase = szbase;
m_module = 0;
m_spec = nspec;
m_alloc_id = -1;
}
//-----------------------------------------------------------------------------
//! virtual constructor
FECoreFactory::~FECoreFactory(){}
//-----------------------------------------------------------------------------
//! set the module ID
void FECoreFactory::SetModuleID(unsigned int mid)
{
m_module = mid;
}
//-----------------------------------------------------------------------------
FECoreBase* FECoreFactory::CreateInstance(FEModel* pfem) const
{
// create a new instance of this class
FECoreBase* pclass = Create(pfem); assert(pclass);
if (pclass == 0) return 0;
// store the factory that created the class
pclass->SetFactoryClass(this);
// build the class descriptor
if (pclass->BuildClass() == false) return 0;
// return the pointer
return pclass;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FESurfacePairConstraint.cpp | .cpp | 1,507 | 36 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FESurfacePairConstraint.h"
//-----------------------------------------------------------------------------
FESurfacePairConstraint::FESurfacePairConstraint(FEModel* pfem) : FEStepComponent(pfem)
{
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEElementList.h | .h | 2,229 | 74 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "fecore_api.h"
class FEMesh;
class FEElement;
//-----------------------------------------------------------------------------
//! utitlity class for accessing all elements without having to go throug the domains
class FEElementList
{
public:
class iterator
{
public:
iterator() { m_pmesh = 0; m_ndom = -1; m_nel = -1; }
iterator(FEMesh* pm) { m_pmesh = pm; m_ndom = 0; m_nel = 0; }
FECORE_API FEElement& operator*();
FECORE_API FEElement* operator->();
FECORE_API operator FEElement* ();
FECORE_API void operator ++ ();
bool operator != (const iterator& it)
{
return ((m_ndom!=it.m_ndom)||(m_nel != it.m_nel));
}
public:
FEMesh* m_pmesh; // pointer to mesh
int m_ndom; // domain index
int m_nel; // element index
};
public:
FEElementList(FEMesh& m) : m_mesh(m){}
iterator begin() { return iterator(&m_mesh); }
iterator end() { return iterator(); }
private:
FEMesh& m_mesh;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/vector.cpp | .cpp | 5,472 | 209 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 <assert.h>
#include "vector.h"
#include "FEMesh.h"
#include "FEDofList.h"
#include <algorithm>
using namespace std;
double operator*(const vector<double>& a, const vector<double>& b)
{
// This algorithm sums positive and negative products separately,
// which is more accurate then just doing the running sum.
assert(a.size() == b.size());
double sum_p = 0, sum_n = 0;
size_t n = a.size();
for (size_t i = 0; i < n; i++)
{
double ab = a[i] * b[i];
if (ab >= 0.0) sum_p += ab; else sum_n += ab;
}
return sum_p + sum_n;
}
vector<double> operator - (vector<double>& a, vector<double>& b)
{
vector<double> c(a);
size_t n = c.size();
for (size_t i=0; i<n; ++i) c[i] -= b[i];
return c;
}
void operator += (vector<double>& a, const vector<double>& b)
{
assert(a.size() == b.size());
for (size_t i = 0; i < a.size(); ++i) a[i] += b[i];
}
void operator -= (vector<double>& a, const vector<double>& b)
{
assert(a.size() == b.size());
for (size_t i = 0; i < a.size(); ++i) a[i] -= b[i];
}
void operator *= (vector<double>& a, double b)
{
for (size_t i=0; i<a.size(); ++i) a[i] *= b;
}
void vcopys(vector<double>& a, const vector<double>& b, double s)
{
assert(a.size() == b.size());
for (size_t i=0; i<a.size(); ++i) a[i] = b[i]*s;
}
void vadds(vector<double>& a, const vector<double>& b, double s)
{
assert(a.size() == b.size());
for (size_t i = 0; i<a.size(); ++i) a[i] += b[i] * s;
}
void vsubs(vector<double>& a, const vector<double>& b, double s)
{
assert(a.size() == b.size());
for (size_t i = 0; i<a.size(); ++i) a[i] -= b[i] * s;
}
void vscale(vector<double>& a, const vector<double>& s)
{
assert(a.size() == s.size());
for (size_t i = 0; i<a.size(); ++i) a[i] *= s[i];
}
void vsub(vector<double>& a, const vector<double>& l, const vector<double>& r)
{
assert((a.size()==l.size())&&(a.size()==r.size()));
for (size_t i=0; i<a.size(); ++i) a[i] = l[i] - r[i];
}
vector<double> operator + (const vector<double>& a, const vector<double>& b)
{
assert(a.size() == b.size());
vector<double> s(a);
for (size_t i = 0; i < s.size(); ++i) s[i] += b[i];
return s;
}
vector<double> operator*(const vector<double>& a, double g)
{
vector<double> s(a.size());
for (size_t i = 0; i < s.size(); ++i) s[i] = a[i]*g;
return s;
}
vector<double> operator - (const vector<double>& a)
{
vector<double> s(a.size());
for (size_t i = 0; i < s.size(); ++i) s[i] = -a[i];
return s;
}
void gather(vector<double>& v, FEMesh& mesh, int ndof)
{
const int NN = mesh.Nodes();
for (int i=0; i<NN; ++i)
{
FENode& node = mesh.Node(i);
int n = node.m_ID[ndof]; if (n >= 0) v[n] = node.get(ndof);
}
}
void gather(vector<double>& v, FEMesh& mesh, const vector<int>& dof)
{
const int NN = mesh.Nodes();
const int NDOF = (const int) dof.size();
for (int i=0; i<NN; ++i)
{
FENode& node = mesh.Node(i);
for (int j=0; j<NDOF; ++j)
{
int n = node.m_ID[dof[j]];
if (n >= 0) v[n] = node.get(dof[j]);
}
}
}
void scatter(vector<double>& v, FEMesh& mesh, int ndof)
{
const int NN = mesh.Nodes();
for (int i=0; i<NN; ++i)
{
FENode& node = mesh.Node(i);
int n = node.m_ID[ndof];
if (n >= 0) node.set(ndof, v[n]);
}
}
void scatter3(vector<double>& v, FEMesh& mesh, int ndof1, int ndof2, int ndof3)
{
const int NN = mesh.Nodes();
#pragma omp parallel for
for (int i = 0; i<NN; ++i)
{
FENode& node = mesh.Node(i);
int n;
n = node.m_ID[ndof1]; if (n >= 0) node.set(ndof1, v[n]);
n = node.m_ID[ndof2]; if (n >= 0) node.set(ndof2, v[n]);
n = node.m_ID[ndof3]; if (n >= 0) node.set(ndof3, v[n]);
}
}
void scatter(vector<double>& v, FEMesh& mesh, const FEDofList& dofs)
{
const int NN = mesh.Nodes();
for (int i = 0; i<NN; ++i)
{
FENode& node = mesh.Node(i);
for (int j = 0; j < dofs.Size(); ++j)
{
int n = node.m_ID[dofs[j]]; if (n >= 0) node.set(dofs[j], v[n]);
}
}
}
double l2_norm(const vector<double>& v)
{
double s = 0.0;
for (auto vi : v) s += vi*vi;
return sqrt(s);
}
double l2_sqrnorm(const vector<double>& v)
{
double s = 0.0;
for (auto vi : v) s += vi*vi;
return s;
}
double l2_norm(double* x, int n)
{
double s = 0.0;
for (int i = 0; i < n; ++i) s += x[i]*x[i];
return sqrt(s);
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEGlobalMatrix.h | .h | 5,999 | 174 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "SparseMatrix.h"
#include "FESolver.h"
#include <vector>
//-----------------------------------------------------------------------------
class FEModel;
class FEMesh;
class FESurface;
class FEElement;
//-----------------------------------------------------------------------------
//! This class represents an element matrix, i.e. a matrix of values and the row and
//! column indices of the corresponding matrix elements in the global matrix.
class FECORE_API FEElementMatrix : public matrix
{
public:
// default constructor
FEElementMatrix(){}
FEElementMatrix(int nr, int nc) : matrix(nr, nc) {}
FEElementMatrix(const FEElement& el);
// constructor for symmetric matrices
FEElementMatrix(const FEElement& el, const vector<int>& lmi);
// constructor
FEElementMatrix(const FEElement& el, vector<int>& lmi, vector<int>& lmj);
// copy constructor
FEElementMatrix(const FEElementMatrix& ke);
FEElementMatrix(const FEElementMatrix& ke, double scale);
// assignment operator
void operator = (const matrix& ke);
// row indices
std::vector<int>& RowIndices() { return m_lmi; }
const std::vector<int>& RowIndices() const { return m_lmi; }
// column indices
std::vector<int>& ColumnsIndices() { return m_lmj; }
const std::vector<int>& ColumnsIndices() const { return m_lmj; }
// set the row and columnd indices (assuming they are the same)
void SetIndices(const std::vector<int>& lm) { m_lmi = m_lmj = lm; }
// set the row and columnd indices
void SetIndices(const std::vector<int>& lmr, const std::vector<int>& lmc) { m_lmi = lmr; m_lmj = lmc; }
// Set the node indices
void SetNodes(const std::vector<int>& en) { m_node = en; }
// get the nodes
const std::vector<int>& Nodes() const { return m_node; }
private:
std::vector<int> m_node; //!< node indices
std::vector<int> m_lmi; //!< row indices
std::vector<int> m_lmj; //!< column indices
};
//-----------------------------------------------------------------------------
//! This class implements a global system matrix.
//! The global system matrix is usually created by the discretization of the FE
//! equations into a linear system of equations. The structure of it depends greatly
//! on the element connectivity and usually results in a sparse matrix structure.
//! Several sparse matrix structures are supported (Compact, Skyline, etc.) and to
//! simplify the creation of the specific matrix structure, the FEGlobalMatrix offers
//! functionality to create the global matrix structure without the need to know
//! what particular sparse matrix format is used by the linear solver.
//! \todo I think the SparseMatrixProfile can handle all of the build functions.
class FECORE_API FEGlobalMatrix
{
protected:
enum { MAX_LM_SIZE = 64000 };
public:
//! constructor
FEGlobalMatrix(SparseMatrix* pK, bool del = true);
//! destructor
virtual ~FEGlobalMatrix();
//! construct the stiffness matrix from a FEM object
bool Create(FEModel* pfem, int neq, bool breset);
//! construct the stiffness matrix from a mesh
bool Create(FEMesh& mesh, int neq);
//! construct the stiffness matrix from a mesh
bool Create(FEMesh& mesh, int nstart, int nend);
//! construct a stiffness matrix from a surface
//! The boundary array is a list of equation numbers.
bool Create(const FESurface& surf, const std::vector<int>& equationIDs);
//! clears the sparse matrix that stores the stiffness matrix
void Clear();
//! Assembly routine
virtual void Assemble(const FEElementMatrix& ke);
//! return the nonzeroes in the sparse matrix
size_t NonZeroes() { return m_pA->NonZeroes(); }
//! return the number of rows
int Rows() { return m_pA->Rows(); }
//! converts a FEGlobalMatrix to a SparseMatrix
operator SparseMatrix* () { return m_pA; }
//! converts a FEGlobalMatrix to a SparseMatrix
operator SparseMatrix& () { return *m_pA;}
//! return a pointer to the sparse matrix
SparseMatrix* GetSparseMatrixPtr() { return m_pA; }
//! zero the sparse matrix
void Zero() { m_pA->Zero(); }
//! get the sparse matrix profile
SparseMatrixProfile* GetSparseMatrixProfile() { return m_pMP; }
public:
void build_begin(int neq);
void build_add(std::vector<int>& lm);
void build_end();
void build_flush();
protected:
SparseMatrix* m_pA; //!< the actual global stiffness matrix
bool m_delA; //!< delete A in destructor
// The following data structures are used to incrementally
// build the profile of the sparse matrix
SparseMatrixProfile* m_pMP; //!< profile of sparse matrix
SparseMatrixProfile m_MPs; //!< the "static" part of the matrix profile
vector< vector<int> > m_LM; //!< used for building the stiffness matrix
int m_nlm; //!< nr of elements in m_LM array
};
| Unknown |
3D | febiosoftware/FEBio | FECore/CompactSymmMatrix.h | .h | 3,110 | 90 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#pragma once
#include "CompactMatrix.h"
#include "fecore_api.h"
//=============================================================================
//! This class stores a sparse matrix in Harwell-Boeing format (i.e. column major, lower triangular compact).
//! This class also assumes the matrix is symmetric and therefor only stores
//! the lower triangular matrix
class FECORE_API CompactSymmMatrix : public CompactMatrix
{
public:
//! class constructor
CompactSymmMatrix(int offset = 0);
//! Create the matrix structure from the SparseMatrixProfile.
void Create(SparseMatrixProfile& mp) override;
//! Assemble an element matrix into the global 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;
//! add a matrix item
void add(int i, int j, double v) override;
//! set matrix item
void set(int i, int j, double v) override;
//! get a matrix item
double get(int i, int j) override;
// alternative access
double operator ()(int i, int j) { return get(i, j); }
//! return the diagonal component
double diag(int i) override { return m_pd[m_ppointers[i] - m_offset]; }
//! multiply with vector
bool mult_vector(double* x, double* r) override;
//! see if a matrix element is defined
bool check(int i, int j) override;
//! is the matrix symmetric or not
bool isSymmetric() override { return true; }
//! this is a column based format
bool isRowBased() override { return false; }
//! calculate the inf norm
double infNorm() const override;
//! calculate the one norm
double oneNorm() const override;
//! do row (L) and column (R) scaling
void scale(const std::vector<double>& L, const std::vector<double>& R) override;
};
| Unknown |
3D | febiosoftware/FEBio | FECore/FEElement.h | .h | 11,213 | 361 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FEElementLibrary.h"
#include "FEElementTraits.h"
#include "FEMaterialPoint.h"
#include "fecore_enum.h"
#include "FEException.h"
class FEMesh;
//-----------------------------------------------------------------------------
class FEElementTraits;
class FEMeshPartition;
//-----------------------------------------------------------------------------
//! The FEElementState class stores the element state data. The state is defined
//! by a material point class for each of the integration points.
class FECORE_API FEElementState
{
public:
//! default constructor
FEElementState() {}
//! destructor
~FEElementState() { Clear(); }
//! copy constructor
FEElementState(const FEElementState& s);
//! assignment operator
FEElementState& operator = (const FEElementState& s);
//! clear state data
void Clear() { for (size_t i=0; i<m_data.size(); ++i) delete m_data[i]; m_data.clear(); }
//! create
void Create(int n) { Clear(); m_data.assign(n, static_cast<FEMaterialPoint*>(0)); }
//! operator for easy access to element data
FEMaterialPoint*& operator [] (int n) { return m_data[n]; }
private:
std::vector<FEMaterialPoint*> m_data;
};
//-----------------------------------------------------------------------------
//! Base class for all element classes
//! From this class the different element classes are derived.
class FECORE_API FEElement
{
public:
enum {MAX_NODES = 27}; // max nr of nodes
enum {MAX_INTPOINTS = 27}; // max nr of integration points
// Status flags.
enum Status {
ACTIVE = 0x01
};
public:
//! default constructor
FEElement();
//! destructor
virtual ~FEElement() {}
//! get the element ID
int GetID() const;
//! set the element ID
void SetID(int n);
//! Get the element's material ID
int GetMatID() const;
//! Set the element's material ID
void SetMatID(int id);
//Get the mesh partition that contains this element
FEMeshPartition * GetMeshPartition() const { return m_part; }
//Set the mesh partition that contains this element
void SetMeshPartition(FEMeshPartition* part){ m_part = part; }
//! Set the Local ID
void SetLocalID(int lid) { m_lid = lid; }
//! Get the local ID
int GetLocalID() const { return m_lid; }
//! clear material point data
void ClearData();
public:
//! Set the type of the element
void SetType(int ntype) { FEElementLibrary::SetElementTraits(*this, ntype); }
//! Set the traits of an element
virtual void SetTraits(FEElementTraits* ptraits);
//! Get the element traits
FEElementTraits* GetTraits() { return m_pT; }
//! return number of nodes
int Nodes() const { return m_pT->m_neln; }
//! return the element class
int Class() const { return m_pT->Class(); }
//! return the element shape
int Shape() const { return m_pT->Shape(); }
//! return the type of element
int Type() const { return m_pT->Type(); }
//! return number of integration points
int GaussPoints() const { return m_pT->m_nint; }
//! shape function values
double* H(int n) { return m_pT->m_H[n]; }
const double* H(int n) const { return m_pT->m_H[n]; }
//! return number of faces
int Faces() const { return m_pT->Faces(); }
//! return the nodes of the face
int GetFace(int nface, int* nodeList) const;
public:
//! Get the material point data
FEMaterialPoint* GetMaterialPoint(int n) { return m_State[n]; }
//! set the material point data
void SetMaterialPointData(FEMaterialPoint* pmp, int n)
{
pmp->m_elem = this;
pmp->m_index = n;
if (m_State[n] != nullptr) delete m_State[n];
m_State[n] = pmp;
}
//! serialize
//! NOTE: state data is not serialized by the element. This has to be done by the domains.
virtual void Serialize(DumpStream& ar);
public:
//! evaluate scalar field at integration point
double Evaluate(double* fn, int n);
double Evaluate(int order, double* fn, int n);
//! evaluate scale field at integration point
double Evaluate(std::vector<double>& fn, int n);
//! evaluate vector field at integration point
vec2d Evaluate(vec2d* vn, int n);
//! evaluate vector field at integration point
vec3d Evaluate(vec3d* vn, int n);
// see if this element has the node n
bool HasNode(int n) const;
// find local element index of node n
int FindNode(int n) const;
// project data to nodes
void project_to_nodes(double* ai, double* ao) const { m_pT->project_to_nodes(ai, ao); }
void project_to_nodes(vec3d* ai, vec3d* ao) const { m_pT->project_to_nodes(ai, ao); }
void project_to_nodes(mat3ds* ai, mat3ds* ao) const { m_pT->project_to_nodes(ai, ao); }
void project_to_nodes(mat3d* ai, mat3d* ao) const { m_pT->project_to_nodes(ai, ao); }
// evaluate scalar field at integration point using specific interpolation order
double Evaluate(double* fn, int order, int n);
int ShapeFunctions(int order);
double* H(int order, int n);
public:
void setStatus(unsigned int n) { m_status = n; }
unsigned int status() const { return m_status; }
bool isActive() const { return (m_status & ACTIVE); }
void setActive() { m_status |= ACTIVE; }
void setInactive() { m_status &= ~ACTIVE; }
protected:
int m_nID; //!< element ID
int m_lid; //!< local ID
int m_mat; //!< material index
unsigned int m_status; //!< element status
FEMeshPartition * m_part; //!< parent mesh partition
public:
std::vector<int> m_node; //!< connectivity
// This array stores the local node numbers, that is the node numbers
// into the node list of a domain.
std::vector<int> m_lnode; //!< local connectivity
public:
// NOTE: Work in progress
// Elements can now also have degrees of freedom, only currently just one.
// Like with nodes, a degree of freedom needs an equation number and a value
// The equation number is in m_lm and the value is in m_val
int m_lm; //!< equation number of element degree of freedom
double m_val; //!< solution value of element degree of freedom
protected:
FEElementState m_State; //!< element state data
FEElementTraits* m_pT; //!< pointer to element traits
};
//-----------------------------------------------------------------------------
class FECORE_API FETrussElement : public FEElement
{
public:
FETrussElement();
FETrussElement(const FETrussElement& el);
FETrussElement& operator = (const FETrussElement& el);
void Serialize(DumpStream& ar) override;
double* GaussWeights() const { return &((FETrussElementTraits*)(m_pT))->gw[0]; }
public:
double m_a0; // cross-sectional area
double m_lam; // current stretch ratio
double m_tau; // Kirchoff stress
double m_L0; // initial length
double m_Lt; // current length
};
//-----------------------------------------------------------------------------
//! Discrete element class
class FECORE_API FEDiscreteElement : public FEElement
{
public:
FEDiscreteElement(){}
FEDiscreteElement(const FEDiscreteElement& e);
FEDiscreteElement& operator = (const FEDiscreteElement& e);
};
//-----------------------------------------------------------------------------
//! This class defines a 2D element
class FECORE_API FEElement2D : public FEElement
{
public:
//! default constructor
FEElement2D(){}
//! copy constructor
FEElement2D(const FEElement2D& el);
//! assignment operator
FEElement2D& operator = (const FEElement2D& el);
double* GaussWeights() { return &((FE2DElementTraits*)(m_pT))->gw[0]; } // weights of integration points
double* Hr(int n) { return ((FE2DElementTraits*)(m_pT))->Gr[n]; } // shape function derivative to r
double* Hs(int n) { return ((FE2DElementTraits*)(m_pT))->Gs[n]; } // shape function derivative to s
double* Hrr(int n) { return ((FE2DElementTraits*)(m_pT))->Grr[n]; } // shape function 2nd derivative to rr
double* Hsr(int n) { return ((FE2DElementTraits*)(m_pT))->Gsr[n]; } // shape function 2nd derivative to sr
double* Hrs(int n) { return ((FE2DElementTraits*)(m_pT))->Grs[n]; } // shape function 2nd derivative to rs
double* Hss(int n) { return ((FE2DElementTraits*)(m_pT))->Gss[n]; } // shape function 2nd derivative to ss
//! values of shape functions
void shape_fnc(double* H, double r, double s) { ((FE2DElementTraits*)(m_pT))->shape(H, r, s); }
//! values of shape function derivatives
void shape_deriv(double* Hr, double* Hs, double r, double s) { ((FE2DElementTraits*)(m_pT))->shape_deriv(Hr, Hs, r, s); }
};
//-----------------------------------------------------------------------------
class FECORE_API FELineElement : public FEElement
{
public:
FELineElement();
FELineElement(const FELineElement& el);
FELineElement& operator = (const FELineElement& el);
void SetTraits(FEElementTraits* pt);
double* GaussWeights() { return &((FELineElementTraits*)(m_pT))->gw[0]; } // weights of integration points
double* Gr(int n) const { return ((FELineElementTraits*)(m_pT))->Gr[n]; } // shape function derivative to r
void shape(double* H, double r) { return ((FELineElementTraits*)(m_pT))->shape(H, r); }
void shape_deriv(double* Hr, double r) { return ((FELineElementTraits*)(m_pT))->shape_deriv(Hr, r); }
void shape_deriv2(double* Hrr, double r) { return ((FELineElementTraits*)(m_pT))->shape_deriv2(Hrr, r); }
vec3d eval(vec3d* d, int n)
{
int ne = Nodes();
double* N = H(n);
vec3d a(0, 0, 0);
for (int i = 0; i < ne; ++i) a += d[i] * N[i];
return a;
}
vec3d eval_deriv(vec3d* d, int j)
{
double* Hr = Gr(j);
int n = Nodes();
vec3d v(0, 0, 0);
for (int i = 0; i < n; ++i) v += d[i] * Hr[i];
return v;
}
};
//-----------------------------------------------------------------------------
class FECORE_API FEBeamElement : public FEElement
{
public:
FEBeamElement();
FEBeamElement(const FEBeamElement& el);
FEBeamElement& operator = (const FEBeamElement& el);
double* GaussWeights() { return &((FEBeamElementTraits*)(m_pT))->gw[0]; }
double* Hr(int n) { return ((FEBeamElementTraits*)(m_pT))->Gr[n]; }
public:
double m_L0; // initial length of beam
mat3d m_E; // columns are local beam orientation
};
| Unknown |
3D | febiosoftware/FEBio | FECore/svd.cpp | .cpp | 6,304 | 284 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "matrix.h"
#include <math.h>
using namespace std;
#define SQR(a) ((a)*(a))
#define FMAX(a, b) ((a)>(b)?(a):(b))
#define IMIN(a, b) ((a)<(b)?(a):(b))
#define SIGN(a, b) ((b) > 0.0 ? fabs(a) : -fabs(a))
void svbksb(matrix& u, vector<double>& w, matrix& v, vector<double>& b, vector<double>& x)
{
int jj, j, i;
double s;
int m = u.rows();
int n = u.columns();
vector<double> tmp(n);
for (j=0; j<n; ++j)
{
s = 0.0;
if (w[j])
{
for (i=0; i<m; ++i) s += u[i][j]*b[i];
s /= w[j];
}
tmp[j] = s;
}
for (j=0; j<n; ++j)
{
s = 0.0;
for (jj=0; jj<n; ++jj) s += v[j][jj]*tmp[jj];
x[j] = s;
}
}
double pythag(double a, double b)
{
double absa, absb;
absa=fabs(a);
absb=fabs(b);
if (absa > absb) return absa*sqrt(1.0 + SQR(absb/absa));
else return (absb == 0.0 ? 0.0 : absb*sqrt(1.0 + SQR(absa/absb)));
}
void svdcmp(matrix& a, vector<double>& w, matrix& v)
{
int flag, i, its, j, jj, k, l, nm;
double anorm, c, f, g, h, s, scale, x, y, z;
int m = a.rows();
int n = a.columns();
vector<double> rv1(n);
g = scale = anorm = 0.0;
for (i=0; i<n; ++i)
{
l=i+1; // diff between c++/c NR
rv1[i] = scale*g;
g = s = scale = 0.0;
if (i < m)
{
for (k=i; k<m; ++k) scale += fabs(a[k][i]);
if (scale != 0.0)
{
for (k=i; k<m; ++k)
{
a[k][i] /= scale;
s += a[k][i]*a[k][i];
}
f = a[i][i];
g = -SIGN(sqrt(s), f);
h = f*g-s;
a[i][i] = f-g;
for (j=l; j<n; ++j) // diff between c++/c NR
{
for (s=0.0, k=i; k<m; k++) s += a[k][i]*a[k][j];
f = s/h;
for (k=i; k<m; ++k) a[k][j] += f*a[k][i];
}
for (k=i; k<m; k++) a[k][i] *= scale;
}
}
w[i] = scale*g;
g=s=scale = 0.0;
if ((i+1<=m) && (i!=n-1)) // diff between c++/c NR
{
for (k=l; k<n; ++k) scale += fabs(a[i][k]); // diff between c++/c NR
if (scale != 0.0)
{
for (k=l; k<n; ++k) // diff between c++/c NR
{
a[i][k] /= scale;
s += a[i][k]*a[i][k];
}
f = a[i][l]; // diff between c++/c NR
g = -SIGN(sqrt(s), f);
h=f*g-s;
a[i][l] = f - g;
for (k=l; k<n; k++) rv1[k] = a[i][k]/h; // diff between c++/c NR
for (j=l; j<m; ++j) // diff between c++/c NR
{
for (s=0.0, k=l; k<n; k++) s += a[j][k]*a[i][k]; // diff between c++/c NR
for (k=l; k<n; k++) a[j][k] += s*rv1[k]; // diff between c++/c NR
}
for (k=l; k<n; k++) a[i][k] *= scale; // diff between c++/c NR
}
}
anorm = FMAX(anorm, (fabs(w[i])+fabs(rv1[i])));
}
for (i=n-1; i>=0; --i)
{
if (i<n-1)
{
if (g != 0.0)
{
for (j=l; j<n; ++j)
v[j][i] = (a[i][j]/a[i][l])/g;
for (j=l; j<n; ++j)
{
for (s=0.0, k=l; k<n; ++k) s += a[i][k]*v[k][j];
for (k=l; k<n; k++) v[k][j] += s*v[k][i];
}
}
for (j=l; j<n; j++) v[i][j] = v[j][i] = 0.0;
}
v[i][i] = 1.0;
g = rv1[i];
l = i;
}
for (i=IMIN(m,n)-1; i>=0; i--)
{
l=i+1;
g=w[i];
for (j=l; j<n; ++j) a[i][j] = 0.0;
if (g != 0.0)
{
g = 1.0/g;
for (j=l; j<n; ++j)
{
for (s=0.0, k=l; k<m; k++) s += a[k][i]*a[k][j];
f = (s/a[i][i])*g;
for (k=i; k<m; k++) a[k][j] += f*a[k][i];
}
for (j=i; j<m; j++) a[j][i] *= g;
}
else for (j=i; j<m; j++) a[j][i] = 0.0;
++a[i][i];
}
for (k=n-1; k>=0; k--)
{
for (its=0; its<30; ++its)
{
flag = 1;
for (l=k; l>=0; --l)
{
nm = l-1;
if ((fabs(rv1[l])+anorm) == anorm)
{
flag = 0;
break;
}
if ((fabs(w[nm])+anorm) == anorm) break;
}
if (flag == 1)
{
c = 0.0;
s = 1.0;
for (i=l; i<=k; ++i) // diff between c++/c NR
{
f = s*rv1[i];
rv1[i] = c*rv1[i];
if ((fabs(f)+anorm) == anorm) break;
g = w[i];
h = pythag(f, g);
w[i] = h;
h = 1.0/h;
c = g*h;
s= -f*h;
for (j=0; j<m; j++)
{
y=a[j][nm];
z=a[j][i];
a[j][nm] = y*c+z*s;
a[j][i] = z*c - y*s;
}
}
}
z = w[k];
if (l == k)
{
if (z < 0.0)
{
w[k] = -z;
for (j=0; j<n; j++) v[j][k] = -v[j][k];
}
break;
}
// TODO: do something drastic when its hits 29
x=w[l];
nm=k-1;
y=w[nm];
g=rv1[nm];
h=rv1[k];
f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y);
g = pythag(f, 1.0);
f=((x-z)*(x+z)+h*((y/(f+SIGN(g, f)))-h)) / x;
c = s = 1.0;
for (j=l; j<=nm; j++)
{
i = j+1;
g = rv1[i];
y = w[i];
h = s*g;
g = c*g;
z = pythag(f, h);
rv1[j] = z;
c = f/z;
s = h/z;
f = x*c + g*s;
g = g*c - x*s;
h = y*s;
y *= c;
for (jj=0; jj<n; ++jj)
{
x=v[jj][j];
z=v[jj][i];
v[jj][j] = x*c + z*s;
v[jj][i] = z*c - x*s;
}
z = pythag(f, h);
w[j] = z;
if (z)
{
z = 1.0/z;
c = f*z;
s = h*z;
}
f = c*g + s*y;
x = c*y - s*g;
for (jj=0; jj<m; ++jj)
{
y = a[jj][j];
z = a[jj][i];
a[jj][j] = y*c + z*s;
a[jj][i] = z*c - y*s;
}
}
rv1[l] = 0.0;
rv1[k] = f;
w[k] = x;
}
}
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEMergedConstraint.cpp | .cpp | 3,217 | 110 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEMergedConstraint.h"
#include <FECore/FEModel.h>
#include <FECore/FELinearConstraintManager.h>
#include <FECore/FELinearConstraint.h>
FEMergedConstraint::FEMergedConstraint(FEModel& fem) : m_fem(fem)
{
}
FEMergedConstraint::~FEMergedConstraint()
{
}
bool FEMergedConstraint::Merge(FEFacetSet* surf1, FEFacetSet* surf2, const vector<int>& dofList)
{
// extract the nodes from the surfaces
FENodeList set1 = surf1->GetNodeList();
FENodeList set2 = surf2->GetNodeList();
// find for each node on surface1 a corresponding node on surface 2 within tolerance
// First, make sure that set2 is larger than set1
if (set1.Size() > set2.Size()) return false;
int N1 = set1.Size();
int N2 = set2.Size();
// make sure there is something to do
if (N1 == 0) return true;
if (dofList.size() == 0) return true;
// alright, let's get going
vector<int> tag(N1, -1);
for (int i=0; i<N1; ++i)
{
// get the node position
vec3d ri = set1.Node(i)->m_rt;
// find the closest node
int n = 0;
double Dmin = (set2.Node(0)->m_rt - ri).norm2();
for (int j=1; j<N2; ++j)
{
vec3d rj = set2.Node(j)->m_rt;
double D2 = (ri - rj).norm2();
if (D2 < Dmin)
{
Dmin = D2;
n = j;
}
}
// since this interface type assumes that the nodes match identically,
// we check that the min distance is indeed very small
if (Dmin > 1e-9) {
return false;
}
// store this node
tag[i] = n;
}
// next, create the linear constraints
// get the linear constraint manager
int ndofs = (int) dofList.size();
FELinearConstraintManager& LCM = m_fem.GetLinearConstraintManager();
for (int i=0; i<N1; ++i)
{
for (int j=0; j<ndofs; ++j)
{
int dof = dofList[j];
FELinearConstraint* lc = fecore_alloc(FELinearConstraint, &m_fem);
lc->SetParentDof(dof, set1[i]);
lc->AddChildDof(dof, set2[tag[i]], 1.0);
LCM.AddLinearConstraint(lc);
}
}
// all done
return true;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEValuator.cpp | .cpp | 1,691 | 43 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEValuator.h"
#include "FEModelParam.h"
FEValuator::FEValuator(FEModel* fem) : FECoreBase(fem), m_param(nullptr) {}
FEValuator::~FEValuator() {}
void FEValuator::SetModelParam(FEModelParam* p) { m_param = p; }
FEModelParam* FEValuator::GetModelParam() { return m_param; }
void FEValuator::Serialize(DumpStream& ar)
{
FECoreBase::Serialize(ar);
if (!ar.IsShallow()) ar& m_param;
}
| C++ |
3D | febiosoftware/FEBio | FECore/MathObject.cpp | .cpp | 8,627 | 295 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "MathObject.h"
#include "MMath.h"
#include "MObjBuilder.h"
#include <float.h>
using namespace std;
//-----------------------------------------------------------------------------
MathObject::MathObject()
{
}
MathObject::MathObject(const MathObject& mo)
{
// copy variable list
for (int i = 0; i < mo.Variables(); ++i)
{
AddVariable(new MVariable(*mo.Variable(i)));
}
}
void MathObject::Clear()
{
for (int i = 0; i < m_Var.size(); ++i) delete m_Var[i];
m_Var.clear();
}
//-----------------------------------------------------------------------------
void MathObject::operator = (const MathObject& mo)
{
// copy variable list
for (int i = 0; i < mo.Variables(); ++i)
{
AddVariable(new MVariable(*mo.Variable(i)));
}
}
//-----------------------------------------------------------------------------
MathObject::~MathObject()
{
for (int i = 0; i < m_Var.size(); ++i) delete m_Var[i];
m_Var.clear();
}
//-----------------------------------------------------------------------------
MVariable* MathObject::AddVariable(const std::string& var, double initVal)
{
if (m_Var.empty() == false)
{
MVarList::iterator it = m_Var.begin();
for (it = m_Var.end(); it != m_Var.end(); ++it)
if ((*it)->Name() == var) return *it;
}
MVariable* pv = new MVariable(var, initVal);
pv->setIndex((int)m_Var.size());
m_Var.push_back(pv);
return pv;
}
void MathObject::AddVariable(MVariable* pv)
{
if (m_Var.empty() == false)
{
MVarList::iterator it = m_Var.begin();
for (it = m_Var.end(); it != m_Var.end(); ++it)
if (*it == pv) return;
}
pv->setIndex((int)m_Var.size());
m_Var.push_back(pv);
}
void MathObject::AddVariables(const vector<std::string>& varList)
{
for (const std::string& s : varList)
{
AddVariable(s);
}
}
//-----------------------------------------------------------------------------
MVariable* MathObject::FindVariable(const string& s)
{
for (MVarList::iterator it = m_Var.begin(); it != m_Var.end(); ++it)
if ((*it)->Name() == s) return *it;
return 0;
}
//-----------------------------------------------------------------------------
int MSimpleExpression::Items()
{
if (m_item.Type() == MSEQUENCE)
{
MSequence* pe = dynamic_cast<MSequence*>(m_item.ItemPtr());
return pe->size();
}
else return 1;
}
bool MSimpleExpression::IsValid() const
{
return (m_item.ItemPtr() != nullptr);
}
//-----------------------------------------------------------------------------
double MSimpleExpression::value(const std::string& s)
{
Create(s);
return value();
}
//-----------------------------------------------------------------------------
double MSimpleExpression::value(const MItem* pi) const
{
switch (pi->Type())
{
case MCONST: return (mnumber(pi)->value());
case MFRAC : return (mnumber(pi)->value());
case MNAMED: return (mnumber(pi)->value());
case MVAR : return (mnumber(pi)->value());
case MNEG: return -value(munary(pi)->Item());
case MADD: return value(mbinary(pi)->LeftItem()) + value(mbinary(pi)->RightItem());
case MSUB: return value(mbinary(pi)->LeftItem()) - value(mbinary(pi)->RightItem());
case MMUL: return value(mbinary(pi)->LeftItem()) * value(mbinary(pi)->RightItem());
case MDIV: return value(mbinary(pi)->LeftItem()) / value(mbinary(pi)->RightItem());
case MPOW: return pow(value(mbinary(pi)->LeftItem()), value(mbinary(pi)->RightItem()));
case MF1D:
{
double a = value(munary(pi)->Item());
return (mfnc1d(pi)->funcptr())(a);
}
break;
case MF2D:
{
double a = value(mbinary(pi)->LeftItem());
double b = value(mbinary(pi)->RightItem());
return (mfnc2d(pi)->funcptr())(a, b);
}
break;
case MSFNC:
{
return value(msfncnd(pi)->Value());
};
break;
case MFND:
{
const MFuncND* f = mfncnd(pi);
int n = f->Params();
vector<double> d(n, 0.0);
for (int i = 0; i < n; ++i) d[i] = value(f->Param(i));
return (f->funcptr())(d.data(), n);
}
break;
default:
assert(false);
return 0;
}
}
//-----------------------------------------------------------------------------
double MSimpleExpression::value(const MItem* pi, const std::vector<double>& var) const
{
switch (pi->Type())
{
case MCONST: return (mnumber(pi)->value());
case MFRAC : return (mnumber(pi)->value());
case MNAMED: return (mnumber(pi)->value());
case MVAR : return (var[mvar(pi)->index()]);
case MNEG: return -value(munary(pi)->Item(), var);
case MADD: return value(mbinary(pi)->LeftItem(), var) + value(mbinary(pi)->RightItem(), var);
case MSUB: return value(mbinary(pi)->LeftItem(), var) - value(mbinary(pi)->RightItem(), var);
case MMUL: return value(mbinary(pi)->LeftItem(), var) * value(mbinary(pi)->RightItem(), var);
case MDIV: return value(mbinary(pi)->LeftItem(), var) / value(mbinary(pi)->RightItem(), var);
case MPOW: return pow(value(mbinary(pi)->LeftItem(), var), value(mbinary(pi)->RightItem(), var));
case MF1D:
{
double a = value(munary(pi)->Item(), var);
return (mfnc1d(pi)->funcptr())(a);
}
break;
case MF2D:
{
double a = value(mbinary(pi)->LeftItem(), var);
double b = value(mbinary(pi)->RightItem(), var);
return (mfnc2d(pi)->funcptr())(a, b);
}
break;
case MSFNC:
{
return value(msfncnd(pi)->Value(), var);
};
break;
case MFND:
{
const MFuncND* f = mfncnd(pi);
int n = f->Params();
vector<double> d(n, 0.0);
for (int i = 0; i < n; ++i) d[i] = value(f->Param(i), var);
return (f->funcptr())(d.data(), n);
}
break;
default:
assert(false);
return 0;
}
}
//-----------------------------------------------------------------------------
MSimpleExpression::MSimpleExpression(const MSimpleExpression& mo) : MathObject(mo), m_item(mo.m_item)
{
// The copy c'tor of MathObject copied the variables, but any MVarRefs still point to the mo object, not this object's var list.
// Calling the following function fixes this
fixVariableRefs(m_item.ItemPtr());
}
//-----------------------------------------------------------------------------
void MSimpleExpression::operator=(const MSimpleExpression& mo)
{
// copy base object
MathObject::operator=(mo);
// copy the item
m_item = mo.m_item;
// The = operator of MathObject copied the variables, but any MVarRefs still point to the mo object, not this object's var list.
// Calling the following function fixes this
fixVariableRefs(m_item.ItemPtr());
}
//-----------------------------------------------------------------------------
void MSimpleExpression::fixVariableRefs(MItem* pi)
{
if (pi->Type() == MVAR)
{
MVarRef* var = static_cast<MVarRef*>(pi);
int index = var->GetVariable()->index();
var->SetVariable(Variable(index));
}
else if (is_unary(pi))
{
MUnary* uno = static_cast<MUnary*>(pi);
fixVariableRefs(uno->Item());
}
else if (is_binary(pi))
{
MBinary* bin = static_cast<MBinary*>(pi);
fixVariableRefs(bin->LeftItem());
fixVariableRefs(bin->RightItem());
}
else if (is_nary(pi))
{
MNary* any = static_cast<MNary*>(pi);
for (int i = 0; i < any->Params(); ++i) fixVariableRefs(any->Param(i));
}
}
//-----------------------------------------------------------------------------
// Create a simple expression object from a string
bool MSimpleExpression::Create(const std::string& expr, bool autoVars)
{
MObjBuilder mob;
mob.setAutoVars(autoVars);
if (mob.Create(this, expr, false) == false) return false;
return true;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEModelComponent.cpp | .cpp | 3,833 | 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 "FEModelComponent.h"
#include "FEModel.h"
#include "FEAnalysis.h"
#include "DumpStream.h"
#include <string.h>
//-----------------------------------------------------------------------------
FEModelComponent::FEModelComponent(FEModel* fem) : FECoreBase(fem)
{
}
//-----------------------------------------------------------------------------
FEModelComponent::~FEModelComponent()
{
}
//-----------------------------------------------------------------------------
void FEModelComponent::Update()
{
}
//-----------------------------------------------------------------------------
double FEModelComponent::CurrentTime() const
{
return GetFEModel()->GetTime().currentTime;
}
//-----------------------------------------------------------------------------
double FEModelComponent::CurrentTimeIncrement() const
{
return GetFEModel()->GetTime().timeIncrement;
}
//-----------------------------------------------------------------------------
double FEModelComponent::GetGlobalConstant(const char* sz) const
{
return GetFEModel()->GetGlobalConstant(sz);
}
//-----------------------------------------------------------------------------
int FEModelComponent::GetDOFIndex(const char* szvar, int n) const
{
return GetFEModel()->GetDOFIndex(szvar, n);
}
//-----------------------------------------------------------------------------
int FEModelComponent::GetDOFIndex(const char* szdof) const
{
return GetFEModel()->GetDOFIndex(szdof);
}
//-----------------------------------------------------------------------------
//! Get the model's mesh
FEMesh& FEModelComponent::GetMesh()
{
return GetFEModel()->GetMesh();
}
//-----------------------------------------------------------------------------
const FETimeInfo& FEModelComponent::GetTimeInfo() const
{
return GetFEModel()->GetTime();
}
FESolver* FEModelComponent::GetSolver()
{
FEAnalysis* step = GetFEModel()->GetCurrentStep();
if (step == nullptr) return nullptr;
return step->GetFESolver();
}
//-----------------------------------------------------------------------------
void FEModelComponent::AttachLoadController(const char* szparam, int lc)
{
FEParam* p = GetParameter(szparam); assert(p);
if (p)
{
FEModel* fem = GetFEModel();
fem->AttachLoadController(p, lc);
}
}
//-----------------------------------------------------------------------------
void FEModelComponent::AttachLoadController(void* pd, int lc)
{
FEParam* p = FindParameterFromData(pd); assert(p);
if (p)
{
FEModel* fem = GetFEModel();
fem->AttachLoadController(p, lc);
}
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEPrescribedDOF.h | .h | 2,050 | 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 "FEPrescribedBC.h"
#include "FEModelParam.h"
//-----------------------------------------------------------------------------
//! Boundary condition for prescribing a degree of freedom
class FECORE_API FEPrescribedDOF : public FEPrescribedNodeSet
{
public:
FEPrescribedDOF(FEModel* pfem);
FEPrescribedDOF(FEModel* pfem, int dof, FENodeSet* nset);
void SetDOF(int ndof);
bool SetDOF(const char* szdof);
FEPrescribedDOF& SetScale(double s, int lc = -1);
bool Init() override;
void CopyFrom(FEBoundaryCondition* pbc) override;
public:
void GetNodalValues(int n, std::vector<double>& val) override;
protected:
int m_dof; //!< degree of freedom to prescribe
FEParamDouble m_scale; //!< overall scale factor
DECLARE_FECORE_CLASS();
};
| Unknown |
3D | febiosoftware/FEBio | FECore/tens3dls.hpp | .hpp | 5,786 | 202 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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
// NOTE: This file is automatically included from tens3d.h
// Users should not include this file manually!
// calculate the transpose ((G_KJi)T = G_iJK)
inline tens3drs tens3dls::transpose()
{
tens3drs GRC;
GRC.d[0] = d[ 0];
GRC.d[1] = d[ 3];
GRC.d[2] = d[ 6];
GRC.d[3] = d[ 9];
GRC.d[4] = d[12];
GRC.d[5] = d[15];
GRC.d[6] = d[ 1];
GRC.d[7] = d[ 4];
GRC.d[8] = d[ 7];
GRC.d[9] = d[10];
GRC.d[10] = d[13];
GRC.d[11] = d[16];
GRC.d[12] = d[ 2];
GRC.d[13] = d[ 5];
GRC.d[14] = d[ 8];
GRC.d[15] = d[11];
GRC.d[16] = d[14];
GRC.d[17] = d[17];
return GRC;
}
// multiply by a double on right (G_ifk * d)
inline tens3dls tens3dls::operator * (const double& f) const
{
tens3dls G;
G.d[0] = d[0]*f;
G.d[1] = d[1]*f;
G.d[2] = d[2]*f;
G.d[3] = d[3]*f;
G.d[4] = d[4]*f;
G.d[5] = d[5]*f;
G.d[6] = d[6]*f;
G.d[7] = d[7]*f;
G.d[8] = d[8]*f;
G.d[ 9] = d[9]*f;
G.d[10] = d[10]*f;
G.d[11] = d[11]*f;
G.d[12] = d[12]*f;
G.d[13] = d[13]*f;
G.d[14] = d[14]*f;
G.d[15] = d[15]*f;
G.d[16] = d[16]*f;
G.d[17] = d[17]*f;
return G;
}
// multiply by a 2o tensor on the right (G_KJi * F_iI)
inline tens3dls tens3dls::operator * (const mat3d& F) const
{
tens3dls G;
G.d[0] = d[0]*F(0,0) + d[1]*F(1,0) + d[2]*F(2,0);
G.d[1] = d[0]*F(0,1) + d[1]*F(1,1) + d[2]*F(2,1);
G.d[2] = d[0]*F(0,2) + d[1]*F(1,2) + d[2]*F(2,2);
G.d[3] = d[3]*F(0,0) + d[4]*F(1,0) + d[5]*F(2,0);
G.d[4] = d[3]*F(0,1) + d[4]*F(1,1) + d[5]*F(2,1);
G.d[5] = d[3]*F(0,2) + d[4]*F(1,2) + d[5]*F(2,2);
G.d[6] = d[6]*F(0,0) + d[7]*F(1,0) + d[8]*F(2,0);
G.d[7] = d[6]*F(0,1) + d[7]*F(1,1) + d[8]*F(2,1);
G.d[8] = d[6]*F(0,2) + d[7]*F(1,2) + d[8]*F(2,2);
G.d[ 9] = d[9]*F(0,0) + d[10]*F(1,0) + d[11]*F(2,0);
G.d[10] = d[9]*F(0,1) + d[10]*F(1,1) + d[11]*F(2,1);
G.d[11] = d[9]*F(0,2) + d[10]*F(1,2) + d[11]*F(2,2);
G.d[12] = d[12]*F(0,0) + d[13]*F(1,0) + d[14]*F(2,0);
G.d[13] = d[12]*F(0,1) + d[13]*F(1,1) + d[14]*F(2,1);
G.d[14] = d[12]*F(0,2) + d[13]*F(1,2) + d[14]*F(2,2);
G.d[15] = d[15]*F(0,0) + d[16]*F(1,0) + d[17]*F(2,0);
G.d[16] = d[15]*F(0,1) + d[16]*F(1,1) + d[17]*F(2,1);
G.d[17] = d[15]*F(0,2) + d[16]*F(1,2) + d[17]*F(2,2);
return G;
}
// calculate the trace Tijk -> Tijj
inline vec3d tens3dls::trace()
{
double a = d[0] + d[4] + d[8];
double b = d[3] + d[10] + d[14];
double c = d[6] + d[13] + d[17];
vec3d v = vec3d(a,b,c);
return v;
}
// generalize tensor from tens3dls to tens3d
// [G] = [G111 G112 G113 G121 G122 G123 G131 G132 G133 G221 G222 G223 G231 G232 G233 G331 G332 G333]
// = G0 G1 G2 G3 G4 G5 G6 G7 G8 G9 G10 G11 G12 G13 G14 G15 G16 G17
// [T] = [T111 T112 T113 T121 T122 T123 T131 T132 T133 T211 T212 T213 T221 T222 T223 T231 T232 T233 T311 T312 T313 T321 T322 T323 T331 T332 T333
// = T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15 T16 T17 T18 T19 T20 T21 T22 T23 T24 T25 T26
inline tens3d tens3dls::generalize()
{
tens3d G;
G.d[0] = d[0];
G.d[1] = d[1];
G.d[2] = d[2];
G.d[3] = d[3];
G.d[4] = d[4];
G.d[5] = d[5];
G.d[6] = d[6];
G.d[7] = d[7];
G.d[8] = d[8];
G.d[9] = d[3];
G.d[10] = d[4];
G.d[11] = d[5];
G.d[12] = d[9];
G.d[13] = d[10];
G.d[14] = d[11];
G.d[15] = d[12];
G.d[16] = d[13];
G.d[17] = d[14];
G.d[18] = d[6];
G.d[19] = d[7];
G.d[20] = d[8];
G.d[21] = d[12];
G.d[22] = d[13];
G.d[23] = d[14];
G.d[24] = d[15];
G.d[25] = d[16];
G.d[26] = d[17];
return G;
}
// calculates the dyadic product T_ijk = 1/2*(L_ij*r_k + L_ji*r_k)
// [G] = [G111 G112 G113 G121 G122 G123 G131 G132 G133 G221 G222 G223 G231 G232 G233 G331 G332 G333]
// = G0 G1 G2 G3 G4 G5 G6 G7 G8 G9 G10 G11 G12 G13 G14 G15 G16 G17
inline tens3dls dyad3ls(const mat3ds& L, const vec3d& r)
{
tens3dls a;
a.d[ 0] = L(0, 0)*r.x;
a.d[ 1] = L(0, 0)*r.y;
a.d[ 2] = L(0, 0)*r.z;
a.d[ 3] = L(0, 1)*r.x;
a.d[ 4] = L(0, 1)*r.y;
a.d[ 5] = L(0, 1)*r.z;
a.d[ 6] = L(0, 2)*r.x;
a.d[ 7] = L(0, 2)*r.y;
a.d[ 8] = L(0, 2)*r.z;
a.d[ 9] = L(1, 1)*r.x;
a.d[10] = L(1, 1)*r.y;
a.d[11] = L(1, 1)*r.z;
a.d[12] = L(1, 2)*r.x;
a.d[13] = L(1, 2)*r.y;
a.d[14] = L(1, 2)*r.z;
a.d[15] = L(2, 2)*r.x;
a.d[16] = L(2, 2)*r.y;
a.d[17] = L(2, 2)*r.z;
return a;
}
| Unknown |
3D | febiosoftware/FEBio | FECore/FEDataArray.cpp | .cpp | 4,211 | 155 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FEDataArray.h"
#include "DumpStream.h"
#include "fecore_type.h"
#include "FENodeDataMap.h"
#include "FEDomainMap.h"
#include "FESurfaceMap.h"
//-----------------------------------------------------------------------------
FEDataArray::FEDataArray(FEDataMapType mapType, FEDataType dataType) : m_mapType(mapType), m_dataType(dataType), m_dataCount(0)
{
m_dataSize = fecore_data_size(dataType);
}
//-----------------------------------------------------------------------------
FEDataArray::~FEDataArray()
{
}
//-----------------------------------------------------------------------------
FEDataArray::FEDataArray(const FEDataArray& map)
{
m_dataType = map.m_dataType;
m_dataSize = map.m_dataSize;
m_dataCount = map.m_dataCount;
m_val = map.m_val;
}
//-----------------------------------------------------------------------------
FEDataArray& FEDataArray::operator = (const FEDataArray& map)
{
m_dataType = map.m_dataType;
m_dataSize = map.m_dataSize;
m_dataCount = map.m_dataCount;
m_val = map.m_val;
return *this;
}
//-----------------------------------------------------------------------------
bool FEDataArray::resize(int n, double val)
{
if (n < 0) return false;
m_val.resize(n*DataSize(), val);
m_dataCount = n;
return true;
}
//-----------------------------------------------------------------------------
bool FEDataArray::realloc(int n)
{
if (n < 0) return false;
m_val.resize(n*DataSize());
m_dataCount = n;
return true;
}
//-----------------------------------------------------------------------------
//! set the data sized
void FEDataArray::SetDataSize(int dataSize)
{
m_dataSize = dataSize;
if (m_val.empty() == false)
{
m_val.resize(m_dataSize*m_dataCount);
}
}
//-----------------------------------------------------------------------------
FEDataType intToDataType(int i)
{
switch (i)
{
case FE_DOUBLE: return FE_DOUBLE; break;
case FE_VEC2D : return FE_VEC2D; break;
case FE_VEC3D : return FE_VEC3D; break;
case FE_MAT3D : return FE_MAT3D; break;
case FE_MAT3DS: return FE_MAT3DS; break;
default:
assert(false);
break;
}
return FE_INVALID_TYPE;
}
void FEDataArray::Serialize(DumpStream& ar)
{
if (ar.IsSaving())
{
ar << m_dataSize;
ar << m_dataCount;
ar << (int)m_dataType;
ar << m_val;
}
else
{
int ntype = 0;
ar >> m_dataSize;
ar >> m_dataCount;
ar >> ntype;
ar >> m_val;
m_dataType = intToDataType(ntype);
assert(m_val.size() == m_dataSize*m_dataCount);
}
}
void FEDataArray::SaveClass(DumpStream& ar, FEDataArray* p)
{
int ntype = (int) p->DataMapType();
ar << ntype;
}
FEDataArray* FEDataArray::LoadClass(DumpStream& ar, FEDataArray* p)
{
int ntype;
ar >> ntype;
p = nullptr;
switch (ntype)
{
case FE_NODE_DATA_MAP: p = new FENodeDataMap; break;
case FE_DOMAIN_MAP : p = new FEDomainMap; break;
case FE_SURFACE_MAP : p = new FESurfaceMap; break;
default:
assert(false);
}
return p;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FENodeNodeList.cpp | .cpp | 7,278 | 350 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION 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 "FENodeNodeList.h"
#include "FENodeElemList.h"
#include "FEMesh.h"
#include "FEDomain.h"
#include "FESurface.h"
#include <stdlib.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
FENodeNodeList::FENodeNodeList()
{
}
FENodeNodeList::~FENodeNodeList()
{
}
FENodeNodeList* FENodeNodeList::m_pthis = 0;
//////////////////////////////////////////////////////////////////////
// FENodeNodeList
//////////////////////////////////////////////////////////////////////
void FENodeNodeList::Create(FEMesh& mesh)
{
int i, j, k, n, m;
// get the nr of nodes
int NN = mesh.Nodes();
// create the node-element list
FENodeElemList EL;
EL.Create(mesh);
// create the nodal tag array
vector<int> tag; tag.assign(NN, 0);
// calculate nodal valences
m_nval.assign(NN, 0);
m_pn.resize(NN);
int nsize = 0;
int* en;
vector<int> buf(NN);
int nb;
for (i=0; i<NN; ++i)
{
nb = 0;
n = EL.Valence(i);
FEElement** pe = EL.ElementList(i);
for (j=0; j<n; ++j)
{
FEElement* pel = pe[j];
m = pel->Nodes();
en = &pel->m_node[0];
for (k=0; k<m; ++k)
if ((en[k] != i) && (tag[ en[k] ] == 0))
{
++m_nval[i];
++tag[en[k]];
buf[nb++] = en[k];
++nsize;
}
}
// clear the tag array
for (j=0; j<nb; ++j) tag[ buf[j] ] = 0;
nb = 0;
}
// create the node reference array
m_nref.resize(nsize);
// set nref pointers
m_pn[0] = 0;
for (i=1; i<NN; ++i)
{
m_pn[i] = m_pn[i-1] + m_nval[i-1];
}
// reset valence pointers
for (i=0; i<NN; ++i) m_nval[i] = 0;
// fill the nref pointers
for (i=0; i<NN; ++i)
{
nb = 0;
n = EL.Valence(i);
FEElement** pe = EL.ElementList(i);
for (j=0; j<n; ++j)
{
FEElement* pel = pe[j];
m = pel->Nodes();
en = &pel->m_node[0];
for (k=0; k<m; ++k)
if ((en[k] != i) && (tag[ en[k] ] == 0))
{
m_nref[m_pn[i] + m_nval[i]] = en[k];
++tag[en[k]];
++m_nval[i];
buf[nb++] = en[k];
++nsize;
}
}
// clear the tag array
for (j=0; j<nb; ++j) tag[ buf[j] ] = 0;
nb = 0;
}
}
//-----------------------------------------------------------------------------
void FENodeNodeList::Create(FEDomain& dom)
{
int i, j, k, n, m;
// get the mesh
FEMesh& mesh = *dom.GetMesh();
// get the nr of nodes
int NN = mesh.Nodes();
// create the node-element list
FENodeElemList EL;
EL.Create(dom);
// create the nodal tag array
vector<int> tag; tag.assign(NN, 0);
// calculate nodal valences
m_nval.assign(NN, 0);
m_pn.resize(NN);
int nsize = 0;
int* en;
vector<int> buf(NN);
int nb;
for (i=0; i<NN; ++i)
{
nb = 0;
n = EL.Valence(i);
FEElement** pe = EL.ElementList(i);
for (j=0; j<n; ++j)
{
FEElement* pel = pe[j];
m = pel->Nodes();
en = &pel->m_node[0];
for (k=0; k<m; ++k)
if ((en[k] != i) && (tag[ en[k] ] == 0))
{
++m_nval[i];
++tag[en[k]];
buf[nb++] = en[k];
++nsize;
}
}
// clear the tag array
for (j=0; j<nb; ++j) tag[ buf[j] ] = 0;
nb = 0;
}
// create the node reference array
m_nref.resize(nsize);
// set nref pointers
m_pn[0] = 0;
for (i=1; i<NN; ++i)
{
m_pn[i] = m_pn[i-1] + m_nval[i-1];
}
// reset valence pointers
for (i=0; i<NN; ++i) m_nval[i] = 0;
// fill the nref pointers
for (i=0; i<NN; ++i)
{
nb = 0;
n = EL.Valence(i);
FEElement** pe = EL.ElementList(i);
for (j=0; j<n; ++j)
{
FEElement* pel = pe[j];
m = pel->Nodes();
en = &pel->m_node[0];
for (k=0; k<m; ++k)
if ((en[k] != i) && (tag[ en[k] ] == 0))
{
m_nref[m_pn[i] + m_nval[i]] = en[k];
++tag[en[k]];
++m_nval[i];
buf[nb++] = en[k];
++nsize;
}
}
// clear the tag array
for (j=0; j<nb; ++j) tag[ buf[j] ] = 0;
nb = 0;
}
}
//-----------------------------------------------------------------------------
void FENodeNodeList::Create(FESurface& surf)
{
// get the nr of nodes
int NN = surf.Nodes();
// create the node-element list
FENodeElemList EL;
EL.Create(surf);
// create the nodal tag array
vector<int> tag; tag.assign(NN, 0);
// calculate nodal valences
m_nval.assign(NN, 0);
m_pn.resize(NN);
int nsize = 0;
int* en;
vector<int> buf(NN);
int nb;
for (int i = 0; i < NN; ++i)
{
nb = 0;
int n = EL.Valence(i);
FEElement** pe = EL.ElementList(i);
for (int j = 0; j < n; ++j)
{
FEElement* pel = pe[j];
int m = pel->Nodes();
en = &pel->m_lnode[0];
for (int k = 0; k < m; ++k)
if ((en[k] != i) && (tag[en[k]] == 0))
{
++m_nval[i];
++tag[en[k]];
buf[nb++] = en[k];
++nsize;
}
}
// clear the tag array
for (int j = 0; j < nb; ++j) tag[buf[j]] = 0;
nb = 0;
}
// create the node reference array
m_nref.resize(nsize);
// set nref pointers
m_pn[0] = 0;
for (int i = 1; i < NN; ++i)
{
m_pn[i] = m_pn[i - 1] + m_nval[i - 1];
}
// reset valence pointers
for (int i = 0; i < NN; ++i) m_nval[i] = 0;
// fill the nref pointers
for (int i = 0; i < NN; ++i)
{
nb = 0;
int n = EL.Valence(i);
FEElement** pe = EL.ElementList(i);
for (int j = 0; j < n; ++j)
{
FEElement* pel = pe[j];
int m = pel->Nodes();
en = &pel->m_lnode[0];
for (int k = 0; k < m; ++k)
if ((en[k] != i) && (tag[en[k]] == 0))
{
m_nref[m_pn[i] + m_nval[i]] = en[k];
++tag[en[k]];
++m_nval[i];
buf[nb++] = en[k];
++nsize;
}
}
// clear the tag array
for (int j = 0; j < nb; ++j) tag[buf[j]] = 0;
nb = 0;
}
}
///////////////////////////////////////////////////////////////////////////////
int FENodeNodeList::compare(const void* e1, const void* e2)
{
int n1 = *((int*) e1);
int n2 = *((int*) e2);
FENodeNodeList& L = *m_pthis;
return (L.Valence(n1) - L.Valence(n2));
}
void FENodeNodeList::Sort()
{
int n, *pn;
m_pthis = this;
for (int i=0; i<Size(); ++i)
{
n = Valence(i);
pn = NodeList(i);
qsort(pn, n, sizeof(int), compare);
}
}
| C++ |
3D | febiosoftware/FEBio | FECore/FEItemList.cpp | .cpp | 2,630 | 105 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "FEItemList.h"
#include "DumpStream.h"
#include "FEModel.h"
#include "FENodeSet.h"
#include "FEFacetSet.h"
#include "FEElementSet.h"
#include "FESegmentSet.h"
FEItemList::FEItemList(FEModel* fem, FEItemType type) : m_type(type)
{
m_mesh = nullptr;
if (fem)
{
m_mesh = &fem->GetMesh();
}
}
FEItemList::FEItemList(FEMesh* mesh, FEItemType type) : m_type(type)
{
m_mesh = mesh;
}
FEItemList::~FEItemList() {}
void FEItemList::Serialize(DumpStream& ar)
{
ar & m_name;
}
// get the mesh
FEMesh* FEItemList::GetMesh() const
{
return m_mesh;
}
void FEItemList::SetMesh(FEMesh* mesh)
{
m_mesh = mesh;
}
const std::string& FEItemList::GetName() const
{
return m_name;
}
void FEItemList::SetName(const std::string& name)
{
m_name = name;
}
FEItemList* FEItemList::LoadClass(DumpStream& ar, FEItemList* p)
{
int ntype = -1;
ar >> ntype;
FEItemList* pi = nullptr;
FEModel* fem = &ar.GetFEModel();
switch (ntype)
{
case FE_NODE_SET : pi = new FENodeSet (fem); break;
case FE_FACET_SET : pi = new FEFacetSet (fem); break;
case FE_ELEMENT_SET: pi = new FEElementSet(fem); break;
case FE_SEGMENT_SET: pi = new FESegmentSet(fem); break;
default:
assert(false);
break;
}
return pi;
}
void FEItemList::SaveClass(DumpStream& ar, FEItemList* p)
{
int ntype = (int) p->Type();
ar << (int)ntype;
}
| C++ |
3D | febiosoftware/FEBio | FECore/FELogElementVolume.cpp | .cpp | 1,832 | 49 | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "FELogElementVolume.h"
#include "FEModel.h"
#include "FESurface.h"
FELogElementVolume::FELogElementVolume(FEModel* fem) : FELogElemData(fem)
{
}
double FELogElementVolume::value(FEElement& el)
{
FEMesh& mesh = GetFEModel()->GetMesh();
return mesh.CurrentElementVolume(el);
}
FELogFaceArea::FELogFaceArea(FEModel* fem) : FELogFaceData(fem) {}
double FELogFaceArea::value(FESurfaceElement& el)
{
FESurface* surface = dynamic_cast<FESurface*>(el.GetMeshPartition());
if (surface == nullptr) return 0.0;
return surface->CurrentFaceArea(el);
}
| C++ |
3D | YellProgram/Yell | documentation/reference.md | .md | 58,596 | 1,328 | Yell Reference
=====
Refers to the program version Yell 1.0
Latest manual update: February 6th, 2014
[TOC]
Installation
=========
Yell is distributed as a self-contained executable. Just copy it in a folder where the shell can find it. Instructions for building the binary from the source files will be added later.
How to run Yell
===========
Yell is a simple console application. In order to run it, open a terminal, navigate to the folder with the `model.txt` file and type
yell.exe
(on Windows) or
yell
(on Mac).
Input files
======
## Yell data format for arrays {#array-format}
All input arrays should be presented in [hdf5](http://www.hdfgroup.org/HDF5/whatishdf5.html) formatted files. The hdf5 format is commonly used in scientific applications to hold large data arrays. It is not editable by hand, but the libraries for preparing and manipulating the files are available for most of the software platforms including Matlab, Python, Java, C++ and R.
Each Yell-formatted hdf5 files should have the following structure: the root `/` of the file is expected to have attribute 'filetype' equal to 'Yell 1.0' and the dataset should be located at the path '/data' within the file. The array should have [row-major order](http://en.wikipedia.org/wiki/Row-major_order). Though, in principle, hdf5 files may contain several datasets, Yell only expects one dataset per file.
Here is code to save file in this format in Matlab:
```
function write4yell(filename,dataset)
dataset=permute(dataset,[3 2 1]); % Matlab uses column-major order, thus we need to permute dimensions
h5create(filename,'/data',size(dataset));
h5write(filename,'/data',double(dataset));
h5writeatt(filename,'/','filetype','Yell 1.0');
```
## Allowed array input files
The following files are used
* **experiment.h5** File containing the experimental diffuse scattering (in reciprocal space). Required for refinement.
* **weights.h5** File containing the least-squares weights (in reciprocal space). Optional. If not present unit weights are used.
* **reciprocal_space_multiplier.h5** File containing the array that will be multiplied to the calculated diffuse scattering (in reciprocal space). Useful for zeroing-out the model intensities in places where experiment was not measured. Optional.
* **pdf_multiplier.h5** File containing the array that will be multiplied to the calculated PDF. Useful to simulate resolution function effects. Optional.
All arrays must have the same shape along all dimensions
The following indicates at which stages the arrays are used:
1. Diffuse scattering is calculated.
2. If available, PDF multipliers are applied in PDF space
3. If available, reciprocal space multipliers are applied in reciprocal space
4. The resulting dataset is called 'model intensities'
During a refinement $weights*(I_{experiment}-I_{model})$ is used for minimization.
No input arrays files are required if the refinement option is switched off (see below).
## model.txt
This file contains the definition of the local structure model. For description see [reference](#reference).
Output files
======
The output files are also in hdf5 format. The following shows a Matlab function which reads in the data:
```
function res=read_from_yell(filename)
res = h5read(filename,'/data');
res = permute(res,[3 2 1]); #Transform from row-major order
```
## Reciprocal space datasets
* **model.h5** Diffuse scattering calculated from the model. If a refinement is performed, `model.h5` is calculated from the final parameters; refined intensities are scaled to the experimental intensities.
* **average.h5** Full scattering calculated from average pairs. Only takes pairs touched by correlations as defined in model.txt, i.e. broad Bragg peaks and truncation ripples are possible. Scaled to the experimental intensities.
* **full.h5** Full scattering from real structure pairs. Only takes those pairs which were touched by correlations. Scaled to the experimental intensities.
## ∆PDF space datasets
All of this datasets are calculated only if [diffuse scattering grid](#DiffuseScatteringGrid) allows FFT.
The datasets are scaled to be in $e^2/A^3$, if the [multiplicity](#Multiplicity) is set correctly.
* **delta-pdf.h5** Modeled ∆PDF.
* **exp-delta-pdf.h5** Experimental ∆PDF, i.e. the normalized Fourier transform of the diffuse intensities provided by experiment.h5.
* **delta-delta-pdf.h5** ∆$^2$PDF = ∆PDF$_{exp}$ - ∆PDF$_{model}$.
Keywords reference {#reference}
========
## File format
The file `model.txt` is a plane text file which describes the crystal model. The file contains the following sections:
* **preamble** defines parameters which influence the calculation
* **UnitCell** section defines the average crystal structure
* **Modes** section defines the possible motions of the atoms or molecules
* **Correlations** section defines the short-range ordering in the crystal
* in **epiloge** the user may request Yell to print various expressions
The input file contains square brackets `[` `]` for grouping various elements, assignments for providing aliases to the various parts of the structure and also variables and arithmetic expressions in order to express constraints.
The parser in Yell is quite flexible considering white spaces. Space, tabulation, newline character and comment are all considered whitespace. In most parts of the input files the whitespace characters are not required, but user can add them to improve the readability.
## Comments
Comments in Yell start with a sharp sign `#` and go until the end of the line.
#this is a comment
Cell 1 1 1 90 90 90 #this is also comment
## Assignments
The parts of the sturucture - atoms, groups of atoms, variants and modes can be given aliases for the later reference in the model. The aliases are expressed as assignments
Cu1_alias = Cu 1 0 0 0 0.01
## Formulas and variables
### Arithmetic expressions {#expressions}
The parser of Yell allows the arithmetic expressions in the place of almost any number in the input file. The expressions will be calculated during diffuse scattering calculation according to usual mathematical rules. Thus the following line
Cell 6-1 1+2*2 4 9*(15-5) 3*3*2*5 120
is equivalent to
Cell 5 5 4 90 90 120
Expressions can contain the operators `+` `-` `*` `/`, brackets `()`, and special mathematical functions `exp` `log` `sin` `cos` `sqrt` `abs` `mod` and `pow`. The whitespace characters are **not** allowed within formulas and will invoke an error.
### Variables
User can define variables to use in arithmetic expressions. The definition of variables is similar to many programming languages:
a=1;
b=12*3;
Variable definition should end with semicolon `;`. The whitespace characters are **not** allowed in the variable definition, e.g. the expression `b = 12 * 3;` is illegal.
Valid names for variables start with upper or lower case letters, names may also contain numbers and underscore. The names are case sensitive. Here are the examples:
A=1;
shift_along_111=1;
The variables can then be used in any arithmetic expression. In any case *float* algorithms are used.
a=12.1;
c=a/2;
alpha=90;
gamma=60;
Cell a a c alpha alpha gamma*2
Variables can be defined only in the "top level" of the input file, i.e. in preamble, epilogue and at the top levels of the definitions of `UnitCell` `Modes` and `Correlations`. Here is an example which explicitly describes where the variables can and cannot be defined
a=1;
Cell 10 10 10 90 90 90
b=1; #Here is ok
DiffuseScatteringGrid -10 -10 -10 0.5 0.5 0.5 20 20 20
UnitCell
[
c=1; #Here is ok
Var = Variant
[
#but not here
(p=0.5) #this is ok because it is a keyword expression and not an assignment to a variable 'p'
[
#not here
Ag 1 0 0 0 0.02
]
(p=0.5)
Void
]
d=1; #Here is ok
]
Modes
[
e=1; #Here is ok
]
Correlations
[
f=1; #Here is ok
[(0,0,0)
#not here
SubstitutionalCorrelation(Var,Var,0.5)
]
]
g=1; #Here is ok
Print "g=" g
### Refinable variables
User can also define a variable as a *refinable variable*. Such variables will be used in the least squares refinement procedure. Their value will be optimized in order to fit experimental data. Other variables, which were not defined as refinable, but depend on refinable variables in the course of refinement will always be updated, based on the actual value of refinable variables they depend upon.
Refinable variables should be refined in the preamble of the file, with `RefinableVariables` keyword. Example:
RefinableVariables
[
a=10; #This variable will be changed in the course of a refinement
]
b=a*2; #This variable will change its value if the value of variable 'a' is modified during the refinment.
Refinable variables can **not** be initialized by expressions:
RefinableVariables
[
a=10/2; #Error
]
### Special functions that may be used in expressions
`exp(x)` $=e^x$
`log(x)` Natural logarithm. Invokes error, if $x \leq 0$.
`sin(x)` sine
`cos(x)` cosine
`sqrt(x)` $=\sqrt{x}$. Invokes error if $x<0$.
`abs(x)` $=|x|$
`mod(x,y)` $= x \mod y$
`pow(x,y)`$=x^y$
## Preamble
The first part of `model.txt` contains general settings of the calculation, like definition of the unit cell, grid for diffuse scattering calculation, point group, definition of refinable variables, the calculation method and several parameters which can affect the calculation and refinement process.
The mandatory fields are `Cell` `DiffuseScatteringGrid` and `PointGroup`, other keywords can be omitted. In such cases the program will use default values.
### Cell
Mandatory field.
Defines the unit cell of the crystal.
Format: Cell $a$ $b$ $c$ $\alpha$ $\beta$ $\gamma$.
Units: Ångströms and degrees.
Example:
Cell 5.406 5.406 5.406 90 90 90
### DiffuseScatteringGrid {#DiffuseScatteringGrid}
Mandatory field.
Defines the grid on which the diffuse scattering should be calculated. In refinements experimental data and weights are to be provided with the same grid definition.
The format is the following:
DiffuseScatteringGrid lower_limit_x lower_limit_y lower_limit_z
step_size_x step_size_y step_size_z
number_of_pixels_x number_of_pixels_y number_of_pixels_z
where `lower_limits` are the minimal `h` `k` and `l` indices of the grid, `step_sizes` are the distances between lattice points in units of `h` `k` and `l`, and `number_of_pixels` are the total number of pixels along each direction.
The main axes of the grid can only be defined along the main axes of the unit cell. If one needs to calculate the diffuse scattering grid along special directions, like, for example `111`, one has to transform the unit cell accordingly.
Yell uses a Fast Fourier Transform (FFT) algorithm for switching between reciprocal and PDF space. This adds two constraints on the diffuse scattering grid:
1. number of pixels along each dimension must be even
2. the origin of reciprocal space must be in the pixel with coordinates `(number_of_pixels_x/2+1, number_of_pixels_y/2+1, number_of_pixels_z/2+1)`
The conditions are a bit unusual for anyone who did not have experience with the FFT before. The arrays with uneven number of pixels and the central pixel in the center seems more natural. In order to use FFT such "natural" datasets should be stripped of the last planes along x y and z direcitons.
The FFT algorithm allows to calculate cross-sections through the center of reciprocal space. Such cross-sections in reciprocal space correspond to the projection of the whole structure to a plane, or a line in PDF space. If the cross-section is calculated the number of pixels is allowed to be equal to 1 along some axis, then the `step_size` along the corresponding dimension is ignored, the `lower_limit` should be equal to 0.
Examples:
DiffuseScatteringGrid -5 -5 -5 0.1 0.1 0.1 50 50 50 #Usual three-dimensional case
DiffuseScatteringGrid -10 -10 0 0.1 0.1 1 20 20 1 #hk0 section of diffuse scattering
If the grid is not consistent with the above mentioned rules, diffuse scattering can be calculated using the [*direct*](#CalculationMethod) calculation algorithm and refinement can still be performed. However, the FFT algorithm is required if you want to
* apply **pdf_multipliers.h5**
* use [fast diffuse scattering calculation algorithm](#CalculationMethod)
* obtain **delta-pdf.h5**, **exp-delta-pdf.h5** and **delta-delta-pdf.h5**.
The following example only works with 'exact' calculation method:
DiffuseScatteringGrid 0 0 0 0.2 0.2 0.2 30 30 30 #Only works with 'exact' calculation method
### LaueSymmetry
Mandatory field.
Possible values: `m-3m` `m-3` `6/mmm` `6/m` `4/mmm` `4/m` `-3:R` `-3:H` `-3m:H` `-3m:R` `mmm` `2/m` `2/m:b` `-1`
Defines the Laue group of the crystal.
Laue groups which have both rhombohedral and hexagonal settings are noted by the `:R` or `:H` letters. The group `2/m` also have two standard settings, with unique `c` and with unique `b`. They are called `2/m` and `2/m:b` respectedly. Non-crystallographic symmetry, e.g. five-fold rotation axes, are not supported by the program, but can be provided explicitly by the definition of correlations (see below).
### Scale {#scale}
default value: 1
Scaling coefficient between model and experiment; always refined.
### RefinableParameters
default: empty `[ ]`
Registers variables in the square brackets to be used during refinement. The variables cannot be initialized with expressions.
Example:
RefinableVariables
[
a=1;
b=12;
]
The scale coefficient, which is also refined, should not be defined here, since it has a special [keyword](#scale).
### RecalculateAverage
possible values: `true` `false`
default value: `true`
Controls whether the average PDF of the structure should be recalculated during refinement. If set to `false` the average PDF is only calculated in the beginning of refinement and kept unchanged throughout the refinement.
In cases, when non of the refined variables may influence the average interatomic vectors, because the average structure is very well known, the recalculation can be turned off. This speeds up the refinement by the factor of two. It is safe to do so, when refinable variables do not appear in sections `UnitCell`, `Modes`, and in `Correlations` in the brackets `(1,0,0)` and in `Multiplicity`.
### DumpPairs
possible values: `true` `false`
default: `false`
When turned on, prints all the interatomic pairs used to calculate diffuse scattering in the program output.
### PrintCovarianceMatrix
possible values: `true`, `false`
default: `false`
When turned on, prints the full refinement covariance matrix in the program output.
### CalculationMethod {#CalculationMethod}
possible values: `exact` `approximate`
default value: `exact`
Selects the diffuse scattering calculation method. Yell currently has two calculation methods:
* `exact ` uses direct sum over all pairs, as shown in [this formula](#TheFormula). Calculation is done in reciprocal space.
* `approximate` goes through real space. This works much quicker because for each interatomic pair it only calculates a certain block where the signal is significant (controlled by flag [`FFTGridSize`](#FFTGridSize)) and ignores most of the PDF space , where the signal is almost zero. Details are described in ([Simonov et al. in. prep.](#YellPaper))
The approximate algorithm provides a significant speedup, but introduces errors. It is adviced to properly set up the `approximate` algorithm in the first stages of refinement, but always check the results with `exact` refinement before publishing.
### Parameters controlling approximate diffuse scattering calculation
#### FFTGridSize {#FFTGridSize}
expects: three numbers
default: `16 16 16`
Controls the size of parallelepiped in pixel units to calculate the PDF signal of a pair. Bigger values give better accuracy, smaller provide more speed. The values should not be bigger than the size of the dataset along the same dimension.
#### FFTGridPadding
expects: three numbers
default: `0 0 0`
Defines the padding in the approximate algorithm.
Prior to PDF calculation, Yell extends reciprocal space by the selected number of pixels; after the calculation the padding is cut.
Frequently, the FFT approximation method has the strongest errors close to the edges of reciprocal space. The padding expands the reciprocal space putting the errors outside the region of interest.
Details are described in ([Simonov et al. in. prep.](#YellPaper)).
#### PeriodicBoundaries {#PeriodicBoundaries}
expects: three booleans
default: `true true true`
During the `approximate` diffuse scattering calculation allows not to periodically repeat the ∆PDF signals which lie outside the calculated PDF grid along specified directions.
**Why this might be interesting**
If the correlations are very long in PDF space, one is forced to reconstruct diffuse scattering on a very fine grid, and use a huge array for ∆PDF refinement. However, sometimes the values of the correlations with long correlation vectors are not interesting. In such case there is a trick one can use to reduce the amount of memory Yell requires for refinement.
Experimental data is prepared in a special way. From the reconstruction on the fine grid one calculates the ∆PDF. Then cuts a central part of the ∆PDF, containing the region of interest. And finally back-transforms the part of the ∆PDF back to reciprocal space.
This procedure introduces strong truncation ripples in reciprocal space, but preserves the ∆PDF. The ∆PDF can then be refined in Yell with the FFT method. The obtained correlations will be accurate, though the diffuse scattering will be modeled poorly.
In such case interatomic pairs which lie close to the edge of calculated ∆PDF region. The part of the ∆PDF signal from such pairs will lie inside the calculated region, and part of the signal will lie outside the calculated region. The *direct* calculation method and the *approximate* algorithm with default settings will wrap the ∆PDF signals which lie outside the calculated region into the calculated area. Turning periodic boundaries off along these dimensions avoids this problem.
Thus, whenever the above mentioned method of preparing diffuse scattering is used, the periodic boundaries should always be turned off along the dimensions along which the ∆PDF map was cut.
### ReportPairsOutsideCalculatedPDF
possible values: `true`, `false`
default: `false`
Reports all the pairs which lie outside calculated ∆PDF map.
If an interatomic pair fall outside the calculated ∆PDF map, its signal will be periodically wrapped inside the ∆PDF map. For diffuse scattering comprising layers and streaks this is a valid behavior. However, if the diffuse scattering is not broad along some dimension, but certain pairs fall outside the calculated ∆PDF map along that dimension, this is an indication that diffuse scattering should be reconstructed on finer grid.
During the refinement with a [specially prepared dataset](#PeriodicBoundaries), with some [`PeriodicBoundaries`](#PeriodicBoundaries) turned off, the signal from most of the interatomic pairs which lie outside the calculated region will be silently discarded. Turning on this option allows to find unexpected behavior caused by this feature.
### Parameters controlling the least square refinement
#### Refine
Possible values: `true`, `false`
Default: `true`
Specifies whether the program should refine diffuse scattering. If set to `false`, the program will just calculate diffuse scattering from a given model.
#### MaxNumberOfIterations
possible values: integer
default: 1000
Defines the maximum number of iterations the refinement algorithm is allowed to run.
#### MinimizerTau
default: 1E-03
Defines the initial Levenberg-Marquandt damping parameter. Note that this value works differently, than the `damping` in standard crystallographic packages. For more information see this [wikipedia article](http://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm) and also somewhat minimalistic [manual](http://users.ics.forth.gr/~lourakis/levmar/) of the levmar library.
#### MinimizerThresholds
possible values: three numbers
default: 1E-17 1E-17 1E-17
Defines the thresholds to detect convergence of least squares procedure. The thresholds are for the size of the gradient, minimization step size, the third criterion works if the experimental and diffuse scattering are the same (say, for synthetic data). For more info see `\epsilon1` `\epsilon2` and `\epsilon3` in [levmar documentation](http://users.ics.forth.gr/~lourakis/levmar/).
#### MinimizerDiff
possible values: one number
default: 1E-06
Yell calculates derivatives by finite difference method. This value provides the increment that is used for the calculation of derivatives.
## Unit cell
This section of the input file defines the contents of the crystal's average unit cell.
In Yell, the average structure is defined in a hierarchical manner: the unit cell consists of topological sites, which are occupied by atoms or groups of atoms. The topological sites are called `Variants`and can be disordered (occupied with a certain probability by more than one group of atoms). Groups of atoms represent ensembles, like molecules or clusters.
Example:
UnitCell[
GdFeVoid_site=Variant [
(p=1/3)
Gd 1 0 0 0 0.035 0.035 0.035 0 0 0
(p=1/3)
iron_molecule = [
Fe 1 0 0 0.2845 0.035 0.035 0.035 0 0 0
Fe 1 0 0 -0.2845 0.035 0.035 0.035 0 0 0
]
(p=1/3)
Void
]
]
In this example `GdFeVoid_site` is either occupied by a gadolinium atom, by a structural building block of two iron atoms, which is aliased as `iron_molecule`, or by a `Void`. On average, each chemical unit is present with the same probability of `p=1/3`.
### Groups of atoms
Atoms can be grouped into one entity. This entities represent atoms which can not appear without each other, usually molecules or clusters.
The groups are defined without keyword, just with square brackets `[` `]`.
Example:
Fe2_molecule = [
Fe 1 0 0 0.2845 0 0 0 0 0 0
Fe 1 0 0 -0.2845 0 0 0 0 0 0
]
The grouping is recurrent, each group may contain not only atoms, but also other groups.
Example:
Fe2_molecule = [
Fe 1 0 0 0.2845 0 0 0 0 0 0
lower_iron = [
Fe 1 0 0 -0.2845 0 0 0 0 0 0
]
]
### Atoms
Atoms can be defined in two formats with both isotropic and anisotropic ADP:
AtomType mult x y z Uiso
AtomType mult x y z U11 U22 U33 U12 U13 U23
`x` `y` and `z` are fractional coordinates, `Uiso` and `Uij` are atomic displacement parameters in Å$^2$. The multiplier `mult` can be thought of as a site multiplicity in the average structure. The occupancy of each atoms is defined as `mult*p` where `p` is the probability of the atomic group the atom belongs to (defined in the construction `(p=...)`) and `mult` is the multiplier. In the vast majority of the cases `mult` should be equal to 1. It is only different if the atomic group contains disorder which is not disentangled into different entries of `Variant`.
Example:
Fe 1 0 0 -0.2845 0 0 0 0 0 0
### Naming the entities of the unit cell
Variants, atomic groups and atoms can be given names for symmetry expansion and use in `Correlations` and `Modes`. Example:
Variant1 = Variant[
(p=1)
Iron_molecule = [
Fe1 = Fe 1 0 0 0.2845 adp_perp adp_perp adp_z 0 0 0
Fe2 = Fe 1 0 0 -0.2845 adp_perp adp_perp adp_z 0 0 0
]
]
### Symmetry
It is possible to apply symmetry elements to atoms and groups of atoms. The syntax is the following:
atomic_group*Symmetry(x,y,z)
Example for mirroring an atom with respect to the xy0 plane:
Fe_atom = Fe 1 0 0 0.2845 0.01
symmetry_equivalent_Fe = Fe_atom*Symmetry(x,y,-z)
Unlike in the average crystal structure, the symmetry elements are sensitive to integer translations. In cases when the center of the molecule is not in `(0,0,0)` user should provide the appropriate translations. Here is example for the same iron molecule, with centered at `(0,0,1)`
Fe_atom = Fe 1 0 0 0.7155 adp_perp adp_perp adp_z 0 0 0
symmetry_equivalent_Fe = Fe_atom*Symmetry(x,y,2-z) #note 2-z here
# resulting coordinates are 0 0 1.2845
## Modes
Modes is a way to define motions of atoms and molecules in Yell. All the motions are linear meaning that a displacement of each atom $\Delta r$ is expressed as a linear combination of translation along all the modes:
$$
\Delta r_i = \sum_n M^n_i \xi_n
$$
where $M^n_i$ is a set of vectors attached to each atom in a molecule, $\xi_n$ is the amplitude of a displacement of the molecule along mode $n$.
Currently Yell supports two types of modes: translations and linear approximation of rotations.
### TranslationalMode
Defines movements of atomic groups as a whole; expressed in Å.
Format: `TranslationalMode(atomic_group,axis)`
or `TranslationalMode(atom,axis)`
where `atomic_group` is a name to a group of atoms, and `axis` could be either `x`,`y` or `z`.
Example:
manganese_x = TranslationalMode(manganese,x)
### RotationalMode
Defines linear approximation to rotation of a group of atoms along arbitrary axis; expressed in radians.
Format: `RotationalMode(atoimc_group, axis_x, axis_y, axis_z, center_x,center_y,center_z)`
where `axis_x` `axis_y` and `axis_z` define the rotation axis direction and `center_x` `center_y` `center_z` define a point on the rotation axis.
A displacement vector for each atom is defined as
$$
r_{axis} \times \frac{r_{atom}-r_{center}}{|r_{atom}-r_{center}|}.
$$
## Correlations
In this section, short-range order pairwise correlations are defined. There are three basic types of correlations: substitutional correlations, displacement correlations and size effect (see [Weber & Simonov, 2012](#WeberSimonov)). The combination of these correlations may describe any disorder in a disordered crystal.
In Yell, correlations which belong to the same group of atoms should be combined together in groups using square brackets. Example:
Correlations [
[(1,0,0)
Multiplicity 2
SubstitutionalCorrelation(CuVoid,AuVoid,0.25+dp)
SizeEffect(Cu,Au_x,dx)
ADPCorrelation(Cu_x,Au_x,dUx)
]
]
Each group starts with a vector `(u,v,w)`, defining the lattice vector between the correlated atoms or molecules. It corresponds to the $\mathbf R_{u,v,w}$ in ([Weber & Simonov, 2012](#WeberSimonov)). The elements of the vector are not required to be integer, and could for example be multiples of 0.5 (in case of C centering) and even irrational (e.g. in case of quasicrystals). The corresponding inter-atomic vector is calculated as $\mathbf R_{u,v,w} + \mathbf r_{Au} - \mathbf r_{Cu}$ , where $\mathbf r_{Cu} $ and $\mathbf r_{Au}$ are the atomic coordinates of the copper and gold atoms defined within `CuVoid` and `AuVoid` variants (not shown in the example).
### Multiplicity {#Multiplicity}
Format: `Multiplicity m`
where `m` is number.
Defines the multiplicity of the interatomic or intermolecular pair with respect to the Laue group.
Effect: multiplies `m` with the multiplicity of each atomic pair in current correlation group. Does not have a letter dedicated to it in ([Weber & Simonov, 2012](#WeberSimonov)), but is equivalent in effect by multiplication `m` to both joint probability $p^{mn}_{uvw}$ and Patterson multiplicity $c_nc_m$.
In Yell, the Laue group is applied to the diffuse scattering automatically. However, Yell currently cannot automatically calculate the multiplicity of each correlation set. It is expected that the user manually provides the multiplicity for it.
The multiplicity `m` of a group should be equal to the number of times such correlation group appears in the ∆PDF space. The correlations in the center of ∆PDF space usually get multiplicity 1, the correlations on general positions get multiplicity that is equal to the order of the crystal Laue group.
For an example see the model for **FeVoid**.
**Warning:** The definition of the multiplicity has to be done with great care. Wrongly defined multiplicities may be perfectly compensated by over- or underestimated structure correlation parameters leading to errors that are difficult to recognize!
For detailed instructions on how to apply multiplicity see [this section](#HowMultiplicity).
### Substitutional correlation
Substitutional correlation means that the occupancies of two `Variants` in the structure depend on each other.
Effect: sets the joint probabilities of atomic pairs to the ones specified as arguments. Affects $p^{mn}_{uvw}$ as stated in ([Weber & Simonov, 2012](#WeberSimonov)).
Format: `SubstitutionalCorrelation(variant_A,variant_B,p11,p12,...,pnm)`
short format: `SubstitutionalCorrelation(variant_A,variant_B,p11,p12,...,pn_minus_1m_minus_1)`
where `pij` are the joint probability coefficients to find both blocks Ai and Bj present at the same time, the `pn_minus_1m_minus_1` is the joint probability $p_{n-1,m-1}$.
#### Example:
SubstitutionalCorrelation(CuAu,CuAu,0.25+x)
#### Extended example
For the unit cell:
UnitCell [
AuCu = Variant[
(p=1/3)
Au 1 0 0 0 0
(p=2/3)
Cu 1 0 0 0 0
]]
Correlations [
[(0,0,0)
SubstitutionalCorrelation(AuCu,AuCu,1/3) #corresponds to the matrix 1/3 0
# 0 2/3
]
]
This will produce the following pairs (differences are typed in red):
<pre>
m p x y z Uxx ... Uyz p̅ x̅ y̅ z̅ U̅xx ... U̅yz
Au Au 1 <font color="brown">0.333333</font> 0 0 0 0 0 0 0 0 0 0.111111 0 0 0 0 0 0 0 0 0
Cu Au 1 <font color="brown">0</font> 0 0 0 0 0 0 0 0 0 0.222222 0 0 0 0 0 0 0 0 0
Au Cu 1 <font color="brown">0</font> 0 0 0 0 0 0 0 0 0 0.222222 0 0 0 0 0 0 0 0 0
Cu Cu 1 <font color="brown">0.666666</font> 0 0 0 0 0 0 0 0 0 0.444444 0 0 0 0 0 0 0 0 0
</pre>
Here the `m` marks pair multiplicicty, `p` is joint probability, `x` `y` `z` are interatomic vector coordinates, `Uxx ... Uyz` are the components of the joint ADP tensors, the letters with overbar `p̅ x̅ y̅ z̅ U̅xx ... U̅yz` relate to the average probability, interatomic vector and ADP tensor.
#### Formal description
Assume that
variant_A = Variant [
(p=pA1)
A1
(p=pA2)
A2
...
(p=pAn)
An
]
variant_B = Variant [
(p=pB1)
B1
(p=pB2)
B2
...
(p=pBm)
Bm
]
Where `Ai` and `Bj` are some chemical units, or void. Then, the full matrix of joint probabilities has size $m \times n$ and the form
$$
P = \left[
\begin{array}{cccc}
p_{A1B1} & p_{A2B1} & ... & p_{AnB1} \\
p_{A1B2} & p_{A2B2} & ... & p_{AnB2} \\
... & ... && ... \\
p_{A1Bm} & p_{A2Bm} & ... & p_{AnBm} \end{array} \right]
$$
This will be expressed in yell in the following way:
SubstitutionalCorrelation(variant_A,variant_B,pA1B1,pA2B1,...,pAnB1,
pA1B2,pA2B2,...,pAnB2,
...
pA1Bm,pA2Bm,...,pAnBm)
Since possibilities `Ai` are all exclusive and $\sum_i p_{Ai}=1$ there are $m+n-1$ independent constraints on $p_{AiBj}$ which constrain the sum of pair probabilities to probabilities of single chemical units:
$$
\sum_i p_{AiBj} = p_{Bj}
$$
$$
\sum_j p_{AiBj} = p_{Ai}
$$
The constraints make it possible to calculate the last row and last column of the matrix $P$, resulting in
$$
P = \left[
\begin{array}{cccc}
p_{A1B1} & ... & p_{An-1B1} & p_{B1}- \sum_{i=1}^{n-1} p_{AiB1} \\
... & ... && ... \\
p_{A1Bm-1} & ... & p_{An-1Bm-1} & p_{Bm-1} - \sum_{i=1}^{n-1} p_{AiBm-1} \\
p_{A1} - \sum_{j=1}^{m-1} p_{A1Bj} & ...
& p_{An-1} - \sum_{j=1}^{m-1} p_{An-1Bj} & p_{AnBm}
\end{array} \right]
$$
where
$$
p_{AnBm}=1+\sum_{i,j=1}^{n-1,m-1}p_{Ai,Bj}-\sum p_{Ai}-\sum p_{Bj}
$$
Yell can automatically calculate the last row and the last column, given the upper left $(m-1)\times(n-1)$ independent part of joint probability matrix. Thus the above definition can be equally well expressed in the short form:
SubstitutionalCorrelation(variant_A,variant_B,pA1B1,pA2B1,...,pAn-1B1,
pA1B2,pA2B2,...,pAn-1B2,
...
pA1Bm-1,pA2Bm-1,...,pAnBm-1)
The short form is in general preferred, because it is a non-redundant representation of the structure model.
#### Neutral joint probabilities
If the occupancies of two variants are independent, e.g. because their interatomic distance is larger than the correlation length of the corresponding local order phenomenon, the joint probabilities are equal to the product of the occupancies $p_{AiBj}^{Patterson}= p_{Ai}p_{Bj}$. Thus the following probability matrix will produce no diffuse scattering and no signals in PDF space (and can be ommited):
$$
P_{neutral} = \left[
\begin{array}{cccc}
p_{A1}p_{B1} & p_{A2}p_{B1} & ... & p_{An}p_{B1} \\
p_{A1}p_{B2} & p_{A2}p_{B2} & ... & p_{An}p_{B2} \\
... & ... && ... \\
p_{A1}p_{Bm} & p_{A2}p_{Bm} & ... & p_{An}p_{Bm} \end{array} \right]
$$
#### Zero - neighbor joint probabilities
For the zero neighbor correlation, i.e. the correlation of a `Variant`with itself, the diagonal elements of the joint probability matrix should be equal to the average occupancy of the corresponding elements, and off-diagonal elements should be equal to zero:
$$
P_{zero} = \left[
\begin{array}{cccc}
p_{A1} & 0 & ... & 0 \\
0 & p_{A2} & ... & 0 \\
... & ... && ... \\
0 & 0 & ... & p_{An} \end{array} \right]
$$
Or in the Yell (long) form:
[(0,0,0)
SubstitutionalCorrelation(variant_A,variant_A,pA1,0,...,0,
0,pA2,...,0,
...
0,0,...,pAn)]
It is important to note that the zero-neighbor correlation **must** be defined for all Variants showing occupational disorder and that the joint probabilities should not be refined but be the same as the occupation probability (p=...) defined in the UnitCell statement.
In practice the zero neighbor correlation is frequently over- or underestimated, because incomplete background subtraction or elimination of broad diffuse scattering with the background (= overcorrection of background) may influence the zero neighbor correlation definition and thus the correct determination of the scale factor. As shown in [(Weber & Simonov, 2012)](#WeberSimonov), such errors may lead to significant systematic deviations in the determination of other pair correlation parameters. Careful background determination is therefore indispensable for a high quality local structure refinement.
## ADPCorrelation
This correlation appears when displacements of two atoms or molecules are not independent.
Effect: changes $\beta^{mn}_{uvw}$ as stated in ([Weber & Simonov, 2012](#WeberSimonov))
Format: `ADPCorrelation(Mode1,Mode2,cov)`
where `cov` is a covariance of the displacements along the two modes $cov = < \xi_1 \xi_2 >$; `cov` is expressed in $\text{units}_1*\text{units}_2$ where $\text{units}_i$ are the units of the two modes (e.g. Å for translational modes and rad for rotational ones).
The correlations of atomic displacements typically manifest themselves as thermal diffuse scattering (TDS), but the correlations could also be of static origin.
Yell assumes that displacements of all atoms in the crystal are jointly Gaussian and the distribution of the displacement differencess $\Delta r_{ik}-\Delta r_{jl}$ is also Gaussian. The correlations of the displacements are expressed in terms of covariances of collective displacement of the blocks along `Modes`. Analogously to independent substitutional correlations ADPCorrelations do not need to be defined, if `Modes` are not correlated with any other mode. In fact, most of the internal modes of rigid molecules are not expected to be correlated.
Note that some ADP correlations, though symmetrically independent, can produce the same signal in PDF space. One very practical example is the covariances $<x_1y_2>$ and $<y_1x_2>$ produce exactly the same effect in PDF space, and should therefore be constrained.
The ADP correlations are subject of symmetry constraints by the symmetry of interatomic or intermolecular pairs. The constraints to the correlations of translational modes are equivalent to the site-symmetry ADP constraints in the average structure. The constraints involving rotational modes are equivalent to the TLS constraints ([Schomaker & Trueblood 1968](#ShomakerTrueblood)).
### Example
#Cu structure (fcc)
#the unit cell has Fm-3m symmetry (225)
LaueSymmetry m-3m
UnitCell [
Variant [
(p=1)
Cu = Cu 1 0 0 0 0.01
]]
Modes [
Cu_x = TranslationalMode(Cu,x)
]
Correlations[
...
[(1,0,0)
ADPCorrelation(Cu_x,Cu_x,0.001)
ADPCorrelation(Cu_y,Cu_y,0.0001)
ADPCorrelation(Cu_z,Cu_z,0.0001)]
...
]
Note that the yy and zz correlations are the same, while xx is different according to symmetry of the pair. Let us assume that the symmetry of this pair is described by the point group $4/mmm$ with the 4-fold axis along **a** of the cubic crystal. This restricts the covarince matrix to the following form:
$$
\left[
\begin{array}{ccc}
cov_{xx} & & \\
& cov_{yy} & \\
& & cov_{yy}
\end{array}
\right]
$$
### Example with correlation matrices
The covariance matrices can be recalculated in correlation matrices.
$$
corr^{mn}_{ij} = \frac{cov^{mn}_{ij}}{\sqrt{\mathbf U^{aver,m}_{ii} \mathbf U^{aver,n}_{jj}}}
$$
where indices $i,j=1,2,3$ mark tensor components, $m$ and $n$ count atoms, $corr^{mn}_{ij}$ is a correlation matrix, $cov^{mn}_{ij}$ is a covariance matirx (in Å$^2$), the $U^{aver,m}$ and $U^{aver,n}$ are the average ADP tensors of atoms $m$ and $n$ (in Å$^2$).
In Yell correlation matrix can be calculated in the epilogue using the `Print` command. The above mentioned example becomes:
#Cu structure (fcc)
#the unit cell has Fm-3m symmetry (225)
LaueSymmetry m-3m
UnitCell [
Uiso=0.01; #define a variable for Uiso
Variant [
(p=1)
Cu = Cu 1 0 0 0 U
]]
Modes [
Cu_x = TranslationalMode(Cu,x)
]
Correlations[
...
cov_11=0.001;
cov_22=0.002;
[(1,0,0)
ADPCorrelation(Cu_x,Cu_x,cov_11)
ADPCorrelation(Cu_y,Cu_y,cov_22)
ADPCorrelation(Cu_z,Cu_z,cov_22)]
...
]
Print "corr_11=" cov_11/Uiso " corr_22=" cov_22/Uiso " corr_33=" cov_22/Uiso
Will print:
Requested output: corr_11=0.1 corr_22=0.01 corr_3=0.01
### Formal definition {#ADPCorr}
The theory is somewhat similar to the normal mode analysis. The notation here is analogous to ([Cyvin 1968](#Cyvin)).
**1.** Denote the equilibrium configuration of N atoms in a molecule $\alpha$ as
$$
\boldsymbol{R}_{\alpha i}=\{X_{\alpha i}, Y_{\alpha i}, Z_{\alpha i} \}=\{R_{\alpha i1}, R_{\alpha i2}, R_{\alpha i3} \}
$$
for i=1,2,...,N. Then the displacements are introduced as deviations from equilibrium:
$$
u_{\alpha ij}=R_{\alpha ij}-<R_{\alpha ij}>
$$
**2.** Introduce another set of coordinates $\boldsymbol \xi_{\alpha}$ which we identify as a set of internal coordinates and introduce a set of matrices $M$ that transform internal coordinates into "external" atomic displacements:
$$
u_{\alpha ij}=\sum_k M^k _{\alpha ij} \xi_{\alpha k}
$$
If $\xi$ has 3N independent coordinates and there exist an inverse transformation
$$
\xi_{\alpha i}=\sum_{jk} M^{-1 jk} _{\alpha i} u_{\alpha jk}
$$
both representations are equivalent.
In Yell, the matrices $M^k _{\alpha ij}$ are called *Modes*, the variables $\xi_{\alpha i}$ are referred to as *the amplitudes of displacement along corresponding modes*.
**3.** Recall, that the elements of the ADP matrix of an individual atom $k$ in the molecule $\alpha$ is defined as follows:
$$
U_{\alpha k}^{ij} = <u_{\alpha k i} u_{\alpha k j}>
$$
The paper ([Weber & Simonov, 2012](#WeberSimonov)) uses the notation $\beta_{\alpha k}^{ij}$; it is equivalent notation since $\beta_{\alpha k}^{ij}=2\pi^2a^*_i a^*_j U_{\alpha k}^{ij}$, where $a^*_i$ and $a^*_j$ are the lengths of the corresponding reciprocal lattice vectors.
**4.** A covariance between the displacements of two atoms belonging to two different molecules can be expressed in terms of covariances of the modes:
$$
<u_{\alpha i j} u_{\beta k l}>=<\sum_m M^m_{\alpha i j}\xi_{\alpha m} \sum_nM^n_{\beta k l}\xi_{\beta n}>=\sum_{mn} M^m_{\alpha i j} M^n_{\beta k l} <\xi_{\alpha m} \xi_{\beta n}>
$$
**5.** The joint atomic displacement parameter matrix of one atom as seen from another atom can be expressed as follows:
$$
U_{\alpha k,\beta l}^{ij} = <(u_{\alpha k i}-u_{\beta l i})(u_{\alpha k j}-u_{\beta l j})>=\\
<u_{\alpha k i}u_{\alpha k j} >+<u_{\beta l i} u_{\beta l j}>-
<u_{\beta l i}u_{\alpha k j}>-<u_{\alpha k i}u_{\beta l j}>=\\
U_{\alpha k}^{ij}+U_{\beta l}^{ij}-\sum_{mn} (M^m_{\alpha i j} M^n_{\beta k l}+M^n_{\alpha i j} M^m_{\beta k l}) <\xi_{\alpha m} \xi_{\beta n}>
$$
Note that in order to define the ADP correlations it is not necessary to construct the full set of internal modes. It is significant to know the ADPs of each pf the atoms from the average structure and only the covariances of the modes which are correlated.
### Neutral correlation
If the displacements of two molecules are independent, all the covariances are equal to zero and don't need to be listed explicitly.
### Zero-neighbor correlation
In theory, the covariance in the zero neighbor is equal to the square of the amplitude of the mode. For example, for single atom, the ADP correlations of the zero neighbor should be identical with its ADP parameter:
adp_cu=0.01;
UnitCell [
Variant [
(p=1)
Cu = Cu 1 0 0 0 adp_cu
]]
Modes [
Cu_x = TranslationalMode(Cu,x)
Cu_y = TranslationalMode(Cu,y)
Cu_z = TranslationalMode(Cu,z)
]
Correlations [
[(0,0,0)
ADPCorrelation(Cu_x,Cu_x,adp_cu)
ADPCorrelation(Cu_y,Cu_y,adp_cu)
ADPCorrelation(Cu_z,Cu_z,adp_cu)]
]
Similar to substitutional correlations zero neighbor ADP correlations may be heavily affected by over- or under-corrected experimental background.
Note that in substitutionally disordered crystals ADP correlations are frequently not seen because corresponding diffuse scattering is usually very weak. In such crystals zero-neighbor ADP correlation need only be defined if there is a clear indication to ADP correlations or size-effect correlations.
## SizeEffect
Size effect occurs when a substitutional disorder in a `Variant` is correlated with a static displacement of another chemical unit.
Effect: changes the $u^{mn}_{uvw}$ as stated in ([Weber & Simonov, 2012](#WeberSimonov))
Format: `SizeEffect(AtomicGroup1,Mode2,amp)`
or `SizeEffect(Mode1,AtomicGroup2,amp)`
The meaning of the `SizeEffect(AtomicGroup1,Mode2,amp)`: in the presence of `AtomicGroup1` the `AtomicGroup2` has an average displacement along the `Mode2` by the amount defined by the amplitude `amp` (expressed in the units of the `Mode2` e.g. Å for translational mode, rad for rotational)
### Example
UnitCell [
Variant [
(p=0.99)
Na = Na 1 0 0 0 0.01
(p=0.01)
Void
]]
Modes [
Na_x = TranslationalMode(Na,x)
]
Correlations [
...
[(1,0,0)
SizeEffect(Na,Na_x,0.02)
]
...
]
### Neutral SizeEffect
When the correlation is absent, the size effect is equal to zero and is not required to be defined.
### Zero-neighbor correlation
The size-effect for the zero-neighbor is equal to zero. However, it is important to add the zero neighbor from the ADPCorrelation, otherwise the model might produce negative intensities.
Example:
#A disordered Fe-Ni alloy
#Space group Fm-3m
PointGroup m-3m
UnitCell
[
ADP=0.0004;
FeNi = Variant[
(p=1/2)
Fe = Fe 1 0 0 0 ADP
(p=1/2)
Ni = Ni 1 0 0 0 ADP
]
]
Modes[
Fe_x = TranslationalMode(Fe,x)
Ni_x = TranslationalMode(Ni,x)
#... same for y and z
]
Correlations [
[(0,0,0)
SubstitutionalCorrelation(FeNi,FeNi,1/2)
#IMPORTANT: even though the crystal does not have ADP correlation,
#zero neighbor ADP correlation should be input in presense of size effect:
ADPCorrelation(Fe_x,Fe_x,ADP)
ADPCorrelation(Ni_x,Ni_x,ADP)
#... same for y and z
]
#...
#
[(1,0,0)
SubstitutionalCorrelation(FeNi,FeNi,0.25*(1+a200))
SizeEffect(Fe,Fe_x,se200_FeFe)
#IMPORTANT: in addition to size effect add ADP correlation
#with amplitude se^2/2
ADPCorrelation(Fe_x,Fe_x,pow(se200_FeFe,2)/2)
SizeEffect(Fe,Ni_x,se200_FeNi)
ADPCorrelation(Fe_x,Ni_x,pow(se200_FeNi,2)/2)
SizeEffect(Ni,Fe_x,se200_FeNi)
ADPCorrelation(Ni_x,Fe_x,pow(se200_FeNi,2)/2)
SizeEffect(Ni,Ni_x,se200_NiNi)
ADPCorrelation(Ni_x,Ni_x,pow(se200_NiNi,2)/2)
]
### Formal definition
In the presence of size-effect:
$$
\bar u^{\alpha k,\beta l}_i = \sum_nM^n_{\beta l i}A_{\beta n}-\sum_nM^n_{\alpha k i}A_{\alpha n}
$$
For description of the notation see [ADPCorrelation](#ADPCorr)
Epilogue
------------
In the last part of the file the custom output from Yell can be requested. The output will be produced after the refinement is finished. The output can contain any expressions whose values will be calculated from the refined variables.
### Print
optional.
Arguments: a list of strings in quotes `"` `"` or arithmetic expressions
Format: `Print "string1" expr1 ...`
Prints the requested output in the terminal.
Example:
a=1;b=2;
Print "The variable a=" a ", b=" b
This line produces the output `Requested output:The variable a=1, b=2`
How to calculate multiplicity {#HowMultiplicity}
=========
Yell can apply the Laue symmetry to the calculated ∆PDF. This is a convenient feature since only the [independent cone](#Cone) of correlations in ∆PDF space have to be defined.
Yell does not distinguish the interatomic pairs on special and average positions. Thus, the multiplicity of each interatomic (intermolecular) pair **must be provided manually**. If multiplicity is not provided, all the pairs except in the center of ∆PDF will get too little density:
![enter image description here][1]
If the multiplicity is provided, the Laue symmetry is applied properly:
![enter image description here][2]
Definition
---------
By *multiplicity* of an interatomic (intermolecular) pair we mean the number of interatomic (intermolecular) pairs which are symmetry related to the current pair.
By symmetry we mean two distinct symmetries: the crystal space group symmetry and [combinatorial symmetry](#Combinatorial) which relates pair (A,B) to (B,A).
First way to determine multiplicity
-----------
Multiplicity can be determined by counting the symmetry equivalent pairs.
### Example
This example is performed in two dimensions, but generalization to three dimensions is straightforward.
Assume a simple two-dimensional square crystal with a space group $p4mm$ and one atom in the unit cell:
![][3]
The zeroth neighbor connects an atom with itself. There is 1 such pair:
![][4]
The first neighbor with interatomic vector (1,0) has 4 symmetry equivalents:
![][5]
The neighbor (1,1) also has 4 symmetry equivalents:
![][6]
also the neighbor (2,0):
![enter image description here][7]
The neighbor (2,1) has 8 equivalents:
![enter image description here][8]
The neighbor (2,2) has again 4 equivalents:
![enter image description here][9]
The list of all pairs (without actual correlations) in Yell format will be the following:
Correlations [
[(0,0,0)
Multiplicity 1
...]
[(1,0,0)
Multiplicity 4
...]
[(1,1,0)
Multiplicity 4
...]
[(2,0,0)
Multiplicity 4
...]
[(2,1,0)
Multiplicity 8
...]
[(2,2,0)
Multiplicity 4
...]
]
Second way to determine multiplicity {#FromSymmetry}
-----------
Sometimes it is complicated to count the number of symmetry related pairs or there is a demand to calculate the multiplicity by an alternative approach to verfy the results. In such cases, the multiplicity can be calculated from the internal symmetry of a single pair.
Assume:
* $p$ is a pair
* $|G|$ is the number of symmetry elements in the crystal space group (space group order)
* $|Int(p)|$ is the number of symmetry elements in the internal symmetry of a pair (internal symmetry order)
Then, number of symmetry equivalent pairs is equal to:
$N_p = 2\frac{|G|}{|Int(p)|}$ if the pair connects different atoms( molecules) and
$N_p = \frac{|G|}{|Int(p)|}$ for zeroth neighbor.
The above mentioned formula is a consequence of the [orbit-stabilizer theorem](http://www.proofwiki.org/wiki/Orbit-Stabilizer_Theorem). The factor 2 appears in the formula due to [compinatorial symmetry](#Combinatorial).
### Example
Again, assume a simple square crystal. The crystal has a plane group $p4mm$ (No. 11 in International Tables of Crystallography):
![enter image description here][10]
The plane group $p4mm$ has following symmetry operations:
$$
\begin{array}{llll}
\text{(1) $x,y$} & \text{(2) $\bar x,\bar y$} & \text{(3) $\bar y,x$} & \text{(4) $y,\bar x$} \\
\text{(5) $\bar x,y$} & \text{(6) $x,\bar y$} & \text{(7) $y,x$} & \text{(8) $\bar y,\bar x$}
\end{array}
$$
Totally there are 8 operations, thus $|G|=8$.
The zeroth neighbor has internal symmetry $4mm$:
![enter image description here][11]
The order of internal symmetry group $4mm$ is 8 (group elements: 1, $4^1$, $4^2$, $4^3$, $m_x$, $m_y$, $m_{xy}$, $m_{yx}$); this pair is a zeroth neighbor:
$$
N_{(0,0)} = \frac{|G|}{|Int(p_{(0,0)})|} = \frac{8}{8}=1
$$
Hence there is 1 such pair.
The neighbor (1,0) has internal symmetry $2mm$:
![enter image description here][12]
On the image the glide planes which are marked orange belong to the space group of the crystal, but not to the internal symmetry of the pair.
The order of $2mm$ is 4 (group elements: 1, 2, $m_x$, $m_y$), thus the number of such pairs is:
$$
N_{(1,0)} = 2\frac{|G|}{|Int(p_{(1,0)})|} = 2\frac{8}{4}=4
$$
Note that glide plane operations do no count in this case, because the internal symmetry of the pair has to be described exclusively by point symmetry operations. In the case of periodic layers or rods, which are disordered along the other dimensions (corresponding to diffuse streaks or layers, respectively), glide or screw operations might also be considered along the periodic directions (see corresponding layer or rod groups).
The neighbor (1,1) also has internal symmetry $2mm$
![enter image description here][13]
The average crystal has two additional planes and a four fold axis (marked orange) passing through coordinates (0.5,0.5), which do not completely belong to the internal symmetry of the pair. They are not counted. The remaining group elements are : 1, $4^2\equiv 2$, $m_{xy}$, $m_{yx}$
The number of (1,1) pairs is therefore:
$$
N_{(1,1)} = 2\frac{|G|}{|Int(p_{(1,1)})|} = 2\frac{8}{4}=4
$$
Neighbor (2,0) again has the symmetry $2mm$
![enter image description here][14]
and $N_{(2,0)} = 2*8/4=4$
Neighbor (2,1) has the symmetry $2$ (group elements: 1, 2):
![enter image description here][15]
Thus the number of such pairs is $N_{(2,0)} = 2*8/2=8$
Neighbor (2,2) has symmetry $2mm$ (group elements: 1, 2, $m_{xy}$, $m_{yx}$):
![enter image description here][16]
And thus there are 4 such pairs.
From symmetry analysis it is clearly seen:
* The zeroth neighbor has symmetry $4mm$ and only 1 equivalent.
* Neighbors $(x,0)$ and $(x,x)$ have symmetry $2mm$ and thus 4 equivalents.
* All the other neighbors $(x,y)$ have symmetry $2$ and thus 8 equivalents.
Combinatorial symmetry {#Combinatorial}
-----------
By *combinatorial equivalent* of an (ordered) pair (A,B) we mean the pair (B,A). In PDF, combinatorial pairs are obtained by inverting interatomic vectors.
Assume we have a planar NaCl-type structure:
![enter image description here][17]
The pair Na-Cl with interatomic vector (0.5,0.5) has a combinatorially equivalent pair Cl-Na with vector (-0.5,-0.5). Thus the multiplicity of such pair is 8:
![enter image description here][18]
When the multiplicity is calculated using [the second method](#FromSymmetry), combinatorially symmetric pairs are automatically counted. The pair Na-Cl (0.5,0.5) has the internal symmetry $m$:
![][19]
The multiplicity is equal to $N_{NaCl} = 2*8/2=8$
Independent cones for all Laue groups {#Cone}
-----------
The following table summarizes the independent parts of each Laue group:
$$
\begin{array}{ccc}
\text{Laue group} &\text{Group order} &\text{Independent cone conditions} \\
m\bar 3m& 48& x \geq y \geq z \geq 0 \\
m\bar 3 & 24 & x \geq z,\; y \geq z,\; z \geq 0 \\
6/mmm & 24 & x \geq 2y \geq 0,\; z\geq0 \\
6/m & 12 & x\geq y\geq 0,\; z \geq 0 \\
\bar 3m:H & 12 & x \geq y \geq 0,\; z \geq 0 \\
\bar 3m:R & 12 & z \geq y \geq x,\; x+y+z \geq 0 \\
\bar 3:H & 6 & x \geq 0,\; y \geq 0,\; z \geq 0 \\
\bar 3:R & 6 & x \geq y,\; x \geq z ,\; x+y+z \geq 0 \\
4/mmm & 16 & z \geq 0,\; x \geq y \geq 0 \\
4/m & 8 & x \geq 0,\; y \geq 0,\; z \geq 0 \\
mmm & 8 & x \geq 0,\; y \geq 0,\; z \geq 0 \\
2/m & 4 & z \geq 0,\; y \geq 0 \\
2/m:b & 4 & z \geq 0,\; y \geq 0 \\
\bar 1 & 2 & z \geq 0
\end{array}
$$
Equation for diffuse scattering calculation {#TheFormula}
=============
Diffuse scattering of a disordered crystal can be calculated by the equation (8) from ([Weber & Simonov 2012](#WeberSimonov):
$$
I_{dif}(\mathbf{h}) =
\sum_{\mathbf{R}_{uvw}}^{cryst} \sum_{mn}^{cell}
\big\{p^{uvw}_{mn}
\exp(-\mathbf{h}^{T}\beta^{mn}_{uvw} \mathbf{h})
\cos [2\pi \mathbf h (\mathbf{R}_{uvw}+\mathbf{r}_{mn}+ \mathbf{\bar u}^{mn}_{uvw} ]-\\
- c_{m}c_{n} \exp(-\mathbf{h}^{T}(\beta^{aver}_m+\beta^{aver}_n) \mathbf{h}) \cos [2 \pi \mathbf{h}(\mathbf{R}_{uvw} + \mathbf{r}_{mn}) ]
\big \} \cdot \\
\cdot f_{m}(\mathbf{h}) f_{n}(\mathbf{h})
$$
Here indices $m$ and $n$ go over all the atoms in a unit cell, $\mathbf{R}_{uvw}$ over all latice vectors; $p^{uvw}_{mn}$ is a joint probability to find atom $n$ in a unit cell and atom $m$ in another unit cell separated by $\mathbf{R}_{uvw}$, $\beta^{mn}_{uvw}$ is a joint ADP matrix expressed in fractional units, $r_{mn}=r_n-r_m$ is the average interatomic vector between atoms $m$ and $n$, $\mathbf{\bar u}^{mn}_{uvw}$ is a size effect parameter, $c_m$ and $c_n$ are the average occupancies, and $\beta^{aver}_m$ and $\beta^{aver}_n$ are the average ADP parameters, $f_m(\mathbf h)$ and $f_n(\mathbf h)$ are the atomic form-factors.
References
========
##### Weber, T., & Simonov, A. (2012). The three-dimensional pair distribution function analysis of disordered single crystals: basic concepts. *Zeitschrift für Kristallographie*, 227(5), 238-247. [researchgate](https://www.researchgate.net/publication/235767166_The_three-dimensional_pair_distribution_function_analysis_of_disordered_single_crystals_basic_concepts) {#WeberSimonov}
##### Schomaker, V., & Trueblood, K. N. (1968). On the rigid-body motion of molecules in crystals. *Acta Crystallographica Section B: Structural Crystallography and Crystal Chemistry*, 24(1), 63-76. [link](http://scripts.iucr.org/cgi-bin/paper?S0567740868001718) {#ShomakerTrueblood}
##### Cyvin, S. J. (1968). *Molecular vibrations and mean square amplitudes.* Universitets Forl.. Chapter 3 {#Cyvin}
##### Simonov, A., Weber, T., Steurer, W., *Yell - a computer program for diffuse scattering analysis via 3D-∆PDF refinement.* in. prep. {#YellPaper}
[1]: https://lh6.googleusercontent.com/ijtDa2ou82uPzYmpkhAoJwkRg-uYx2teR2AKzBVyzu0=s600
[2]: https://lh6.googleusercontent.com/1iW1RNDe3IXG6yjvmxF44UPsS_RfR28LoXJi5Do7BYc=s600
[3]: https://lh3.googleusercontent.com/8YG3ZmWPOcUOr5B6iMYc8aE408ETOHXlng2q1Xv_4zM=s300
[4]: https://lh5.googleusercontent.com/029euAKAuzzT0_EjpQR36ghC7Z1kfWfxM4SIBq9St7o=s300
[5]: https://lh4.googleusercontent.com/mHDYn0VHH8Q9VIaNy3mBbZXb8cv0oPHb-YStyhumpl8=s300
[6]: https://lh5.googleusercontent.com/GH8IkDiOtM4DfR5scDmrvQwRjhz7OM8kcmZf00mUcaQ=s300
[7]: https://lh3.googleusercontent.com/Guw5EK2cBAsKsPH4_MNabz5Plg5vL4s3erYF5Y11FB8=s300
[8]: https://lh6.googleusercontent.com/CBZwrTbE3CtRohPa9u1L7Y4Gr-Qlq3jrP4VpbsU9GSY=s300
[9]: https://lh3.googleusercontent.com/XZrzH28SR3XrQSl2nJlB0aoUkflqMM9bV1XfL93Dlo4=s300
[10]: https://lh4.googleusercontent.com/_q2pPCcpWjywdCnL391OhM7GeeiT7X9nnLCRsGIYBhA=s600
[11]: https://lh3.googleusercontent.com/QH2LQbeljajEbxPlJlc5lmaa7bssClaQ--4pO3gxuyA=s600
[12]: https://lh6.googleusercontent.com/p2Y_0uI0QJ-E4sfOTb_oMpHPghPcogAU7H7DlMM3RiM=s600
[13]: https://lh5.googleusercontent.com/XPNTxskn1FCCARzcPrYk6JZbs696oMoWr0VeiixeZ40=s600
[14]: https://lh4.googleusercontent.com/Xx0l08giXHN-azKwZQlFE7joCcg0U0-AGHsKXehGCBE=s600
[15]: https://lh5.googleusercontent.com/xYBJYzKWc1meOpN1KcmHq77KihMfuMGMuSdEufRNFFw=s600
[16]: https://lh3.googleusercontent.com/wHBFjQQuDMyJhj0ZizRvT0fvtpndqoTIIQBdZyAnarc=s600
[17]: https://lh5.googleusercontent.com/AIBvkOR4j_t9K1sr0HifYynBOGsd59xy29vopSox2h0=s300
[18]: https://lh4.googleusercontent.com/YcF870Bckp7yCAvJPswlwTb1jstT6OkFaCwTOWl9fH4=s300
[19]: https://lh4.googleusercontent.com/-GHrkdfqmj8jFQbvINVpzuTfppmu8Md6aR3uhoiRxvI=s450 | Markdown |
3D | YellProgram/Yell | src/OutputHandler.cpp | .cpp | 725 | 21 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "OutputHandler.h"
| C++ |
3D | YellProgram/Yell | src/diffuser_core.h | .h | 15,393 | 549 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DIFFUSER_CORE
#define DIFFUSER_CORE
#include <scitbx/array_family/versa.h>
#include <scitbx/array_family/accessors/c_grid.h>
#include <scitbx/fftpack/complex_to_complex_3d.h>
#include <complex>
#include <assert.h>
#include "basic_io.h"
#include "math.h"
#include <cctbx/uctbx.h>
#include "OutputHandler.h"
#include "exceptions.h"
#include <H5Cpp.h>
using namespace H5;
extern OutputHandler report;
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795029L
#endif
const double M_2PI=2*M_PI;
const double M2PISQ=-2*M_PI*M_PI;
using namespace scitbx;
using namespace std;
//I figured out that i was using complex real() as accessor which it is not. Here is a hack to solve this under windows. ICC and GCC compilers work nicely without this hack
double& real(complex<double>& inp);
const double EPSILON = 0.0000000001; //i picked it at random
bool almost_equal(double a, double b);
template<int matrix_size,class FixedSizeMatrix>
bool almost_equal(FixedSizeMatrix a,FixedSizeMatrix b)
{
bool res=true;
for(int i=0; i<matrix_size; ++i)
res = res && almost_equal(a[i],b[i]);
return res;
}
bool almost_equal(vec3<double> a,vec3<double> b);
bool almost_equal(mat3<double> a,mat3<double> b);
bool almost_equal(scitbx::af::tiny<double,6>,scitbx::af::tiny<double,6>);
string format_esd(double val,double esd);
//element-wise multiplication of vec3-type vectors
template<class vec3type, class another_array>
vec3type ew_mult(vec3type v1,another_array v2)
{
return vec3type(v1[0]*v2[0],v1[1]*v2[1],v1[2]*v2[2]);
}
class Grid {
public:
Grid()
{}
Grid(cctbx::uctbx::unit_cell cell,
vec3<double> grid_steps,
vec3<double> lower_limits,
vec3<int> grid_size = vec3<int>(1, 1, 1),
bool reciprocal_flag = true) : // by default the grid is defined in reciprocal space. Usually we start working with diffuse scattering
cell(cell), grid_steps(grid_steps), lower_limits(lower_limits), grid_size(grid_size),
reciprocal_flag(reciprocal_flag)
{}
Grid in_pdf_space()
{
if(!reciprocal_flag)
return *this;
else
return reciprocal();
}
vec3<double> s_at(af::tiny<int,3> const & index) {
return lower_limits+ew_mult(grid_steps,index);
}
double d_star_square_at(af::tiny<int,3> const & index) {
return cell.d_star_sq(cctbx::miller::index<double>(s_at(index)));
}
/// Returns corresponding grid in reciprocal space.
Grid reciprocal() {
vec3<double> res_grid_steps(1, 1, 1);
vec3<double> res_lower_limits(0, 0, 0);
for(int i=0; i<3; i++)
{
//cout << "lower limit " << i << " " << lower_limits[i];
if(abs(lower_limits[i])!=0)
{
res_grid_steps[i]= -0.5 / lower_limits[i];
res_lower_limits[i]= -0.5 / grid_steps[i];
}
}
return Grid(cell.reciprocal(), res_grid_steps, res_lower_limits, grid_size, !reciprocal_flag);
}
/// Function for unit tests.
bool operator==(const Grid& inp) {
return almost_equal(grid_steps,inp.grid_steps)\
&& almost_equal(lower_limits, inp.lower_limits) \
&& almost_equal(cell.parameters(),inp.cell.parameters()) \
&& grid_size==inp.grid_size;
}
vec3<double> upper_limits() {
return lower_limits+grid_steps.each_mul(grid_size-1);
}
bool grid_is_compatible_with_fft() {
for(int i=0; i<3; ++i)
{
if(grid_size[i]==1)
{
if(almost_equal(lower_limits[i],0))
continue;
else
return false;
}
else
{
if(grid_size[i]%2==1)
return false;
if(!almost_equal(lower_limits[i]+grid_size[i]/2*grid_steps[i], 0))
return false;
}
}
return true;
}
/// Returns the volume which the grid covers.
double volume() {
return cell.volume()*grid_steps.each_mul(grid_size).product();
}
/// Returns the grid with padding by n pixels
Grid pad(vec3<int> padding) {
Grid res = *this;
res.lower_limits-=grid_steps.each_mul(padding);
res.grid_size+=2*padding;
return res;
}
cctbx::uctbx::unit_cell cell;
vec3<double> grid_steps; ///< array of steps of the grid in angstroms or reciprical angstroms
vec3<double> lower_limits; ///< array of lowest bounds of grid
vec3<int> grid_size;
bool reciprocal_flag; ///< true if grid is in reciprocal coordinates (\AA^-1) and false if it is in PDF units.
};
/**
* Distributes r between vector which is compatible with grid and residual.
* \param r input vector.
* \param r_grid component of r which is compatible with grid. Equals number of steps from lowerest bounds to grid point which is closest to r.
* \param r_res residual component of r.
*/
void grid_and_residual(vec3<double> r,Grid grid,vec3<int> & r_grid,vec3<double> & r_res);
/**
* Holds 3D array of diffuse scattering intensity.
*/
class IntensityMap {
public:
IntensityMap() { }
IntensityMap(const IntensityMap& inp) {
Init(inp.data_accessor[0],inp.data_accessor[1],inp.data_accessor[2]);
if(inp.grid_is_initialized)
set_grid(inp.grid);
for(int i=0; i<data_accessor.size_1d(); ++i)
data[i]=inp.data[i];
}
IntensityMap(Grid grid) : grid(grid) {
Init(grid.grid_size[0],grid.grid_size[1],grid.grid_size[2]);
grid_is_initialized=true;
}
IntensityMap(vec3<int> map_size)
{
Init(map_size[0],map_size[1],map_size[2]);
}
IntensityMap(int a,int b, int c)
{
Init(a,b,c);
}
void set_grid(cctbx::uctbx::unit_cell cell,vec3<double> grid_steps, vec3<double> lower_limits)
{
set_grid( Grid(cell, grid_steps, lower_limits));
}
void set_grid(Grid inp_grid)
{
grid = inp_grid;
grid_is_initialized=true;
}
void erase_data()
{
for(int i=0; i<data.size(); ++i)
data[i]=0;
}
double& at(int a,int b,int c)
{
return real(data[data_accessor(a,b,c)]);
}
complex<double>& at_c(af::c_grid<3,int>::index_type _index)
{
return data[data_accessor(_index)];
}
double& at(af::c_grid<3,int>::index_type _index)
{
return real(data[data_accessor(_index)]);
}
double& at(int _index)
{
return real(data[_index]);
}
complex<double>& at_c(int _index)
{
return data[_index];
}
void subtract(IntensityMap& inp)
{
assert(data.size() == inp.data.size());
for(int i=0; i<data.size(); ++i)
data[i]-=inp.data[i];
}
IntensityMap padded (vec3<int> padding)
{
IntensityMap res(size()+2*padding);
res.set_grid(grid.pad(padding));
return res;
}
void copy_from_padded(vec3<int> padding,IntensityMap& pad)
{
for(int i=0; i<size()[0]; ++i)
for(int j=0; j<size()[1]; ++j)
for(int k=0; k<size()[2]; ++k)
at(i,j,k)=pad.at(i+padding[0],j+padding[1],k+padding[2]);
}
void scale_and_fft(double scale)
{
assert(grid_is_initialized);
double pdf_space_volume = grid.volume();
for(int i=0; i<data.size(); ++i)
data[i] *= scale/pdf_space_volume/4; //dunno where this 1/4 comes from
invert();
}
/// Performs fourier transform of intensity map and inverts grid
void invert()
{
perform_shifted_fft();
invert_grid();
}
/// Inverts grid, does nothing with intensity map
void invert_grid()
{
if (grid_is_initialized)
grid=grid.reciprocal();
}
/** Applies -1 to every element of array if sum Ni/2 is odd
*
* The accurate formula for shifted FFT looks the following
* X_n-m = FT[ x_n-m * exp( n*2*pi*i*m/N ) ]*exp( (n-m)*2*pi*i*m/N )
* given that m = N/2 it transforms into
* X_n-m = FT[ x_n-m * -1^( mod(n,2) ) ]*-1^( mod(n-m,2) )
* -1^( mod(n,2) ) - is a chessboard and was applied in the following functions
* -1^( mod(n-m,2) ) = -1^( mod(n,2) ) when N/2 is even. In such cases this funciton does nothing.
* -1^( mod(n-m,2) ) = -(-1^( mod(n,2) )) when N/2 is odd. In such cases this function applies the minus to all the elements in the array
*/
void flip_signs_if_nessesary()
{
int disp=0;
for(int i=0; i<3; ++i)
if(data_accessor[i]>1)
disp+=data_accessor[i];
if((disp/2)%2==1)
for(int i=0; i<data_accessor[0]; i++)
for(int j=0; j<data_accessor[1]; j++)
for(int k=0; k<data_accessor[2]; k++)
data[data_accessor(i,j,k)]*=-1;
}
/// Multiplies the array to -1 in a chessboard-way. The center N/2,M/2,K/2 keeps positive sign
void flip_signs_in_chessboard_way()
{
for(int i=0; i<data_accessor[0]; i++)
for(int j=0; j<data_accessor[1]; j++)
for(int k=0; k<data_accessor[2]; k++)
if((i+j+k)%2==1)
data[data_accessor(i,j,k)]*=-1;
}
/** performs fourier transform, assuming that origin of coordinates is in point grid_size/2.
*/
void perform_shifted_fft()
{
flip_signs_in_chessboard_way();
perform_fft();
flip_signs_in_chessboard_way();
flip_signs_if_nessesary();
}
void perform_fft()
{
scitbx::fftpack::complex_to_complex_3d<double> fft(data_accessor);
scitbx::af::ref<std::complex<double>, scitbx::af::c_grid<3,int> > cmap(data.begin(), data_accessor);
if (is_in_reciprocal_space())
fft.backward(cmap);
else
{
fft.forward(cmap);
// for some reason this forward and backward transforms do not divide by number of pixels in the map. This is why we apply it by hand
double scale = 1.0/data_accessor.size_1d();
init_iterator();
while(next())
current_array_value_c()*=scale;
}
}
void init_iterator()
{
iterator=-1;//because next() will be used before first actions
}
bool next()
{
return (++iterator<data_accessor.size_1d());
}
double& current_array_value()
{
return real(data[data_accessor(current_index())]);
}
complex<double>& current_array_value_c()
{
return data[data_accessor(current_index())];
}
vec3<double> current_s()
{
return grid.s_at(current_index());
}
double current_d_star_square()
{
return grid.d_star_square_at(current_index());
}
cctbx::uctbx::unit_cell & unit_cell()
{
return grid.cell;
}
vec3<double> & grid_steps()
{
return grid.grid_steps;
}
vec3<int> size()
{
vec3<int> res;
for(int i=0; i<3; i++)
res[i]=data_accessor[i];
return res;
}
int size_1d()
{
return data_accessor.size_1d();
}
af::c_grid<3,int>::index_type current_index()
{
return data_accessor.index_nd(iterator);
}
bool is_in_reciprocal_space()
{
return grid.reciprocal_flag;
}
void to_reciprocal()
{
if(!is_in_reciprocal_space())
invert();
}
void to_real()
{
if(is_in_reciprocal_space())
invert();
}
bool can_be_fourier_transformed() {
return grid.grid_is_compatible_with_fft();
}
Grid grid;
private:
void Init(int a,int b, int c)
{
data_accessor = af::c_grid<3,int>(a,b,c);
data = af::versa<complex<double>, af::c_grid<3,int> > (data_accessor);
grid_is_initialized=false;
}
af::versa<complex<double>, af::c_grid<3,int> > data;
af::c_grid<3,int> data_accessor;
int iterator;
bool grid_is_initialized;
};
/**
* Function for reading in data from hdf5 format. So far just reads in the "/data" dataset in a file.
* \todo develop the format
* \todo error handling
*/
IntensityMap ReadHDF5(string filename);
template<typename T>
DataType getH5Type();
template <typename T>
void creadeAndWriteDataset(H5File& file, string datasetName, T* data, hsize_t n, hsize_t* dims);
/**
* function writes intensity map in a hdf5 file.
* \todo develop the format
* \todo error handling
*/
void WriteHDF5(string filename,IntensityMap& input);
/**
* Class for wrapping all the datasets which are optionaly provided by user, such as weights, measured pixels and resolution function correction.
*/
class OptionalIntensityMap {
public:
OptionalIntensityMap() : is_loaded(false), default_value(1) //we mainly use these arrays for multipliers, and 1 is neutral there
{ }
OptionalIntensityMap(double def_val) : is_loaded(false), default_value(def_val)
{ }
bool is_loaded;
double default_value;
void load_data(string filename)
{
if(file_exists(filename))
{
intensity_map = ReadHDF5(filename);
is_loaded = true;
}
}
void load_data_and_report(string filename, string dataset_name, vec3<int> expected_size)
{
load_data(filename);
if(is_loaded)
{
if(intensity_map.size()!=expected_size)
{
REPORT(ERROR) << "Dataset " << filename << " has incorrect size (" << intensity_map.size()[0] << " " << intensity_map.size()[1] << " " << intensity_map.size()[2]
<< ") expected (" << expected_size[0] << " " << expected_size[1] << " " << expected_size[2] << ")\n\n";
cout.flush();
throw(TerminateProgram());
}
for(int i=0; i<intensity_map.size_1d(); ++i)
if(intensity_map.at(i)!=intensity_map.at(i)) //isnan
{
REPORT(ERROR) << "Dataset " << filename << " contains NaNs\n\n";
cout.flush();
throw(TerminateProgram());
}
REPORT(MAIN) << "Loaded " << dataset_name << "\n";
}
}
double at(int index)
{
if(is_loaded)
return intensity_map.at(index);
else
return default_value;
}
IntensityMap* get_intensity_map() {
assert(is_loaded);
return &intensity_map;
}
private:
IntensityMap intensity_map;
};
#endif | Unknown |
3D | YellProgram/Yell | src/FormulaParser.h | .h | 1,986 | 71 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef H_FORMULA_PARSER
#define H_FORMULA_PARSER
#include <vector>
#include <string>
#include "precompiled_header.h"
#include <math.h>
using namespace std;
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
typedef iterator_ Iterator;
struct FormulaParser : qi::grammar<Iterator, double()>{
FormulaParser();
typedef qi::rule<Iterator, double()> formula_parser_rule;
formula_parser_rule start;
formula_parser_rule term,fact,expr,assignment,identifier,special_function;
qi::rule<Iterator,string()> valid_identifier;
typedef qi::symbols<char,double> ReferenceTable;
ReferenceTable references;
vector<double> array;
int current_array_value;
formula_parser_rule array_element;
void initialize_refinable_variables(vector<string> names,vector<double> values) {
int number_of_variables=names.size();
for(int i=1; i<number_of_variables; ++i) // minus scale
{
references.add(names.at(i),values.at(i));
}
}
static void add_key(ReferenceTable& table,string key,double val)
{
if(table.find(key)!=NULL)
table.remove(key);
table.add(key,val);
}
static double extract_array_value(vector<double> arr, int index)
{
return arr.at(index);
}
};
#endif
| Unknown |
3D | YellProgram/Yell | src/exceptions.h | .h | 241 | 17 | //
// Created by Arkadiy on 19/02/2016.
//
#ifndef YELL_EXCEPTIONS_H
#define YELL_EXCEPTIONS_H
class TerminateProgram : std::exception {
public:
TerminateProgram() {}
~TerminateProgram() throw() {}
};
#endif //YELL_EXCEPTIONS_H
| Unknown |
3D | YellProgram/Yell | src/InputFileParser.cpp | .cpp | 7,391 | 225 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InputFileParser.h"
// templated funcitons somehow do not get binded with phoenix
void report_after_refinement_dbl(double inp) {
REPORT(AFTER_REFINEMENT) << inp;
}
void report_after_refinement(string inp) {
REPORT(AFTER_REFINEMENT) << inp;
}
InputParser::InputParser() : InputParser::base_type(start)
{
using namespace qi;
using phoenix::bind;
using phoenix::ref;
//check unit cell is initialized
start =
program_options
> unit_cell [_pass = bind(&Model::unit_cell_is_initialized,*ref(model))]
> -modes
> correlations [bind(&Model::add_correlations,*ref(model),_1)]
>> maybe_assignments
>> *(print_command_parser >> maybe_assignments)
;
program_options =
maybe_assignments
>> *(program_option >> maybe_assignments)
;
modes =
lit("Modes")
> "[" >> maybe_assignments
> (*(mode_assignement >> maybe_assignments))[bind(&Model::add_modes,*ref(model),_1)]
> "]"
;
unit_cell =
lit("UnitCell")
> "[" >> maybe_assignments
> *( (variant | variant_assignement) >> maybe_assignments )[bind(&Model::add_variant,*ref(model),_1)]
> "]"
;
correlations %=
lit("Correlations")
> "[" >> maybe_assignments
> *(atomic_pair_pool >> maybe_assignments)
> "]"
;
maybe_assignments = *(formula.assignment >> ';');
program_option =
(lit("Cell") > repeat(6)[number]) [bind(&Model::initialize_unit_cell,*ref(model),_1)]
| (lit("DiffuseScatteringGrid") > repeat(9)[number])[bind(&Model::initialize_intensity_grid,*ref(model),_1)]
| (lit("MaxNumberOfIterations") > int_) [bind(&Model::set_max_number_of_iterations,*ref(model),_1)]
| (lit("MinimizerTau") > double_) [bind(&Model::set_tau,*ref(model),_1)]
| (lit("MinimizerThresholds") > repeat(3)[double_]) [bind(&Model::set_thresholds,*ref(model),_1)]
| (lit("MinimizerDiff") > double_) [bind(&Model::set_diff,*ref(model),_1)]
| (lit("FFTGridSize") > repeat(3)[int_]) [bind(&Model::set_fft_grid_size,*ref(model),_1)]
| (lit("FFTGridPadding") > repeat(3)[int_]) [bind(&Model::set_padding,*ref(model),_1)]
| (lit("DumpPairs") > bool_) [bind(&Model::set_dump_pairs,*ref(model),_1)]
| (lit("CalculateJacobians") > bool_) [bind(&Model::set_calculate_jacobians,*ref(model),_1)]
| program_option1
;
program_option1 =
(lit("Refine") > bool_) [bind(&Model::set_refinement_flag,*ref(model),_1)]
| (lit("ReportPairsOutsideCalculatedPDF") > bool_) [bind(&Model::set_report_pairs_outside_pdf_grid,*ref(model),_1)]
| (lit("PeriodicBoundaries") > repeat(3) [bool_]) [bind(&Model::set_periodic_boundaries,*ref(model),_1)]
| (lit("RecalculateAverage") > bool_) [bind(&Model::set_recalculation_flag,*ref(model),_1)]
| (lit("CalculationMethod") > calculation_methods) [bind(&Model::set_calculation_method,*ref(model),_1)]
| (lit("LaueSymmetry")
> lexeme[point_group_symbol >> !char_("-:/a-zA-Z0-9")]) [bind(&Model::set_point_group,*ref(model),_1)]
| (lit("Scale") > double_ > -(omit[lit('(')>int_>lit(')')]))[bind(&Model::set_scale,*ref(model),_1)]
| (lit("PrintCovarianceMatrix")> bool_) [bind(&Model::set_print_covariance_matrix,*ref(model),_1)]
| refinable_parameters [bind(&Model::set_refinable_parameters,*ref(model),ref(formula),_1)]
| program_option2
;
/* TODO: fixe possible problem coming from the fact that atoms can be defined in molecular scatterers before the
* scattering type is defined in such a case some of the atoms will be default XRay, while other will be Neutrons
* */
program_option2 =
molecular_scatterers
| (lit("Scattering") > scattering_type) [bind(&Model::set_scattering_type,*ref(model),_1)]
;
scattering_type.add
("x-ray", XRay)
("neutron", Neutron)
("electron", Electrons)
;
refinable_parameters %=
lit("RefinableVariables")
> "["
>> *(valid_identifier
> "="
> double_
> -(lit('(') > int_ > lit(')'))
> -lit(';')
)
> "]"
;
string_in_quotes %=
'"'
> *(char_-'"')
> '"'
;
print_command_parser =
lit("Print")[bind(&report_after_refinement,"Requested output:")]
>> *(
(formula.expr >> !char_(';'))[bind(&report_after_refinement_dbl,_1)]
| string_in_quotes[bind(&report_after_refinement,_1)]
)
>> eps[bind(&report_after_refinement,"\n")]
;
calculation_methods.add
("direct",true)
("exact reciprocal",true)
("exact",true)
("reciprocal",true)
("approximate",false)
("approximate pdf",false)
("pdf",false)
("fft",false)
;
point_group_symbol.add
("m-3m", "m-3m")
("m-3", "m-3")
("6/mmm", "6/mmm")
("6/m", "6/m")
("-3mH", "-3mH")
("-3mR", "-3mR")
("-3H", "-3H")
("-3R", "-3R")
("4/mmm", "4/mmm")
("4/m", "4/m")
("mmm", "mmm")
("2/m", "2/m")
("2/mb", "2/mb")
("-1", "-1")
// synonims
("-3:R","-3R")
("-3:H","-3H")
("-3m:H","-3mH")
("-3m:R","-3mR")
("2/m:b","2/mb")
("m3m","m-3m")
;
atomic_pair_pool = lit("[")[_val = phoenix::new_<AtomicPairPool>()]
> *(
cell_shifter [bind(&AtomicPairPool::add_modifier,*_val,_1)]
| multiplicity_correlation [bind(&AtomicPairPool::add_modifier,*_val,_1)]
| substitutional_correlation [bind(&AtomicPairPool::add_modifiers,*_val,_1)]
| adp_correlation [bind(&AtomicPairPool::add_modifier,*_val,_1)]
| size_effect [bind(&AtomicPairPool::add_modifier,*_val,_1)]
)
> "]";
translational_mode =
lit("TranslationalMode")
> '('
> ( identifier > ',' > basis_vector )[_val = bind(&Model::create_translational_mode,*ref(model),_1,_2)]
> ')'
;
rotational_mode =
lit("RotationalMode")
> '('
> ( identifier > repeat(6)[',' > number])[_val = bind(&Model::create_rotational_mode,*ref(model),_1,_2)]
> ')'
;
mode_assignement =
(
valid_identifier
> "="
> (rotational_mode | translational_mode)[_val=_1]
)[bind(InputParser::add_reference,phoenix::ref(references),_1,_2)]
;
InputParserI();
InputParserII();
InputParserIII();
}
| C++ |
3D | YellProgram/Yell | src/InputFileParserI.cpp | .cpp | 4,022 | 102 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InputFileParser.h"
#include <boost/phoenix/statement/try_catch.hpp>
#include <boost/phoenix/core/nothing.hpp>
void InputParser::InputParserI()
{
using namespace qi;
using phoenix::bind;
using phoenix::ref;
cell_shifter = '(' >
( number > ',' > number > ',' > number)[_val = phoenix::new_<CellShifter>(_1,_2,_3)]
> ')'
;
multiplicity_correlation = lit("Multiplicity") > number[_val = phoenix::new_<MultiplicityCorrelation>(_1)];
substitutional_correlation =
lit("SubstitutionalCorrelation")
> "(" //due to some bug, it is necessary to turn try_... into sequence by adding noop in the beginninghttp://stackoverflow.com/questions/32245224/boostphoenix-try-catch-all-construct-fails-to-compile
> (identifier > "," > identifier > "," > number % ',')[phoenix::nothing,
phoenix::try_
[
_val = bind(Model::correlators_from_cuns_,_1,_2,_3)
].catch_all
[
_pass = false
] ]
> ")"
;
adp_correlation =
lit("ADPCorrelation")
> '('
> (identifier > ',' > identifier > ',' > number)[phoenix::nothing,
phoenix::try_
[
_val = bind(&Model::create_double_adp_mode,_1,_2,_3)
].catch_all
[
_pass = false
]]
> ')'
;
size_effect =
lit("SizeEffect")
> '('
> (identifier > ',' > identifier > ',' > number)[phoenix::nothing,
phoenix::try_
[
_val = bind(&Model::create_size_effect,_1,_2,_3)
].catch_all
[
_pass = false
]]
> ')'
;
number %= formula | double_;
skipper_no_assignement = boost::spirit::ascii::space | comment;
skipper = omit[(formula.assignment >> ';')] | skipper_no_assignement;
comment = lit("#") >> *(char_ - eol) >> eol;
basis_vector.add("x",0)("y",1)("z",2);
permutation_component =
eps[_val = phoenix::construct<vector<double> >(4,0)]
>> -basis_vector[_val[_1]=1]
>> *(
('+' >> basis_vector)[_val[_1]=1]
| ('-' >> basis_vector)[_val[_1]=-1]
| (-lit('+') >> double_ >> lit("/") >> int_)[_val[3]=_1/_2]
| ('-' >> double_ >> lit("/") >> int_)[_val[3]=-_1/_2]
| (-lit('+') >> double_)[_val[3]=_1]
| ('-' >> double_)[_val[3]=-_1]
)
;
}; | C++ |
3D | YellProgram/Yell | src/basic_classes.h | .h | 52,162 | 1,694 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef basic_classes_H
#define basic_classes_H
///////#define SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_NO_PRAGMA_OMP
#include <iostream>
#include <scitbx/array_family/versa.h>
#include <scitbx/array_family/accessors/c_grid.h>
#include <scitbx/fftpack/complex_to_complex_3d.h>
#include <cctbx/sgtbx/rt_mx.h>
#include <sstream>
#include "diffuser_core.h"
#include <complex>
#include <map>
#include <math.h>
#include "levmar.h" //for minimizer
#include <scitbx/vec3.h>
#include <scitbx/sym_mat3.h>
#include <vector>
#include <string>
#include <cctbx/eltbx/neutron.h> //these three are for AtomicType
#include <cctbx/eltbx/electron_scattering.h>
#include <cctbx/eltbx/xray_scattering.h>
#include <cctbx/eltbx/xray_scattering/gaussian.h>
#include <cctbx/uctbx.h> //These guys are for cell and
#include <scitbx/array_family/tiny.h>
#include <assert.h>
#include "OutputHandler.h"
using namespace std;
using namespace scitbx;
using namespace cctbx::sgtbx;
extern OutputHandler report;
const int VectorStart=0;
const int VectorEnd=1;
/// Skips check for matrix being symmetric. Just takes upper-triangular part.
sym_mat3<double> trusted_mat_to_sym_mat(mat3<double> inp);
class AtomicPairPool;
class PairModifier {
public:
virtual ~PairModifier() { };
virtual bool generates_pairs()=0;
virtual void modify_pairs(AtomicPairPool* const)=0;
};
/** \brief Class of pointer vectors.
Unsafe class which holds a vector of pointers to some objects,
gives access to them with operator[] and destroys objects that
it is points to on destruction.
Probably, it should be replaced with boost ptr_vector
*/
template<class Obj>
class p_vector{
public:
p_vector(p_vector const &in) {
assert(false); //copy constructur is not implemented
}
p_vector() : pointer_vector()
{}
~p_vector()
{
for(int i=0; i<pointer_vector.size(); i++)
delete pointer_vector[i];
}
void push_back(Obj* a)
{
pointer_vector.push_back(a);
}
void concat(vector<Obj*> a)
{
pointer_vector.insert( pointer_vector.end(), a.begin(), a.end() );
}
int size()
{
return pointer_vector.size();
}
Obj& operator[](int i)
{
return (*pointer_vector[i]);
}
private:
vector<Obj*> pointer_vector;
};
class Atom;
class AtomicPair;
class UnitCell;
/// Holds the laue symmetry of crystal and has function to apply the symmetry. Also keeps track of which elements should be applied on the level of
class LaueSymmetry
{
public:
string label;
/** Sometimes grid for diffuse scattering or PDF is incompatible with crystal Laue symmetry. In such cases generators that are incompatible will be applied to AtomicPairs
*/
vector<string> generators_on_map;
/// Generators of Laue group that could not be applied to the grid directly
vector<string> generators_on_vectors;
LaueSymmetry()
{}
/** This function separates the symmetry generators in those which should be applied on the map and those which should be appliet to AtomicPairs.
Note that if the grid is not provided, Laue class will try to apply all generators on the level of diffuse scattering map and user is responsible to control correctess of the grid steps, and centering.
*/
LaueSymmetry(string const & sym,
Grid const & grid = Grid(cctbx::uctbx::unit_cell(),
vec3<double>(0,0,0),
vec3<double>(0,0,0),
vec3<int>(1,1,1)) ) :
label(sym) {
vector<string> generators = laue_class_generators();
// Я должен признать поражение
// в этих лабиринтах я
// странная манера искать правила и им следовать под наркотой
// Думать об абстрактных концепциях гораздо круче под этой наркотой. Алгебра, все это решает
// я заблудился, стоит мне испепелять этот баг, или есть тчо-то более полезное что я все-таки могу сделать?
for (int i=0; i<generators.size(); ++i)
{
if (generator_can_be_applied_on_the_map(generators[i],grid))
generators_on_map.push_back(generators[i]);
else
{
REPORT(FIRST_RUN) << "Diffuse scattering grid is incompatible with generator " << generators[i] << ". Generator will be applied directly to atomic pairs (slow)\n";
generators_on_vectors.push_back(generators[i]);
}
}
}
/// used in generator_can_be_applied_on_the_map. Checks if grids in two directions are compatible ie have the same step, nuber of pixels and lower limits
bool have_same_step_and_ll(Grid const & grid,string const & axes) {
int ax1=0,ax2;
for (int i=1; i<axes.size(); i+=2) {
//assume we have only xy and xz symbols there
if(axes[i]=='y')
ax2=1;
else
ax2=2;
if( !(grid.grid_size[ax1]==grid.grid_size[ax2] &&
almost_equal(grid.grid_steps[ax1],grid.grid_steps[ax2]) &&
almost_equal(grid.lower_limits[ax1],grid.lower_limits[ax2])) )
return false;
}
return true;
}
/// used in generator_can_be_applied_on_the_map. checks if the center of grid in some direction is at pixel number N/2+1 (counting from 1) for N even or in case N=1 that lower limit is equal to 0;
bool centered_correctly(Grid const & grid,string const & axes) {
int ax;
for(int i=0;i<axes.size();++i)
{
// transform symbols xyz to 012
if (axes[i]=='x')
ax=0;
else if(axes[i]=='y')
ax=1;
else if(axes[i]=='z')
ax=2;
// actual checks
if (grid.grid_size[ax]==1)
{
if(!(almost_equal(grid.lower_limits[ax],0)))
return false;
}
else if(grid.grid_size[ax]%2==1)
return false;
else if(!almost_equal(-grid.lower_limits[ax],0.5*grid.grid_size[ax]*grid.grid_steps[ax]))
return false;
}
return true;
}
/// Used to separate generators in two groups. One group is applied to the map (fast) the other is applied to AtomicPairs (slow)
bool generator_can_be_applied_on_the_map(string generator,Grid const & grid) {
if(generator=="-x,-y,-z")
return centered_correctly(grid,"xyz");
else if(generator=="-x,y,z")
return centered_correctly(grid,"x");
else if(generator=="x,-y,z")
return centered_correctly(grid,"y");
else if(generator=="x,y,-z")
return centered_correctly(grid,"z");
else if(generator=="z,x,y")
return have_same_step_and_ll(grid,"xyxz");
else if(generator=="y,x,z")
return have_same_step_and_ll(grid,"xy");
else if(generator=="-y,x-y,z")
return have_same_step_and_ll(grid,"xy") && centered_correctly(grid,"xy");
else if(generator=="y,x,-z")
return have_same_step_and_ll(grid,"xy") && centered_correctly(grid,"z");
else if(generator=="y,-x,z")
return have_same_step_and_ll(grid,"xy") && centered_correctly(grid,"xy");
else
return true; // or rather throw error
}
vector<string> laue_class_generators() {
vector<string> generators;
if(label=="m-3m")
{
generators.push_back("z,x,y");
generators.push_back("-x,-y,-z");
generators.push_back("-x,y,z");
generators.push_back("x,-y,z");
generators.push_back("y,x,z");
}else if(label=="m-3")
{
generators.push_back("z,x,y");
generators.push_back("-x,-y,-z");
generators.push_back("-x,y,z");
generators.push_back("x,-y,z");
}else if(label=="6/mmm")
{
generators.push_back("-x,-y,-z");
generators.push_back("y,x,z");
generators.push_back("x,y,-z");
generators.push_back("-y,x-y,z");
}
else if(label=="6/m")
{
generators.push_back("-x,-y,-z");
generators.push_back("x,y,-z");
generators.push_back("-y,x-y,z");
}
else if(label=="-3mH")
{
generators.push_back("-x,-y,-z");
generators.push_back("y,x,-z");
generators.push_back("-y,x-y,z");
}
else if(label=="-3mR")
{
generators.push_back("-x,-y,-z");
generators.push_back("y,x,z");
generators.push_back("z,x,y");
}
else if(label=="-3H")
{
generators.push_back("-x,-y,-z");
generators.push_back("-y,x-y,z");
}
else if(label=="-3R")
{
generators.push_back("-x,-y,-z");
generators.push_back("z,x,y");
}
else if(label=="4/mmm")
{
generators.push_back("-x,-y,-z");
generators.push_back("-x,y,z");
generators.push_back("x,-y,z");
generators.push_back("y,x,z");
}
else if(label=="4/m")
{
generators.push_back("y,-x,z"); // four fold rotation
generators.push_back("-x,-y,-z");
}
else if(label=="mmm")
{
generators.push_back("-x,-y,-z");
generators.push_back("-x,y,z");
generators.push_back("x,-y,z");
}
else if(label=="2/m")
{
generators.push_back("-x,-y,-z");
generators.push_back("x,y,-z");
}
else if(label=="2/mb")
{
generators.push_back("-x,-y,-z");
generators.push_back("x,-y,z");
}else if(label=="-1")
{
generators.push_back("-x,-y,-z");
}
return generators;
}
vector<AtomicPair> filter_pairs_from_asymmetric_unit(vector<AtomicPair>& pairs);
// радужная пена - это подарок нам из ЛСД
// все чувства задействованы
void apply_patterson_symmetry(IntensityMap& map)
{
for (int i=0; i<generators_on_map.size(); ++i)
apply_generator(map,generators_on_map[i]);
}
vector<AtomicPair> apply_patterson_symmetry(vector<AtomicPair> pairs)
{
for(int i=0; i<generators_on_vectors.size(); ++i)
{
rt_mx generator(generators_on_vectors[i]);
pairs = apply_matrix_generator(pairs,generator.r().as_double(),generator.r().order());
}
return pairs;
}
/// Applies generator to IntensityMap
/**
Explicitely applies all generators. Hopefully this way is faster.
*/
void apply_generator(IntensityMap& map,string generator_symbol)
{
double t;
vec3<int> size = map.size();
if(generator_symbol=="-x,-y,-z") // -1
for(int i=size[0]/2; i<size[0]; ++i)
for(int j=1; j<size[1]; ++j)
for(int k=1; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(size[0]-i,size[1]-j,size[2]-k))/2;
map.at(i,j,k) = t;
map.at(size[0]-i,size[1]-j,size[2]-k) = t;
}
else if(generator_symbol=="-x,y,z") // mx
for(int i=size[0]/2; i<size[0]; ++i)
for(int j=0; j<size[1]; ++j)
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(size[0]-i,j,k))/2;
map.at(i,j,k) = t;
map.at(size[0]-i,j,k) = t;
}
else if(generator_symbol=="x,-y,z") //my
for(int i=0; i<size[0]; ++i)
for(int j=size[1]/2; j<size[1]; ++j)
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(i,size[1]-j,k))/2;
map.at(i,j,k) = t;
map.at(i,size[1]-j,k) = t;
}
else if(generator_symbol=="x,y,-z") //mz
for(int i=0; i<size[0]; ++i)
for(int j=0; j<size[1]; ++j)
for(int k=size[2]/2; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(i,j,size[2]-k))/2;
map.at(i,j,k) = t;
map.at(i,j,size[2]-k) = t;
}
else if(generator_symbol=="z,x,y") //3 along 111
for(int i=0; i<size[0]; ++i)
for(int j=0; j<size[1]; ++j)
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(k,i,j) + map.at(j,k,i))/3;
map.at(i,j,k) = t;
map.at(k,i,j) = t;
map.at(j,k,i) = t;
}
else if(generator_symbol=="y,x,z") //mx-y
for(int i=0; i<size[0]; ++i)
for(int j=0; j<size[1]; ++j)
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(j,i,k))/2;
map.at(i,j,k) = t;
map.at(j,i,k) = t;
}
else if(generator_symbol=="-y,x-y,z") // three-fold rotation axis in hexagonal settings
if(map.grid.reciprocal_flag)
{
//we need to apply symmetry element reciprocal to -y,x-y,z namely y,-x-y,z and -x-y,x,z
for(int i=1; i<size[0]; ++i)
for(int j=max(size[0]/2-i+1,1); j<min(size[0]*3/2-i,size[1]); ++j) //note that here are strange borders
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(j,size[0]*3/2-i-j,k) + map.at(size[0]*3/2-i-j,i,k))/3;
map.at(i,j,k) = t;
map.at(size[0]*3/2-i-j,i,k) = t;
map.at(j,size[0]*3/2-i-j,k) = t;
}
}
else {
for(int i=1; i<size[0]; ++i)
for(int j=max(i-size[0]/2+1,1); j<min(i+size[0]/2,size[1]); ++j) //note that here are strange borders
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(size[0]-j,size[0]/2+i-j,k) + map.at(size[0]/2+j-i,size[0]-i,k))/3;
map.at(i,j,k) = t;
map.at(size[0]-j,size[0]/2+i-j,k) = t;
map.at(size[0]/2+j-i,size[0]-i,k) = t;
}
}
else if(generator_symbol=="y,x,-z") //2-fold xy direction
for(int i=0; i<size[0]; ++i)
for(int j=0; j<size[1]; ++j)
for(int k=size[2]/2; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(j,i,size[2]-k))/2;
map.at(i,j,k) = t;
map.at(j,i,size[2]-k) = t;
}
else if(generator_symbol=="y,-x,z") // Four-fold rotation applied four times.
for(int j=size[0]/2; j<size[1]; ++j)
for(int i=size[1]/2; i<size[0]; ++i)
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,j,k) + map.at(j,size[1]-i,k) + map.at(size[0]-j,i,k) + map.at(size[0]-i,size[1]-j,k))/4;
map.at(i,j,k) = t;
map.at(j,size[1]-i,k) = t;
map.at(size[0]-j,i,k) = t;
map.at(size[0]-i,size[1]-j,k) = t;
}
// And then a special case for j=0 since there we need to make sure that -y coordinate is again at 0 pixel, or is it????
int j=0;
for(int i=1; i<size[0]; ++i)
for(int k=0; k<size[2]; ++k)
{
t=(map.at(i,0,k) + map.at(0,size[1]-i,k) + map.at(0,i,k) + map.at(size[0]-i,0,k))/4;
map.at(i,0,k) = t;
map.at(0,size[1]-i,k) = t;
map.at(0,i,k) = t;
map.at(size[0]-i,0,k) = t;
}
}
bool is_compatible_with_cell(const UnitCell& cell);
/// Applies transformation matrix to atomic pair
vector<AtomicPair> multiply_pairs_by_matrix(vector<AtomicPair> pairs,mat3<double> transformation_matrix);
/// Applies
vector<AtomicPair> filter_pairs_from_asymmetric_unit_and_scale(vector<AtomicPair>& pairs);
/// Applies generator which is expressed in matrix form to pairs.
/**
\param transformation_matrix in the trasformation matrix to be applied
\param times the class of generator
*/
vector<AtomicPair> apply_matrix_generator(vector<AtomicPair> pairs,mat3<double> transformation_matrix,int times);
};
class ChemicalUnit
{
public:
virtual ~ChemicalUnit() { };
virtual double get_occupancy()=0;
virtual void set_occupancy(double)=0;
virtual vector<Atom*> get_atoms() =0;
virtual ChemicalUnit* create_symmetric(mat3<double>,vec3<double>) =0;
virtual ChemicalUnit* operator[](int) =0;
};
class AtomicAssembly : public ChemicalUnit
{
public:
AtomicAssembly()
{}
AtomicAssembly(vector<ChemicalUnit*> units)
{
for(int i=0; i<units.size(); i++)
chemical_units.push_back(units[i]);
}
void add_chemical_unit(ChemicalUnit * unit)
{
chemical_units.push_back(unit);
}
double get_occupancy()
{ return occupancy;}
void set_occupancy(double _occ)
{
occupancy=_occ;
for(int i=0; i<chemical_units.size(); ++i)
chemical_units[i].set_occupancy(_occ);
}
vector<Atom*> get_atoms()
{
vector<Atom*> atoms;
vector<Atom*> t;
for(int i=0; i<chemical_units.size(); i++)
{
t=chemical_units[i].get_atoms();
atoms.insert(atoms.end(),t.begin(),t.end());
}
return atoms;
}
AtomicAssembly* create_symmetric(mat3<double> sym_matrix,vec3<double> translation)
{
AtomicAssembly* result = new AtomicAssembly();
for(int i=0; i<chemical_units.size(); i++)
result->add_chemical_unit(chemical_units[i].create_symmetric(sym_matrix,translation));
return result;
}
ChemicalUnit* operator[](int n)
{
return &chemical_units[n];
}
double occupancy;
p_vector<ChemicalUnit> chemical_units;
};
class ChemicalUnitNode{
public:
ChemicalUnitNode()
{}
void add_chemical_unit(ChemicalUnit* unit)
{
chemical_units.push_back(unit);
}
p_vector<ChemicalUnit> chemical_units;
bool complain_if_sum_of_occupancies_is_not_one()
{
double sum=0;
for(int i=0; i<chemical_units.size(); ++i)
sum+=chemical_units[i].get_occupancy();
if(almost_equal(1,sum))
return true;
else
REPORT(ERROR) << "The sum of occupancies should be 1. Here it is " << sum << "\n";
return false;
}
};
class UnitCell
{
public:
cctbx::uctbx::unit_cell cell;
LaueSymmetry laue_symmetry;
UnitCell() { }
UnitCell(double a,double b, double c, double alpha, double beta, double gamma) :
cell(scitbx::af::tiny<double,6>(a,b,c,alpha,beta,gamma))
{ }
void set_laue_symmetry(string sym)
{
laue_symmetry=LaueSymmetry(sym);
}
void add_node(ChemicalUnitNode* node)
{
chemical_unit_nodes.push_back(node);
}
/**
* Function for test purposes. For now checks that unit cell parameters are almost equal.
*/
bool operator==(const UnitCell& inp)
{
return almost_equal(cell.parameters(),inp.cell.parameters());
}
string to_string()
{
std::ostringstream res;
for(int i=0; i<6; ++i)
res << cell.parameters()[i] << " ";
return res.str();
}
//private:
p_vector<ChemicalUnitNode> chemical_unit_nodes;
};
class ADPMode;
sym_mat3<double> outer_product(vec3<double> v1, vec3<double> v2);
class SubstitutionalCorrelation;
ADPMode* translational_mode(ChemicalUnit* unit,int direction,sym_mat3<double>);
ADPMode z_rot_mode(ChemicalUnit* unit);
ADPMode* rot_mode(ChemicalUnit* unit,vec3<double> axis , vec3<double> point_on_axis ,sym_mat3<double> metrical_matrix);
ADPMode combine_modes(vector<ADPMode> modes);
vector<SubstitutionalCorrelation*> correlators_from_cuns(ChemicalUnitNode* node1,ChemicalUnitNode* node2,vector<double> corr);
enum ScatteringType {XRay, Neutron, Electrons}; //TODO: after changing to C++11 change to enum class
class Scatterer;
class AtomicTypeCollection
{
public:
AtomicTypeCollection() { }
~AtomicTypeCollection();
static AtomicTypeCollection& get();
map<string,Scatterer*> types;
static void calculate_form_factors_of_all_atoms_on_grid(vec3<int>map_size, Grid grid);
static void update_current_form_factors(vec3<double> s, double d_star_square);
/** Creates AtomicType and registers it in ~AtomicTypeCollection. if it is already registered returns existing AtType
*/
static Scatterer* get(string const & label, ScatteringType t);
static string strip_label(string const & label);
static void add(string const & label, Scatterer* s);
};
class Scatterer {
public:
virtual complex<double> form_factor_at_c(vec3<double>s, double d_star_sq)=0;
virtual double form_factor_at(double d_star_sq)=0;
virtual ~Scatterer() {};
void update_current_form_factor(vec3<double>s,double d_star_sq) {
current_form_factor=form_factor_at_c(s,d_star_sq);
}
void calculate_form_factors_on_grid(vec3<int>map_size,Grid grid)
{
gridded_form_factors = IntensityMap(map_size);
gridded_form_factors.set_grid(grid);
gridded_form_factors.init_iterator();
while(gridded_form_factors.next())
{
AtomicTypeCollection::update_current_form_factors(gridded_form_factors.current_s(), gridded_form_factors.current_d_star_square());
gridded_form_factors.current_array_value_c()=current_form_factor;
}
}
IntensityMap gridded_form_factors;
complex<double> current_form_factor; ///< here form factor for direct calculation will be cached
};
//gives access to computation of X-ray atomic form factor
class AtomicType : public Scatterer {
public:
AtomicType()
{}
AtomicType(string const & _label) {
cctbx::eltbx::xray_scattering::wk1995 wk(_label);
gauss=wk.fetch();
}
double form_factor_at(double d_star_sq) {
return gauss.at_d_star_sq(d_star_sq); //TODO: check funny sequence here. The entry with _c seems to be real which is ok for normal scattering though
}
complex<double> form_factor_at_c(vec3<double> s, double d_star_sq) {
return form_factor_at(d_star_sq);
}
private:
cctbx::eltbx::xray_scattering::gaussian gauss;
};
// TODO: add tests
// TODO: remove copy-pastes in this code
//gives access to computation of Neutron atomic form factor
class NeutronScattererAtom : public Scatterer {
public:
NeutronScattererAtom()
{}
NeutronScattererAtom(string const & _label) :
scat_table_entry(_label)
{}
double form_factor_at(double) {
return 0; //TODO: check why is this one needed at all
}
complex<double> form_factor_at_c(vec3<double>s,double d_star_sq) {
return scat_table_entry.bound_coh_scatt_length();
}
private:
cctbx::eltbx::neutron::neutron_news_1992_table scat_table_entry;
};
class ElectronScattererAtom : public Scatterer {
public:
ElectronScattererAtom()
{}
ElectronScattererAtom(string const & _label) {
cctbx::eltbx::electron_scattering::peng1996 wk(_label);
gauss=wk.fetch();
}
double form_factor_at(double d_star_sq) {
return gauss.at_d_star_sq(d_star_sq); //TODO: check funny sequence here. The entry with _c seems to be real which is ok for normal scattering though
}
complex<double> form_factor_at_c(vec3<double> s, double d_star_sq) {
return form_factor_at(d_star_sq);
}
private:
cctbx::eltbx::xray_scattering::gaussian gauss;
};
class MolecularScatterer : public Scatterer {
public:
MolecularScatterer(ChemicalUnit* molecule) {
constituent_atoms = molecule->get_atoms();
}
double form_factor_at(double t) {
return 0;
}
complex<double> form_factor_at_c(vec3<double>s,double d_star_sq);
private:
vector<Atom*> constituent_atoms;
inline static complex<double> form_factor_in_a_point(complex<double> f,
double p,
double N,
vec3<double> r,
sym_mat3<double> U,
vec3<double> s);
};
//This is just a structure which holds occupancy, position and ADP-tensor
//used in atom and AtomicPair
class AtomicParams {
public:
double occupancy;
vec3<double> r;
sym_mat3<double> U;
//on windows cygwin gets _U defined as numeric constant from somewhere
AtomicParams(double _occupancy, vec3<double> _r, sym_mat3<double> _Uinp) : occupancy(_occupancy), r(_r), U(_Uinp)
{}
AtomicParams()
{}
/// Operator for test functions. returns true if all variables of both input classes are almost equal
bool operator== (const AtomicParams& inp) const
{
return almost_equal(occupancy,inp.occupancy) && almost_equal(r,inp.r) && almost_equal(U,inp.U);// TODO:check ADPs
}
};
///TODO: make sure that precessor constructors are not accessible
///TODO: change the name U to beta
class Atom : public ChemicalUnit
{
public:
string label;
Scatterer* atomic_type;
double occupancy;
double multiplier; //< Variable which holds say a multiplier which comes from symmetry. Like occupancy, but is not affected by the SubstitutionalCorrelation logic
vec3<double> r;
sym_mat3<double> U;
Atom()
{}
/// Atom initialization with Uiso and metric tensor.
Atom(string const & _label,double _multiplier, double _occupancy,
double r1, double r2, double r3,
double Uiso,
sym_mat3<double> reciprocal_metric_tensor,
ScatteringType scattering_type = XRay) :
multiplier(_multiplier), occupancy(_occupancy),label(_label),r(r1,r2,r3), U(Uiso*reciprocal_metric_tensor)
{
atomic_type=AtomicTypeCollection::get(_label, scattering_type);
}
/// Function only used for tests.
Atom(string const & _label, double _occupancy,
double r1, double r2, double r3, //position
double U11, double U22, double U33, double U12, double U13, double U23) : //ADP
occupancy(_occupancy), r(r1,r2,r3), U(U11,U22,U33,U12,U13,U23),label(_label), multiplier(1)
{
atomic_type=AtomicTypeCollection::get(_label, XRay);
}
/// Atom initialization. Be careful, even though they are called Uij, the input parameters are supposed to be Uij/aiaj.
Atom(string const & _label, double _multiplier, double _occupancy,
double r1, double r2, double r3, //position
double U11, double U22, double U33, double U12, double U13, double U23,
ScatteringType scattering_type = XRay) : //ADP
multiplier(_multiplier), occupancy(_occupancy), r(r1,r2,r3), U(U11,U22,U33,U12,U13,U23),label(_label)
{
atomic_type=AtomicTypeCollection::get(_label, scattering_type);
}
double get_occupancy(){
return occupancy;
}
void set_occupancy(double _occupancy){
occupancy = _occupancy;
}
vector<Atom*> get_atoms() {
vector<Atom*> v;
v.push_back(this);
return v;
}
Atom* create_symmetric(mat3<double> transformation_matrix,vec3<double> translation)
{
Atom* result = new Atom( *this );
result->r=transformation_matrix*r+translation;
result->U=trusted_mat_to_sym_mat(transformation_matrix*U*transformation_matrix.transpose());
return result;
}
ChemicalUnit* operator[](int n)
{
throw "atom is a leaf node";
}
bool operator==(const Atom & inp)
{
return almost_equal(occupancy,inp.occupancy) && almost_equal(r,inp.r) && almost_equal(U,inp.U) && atomic_type==inp.atomic_type;
}
};
class AtomicPair {
public:
AtomicPair()
{}
//Most useful constructor which makes atomic pair form 2 atoms
AtomicPair(Atom& _atom1, Atom& _atom2) :
real(_atom1.occupancy * _atom2.occupancy,_atom2.r-_atom1.r, _atom1.U+_atom2.U),
average(_atom1.occupancy * _atom2.occupancy,_atom2.r-_atom1.r, _atom1.U+_atom2.U),
atomic_type1(_atom1.atomic_type),
atomic_type2(_atom2.atomic_type),
multiplier(_atom1.multiplier * _atom2.multiplier),
atom1(&_atom1),
atom2(&_atom2)
{}
//next three accessors return parameters of either average or real atomic pair
//depending on the value of average_flag
double& p(bool average_flag=false)
{
return params(average_flag).occupancy;
}
vec3<double>& r(bool average_flag=false)
{
return params(average_flag).r;
}
sym_mat3<double>& U(bool average_flag=false)
{
return params(average_flag).U;
}
double& average_p()
{
return p(true);
}
double& real_p()
{
return p(false);
}
vec3<double>& average_r()
{ return r(true); }
vec3<double>& real_r()
{ return r(false); }
sym_mat3<double>& average_U()
{ return U(true); }
sym_mat3<double>& real_U()
{ return U(false); }
Scatterer* atomic_type1;
Scatterer* atomic_type2;
double multiplier; //< Takes care of pair multiplicity due to symmetry. Supposed to be equal to 1/multiplicity.
Atom *atom1, *atom2;
bool operator==(const AtomicPair& inp)
{
return average==inp.average & real==inp.real & atom1==inp.atom1 & atom2==inp.atom2 & almost_equal(multiplier, inp.multiplier);
}
bool pair_is_withing(Grid grid)
{
for(int i=0;i<3; ++i)
if(abs(average_r()[i])>abs(grid.lower_limits[i]))
return false;
return true;
}
string to_string()
{
std::ostringstream oss;
oss << atom1->label << ' ' << atom2->label << ' ' << multiplier << ' ' << p() << ' ' << r()[0] << ' ' << r()[1] << ' ' << r()[2];
for(int j=0; j<6; ++j)
oss << ' ' << U()[j];
oss << ' ' << average_p() << ' ' << average_r()[0] << ' ' << average_r()[1] << ' ' << average_r()[2];
for(int j=0; j<6; ++j)
oss << ' ' << average_U()[j];
return oss.str();
}
private:
AtomicParams& params(bool average_flag)
{
if(average_flag)
return average;
else
return real;
}
AtomicParams real; //parameters of a pair in disordered and
AtomicParams average; //in average structure
};
/**
* Adds values of small_piece array to corresponding vectors of accumulator.
* \param r vector from lower left corner of accumulator to center of small_piece matrix, center assumed to be in point size/2 + 1
*/
void add_pair_to_appropriate_place(IntensityMap & small_piece,IntensityMap & accumulator,vec3<int> r,vector<bool> periodic);
/**
* Prints vector in standart output.
* For test reasons since elements of vec3 are not visible in debugger
*/
template<class NumType>
void print_vector(vec3<NumType> v)
{
cout << v[0] << " " << v[1] << " " << v[2] << endl;
}
class IntnsityCalculator {
public:
static void calculate_patterson_map_from_pairs_f(vector<AtomicPair>pairs,IntensityMap& patterson_map,bool average_flag,vec3<int> pair_grid_size,vector<bool> periodic_directions = vector<bool>(3,false))
{
double d_star_square;
complex<double> f1,f2;
vec3<double> s,r_res;
vec3<int> r_grid;
double scale = patterson_map.size_1d(); // we need to multiply the signal by this, to preserve scaling
for(int i=0; i<patterson_map.size_1d(); ++i)
patterson_map.at_c(i)=0;
//std::vector<AtomicPair>::iterator pair;
AtomicPair* pair;
//cout << "pmap "<< patterson_map.grid_steps()[0] << patterson_map.grid_steps()[1] << " " << patterson_map.grid_steps()[2] << endl;
Grid grid_for_pairs_p(patterson_map.unit_cell(),
patterson_map.grid_steps(),
patterson_map.grid_steps().each_mul(-pair_grid_size/2),//Center is in position pair_grid_size/2+1
patterson_map.grid.reciprocal_flag); // going to be false for direct space, i believe
Grid grid_for_pairs_r=grid_for_pairs_p.reciprocal(); // grid in reciprocal (diffse scattering) space
AtomicTypeCollection::calculate_form_factors_of_all_atoms_on_grid(pair_grid_size,grid_for_pairs_r);
omp_set_num_threads(8);
#pragma omp parallel for private(s,r_res,r_grid,d_star_square,f1,f2,pair)
//shared(patterson_map)
for (int i=0; i< pairs.size(); ++i)
{
pair=&pairs[i];
IntensityMap pair_patterson_map(pair_grid_size);
pair_patterson_map.set_grid(grid_for_pairs_r);
grid_and_residual(pair->average_r(),patterson_map.grid,r_grid,r_res);
if (!average_flag)
r_res+=pair->r()-pair->average_r();
pair_patterson_map.init_iterator();
while(pair_patterson_map.next())
{
s=pair_patterson_map.current_s();
d_star_square=pair_patterson_map.current_d_star_square();
f1=pair->atomic_type1->gridded_form_factors.at_c(pair_patterson_map.current_index());
f2=pair->atomic_type2->gridded_form_factors.at_c(pair_patterson_map.current_index());
pair_patterson_map.current_array_value_c()=scale*calculate_scattering_from_a_pair_in_a_point_c(f1,f2,
pair->p(average_flag),
pair->multiplier,
s,
r_res,
pair->U(average_flag));
}
pair_patterson_map.invert();
#pragma omp critical
add_pair_to_appropriate_place(pair_patterson_map,patterson_map,r_grid,periodic_directions);
}
}
static void calculate_scattering_from_pairs(vector<AtomicPair>pairs,IntensityMap& I,bool average_flag)
{
double d_star_square;
complex<double> f1,f2;
vec3<double> s;
AtomicPair* pair;
I.init_iterator();
while(I.next())
{
s=I.current_s();
d_star_square=I.current_d_star_square();
AtomicTypeCollection::update_current_form_factors(s,d_star_square);
int sz=pairs.size();
double Intensity_in_current_point = 0;
//#pragma omp parallel for default(shared) private(f1,f2,pair) shared(d_star_square,s,average_flag) reduction(+: Intensity_in_current_point)
for ( int i=0; i<sz; i++ )
{
pair = &pairs[i];
f1=pair->atomic_type1->current_form_factor;
f2=pair->atomic_type2->current_form_factor;
Intensity_in_current_point+=real(calculate_scattering_from_a_pair_in_a_point_c(
f1,
f2,
pair->p(average_flag),
pair->multiplier,
s,
pair->r(average_flag),
pair->U(average_flag)));
}
I.current_array_value() = Intensity_in_current_point;
}
}
inline static complex<double> calculate_scattering_from_a_pair_in_a_point_c(complex<double> const & f1, complex<double> const & f2, //form factors at the point
double const & p, //joint probability
double const & N, //multiplier
vec3<double> const & s, //vector of reciprocal coordinates of the point
vec3<double> const & r, //vector of distance between atoms in a pair
sym_mat3<double> const & U) //tensor of ADP of prevoius vector
{
return conj(f1)*f2*p*N*exp( complex<double>(M2PISQ*(s*U*s),M_2PI*(s*r)) );
}
class UnknownSymmetry {};
};
class AtomicPairPool {
public:
AtomicPairPool()
{}
AtomicPair& get_pair(Atom * atom1,Atom * atom2)
{
for(vector<AtomicPair>::iterator pair = pairs.begin(); pair != pairs.end(); pair++)
{
if(pair->atom1 == atom1 && pair->atom2 == atom2)
return *pair;
}
pairs.push_back(AtomicPair(*atom1,*atom2));
return pairs.back();
}
void add_modifiers(vector<SubstitutionalCorrelation*> _modifiers)
{
vector<SubstitutionalCorrelation*>::iterator it;
for(it=_modifiers.begin(); it!=_modifiers.end(); it++)
modifiers.push_back((PairModifier*)(*it));
}
void add_modifier(PairModifier* modifier)
{
modifiers.push_back(modifier);
}
/* void add_modifiers(vector<PairModifier*> _modifiers)
{
modifiers.concat(_modifiers);
}*/
void invoke_correlators()
{
vector<PairModifier*> non_generating_modifiers;
//int s = modifiers.size();
//Invoke all generating modifiers
for(int i=0; i<modifiers.size(); i++)
{
if(modifiers[i].generates_pairs())
{
modifiers[i].modify_pairs(this);
} else {
non_generating_modifiers.push_back(&modifiers[i]);
}
}
vector<PairModifier*>::iterator it;
for(it=non_generating_modifiers.begin(); it!=non_generating_modifiers.end(); it++)
{
(*it)->modify_pairs(this);
}
}
vector<AtomicPair> pairs;
//private:
p_vector<PairModifier> modifiers;
};
class CellShifter : public PairModifier
{
public:
CellShifter(double r1, double r2, double r3) :
shift(r1,r2,r3)
{}
bool generates_pairs()
{ return false; }
void modify_pairs(AtomicPairPool* const pool)
{
for(vector<AtomicPair>::iterator pair = pool->pairs.begin(); pair != pool->pairs.end(); pair++)
{
pair->r()+=shift;
pair->average_r()+=shift;
}
}
bool operator==(const CellShifter& inp)
{
return almost_equal(shift,inp.shift);
}
vec3<double> shift;
};
class SubstitutionalCorrelation : public PairModifier{
public:
SubstitutionalCorrelation(ChemicalUnit* unit1, ChemicalUnit* unit2, double _joint_probability) :
joint_probability(_joint_probability)
{
chemical_units[0] = unit1;
chemical_units[1] = unit2;
}
bool generates_pairs()
{ return true; }
void modify_pairs(AtomicPairPool* const pool)
{
vector<Atom*> atoms1=chemical_units[0]->get_atoms();
vector<Atom*> atoms2=chemical_units[1]->get_atoms();
vector<Atom*>::iterator atom1, atom2;
for(atom1=atoms1.begin(); atom1!=atoms1.end(); atom1++)
{
for(atom2=atoms2.begin(); atom2!=atoms2.end(); atom2++)
{
pool->get_pair(*atom1,*atom2).p()=joint_probability;
}
}
}
/**
* Comparison for test purposes. Now only works if the object references to the same chemical units.
* does not work when the order of chemical units is different, which is correct behavior in current program implementation (because symmetry is not yet attached to chemical untis)
* \TODO implement comparison when chemical units are not identical but equivalent once the comparison of chemical units is implemented
*/
bool operator==(const SubstitutionalCorrelation& inp)
{
return almost_equal(joint_probability,inp.joint_probability) && chemical_units[0]==inp.chemical_units[0] && chemical_units[1]==inp.chemical_units[1];
}
ChemicalUnit* chemical_units[2];
double joint_probability;
};
class AtomicDisplacement{
public:
Atom* atom;
vec3<double> displacement_vector;
bool operator==(const AtomicDisplacement& inp)
{
return atom==inp.atom && almost_equal(displacement_vector, inp.displacement_vector);
}
};
class ADPMode
{
public:
ADPMode()
{}
void add_atom(Atom* _atom, vec3<double> r)
{
AtomicDisplacement t;
t.atom = _atom;
t.displacement_vector = r;
atomic_displacements.push_back(t);
}
vector<AtomicDisplacement> atomic_displacements;
/**
* Operator for test functions.
*/
bool operator==(const ADPMode& inp)
{
if(inp.atomic_displacements.size()!=atomic_displacements.size())
return false;
for(int i=0; i<atomic_displacements.size(); i++)
if(!(atomic_displacements[i]==inp.atomic_displacements[i]))
return false;
return true;
}
/**
* Operator for test functions
*/
bool operator!=(const ADPMode& inp)
{
return !operator==(inp);
}
};
class DoubleADPMode : public PairModifier{
public:
DoubleADPMode(ADPMode* mode1,ADPMode* mode2,double _amplitude)
:amplitude(_amplitude)
{
modes[0]=mode1;
modes[1]=mode2;
}
bool generates_pairs()
{ return true; }
void modify_pairs(AtomicPairPool* const pool)
{
vector<AtomicDisplacement>::iterator disp1,disp2;
for(disp1=modes[0]->atomic_displacements.begin(); disp1!=modes[0]->atomic_displacements.end(); disp1++)
{
for(disp2=modes[1]->atomic_displacements.begin(); disp2!=modes[1]->atomic_displacements.end(); disp2++)
{
sym_mat3<double> U=pool->get_pair(disp1->atom,disp2->atom).U();
pool->get_pair(disp1->atom,disp2->atom).U()+= -amplitude*(outer_product(disp1->displacement_vector,disp2->displacement_vector)+outer_product(disp2->displacement_vector,disp1->displacement_vector));
// TODO: CHECK WHY THERE IS factor 2 here. I think it is WRONG!. Check some special case with perfect correlation between x and y and see if matrices will become ill-defined
if(false)
{
sym_mat3<double> U1=pool->get_pair(disp1->atom,disp2->atom).U();
sym_mat3<double> O = outer_product(disp1->displacement_vector,disp2->displacement_vector);
vec3<double> r = pool->get_pair(disp1->atom,disp2->atom).r();
for(int i=0; i<6; i++)
cout << " " << U[i];
cout << endl;
for(int i=0; i<6; i++)
cout << " " << O[i];
cout << endl;
for(int i=0; i<3; i++)
cout << " " << r[i];
cout << endl;
for(int i=0; i<6; i++)
cout << " " << U1[i];
cout << endl;
cout << "go\n";
}
}
}
}
bool operator==(const DoubleADPMode& inp)
{
return inp.modes[0]==modes[0] && inp.modes[1]==modes[1] && almost_equal(amplitude, inp.amplitude);
}
private:
ADPMode* modes[2];
double amplitude;
};
template<class T>
vector<T> unique_elements(vector<T> inp)
{
vector<T> res;
sort (inp.begin(),inp.end());
unique_copy( inp.begin(), inp.end(), back_inserter(res) );
return res;
}
class StaticShift : public PairModifier
{
public:
StaticShift()
{
}
bool generates_pairs()
{ return true; }
struct ModeAndAmplitude
{
ADPMode* mode;
double amplitude;
};
void add_displacement(const int& StartOrEnd, ADPMode* mode,double amplitude)
{
if (StartOrEnd!=0 && StartOrEnd!=1)
throw string("StartOrEnd flag should be 0 for start or 1 for end");
ModeAndAmplitude ma={mode,amplitude};
modes_and_amplitudes[StartOrEnd].push_back(ma);
}
void modify_pairs(AtomicPairPool* const pool)
{
vector<Atom*> atoms[2];
vector<vec3<double> > displacements[2];
vector<ModeAndAmplitude>::iterator mode_and_amplitude;
vector<AtomicDisplacement>::iterator at_disp;
for(int st_end=0; st_end<2; st_end++)
for(mode_and_amplitude=modes_and_amplitudes[st_end].begin(); mode_and_amplitude!=modes_and_amplitudes[st_end].end(); mode_and_amplitude++)
for(at_disp = mode_and_amplitude->mode->atomic_displacements.begin(); at_disp!=mode_and_amplitude->mode->atomic_displacements.end(); at_disp++)
{
atoms[st_end].push_back(at_disp->atom);
displacements[st_end].push_back(at_disp->displacement_vector*mode_and_amplitude->amplitude);
}
vector<Atom*>::iterator atom1, atom2;
vector<vec3<double> >::iterator displacement1,displacement2;
vector<Atom*> unique_atoms=unique_elements(atoms[0]);
for(atom1=unique_atoms.begin(); atom1!=unique_atoms.end(); atom1++)
{
for(atom2=atoms[1].begin(), displacement2=displacements[1].begin(); atom2!=atoms[1].end(); atom2++,displacement2++)
{
pool->get_pair(*atom1,*atom2).r()+=*displacement2;
}
}
unique_atoms=unique_elements(atoms[1]);
for(atom1=atoms[0].begin(), displacement1=displacements[0].begin(); atom1!=atoms[0].end(); atom1++,displacement1++)
{
for(atom2=unique_atoms.begin(); atom2!=unique_atoms.end(); atom2++)
{
pool->get_pair(*atom1,*atom2).r()-=*displacement1;
}
}
}
vector<ModeAndAmplitude> modes_and_amplitudes[2]; //< shift modes of start [0] and end[1] PDF vectors
};
class SizeEffect : public PairModifier {
public:
bool generates_pairs()
{ return true; }
SizeEffect(ADPMode* _mode, ChemicalUnit* _cu, double _amplitude) :
cu(_cu),mode(_mode),amplitude(_amplitude),cu_to_adp_mode(false)
{ };
SizeEffect(ChemicalUnit* _cu,ADPMode* _mode, double _amplitude) :
cu(_cu),mode(_mode),amplitude(_amplitude),cu_to_adp_mode(true)
{ };
void modify_pairs(AtomicPairPool* const pool)
{
//Implement
vector<Atom*> atoms = cu->get_atoms();
vector<Atom*>::iterator atom;
vector<AtomicDisplacement>::iterator atomic_displacement;
for(atom = atoms.begin(); atom!=atoms.end(); atom++)
for(atomic_displacement = mode->atomic_displacements.begin(); atomic_displacement != mode->atomic_displacements.end(); ++atomic_displacement)
if(cu_to_adp_mode)
pool->get_pair(*atom,atomic_displacement->atom).r()+=atomic_displacement->displacement_vector*amplitude;
else
pool->get_pair(atomic_displacement->atom,*atom).r()-=atomic_displacement->displacement_vector*amplitude;
}
bool operator==(const SizeEffect& inp)
{
return cu==inp.cu && mode==inp.mode && almost_equal(amplitude,inp.amplitude) && cu_to_adp_mode==inp.cu_to_adp_mode;
}
bool cu_to_adp_mode; ///<Boolean which is true if the modifier is atteched to chemical unit at beginnig of the vector and to adp mode at the end
ChemicalUnit* cu;
ADPMode* mode;
double amplitude;
};
class ZeroVectorCorrelation : public PairModifier
{
public:
ZeroVectorCorrelation() {}
bool generates_pairs()
{ return false; }
void modify_pairs(AtomicPairPool* const pool)
{
for(vector<AtomicPair>::iterator pair = pool->pairs.begin(); pair != pool->pairs.end(); pair++)
{
if((pair->r().length()<0.0001)&&(pair->atom1 == pair->atom2))
{
pair->U()=sym_mat3<double>(0,0,0,0,0,0);
pair->p()=pair->atom1->occupancy;
}
if((pair->r().length()<0.0001)&&(pair->atom1 != pair->atom2))
{
//cout << "missed p = 0" << endl;
pair->p()=0;
}
//cout << "probabilities are " << pair->p() << " " << pair->average_p() << endl;
//cout << "adps are " << pair->U()[0] << " " << pair->average_U()[0] << endl;
}
}
};
class MultiplicityCorrelation : public PairModifier{
public:
MultiplicityCorrelation(double _multiplier) :
multiplier(_multiplier) {}
bool generates_pairs()
{ return false; }
void modify_pairs(AtomicPairPool* const pool)
{
for(vector<AtomicPair>::iterator pair = pool->pairs.begin(); pair != pool->pairs.end(); pair++)
{
pair->multiplier*=multiplier;
}
}
bool operator==(const MultiplicityCorrelation& inp)
{
return almost_equal(multiplier, inp.multiplier);
}
//private:
double multiplier;
};
/**
* An interface to minima finding routine.
*/
class MinimizerCalculator{
public:
/**
* This function shoul fill in the calculated diffuse scattering or PDF map.
* \param p - is a raw vector of model parameters
*/
virtual void calculate(vector<double> p) = 0;
/// Accessor to calculated map
virtual IntensityMap& data() = 0;
};
/**
* Structure holds parameters to run minimization. For info see levmar documentation
*/
struct RefinementOptions {
int max_number_of_iterations;
double tau;
double thresholds [3];
double difference;
static RefinementOptions default_refinement_options() {
RefinementOptions result = { 1000, //max_number_of_iterations
1E-03, //tau
{1E-17,1E-17,1E-17}, //thresholds
1E-06}; //difference
return result;
}
};
/**
* This class wraps levmar library for least-square solution of a problem min(I_model(params)-I_experimental)
*/
class Minimizer {
public:
/**
* This function makes a setup for minimizer.
* \todo add initialization of minima finding parameters, like number of iterations and so on
* \todo make a separate file for the minimizer, or move it to core file
*/
Minimizer() {
covar = NULL;
}
/**
* Solves the problem of finding parameters which minimize I_model(params)-I_experimental in a least-square sence.
* \param _calc - a reference to an object that calculates model diffuse scattering (or PDF). The object should implement MinimizerCalculator interface
*/
vector<double> minimize(const vector<double> initial_params,IntensityMap * _experimental_data, MinimizerCalculator * _calc, OptionalIntensityMap * _weights, RefinementOptions refinement_options = RefinementOptions::default_refinement_options())
{
calc = _calc;
experimental_data = _experimental_data;
weights = _weights;
double * p = (double*) malloc(sizeof(double)*initial_params.size());
for(int i=0; i<initial_params.size(); i++)
p[i]=initial_params[i];
double * x = (double*) malloc(sizeof(double)*experimental_data->size_1d());
for(int i=0; i<experimental_data->size_1d(); i++)
x[i]=0;
covar = (double*) malloc(sizeof(double)*initial_params.size()*initial_params.size());
double opts[5];
opts[0] = refinement_options.tau;
for(int i=0; i<3; ++i)
opts[i+1]=refinement_options.thresholds[i];
opts[4] = refinement_options.difference;
double info[10];
int ret=dlevmar_dif(func_for_levmar, p, x, initial_params.size(),experimental_data->size_1d(), refinement_options.max_number_of_iterations, opts, info, NULL, covar, this);
if (ret<0)
REPORT(ERROR) << "Error, least square solution failed\n";
switch((int)info[6]) {
case 1: REPORT(MAIN) << "Least squares solution ended normally because of small gradient\n"; break;
case 2: REPORT(MAIN) << "Least squares solution ended normally because of convergence\n"; break;
case 3: REPORT(MAIN) << "Least squares solution stopped because maximum iteraction count is exceeded\n"; break;
case 4: REPORT(ERROR) << "Warning, least square solution stopped because of singular matrix\n"; break;
case 5: REPORT(MAIN) << "Least squares solution ended normally because no further error reduction is possible.\n"; break;
case 6: REPORT(MAIN) << "Least squares solution ended normally because experiment and model are almost the same\n"; break;
case 7: REPORT(ERROR) << "Error, least square solution aborted. Found invalid (i.e. NaN or Inf) values in diffuse scattering\n"; break;
}
static
vector<double> result(p,p+initial_params.size());
delete p;
delete x;
return result;
}
~Minimizer() {
free(covar);
}
double * covar;
private:
/**
* the function which is called by levmar. The function has the structure that lev mar supports. the field data is used to store reference to the minimizer object,
* so even though this function is technically static, it works like a normal member function
*/
static void func_for_levmar(double *p, double *x, int parameters_number, int datapoints_number, void *data)
{
Minimizer * _this = reinterpret_cast<Minimizer*> (data);
vector<double> parameters(p,p+parameters_number);
_this->calc->calculate(parameters);
//TODO: save space. Here, use in_asu
//copy difference to the *x array
for(int i=0; i<datapoints_number; i++)
x[i] = (_this->experimental_data->at(i) - _this->calc->data().at(i))*_this->weights->at(i);
}
MinimizerCalculator * calc; //< model diffuse scattering of PDF calculator.
IntensityMap * experimental_data;
OptionalIntensityMap * weights;
};
class SymmetryElement{
public:
SymmetryElement(mat3<double> _permutation_matrix,vec3<double> _displacement) :
permutation_matrix(_permutation_matrix),displacement(_displacement) { }
SymmetryElement() :
permutation_matrix(mat3<double>(1,0,0,0,1,0,0,0,1)),displacement(vec3<double>(0,0,0)) { }
bool operator==(SymmetryElement inp)
{
return almost_equal(displacement,inp.displacement) && almost_equal(permutation_matrix,inp.permutation_matrix);
}
vec3<double> displacement;
mat3<double> permutation_matrix;
};
class Error{
public:
Error(string inp) : message(inp) { }
string message;
};
#endif | Unknown |
3D | YellProgram/Yell | src/basic_classes.cpp | .cpp | 16,084 | 545 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "basic_classes.h"
#include "diffuser_core.h"
#include <math.h>
double vector_norm(vec3<double> v, sym_mat3<double> M)
{
return sqrt(v*M*v);
}
sym_mat3<double> outer_product(vec3<double> v1, vec3<double> v2) {
return sym_mat3<double>(v1[0]*v2[0],v1[1]*v2[1],v1[2]*v2[2],v1[0]*v2[1],v1[0]*v2[2],v1[1]*v2[2]);
}
ADPMode* translational_mode(ChemicalUnit* unit,int direction,sym_mat3<double> metrical_matrix) {
vector<Atom*> atoms = unit->get_atoms();
vector<Atom*>::iterator atom;
vec3<double> r(0,0,0);
r[direction]=1;
r=r/vector_norm(r,metrical_matrix);
ADPMode* mode = new ADPMode();
for(atom=atoms.begin(); atom!=atoms.end(); atom++)
mode->add_atom(*atom,r);
return mode;
}
ADPMode z_rot_mode(ChemicalUnit* unit) //only for hex system
{
vector<Atom*> atoms = unit->get_atoms();
vector<Atom*>::iterator atom;
ADPMode mode;
mat3<double> rotation(1/sqrt(3.0),-2/sqrt(3.),0,2/sqrt(3.),-1/sqrt(3.),0,0,0,0);
for(atom=atoms.begin(); atom!=atoms.end(); atom++)
mode.add_atom(*atom,rotation*((*atom)->r));
return mode;
}
ADPMode* rot_mode(ChemicalUnit* unit,vec3<double> axis , vec3<double> point_on_axis ,sym_mat3<double> metrical_matrix) {
vector<Atom*> atoms = unit->get_atoms();
vector<Atom*>::iterator atom;
axis = axis/vector_norm(axis, metrical_matrix.inverse());
ADPMode* mode = new ADPMode();
/*
mat3<double> rotation(1/sqrt(3),-2/sqrt(3),0,2/sqrt(3),-1/sqrt(3),0,0,0,0);
*/
for(atom=atoms.begin(); atom!=atoms.end(); atom++)
mode->add_atom(*atom,metrical_matrix*(axis.cross((*atom)->r - point_on_axis))/sqrt(metrical_matrix.determinant()));
return mode;
}
ADPMode combine_modes(vector<ADPMode> modes) {
ADPMode result;
vector<ADPMode>::iterator mode;
for(mode=modes.begin(); mode!=modes.end(); mode++)
result.atomic_displacements.insert(result.atomic_displacements.end(),mode->atomic_displacements.begin(),mode->atomic_displacements.end());
return result;
}
vector<SubstitutionalCorrelation*> correlators_from_cuns(ChemicalUnitNode* node1,ChemicalUnitNode* node2,vector<double> corr) {
int s1 = node1->chemical_units.size();
int s2 = node2->chemical_units.size();
vector<double> correlations(s1*s2);
//check there are enough numbers in the matrix
//fill the correlations
//if full version, check the last column-row
bool full_version;
if(corr.size()==(s1-1)*(s2-1)) {
full_version = false;
//fill upper-right corner of correlation matrix
for(int i=0; i<s1-1; i++)
for(int j=0; j<s2-1; j++)
correlations[i+s1*j] = corr[i+j*(s1-1)];
} else if(corr.size()==s1*s2) {
full_version = true;
correlations = corr;
} else {
REPORT(ERROR) << "Wrong number of joint probabilities, expected a " << (s1-1)<< "x" << (s2-1) << " or a " << s1 << "x" << s2 << " matrix. Found " << corr.size() << " values.\n";
throw "fail";
}
//fill last row
for(int j=0; j<s2-1; j++){
correlations[s1*j+s1-1]=node2->chemical_units[j].get_occupancy();
for(int i=0; i<s1-1; i++)
correlations[s1*j+s1-1]-=correlations[i+s1*j];
}
//fill last coloumn
for(int i=0; i<s1; i++) {
correlations[(s2-1)*s1+i]=node1->chemical_units[i].get_occupancy();
for(int j=0; j<s2-1; j++)
correlations[(s2-1)*s1+i] -= correlations[i+s1*j];
}
if(full_version)
for(int i=0; i<correlations.size(); ++i)
if(!(almost_equal(corr[i],correlations[i]))){
REPORT(ERROR) << "The joint probabilities are incompatible with the average structure.\n";
throw "fail";
}
//create correlations
vector<SubstitutionalCorrelation*> res;
for(int j=0; j<s2; j++)
{
for(int i=0; i<s1; i++)
{
res.push_back( new SubstitutionalCorrelation(& node1->chemical_units[i],& node2->chemical_units[j], correlations[i+s1*j]));
}
}
return res;
}
/// Skips check for matrix being symmetric. Just takes upper-triangular part.
sym_mat3<double> trusted_mat_to_sym_mat(mat3<double> inp) {
return sym_mat3<double>(inp[0],inp[4],inp[8],inp[1],inp[2],inp[5]);
}
// I had to move it here because it depends on AtomicPair class which is defined after LaueSymmetry
vector<AtomicPair> LaueSymmetry::multiply_pairs_by_matrix(vector<AtomicPair> pairs,mat3<double> transformation_matrix) {
vector<AtomicPair>::iterator pair;
for(pair=pairs.begin(); pair!=pairs.end(); pair++)
{
for(int average=0; average<2; average++)
{
pair->r(average)=transformation_matrix*pair->r(average);
pair->U(average)=trusted_mat_to_sym_mat(transformation_matrix*pair->U(average)*transformation_matrix.transpose());
}
}
return pairs;
}
void add_pair_to_appropriate_place(IntensityMap & small_piece,IntensityMap & accumulator,vec3<int> r,vector<bool> periodic) {
vec3<int> piece_size=small_piece.size();
vec3<int> acc_size=accumulator.size();
r=r-(piece_size/2);
vec3<int> borders;
for(int i=0; i<3; i++)
{
borders[i]=0;//(acc_size[i]>1);
}
vec3<int> llimits, ulimits;
for(int i=0; i<3; ++i)
{
llimits[i]=r[i];
ulimits[i]=r[i]+piece_size[i]+borders[i];
if(!periodic.at(i))
{
llimits[i]=max(0,llimits[i]);
ulimits[i]=min(acc_size[i],ulimits[i]);
}
}
for(int i=llimits[0];i<ulimits[0]; i++)
{
int is=(i-r[0])%piece_size[0];
for(int j=llimits[1];j<ulimits[1]; j++)
{
int js=(j-r[1])%piece_size[1];
for(int k=llimits[2];k<ulimits[2]; k++)
{
int ks=(k-r[2])%piece_size[2];
accumulator.at((i+acc_size[0])%acc_size[0],
(j+acc_size[1])%acc_size[1],
(k+acc_size[2])%acc_size[2])+=small_piece.at(is,js,ks);
}
}
}
}
AtomicTypeCollection::~AtomicTypeCollection() {
map<string,Scatterer*>::iterator atomic_type;
for(atomic_type=types.begin(); atomic_type!=types.end(); atomic_type++)
delete atomic_type->second;
}
AtomicTypeCollection& AtomicTypeCollection::get() {
static AtomicTypeCollection collection;
return collection;
}
void AtomicTypeCollection::calculate_form_factors_of_all_atoms_on_grid(vec3<int>map_size,Grid grid)
{
map<string,Scatterer*>::iterator atomic_type;
for(atomic_type=AtomicTypeCollection::get().types.begin(); atomic_type!=AtomicTypeCollection::get().types.end(); atomic_type++)
{
atomic_type->second->calculate_form_factors_on_grid(map_size,grid);
}
}
void AtomicTypeCollection::update_current_form_factors(vec3<double>s, double d_star_square)
{
map<string,Scatterer*>::iterator atomic_type;
for(atomic_type=AtomicTypeCollection::get().types.begin(); atomic_type!=AtomicTypeCollection::get().types.end(); atomic_type++)
{
atomic_type->second->update_current_form_factor(s, d_star_square);
}
}
string AtomicTypeCollection::strip_label(string const & label)
{
string result;
result.append(label,0,1);
if (label[1]>=('A'))
result.append(label,1,1);
return result;
}
Scatterer* AtomicTypeCollection::get(string const & label, ScatteringType scattering_type)
{
if(AtomicTypeCollection::get().types.find(label) != AtomicTypeCollection::get().types.end())
return AtomicTypeCollection::get().types[label];
else {
string stripped_label = strip_label(label);
if(AtomicTypeCollection::get().types.find(stripped_label) != AtomicTypeCollection::get().types.end())
return AtomicTypeCollection::get().types[stripped_label];
else
{
Scatterer *t;
switch(scattering_type) {
case XRay:
t = new AtomicType(stripped_label);
break;
case Neutron:
t = new NeutronScattererAtom(stripped_label);
break;
case Electrons:
t = new ElectronScattererAtom(stripped_label);
break;
}
AtomicTypeCollection::add(stripped_label, t);
return t;
}
}
}
void AtomicTypeCollection::add(string const & label, Scatterer* s) {
AtomicTypeCollection::get().types.insert(pair<string,Scatterer*>(label, s));
}
complex<double> MolecularScatterer::form_factor_at_c(vec3<double>s,double d_star_sq) {
//This method can only be used by AtomicTypeCollection::update_current_form_factor function since it relies on the fact that
//the form factor of all its underlying atoms is calculated prior to calling this function
complex<double> result;
vector<Atom*>::iterator it;
Atom* at;
for(it=constituent_atoms.begin(); it!=constituent_atoms.end(); ++it) {
at=*it;
result += form_factor_in_a_point(at->atomic_type->current_form_factor,
at->occupancy,
at->multiplier,
at->r,
at->U,
s);
}
return result;
}
complex<double> MolecularScatterer::form_factor_in_a_point(complex<double> f,
double p,
double N,
vec3<double> r,
sym_mat3<double> U,
vec3<double> s)
{
return f*p*N*exp( complex<double>(M2PISQ*(s*U*s),M_2PI*(s*r)) );
}
#define Z it->average_r()[2]
#define Y it->average_r()[1]
#define X it->average_r()[0]
#define decrease_multiplicity(m) {result.back().p()/=m; result.back().average_p()/=m;}
///\TODO: move it to appropriate place. Probably to files LaueSymmetry.h and LaueSymmetry.cpp
vector<AtomicPair> LaueSymmetry::filter_pairs_from_asymmetric_unit_and_scale(vector<AtomicPair>& pairs)
{
vector<AtomicPair> result;
vector<AtomicPair>::iterator it;
if(label=="6/m" || label=="4/m" || label=="2/m")
{
for(it=pairs.begin(); it!=pairs.end(); it++)
{
if( Z<0 )
continue;
result.push_back(*it);
if(Z==0)
decrease_multiplicity(2)
}
return result;
}else if(label=="mmm" || label=="m-3")
{
for(it=pairs.begin(); it!=pairs.end(); it++)
{
if( Z<0 || X<0 || Y<0 )
continue;
result.push_back(*it);
if(Z==0)
decrease_multiplicity(2);
if(X==0)
decrease_multiplicity(2);
if(Y==0)
decrease_multiplicity(2);
}
return result;
}
else if(label=="4/mmm")
{
for(it=pairs.begin(); it!=pairs.end(); it++)
{
if(!( Z>=0 && X>=Y && Y>=0 ))
continue;
result.push_back(*it);
if(Z==0)
decrease_multiplicity(2);
if(Y==0)
decrease_multiplicity(2);
if(X==Y)
decrease_multiplicity(2);
if(X==0)
decrease_multiplicity(2);
}
return result;
}
else if(label=="m-3m")
{
for(it=pairs.begin(); it!=pairs.end(); it++)
{
if(!( Z>=-0 && Y >=Z && X>=Y ))
continue;
result.push_back(*it);
if(X==0)// 0 0 0
decrease_multiplicity(48)
else if(Y==0 && Z==0) // x 0 0
decrease_multiplicity(8)
else if(X==Y && X==Z) // x x x
decrease_multiplicity(6)
else if(X==Y && Z==0) // x x 0
decrease_multiplicity(4)
else if(Z==0 ||Y==Z || X==Y) // x y 0, x y y, x x z
decrease_multiplicity(2)
}
return result;
}else if(label=="6/mmm")
{
for(it=pairs.begin(); it!=pairs.end(); it++)
{
if(!( Z>=0 && Y>=0 && X>=2*Y )) //if y<0 or z<0 or x<2y
continue;
result.push_back(*it);
//DO separately xy and z parts
if(X==0 && Y==0)// 0 0
decrease_multiplicity(12)
else if(Y==0 || X==2*Y) //x 0 and 2y y
decrease_multiplicity(2);
if(Z==0)// x y 0
decrease_multiplicity(2);
}
return result;
}else if(label=="-3mH")
{
for(it=pairs.begin(); it!=pairs.end(); it++)
{
if(!( X>=-Y && X>=2*Y ))
continue;
result.push_back(*it);
if(X==0 && Y==0)// 0 0
decrease_multiplicity(6)
else if(X==-Y || X==2*Y)
decrease_multiplicity(2);
}
return result;
}else if(label=="-3mR")
{
for(it=pairs.begin(); it!=pairs.end(); it++)
{
if(!( X>=Y && Y>=Z ))
continue;
result.push_back(*it);
if(X==Y && Y==Z)
decrease_multiplicity(6)
else if(X==Y || Y==Z)
decrease_multiplicity(2);
}
return result;
}
else //-3R and -3H
return pairs;
}
#undef Z
#undef X
#undef Y
vector<AtomicPair> LaueSymmetry::filter_pairs_from_asymmetric_unit(vector<AtomicPair>& pairs)
{
vector<AtomicPair> result = filter_pairs_from_asymmetric_unit_and_scale(pairs);
vector<AtomicPair>::iterator it;
double group_multiplicity=0;
if (label=="m-3m") group_multiplicity=48;
else if(label=="m-3") group_multiplicity=24;
else if(label=="6/mmm") group_multiplicity=24;
else if(label=="6/m") group_multiplicity=12;
else if(label=="-3mH") group_multiplicity=12;
else if(label=="-3mR") group_multiplicity=12;
else if(label=="-3H") group_multiplicity=6;
else if(label=="-3R") group_multiplicity=6;
else if(label=="4/mmm") group_multiplicity=16;
else if(label=="4/m") group_multiplicity=8;
else if(label=="mmm") group_multiplicity=8;
else if(label=="2/m") group_multiplicity=4;
else if(label=="2/mb") group_multiplicity=4/2; //mysterious 1/2 constant
else if(label=="-1") group_multiplicity=2;
assert(!(group_multiplicity==0));
for(it=result.begin(); it!=result.end(); it++)
it->multiplier*=group_multiplicity;
return result;
}
bool LaueSymmetry::is_compatible_with_cell(const UnitCell& cell)
{
double a=cell.cell.parameters()[0];
double b=cell.cell.parameters()[1];
double c=cell.cell.parameters()[2];
double alpha=cell.cell.parameters()[3];
double beta=cell.cell.parameters()[4];
double gamma=cell.cell.parameters()[5];
//took this from International Tables Vol A p 15
if (label=="-1") return true;
if (label=="2/m") return alpha==90 && beta==90;
if (label=="2/mb") return alpha==90 && gamma==90;
if (label=="mmm") return alpha==90 && beta==90 && gamma==90;
if (label=="4/m" || label=="4/mmm")return almost_equal(a, b) && alpha==90 && beta==90 && gamma==90;
if (label=="-3H" || label=="-3mH") return almost_equal(a, b) && alpha==90 && beta==90 && gamma==120;
if (label=="-3R" || label=="-3mR") return almost_equal(a, b) && almost_equal(a, c) && almost_equal(alpha, beta) && almost_equal(alpha,gamma);
if (label=="6/m" || label=="6/mmm")return almost_equal(a, b) && alpha==90 && beta==90 && gamma==120;
if (label=="m-3" || label=="m-3m") return almost_equal(a, b) && almost_equal(a, c) && alpha==90 && beta==90 && gamma==90;
return false;
}
vector<AtomicPair> LaueSymmetry::apply_matrix_generator(vector<AtomicPair> pairs,mat3<double> transformation_matrix,int times) {
vector<AtomicPair> result=pairs;
for(int repeat=0; repeat<times-1; repeat++)
{
pairs = multiply_pairs_by_matrix(pairs,transformation_matrix);
result.insert(result.end(),pairs.begin(),pairs.end());
}
for(vector<AtomicPair>::iterator it=result.begin(); it!=result.end(); ++it)
it->multiplier/=times;
return result;
}
| C++ |
3D | YellProgram/Yell | src/model.cpp | .cpp | 6,029 | 185 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "model.h"
#include "InputFileParser.h"
#include <sstream>
#include "exceptions.h"
extern OutputHandler report;
typedef iterator_ Iterator;
Iterator line_start(Iterator pos, const Iterator& start) {
if(pos!=start and *pos=='\n')
--pos;
while (pos!=start && *pos != '\n')
--pos;
return pos;
}
Iterator line_end(Iterator pos, const Iterator& end) {
if(pos!=end and *pos=='\n')
++pos;
while (pos!=end && *pos != '\n')
++pos;
return pos;
}
Iterator step_from_newline(const Iterator& pos, const Iterator& end) {
if(pos!=end and *pos=='\n')
return pos + 1;
else
return pos;
}
void complain_about_error(Iterator start, Iterator current, Iterator end)
{
//skip empty spaces till the line where the error happened
InputParser a_parser;
qi::parse(current,end,a_parser.skipper_no_assignement);
current = step_from_newline(current,end);
int line_number = 0;
for(Iterator it=current; it!=start; it--)
if(*it=='\n')
line_number++;
Iterator lstart = line_start(current, start);
int error_pos_within_line = 0;
for(Iterator t = step_from_newline(lstart,end); t!=current; ++t)
++error_pos_within_line;
// Print two lines before the error line
Iterator context_start = step_from_newline(line_start(line_start(lstart,start),start),end);
Iterator lend = line_end(current,end);
Iterator next_two_lines_start = step_from_newline(lend,end);
Iterator next_two_lines_end = line_end(line_end(next_two_lines_start,end),end);
std::string trouble_line_with_context(context_start,lend);
std::string next_two_lines(next_two_lines_start,next_two_lines_end);
std::ostringstream complain;
complain << "Parsing failed with exception around line " << line_number+1 << ":\n\n" << trouble_line_with_context <<"\n";
for(int i=0; i < error_pos_within_line - 1; ++i)
complain << ' ';
complain << "^-----roughly here\n";
complain << next_two_lines << "\n";
REPORT(ERROR) << complain.str();
}
void Model::calculate(vector<double> params,bool average_flag)
{
///\TODO: since calculate function funs several times, move parser creation to initialization stage
InputParser a_parser;
a_parser.add_model(this);
a_parser.formula.initialize_refinable_variables(refined_variable_names,params);
a_parser.formula.array = params;
Iterator start = model.begin();
Iterator end = model.end();
bool r;
try{
r = qi::phrase_parse(start,end,a_parser,a_parser.skipper_no_assignement);
}catch(const qi::expectation_failure<Iterator>& e)
{
complain_about_error(model.begin(), e.first, model.end());
throw(TerminateProgram());
}
if(!r || start!=end)
{
string rest(start,end);
REPORT(ERROR) << "Parsing failed, the rest of the file is:\n" << rest;
throw "Parsing failed";
}
vector<AtomicPair> pairs;
vector<AtomicPairPool*>::iterator pool;
for(pool=pools.begin(); pool!=pools.end(); pool++)
{
(*pool)->invoke_correlators();
pairs.insert(pairs.end(),(*pool)->pairs.begin(),(*pool)->pairs.end());
}
// pairs = cell.laue_symmetry.filter_pairs_from_asymmetric_unit(pairs); //We decided to use another way for multiplicity
REPORT(FIRST_RUN) << "created " << pairs.size() << " pairs\n\n";
// output pairs
if(dump_pairs)
for(int i=0; i<pairs.size(); i++)
REPORT(FIRST_RUN) << pairs[i].to_string() <<'\n';
if(report_pairs_outside_pdf_grid)
{
Grid pdf_grid = grid.in_pdf_space();
for(int i=0; i<pairs.size(); i++)
if(!pairs[i].pair_is_withing(pdf_grid))
REPORT(FIRST_RUN) << "Warning, pair is outside PDF grid " << pairs[i].to_string() << '\n';
}
pairs = cell.laue_symmetry.apply_patterson_symmetry(pairs);
atomic_pairs = pairs; //save them to check that everything is fine
IntensityMap* calc_intensity_map;
if(average_flag==AVERAGE)
calc_intensity_map=&average_intensity_map;
else
calc_intensity_map=&intensity_map;
if(direct_diffuse_scattering_calculation)
{
vec3<int> sym_boundary;
for(int i=0; i<3; ++i)
sym_boundary[i]=calc_intensity_map->size()[i]>1;
IntensityMap padded = calc_intensity_map->padded(sym_boundary); //this will avoid the problem with symmetry.
IntnsityCalculator::calculate_scattering_from_pairs(pairs,padded,average_flag);
cell.laue_symmetry.apply_patterson_symmetry(padded);
calc_intensity_map->copy_from_padded(sym_boundary,padded);
}else
{
vec3<int> sym_boundary;
for(int i=0; i<3; ++i)
sym_boundary[i]=calc_intensity_map->size()[i]>1 && !(periodic_boundaries[i]);
IntensityMap recipr_padded = calc_intensity_map->padded(padding); //for better fft accuracy
recipr_padded.invert_grid();
IntensityMap padded = recipr_padded.padded(sym_boundary); //for symmetry
IntnsityCalculator::calculate_patterson_map_from_pairs_f(pairs,padded,average_flag,fft_grid_size,periodic_boundaries);
cell.laue_symmetry.apply_patterson_symmetry(padded);
recipr_padded.copy_from_padded(sym_boundary,padded);
recipr_padded.invert();
calc_intensity_map->copy_from_padded(padding,recipr_padded);
}
apply_resolution_function_if_possible(*calc_intensity_map);
apply_reciprocal_space_multipliers_if_possible(*calc_intensity_map);
calc_intensity_map->to_reciprocal();
report.calculation_is_finished();
} | C++ |
3D | YellProgram/Yell | src/diffuser_core.cpp | .cpp | 6,505 | 212 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "diffuser_core.h"
#include <H5Cpp.h> //for reading HDF5
using namespace H5;
//I figured out that i was using complex real() as accessor which it is not. Here is a hack to solve this under windows. ICC and GCC compilers work nicely without this hack
double& real(complex<double>& inp)
{
return reinterpret_cast<double&> (inp);
}
double round(double d)
{
return floor(d + 0.5);
}
void grid_and_residual(vec3<double> r,Grid grid,vec3<int> & r_grid,vec3<double> & r_res)
{
r=r-grid.lower_limits;
vec3<double> r_in_steps=r/grid.grid_steps;
for(int i=0; i<3; i++)
{
r_grid[i]=int( round(r_in_steps[i]) );
r_res[i]=r_in_steps[i]-r_grid[i];
}
r_res=r_res.each_mul(grid.grid_steps);
}
IntensityMap ReadHDF5(string filename)
{
H5File file( filename, H5F_ACC_RDONLY );
DataSet dataset = file.openDataSet( "data" );
DataSpace dataspace = dataset.getSpace();
hsize_t dims_out[3];
int no_dimensions = dataspace.getSimpleExtentDims( dims_out, NULL);
//\TODO: assert that there is not too much dimensions in input vector
for(int i=no_dimensions; i<3; i++)
dims_out[i]=1; //fill additional dimensions if input matrix has less then 3 dimensions
double * temp_map_holder = (double*) malloc(dims_out[0]*dims_out[1]*dims_out[2] * sizeof(double));
dataset.read(temp_map_holder, PredType::NATIVE_DOUBLE);
IntensityMap result(dims_out[0], dims_out[1], dims_out[2]); ///\TODO: copy data directly into versa, not like this, with additional array
for(int i=0; i<dims_out[0]*dims_out[1]*dims_out[2]; i++)
result.at(i) = temp_map_holder[i];
free(temp_map_holder);
return result;
}
template<typename T>
DataType getH5Type() {}
template<>
DataType getH5Type<int> () {
return PredType::NATIVE_INT;
}
template<>
DataType getH5Type<bool> () {
return PredType::NATIVE_HBOOL;
}
template<>
DataType getH5Type<double> () {
return PredType::NATIVE_DOUBLE;
}
template <typename T>
void creadeAndWriteDataset(H5File& file, string datasetName, T* data, hsize_t n, hsize_t* dims) {
DataSpace dataspace( n, dims );
DataSet dataset = file.createDataSet( datasetName, getH5Type<T>(), dataspace );
dataset.write( data, getH5Type<T>() );
}
template <typename T>
void writeConstant(H5File& file, string datasetName, T data) {
H5::DataSet ds = file.createDataSet(datasetName, getH5Type<T>(), H5::DataSpace(H5S_SCALAR));
ds.write(&data, getH5Type<T>());
}
template <typename T, std::size_t N>
void writeVector(H5File& file, string datasetName, af::tiny_plain<T,N> v) {
T dataAsPlaneArray[N];
for(int i=0; i<N; ++i)
dataAsPlaneArray[i]=v[i];
hsize_t sz[N]={N};
creadeAndWriteDataset<T>(file, datasetName, dataAsPlaneArray, 1, sz);
}
void writeFormatString(H5File& file) {
string format = "Yell 1.0";
H5::StrType h5stringType(H5::PredType::C_S1, H5T_VARIABLE); // + 1 for trailing zero
H5::DataSet ds = file.createDataSet("format", h5stringType, H5::DataSpace(H5S_SCALAR));
ds.write(format, h5stringType);
}
void WriteHDF5(string filename, IntensityMap& input)
{
H5File file( filename, H5F_ACC_TRUNC );
hsize_t dimsf[3];
//Fill it from input
vec3<int> dims = input.size();
for(int i=0; i<3; i++)
dimsf[i] = dims[i];
double * temp_map_holder = (double*) malloc(dimsf[0]*dimsf[1]*dimsf[2] * sizeof(double));
for(int i=0; i<dimsf[0]*dimsf[1]*dimsf[2]; i++)
temp_map_holder[i] = input.at(i);
creadeAndWriteDataset<double>(file, "data", temp_map_holder, 3, dimsf);
free(temp_map_holder);
Grid& g=input.grid;
// Write out the grid settings
//creadeAndWriteDataset<double>(file, "lower_limits", {g.lower_limits[0], g.lower_limits[1], g.lower_limits[2]}, 1, {3});
writeVector(file, "lower_limits", g.lower_limits);
writeConstant(file, "is_direct", !g.reciprocal_flag);
writeVector(file, "step_sizes", g.grid_steps);
cctbx::uctbx::unit_cell cell = g.cell;
if(!g.reciprocal_flag)
cell=cell.reciprocal();
writeVector(file, "unit_cell", cell.parameters());
writeFormatString(file);
}
bool almost_equal(double a, double b)
{
return abs(a-b)<EPSILON;
}
bool almost_equal(vec3<double> a,vec3<double> b)
{
return almost_equal<3,vec3<double> >(a,b);
}
bool almost_equal(mat3<double> a,mat3<double> b)
{
return almost_equal<9,mat3<double> >(a,b);
}
bool almost_equal(scitbx::af::tiny<double,6> a,scitbx::af::tiny<double,6> b)
{
return almost_equal<6,scitbx::af::tiny<double,6> >(a,b);
}
string format_esd(double val,double esd)
{
std::ostringstream res;
if(esd==0 || isnan(esd)) //special case, if standard deviation is not set, report the result as-is
{
res << val << '(' << esd << ')';
return res.str();
}
int leading_power_parameter=1000;
if (abs(val)>=1e-32) {
leading_power_parameter = floor(log(abs(val))/log((double)10));
}
//the position of the leading digit. positive are to the right of the zero, negative - to the left
//we take abs of the esd because in ill-defined cases they can be calculated as negative
int leading_power_esd = floor(log(abs(esd))/log((double)10));
int leading_power = min(leading_power_esd, leading_power_parameter); //This way we will make sure that if a parameter is very very small, but not insignificant, it would still be reported
int leading_digit = floor(esd * pow((double)10,-leading_power)); //the digits of the esd which should be reported
if(leading_digit==1) {
leading_power -= 1;
leading_digit = floor(esd * pow((double)10,-leading_power)); //add one more digit
}//TODO: else leading_digit = round(esd*pow....
int precision = max(-leading_power,0);
res.setf(std::ios::fixed);
res.precision(precision);
res << val << '(' << leading_digit << ')';
return res.str();
}
| C++ |
3D | YellProgram/Yell | src/InputFileParserII.cpp | .cpp | 1,886 | 53 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InputFileParser.h"
void InputParser::InputParserII()
{
using namespace qi;
using phoenix::bind;
using phoenix::ref;
symmetry_element =
lit("Symmetry")
> '('
> permutation_component[_val = bind(&update_symmetry_component,_val,_1,0)]
> ',' > permutation_component[_val = bind(&update_symmetry_component,_val,_1,1)]
> ',' > permutation_component[_val = bind(&update_symmetry_component,_val,_1,2)]
> ')'
;
variant = (
lit("Variant") [_val = phoenix::new_<ChemicalUnitNode>()]
> '['
> *(
'(' > omit[ char_("pP") ] > '=' > number > ')' >
chemical_unit[bind(&ChemicalUnitNode::add_chemical_unit,*_val,_1)]
) [bind(&ChemicalUnit::set_occupancy,*_2,_1)]
> ']'
> eps [_pass = bind(&ChemicalUnitNode::complain_if_sum_of_occupancies_is_not_one,_val)]
);
variant_assignement = (valid_identifier >> '=' >> variant[_val=_1])[bind(InputParser::add_reference,phoenix::ref(references),_1,phoenix::construct<StructurePartRef>(_val))];
valid_identifier %= alpha >> *char_("a-zA-Z_0-9") >> !char_("a-zA-Z_0-9");
}; | C++ |
3D | YellProgram/Yell | src/basic_io.cpp | .cpp | 1,022 | 39 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "basic_io.h"
#include <string>
#include <fstream>
bool file_exists(string fname)
{
ifstream ifile(fname.c_str());
return ifile.good();
}
string read_input_file(string filename)
{
string buf;
string line;
ifstream in(filename.c_str());
while(getline(in,line))
buf += line + "\n";
return buf;
} | C++ |
3D | YellProgram/Yell | src/main.cpp | .cpp | 12,004 | 332 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <time.h>
#include <math.h>
#include <sys/timeb.h>
#include <sys/types.h>
#include <exception> // std::terminate
#include <string>
#include <fstream>
#include "basic_classes.h"
#include "diffuser_core.h"
#include "InputFileParser.h"
#include "basic_io.h"
#include "exceptions.h"
using namespace std;
struct correlation_tuple {
int x;
int y;
double correlation;
};
bool larger_correlation (correlation_tuple i,correlation_tuple j) { return abs(i.correlation)>abs(j.correlation); }
void sort_correlations(vector<correlation_tuple>& inp) {
std::sort(inp.begin(),inp.end(),larger_correlation);
}
void print_correlation_tuple(vector<correlation_tuple>& inp,vector<string> refined_variable_names) {
for(vector<correlation_tuple>::iterator corr=inp.begin(); corr!=inp.end(); ++corr)
REPORT(MAIN) << refined_variable_names[corr->x] << " - " << refined_variable_names[corr->y] << " " << corr->correlation << "\n";
}
void print_covariance(double* covar, vector<double> refined_params) {
int sz=refined_params.size();
REPORT(MAIN) << "Covariance matrix:\n";
for (int i=0,k=0;i<refined_params.size();++i)
{
for (int j=0;j<refined_params.size();++j,++k)
REPORT(MAIN) << covar[k] << ' ';
REPORT(MAIN) << "\n";
}
}
void print_correlations(double* covar, vector<double> refined_params,vector<string> refined_variable_names)
{
int sz=refined_params.size();
vector<correlation_tuple> correlations;
vector<correlation_tuple> correlations_larger_then_09;
for (int i=0; i<sz; ++i)
for (int j=i+1; j<sz; ++j)
{
double denom = sqrt(covar[i+i*sz]*covar[j+sz*j]);
double t;
if(denom!=0)
t=covar[i+j*sz]/denom;
else
t=0;
correlation_tuple corr={i,j,t};
correlations.push_back(corr);
if(abs(corr.correlation)>0.9)
correlations_larger_then_09.push_back(corr);
}
if(correlations_larger_then_09.size()>=10)
{
REPORT(MAIN) << "Correlations greater than 0.9:\n";
print_correlation_tuple(correlations_larger_then_09,refined_variable_names);
}
else if (correlations.size()>10)
{
REPORT(MAIN) << "Ten largest correlations:\n";
sort_correlations(correlations);
vector<correlation_tuple> ten_largest(correlations.begin(),correlations.begin()+10);
print_correlation_tuple(ten_largest,refined_variable_names);
}
else if (correlations.size()>0)
{
REPORT(MAIN) << "All correlations:\n";
sort_correlations(correlations);
print_correlation_tuple(correlations,refined_variable_names);
}
}
void print_essential_information_about_crystal(Model& model)
{
af::double6 cell = model.cell.cell.parameters();
REPORT(MAIN) << "Unit cell: ";
for(int i=0; i<6; ++i)
REPORT(MAIN) << cell[i] << ' ';
REPORT(MAIN) << '\n';
af::double6 rec_cell = model.cell.cell.reciprocal_parameters();
REPORT(MAIN) << "Reciprocal unit cell: ";
for(int i=0; i<6; ++i)
REPORT(MAIN) << rec_cell[i] << ' ';
REPORT(MAIN) << '\n';
REPORT(MAIN) << "Laue symmetry: " << model.cell.laue_symmetry.label << '\n';
Grid grid=model.grid;
REPORT(MAIN) << "Diffuse scattering array size: " << grid.grid_size[0] << ' ' << grid.grid_size[1] << ' '<< grid.grid_size[2] << '\n';
REPORT(MAIN) << "Diffuse scattering grid limits: ";
for(int i=0; i<3; ++i)
REPORT(MAIN) << grid.lower_limits[i] << ' ' << grid.upper_limits()[i] <<", ";
REPORT(MAIN) << '\n';
REPORT(MAIN) << "Grid step sizes: " << grid.grid_steps[0] << ' ' << grid.grid_steps[1] << ' '<< grid.grid_steps[2] << '\n';
Grid igrid = grid.reciprocal();
REPORT(MAIN) << "Grid limits in PDF space: ";
for(int i=0; i<3; ++i)
REPORT(MAIN) << igrid.lower_limits[i] << ' ' << igrid.upper_limits()[i] <<", ";
REPORT(MAIN) << '\n';
REPORT(MAIN) << "Grid step sizes in PDF space: " << igrid.grid_steps[0] << ' ' << igrid.grid_steps[1] << ' '<< igrid.grid_steps[2] << '\n';
if(!model.direct_diffuse_scattering_calculation)
{
REPORT(MAIN) << "Calculation method: fft\n";
if(!grid.grid_is_compatible_with_fft())
{
REPORT(ERROR) << "ERROR: Grid is incompatible with fft calculation algorithm. To work properly, algorithm needs that diffuse scattering grid has even number of pixels in each dimension and that the center of reciprocal space is in Ni/2+1 pixel\n";
throw(TerminateProgram());
}
}
else
{
REPORT(MAIN) << "Calculation method: direct\n";
// if(!grid.grid_is_compatible_with_fft() && model.) //TODO: Here list all the things which will turn on fft in the program. Resolution function will for sure, and also weights in PDF space
}
}
vector<double> esd_from_covar(double* covar, vector<double> refined_params) {
int sz=refined_params.size();
vector<double> res(sz);
REPORT(MAIN) << "Covariance matrix:\n";
for (int i=0;i<refined_params.size();++i)
res[i] = sqrt(covar[i*(1+sz)]); //diag
return res;
}
void calculate_Jacobians(Model& a_model) {
REPORT(MAIN) << "Calculating Jacobians\n";
const double increment = 1E-6;
IntensityMap base_model = a_model.model_scaled_to_experiment();
vector<double> refined_params = a_model.refinement_parameters;
vector<string> refined_params_names = a_model.refined_variable_names;
double inverse_scale = 1/refined_params[0];
for(int i=1; i<refined_params.size(); ++i){
vector<double> incremented_refined_parameters = refined_params;
incremented_refined_parameters[i]+=increment;
a_model.calculate(incremented_refined_parameters);
IntensityMap jacobian = a_model.model_scaled_to_experiment();
jacobian.subtract(base_model);
WriteHDF5("Jacobian_" + refined_params_names[i] + ".h5", jacobian);
if(jacobian.can_be_fourier_transformed()) {
jacobian.scale_and_fft(inverse_scale);
WriteHDF5("PDF_Jacobian_" + refined_params_names[i] + ".h5", jacobian);
}
}
}
OutputHandler report;
int main (int argc, char * const argv[]) {
try {
REPORT(MAIN) << "Yell 1.2.6\n";
REPORT(MAIN) <<
"The software is provided 'as-is', without any warranty.\nIf you find any bug report it to https://github.com/YellProgram/Yell/issues\n\n";
if (!file_exists("model.txt")) {
REPORT(ERROR) << "model.txt does not exits.\n";
throw(TerminateProgram());
}
string input = read_input_file("model.txt");
Model a_model(input);
REPORT(MAIN) << "Input file read, performing a test calculation...\n";
///estimate calculation time. Also initialize a_model.refinement_parameters
time_t start, end;
start = time(NULL);
vector<double> initial_params(100000, 0);//TODO: I do not need it now. Check.
a_model.calculate(initial_params, false);// Ititial run. measures time, imports initial parameters.
end = time(NULL);
REPORT(MAIN) << "Parsing is ok.\n";
REPORT(MAIN) << "Scattering is calculated in " << difftime(end, start) << " sec.\n";
print_essential_information_about_crystal(a_model);
REPORT(MAIN) << "Number of refined parameters: " << a_model.refinement_parameters.size() << '\n';
/* for(int i=0; i<a_model.refinement_parameters.size(); ++i)
REPORT(MAIN)<< a_model.refinement_parameters[i] << ' ';
REPORT(MAIN) << '\n';*/
vec3<int> grid_size = a_model.grid.grid_size;
a_model.pdf_multiplier.load_data_and_report("pdf_multiplier.h5", "pdf multiplier", grid_size);
a_model.weights.load_data_and_report("weights.h5", "weights", grid_size);
a_model.reciprocal_space_multiplier.load_data_and_report("reciprocal_space_multiplier.h5",
"reciprocal space multiplier", grid_size);
report.expect_first_calculation(); //set up the output handler so that it prints all the nessesary information from the first run
OptionalIntensityMap experimental_diffuse_map;
experimental_diffuse_map.load_data_and_report("experiment.h5", "experimental data", grid_size);
if (experimental_diffuse_map.is_loaded)
experimental_diffuse_map.get_intensity_map()->set_grid(a_model.grid);
if (a_model.refinement_flag) //refinement
{
if (!experimental_diffuse_map.is_loaded) {
REPORT(ERROR) << "Experimental data not found \n";
throw(TerminateProgram());
}
Minimizer a_minimizer;
vector<double> refined_params;
refined_params = a_minimizer.minimize(a_model.refinement_parameters, experimental_diffuse_map.get_intensity_map(),
&a_model, &a_model.weights, a_model.refinement_options);
vector<double> esd = esd_from_covar(a_minimizer.covar, refined_params);
REPORT(MAIN) << "Refined parameters are:\nScale " << format_esd(refined_params[0], esd[0]) <<
"\nRefinableVariables\n[\n";
for (int i = 1; i < refined_params.size(); ++i)
REPORT(MAIN) << a_model.refined_variable_names[i] << '=' << format_esd(refined_params[i], esd[i]) << ";\n";
REPORT(MAIN) << "]\n";
std::ofstream out_refined_params("refined_parameters.txt");
out_refined_params << "Refined parameters are:\nScale " << refined_params[0]<<
"\nRefinableVariables\n[\n";
for (int i = 1; i < refined_params.size(); ++i)
out_refined_params << a_model.refined_variable_names[i] << '=' << refined_params[i]<< ";\n";
out_refined_params << "]\n";
report.last_run();
a_model.calculate(refined_params);
a_model.refinement_parameters = refined_params;
if (a_model.print_covariance_matrix)
print_covariance(a_minimizer.covar, refined_params);
print_correlations(a_minimizer.covar, refined_params, a_model.refined_variable_names);
}
else {
report.last_run();
a_model.calculate(a_model.refinement_parameters);
}
if (experimental_diffuse_map.is_loaded) {
REPORT(MAIN) << " Rw=" << a_model.R_factor(*experimental_diffuse_map.get_intensity_map(), R2, WEIGHTED) << endl;
}
WriteHDF5("full.h5", a_model.intensity_map);
WriteHDF5("average.h5", a_model.average_intensity_map);
WriteHDF5("model.h5", a_model.model_scaled_to_experiment());
if (a_model.grid.grid_is_compatible_with_fft()) {
IntensityMap normalized_delta_pdf = a_model.model_scaled_to_experiment();
normalized_delta_pdf.scale_and_fft(1 / a_model.refinement_parameters[0]);
WriteHDF5("delta-pdf.h5", normalized_delta_pdf);
if (experimental_diffuse_map.is_loaded) {
IntensityMap normalized_d2_pdf = *experimental_diffuse_map.get_intensity_map();
normalized_d2_pdf.subtract(a_model.model_scaled_to_experiment());
WriteHDF5("exp-minus-model.h5", normalized_d2_pdf);
normalized_d2_pdf.scale_and_fft(1 / a_model.refinement_parameters[0]);
WriteHDF5("delta-delta-pdf.h5", normalized_d2_pdf);
experimental_diffuse_map.get_intensity_map()->scale_and_fft(1 / a_model.refinement_parameters[0]);
WriteHDF5("exp-delta-pdf.h5", *experimental_diffuse_map.get_intensity_map());
}
}
if (a_model.calculate_jacobians)
calculate_Jacobians(a_model);
REPORT(MAIN) << '\n';
return EXIT_SUCCESS;
} catch (const TerminateProgram&)
{
return EXIT_FAILURE;
}
}
| C++ |
3D | YellProgram/Yell | src/precompiled_header.h | .h | 1,413 | 41 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_real.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/phoenix/bind/bind_member_function.hpp>
#include <boost/phoenix/operator/member.hpp>
#include <boost/phoenix/operator/self.hpp>
#include <boost/phoenix/object/construct.hpp>
#include <boost/phoenix/bind/bind_function.hpp>
#include <boost/phoenix/object/new.hpp>
#include <boost/variant.hpp>
#include "boost/tuple/tuple.hpp"
#include <vector>
#include <string>
namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
typedef std::string::iterator iterator_ ; | Unknown |
3D | YellProgram/Yell | src/test_diffuser.h | .h | 95,823 | 2,542 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cxxtest/TestSuite.h>
#include "basic_classes.h"
#include <boost/fusion/tuple.hpp>
#include "precompiled_header.h"
#include "InputFileParser.h"
#include <cstdlib>
#define a_skipper a_parser.skipper_no_assignement
#include <iostream>
#include <fstream>
#ifndef PATH_TO_YELL_SRC
#define PATH_TO_YELL_SRC "./src"
#endif
OutputHandler report;
namespace qi = boost::spirit::qi;
typedef std::string::iterator iterator_;
class TestDummy
{
public:
class Destructed {};
TestDummy() {}
~TestDummy()
{
throw Destructed();
}
};
class TestMinimizerCalculator : public MinimizerCalculator{
public:
TestMinimizerCalculator(): data_(10,1,1) { }
void calculate(vector<double> inp_params)
{
for(int i=0; i<10; i++)
data_.at(i)=inp_params[i];
}
IntensityMap& data() { return data_; }
IntensityMap data_;
};
class MyTestSuite : public CxxTest::TestSuite
{
public:
void setUp() {
unit_matrix=sym_mat3<double>(1,1,1,0,0,0);
trivial_unit_cell=cctbx::uctbx::unit_cell(scitbx::af::tiny<double,6>(1,1,1,90,90,90));
atom1 = Atom(string("C"),0.5,0,0,0,1,1,1,0,0,0);
atom2 = Atom(string("C2"),0.5,.5,.5,.5,1,1,1,0,0,0);
p_atom1 = new Atom(atom1);
p_atom2 = new Atom(atom2);
}
InputParser a_parser;
sym_mat3<double> unit_matrix;
cctbx::uctbx::unit_cell trivial_unit_cell;
Atom atom1;
Atom atom2;
Atom* p_atom1;
Atom* p_atom2;
void testOutputHandlerSitsShut() {
REPORT(FIRST_RUN) << "ERROR in testOutputHandlerSitsShut\n";
}
void testIntensityMapActsLikeArray (void) {
IntensityMap I(2,1,1);
I.at(0,0,0)=1;
TS_ASSERT_EQUALS(I.at(0,0,0),1);
}
void testIntensityMap_flip_signs_in_chessboard_way()
{
IntensityMap I(2,1,1);
I.at(0,0,0)=1;
I.at(1,0,0)=1;
I.flip_signs_in_chessboard_way();
TS_ASSERT_EQUALS(1,I.at(0,0,0)); // 1 1 -> -1 (1)
TS_ASSERT_EQUALS(-1,I.at(1,0,0));
IntensityMap I4(4,1,1);
for(int i=0; i<4; ++i)
I4.at(i,0,0)=1;
I4.flip_signs_in_chessboard_way();
TS_ASSERT_EQUALS(1,I4.at(0,0,0)); // 1 1 (1) 1 -> 1 -1 (1) -1
TS_ASSERT_EQUALS(-1,I4.at(1,0,0));
TS_ASSERT_EQUALS(1,I4.at(2,0,0));
TS_ASSERT_EQUALS(-1,I4.at(3,0,0));
}
void test_grid_gives_grid_in_pdf_space()
{
Grid grid(cctbx::uctbx::unit_cell(scitbx::af::tiny<double,6>(1,1,1,90,90,90)), vec3<double>(1,1,1),vec3<double>(-1,0,0));
TS_ASSERT_EQUALS(false,grid.in_pdf_space().reciprocal_flag);
}
void test_grid_checks_pairs_within()
{
Grid grid(cctbx::uctbx::unit_cell(scitbx::af::tiny<double,6>(1,1,1,90,90,90)), vec3<double>(1,1,1),vec3<double>(-1,-1,-1),false);
// we will assume grid is symmetric boundaries
AtomicPair a_pair(atom1,atom2);
TS_ASSERT_EQUALS(true, a_pair.pair_is_withing(grid));
a_pair.average_r()=vec3<double>(2,0,0);
TS_ASSERT_EQUALS(false, a_pair.pair_is_withing(grid));
}
void testIntensityConditionalInverts()
{
IntensityMap I(2,1,1);
I.set_grid(cctbx::uctbx::unit_cell(scitbx::af::tiny<double,6>(1,1,1,90,90,90)), vec3<double>(1,1,1),vec3<double>(-1,0,0));
double reciprocal=12;
I.at(0,0,0)=reciprocal;
I.at(1,0,0)=17;
double pdf=(17.0-12);
I.to_reciprocal();
TS_ASSERT_EQUALS(reciprocal,I.at(0,0,0));
I.to_real();
TS_ASSERT_EQUALS(pdf,I.at(0,0,0));
I.to_real();
TS_ASSERT_EQUALS(pdf,I.at(0,0,0));
I.to_reciprocal();
TS_ASSERT_EQUALS(reciprocal,I.at(0,0,0));
}
void testIntensityInvert()
{
IntensityMap I(2,1,1);
I.set_grid(cctbx::uctbx::unit_cell(scitbx::af::tiny<double,6>(1,1,1,90,90,90)), vec3<double>(1,1,1),vec3<double>(-1,0,0));
I.at(0,0,0)=1;
I.at(1,0,0)=1;
I.invert();
TS_ASSERT_EQUALS(I.at(0,0,0),0);
TS_ASSERT_EQUALS(I.at(1,0,0),2);
I.at(0,0,0)=12;
I.at(1,0,0)=17;
I.invert();
TS_ASSERT_EQUALS((17.0-12)/2,I.at(0,0,0));
TS_ASSERT_EQUALS((17.0+12)/2,I.at(1,0,0));
I.invert();
TS_ASSERT_EQUALS(12,I.at(0,0,0));
TS_ASSERT_EQUALS(17,I.at(1,0,0));
}
void test_ew_mult()
{
vec3<double> v(1,2,3);
TS_ASSERT_EQUALS(ew_mult(v,v),vec3<double>(1,4,9));
TS_ASSERT_EQUALS(ew_mult(v,vec3<double>(2,2,2)),
vec3<double>(2,4,6));
}
void testIntensityMapActsLikeIterator()
{
IntensityMap I(1,2,3);
I.init_iterator();
for(int i=0; i<6; i++)
{
TS_ASSERT_EQUALS(I.next(),true);
I.current_array_value()=i;
}
TS_ASSERT_EQUALS(I.next(),false);
TS_ASSERT_EQUALS(I.at(0,1,2),5);
}
void testGrid()
{
Grid aGrid(cctbx::uctbx::unit_cell(scitbx::af::tiny<double,6>(10,10,10,90,90,90)), //unit cell
vec3<double>(0.1,0.1,0.1), //grid steps
vec3<double>(-1,-1,-1)); //lower limits of grid
TS_ASSERT_EQUALS(aGrid.s_at(af::tiny<int,3>(0,0,0)),vec3<double>(-1,-1,-1));
TS_ASSERT_EQUALS(aGrid.s_at(af::tiny<int,3>(0,1,2)),vec3<double>(-1,-0.9,-.8));
TS_ASSERT_DELTA(aGrid.d_star_square_at(af::tiny<int,3>(0,0,0)),.03,.0000001);
}
void testIntensityIsIntegratedWithGrid()
{
IntensityMap I(2,2,2);
I.set_grid(trivial_unit_cell,
vec3<double>(1,1,1),
vec3<double>(-.5,-.5,-.5));
I.set_grid(Grid(trivial_unit_cell,
vec3<double>(1,1,1),
vec3<double>(-.5,-.5,-.5)));
I.init_iterator();
I.next();
TS_ASSERT_DELTA(I.current_d_star_square(),0.75,0.00001);
TS_ASSERT_EQUALS(I.current_s(),vec3<double>(-.5,-.5,-.5));
}
void testIntensityCalculatorAtLeastPretendsThatItWorks()
{
bool AVERAGE = true;
vector<AtomicPair> pairs;
//Atom atom1(string("C"),0.5,0,0,0,1,1,1,0,0,0);
//Atom atom2(string("C2"),0.5,.5,.5,.5,1,1,1,0,0,0);
pairs.push_back(AtomicPair(atom1,atom2));
pairs.push_back(AtomicPair(atom1,atom1));
pairs.push_back(AtomicPair(atom2,atom2));
IntensityMap I(2,2,2);
I.set_grid(trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-.5,-.5,-.5));
TS_ASSERT_THROWS_NOTHING(IntnsityCalculator::calculate_scattering_from_pairs(pairs,I,AVERAGE));
}
void testIntensityCalculatorAtom()
{
double pi=M_PI;
TS_ASSERT_DELTA(real(IntnsityCalculator::calculate_scattering_from_a_pair_in_a_point_c(1, 1, 1, 1, vec3<double>(0.5,0.5,0.5), //s
vec3<double>(0.25,0.25,0.25), //r
sym_mat3<double>(0.01,0.02,0.03,0,0,0))),
-1/1.41421356237*exp(-2*pi*pi*(0.01+0.02+0.03)*0.5*0.5),0.0001); //1.41421356237 is sqrt(2)
}
void testVectorMultiplication() {
vec3<double>a(1,1,1);
TS_ASSERT_DELTA(a*a,3,0.00001);
}
void testIntensityMap_size() {
IntensityMap I(2,12,1);
TS_ASSERT_EQUALS(12,I.size()[1]);
TS_ASSERT_EQUALS(vec3<int>(2,12,1),I.size());
}
void testIntensityMapCopiesDeeply() {
IntensityMap I1(1,1,1);
I1.at(0,0,0)=100;
IntensityMap I2 = I1;
I2.at(0,0,0)=200;
IntensityMap I22 = I2;
TS_ASSERT_EQUALS(100,I1.at(0,0,0));
TS_ASSERT_EQUALS(200,I2.at(0,0,0));
TS_ASSERT_EQUALS(200,I22.at(0,0,0));
}
void testAtomicTypeAndCollection() {
Scatterer* at=AtomicTypeCollection::get(string("C"), XRay);
Scatterer* at2=AtomicTypeCollection::get(string("C1"), XRay);
TS_ASSERT_DELTA(at->form_factor_at(0),5.9972,0.0001);
TS_ASSERT_EQUALS(at,at2);
TS_ASSERT_THROWS_NOTHING(AtomicTypeCollection::calculate_form_factors_of_all_atoms_on_grid(vec3<int>(2,2,2),Grid(trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-1,-1,-1))));
}
void testNeutronScattering() {
Scatterer* at=AtomicTypeCollection::get(string("H"), Neutron);
double res = at->form_factor_at_c(vec3<double> (0,0,0), 0).real();
TS_ASSERT_DELTA(res, -3.7390, 0.0001);
}
void testElectronScattering() {
Scatterer* at=AtomicTypeCollection::get(string("C"), Electrons);
TS_ASSERT_DELTA(at->form_factor_at(0),5.9972,0.0001); //Once it fails here stick the correct value which is 2.5092
}
void testMolecularType() {
Atom* an_atom = new Atom(string("C2"),0.5,.5,.5,.5,0,0,0,0,0,0);
AtomicAssembly a_molecule;
a_molecule.add_chemical_unit(an_atom);
MolecularScatterer scatterer(&a_molecule);
vec3<double> s(1,0,0);
AtomicTypeCollection::update_current_form_factors(s,0);
//sr = 0.5
TS_ASSERT_DELTA(-5.9972/2, scatterer.form_factor_at_c(s,0).real(), 0.0001);
TS_ASSERT_DELTA(0, scatterer.form_factor_at_c(s,0).imag(), 0.0001);
// Add interface in the input file
// check against some old calculated dataset
}
void testStripAtomicLabel() {
TS_ASSERT_EQUALS("C",AtomicTypeCollection::strip_label("C"));
TS_ASSERT_EQUALS("Cl",AtomicTypeCollection::strip_label("Cl"));
TS_ASSERT_EQUALS("Cl",AtomicTypeCollection::strip_label("Cl15690"));
TS_ASSERT_EQUALS("C",AtomicTypeCollection::strip_label("C25"));
}
void testAtomicAssembly()
{
AtomicAssembly molecule;
AtomicAssembly* molecule_fragment = new AtomicAssembly();
molecule_fragment->add_chemical_unit(p_atom1);
molecule.add_chemical_unit(molecule_fragment);
molecule.add_chemical_unit(p_atom2);
vector<Atom*> v;
v.push_back(p_atom1);
v.push_back(p_atom2);
TS_ASSERT_EQUALS(v,molecule.get_atoms());
}
void testAtom()
{
Atom anAtom(string("C12"),1,0,0,0,1,1,1,0,0,0);
TS_ASSERT_EQUALS(anAtom.r,vec3<double>(0,0,0));
TS_ASSERT_DELTA(anAtom.atomic_type->form_factor_at(0),5.9972,0.0001);
vector<Atom*> v;
v.push_back(&anAtom);
TS_ASSERT_EQUALS(v ,anAtom.get_atoms());
}
void testAtomUiso()
{
cctbx::uctbx::unit_cell cell(af::double6(1,1,7,90,90,120));
Atom anAtom(string("C12"),1, 1,0,0,0, 0.1, cell.reciprocal_metrical_matrix());
TS_ASSERT_DELTA(0.4/3,anAtom.U[0],0.00001);
TS_ASSERT_DELTA(0.4/3,anAtom.U[1],0.00001);
TS_ASSERT_DELTA(0.1/7/7,anAtom.U[2],0.00001);
TS_ASSERT_DELTA(0.4/6,anAtom.U[3],0.00001);
TS_ASSERT_DELTA(0,anAtom.U[4],0.00001);
TS_ASSERT_DELTA(0,anAtom.U[5],0.00001);
}
void testAtomicPair()
{
AtomicPair a;
a.r()=vec3<double>(1,1,1);//real
a.r(true)=vec3<double>(0,0,0);//average
TS_ASSERT_EQUALS(a.r(false),vec3<double>(1,1,1));
TS_ASSERT_EQUALS(a.r(true),vec3<double>(0,0,0));
}
void testAtomAndPair()
{
Atom at1(string("C"),0.12,0.5,0,0,0,1,1,1,0,0,0);
Atom at2(string("C2"),0.7,0.5,1,1,1,1,1,1,0,0,0);
AtomicPair pair(at1,at2);
TS_ASSERT_EQUALS(pair.r(),vec3<double>(1,1,1));
TS_ASSERT_EQUALS(pair.U(),sym_mat3<double>(2,2,2,0,0,0));
TS_ASSERT_EQUALS(pair.p(),0.25);
TS_ASSERT_EQUALS(pair.average_r(),vec3<double>(1,1,1));
TS_ASSERT_EQUALS(pair.average_U(),sym_mat3<double>(2,2,2,0,0,0));
TS_ASSERT_EQUALS(pair.average_p(),0.25);
TS_ASSERT_DELTA(pair.atomic_type1->form_factor_at(0),5.9972,0.0001);
TS_ASSERT_DELTA(pair.multiplier,0.7*0.12,0.00001);
}
void helperTestPointerVector()
{
p_vector<TestDummy> v;
v.push_back(new TestDummy());
TS_ASSERT_THROWS_NOTHING(v[0]);
TS_ASSERT_EQUALS(v.size(),1);
}
void testPointerVector()
{
TS_ASSERT_THROWS_ANYTHING(helperTestPointerVector()); //TestDummy will throw exception on destruction
}
void testItIsPossibleToCreateArray()
{
UnitCell cell(1,1,1,90,90,90);
cell.set_laue_symmetry("4mm");
ChemicalUnitNode* node = new ChemicalUnitNode();
AtomicAssembly* cu = new AtomicAssembly();
Atom* atom = new Atom(string("C"),0.5,0,0,0,1,1,1,0,0,0);
cu->add_chemical_unit(atom);
atom = new Atom(string("C2"),0.5,0,0,0,1,1,1,0,0,0);
cu->add_chemical_unit(atom);
node->add_chemical_unit(cu);
cell.add_node(node);
CreateThomasStructure();
//maybe check that the construction is valid?
}
void CreateThomasStructure()
{/*
UnitCell cell(3,3,1,90,90,90);
cell.set_laue_symmetry("4mm");
ChemicalUnitNode* node = new ChemicalUnitNode();
AtomicAssembly* cu1 = new AtomicAssembly();
cu1->set_occupancy(0.5);
cu1->add_chemical_unit(new Atom("C",0.5,0.54,0.54,0,0.05,0.05,0,0,0,0));
cu1->add_chemical_unit(new Atom("C",0.5,-0.54,-0.54,0,0.05,0.05,0,0,0,0));
node->add_chemical_unit(cu1);
AtomicAssembly* cu2 = new AtomicAssembly();
cu2->set_occupancy(0.5);
cu2->add_chemical_unit(new Atom("C",0.5,-0.54,0.54,0,0.05,0.05,0,0,0,0));
cu2->add_chemical_unit(new Atom("C",0.5,0.54,-0.54,0,0.05,0.05,0,0,0,0));
node->add_chemical_unit(cu2);
cell.add_node(node);
const int X=0;
const int Y=1;
//Create translational modes
ADPMode cu1_x = translational_mode(cu1,X);
ADPMode cu1_y = translational_mode(cu1,Y);
ADPMode cu2_x = translational_mode(cu2,X);
ADPMode cu2_y = translational_mode(cu2,Y);
AtomicPairPool zeroth_neighbor;
//Create manually things that should've been generatrd by node
zeroth_neighbor.add_modifier( new SubstitutionalCorrelation(cu1,cu2,0));
zeroth_neighbor.add_modifier( new SubstitutionalCorrelation(cu1,cu1,1));
zeroth_neighbor.add_modifier( new SubstitutionalCorrelation(cu2,cu2,1));
//Now we manually find that amplitude of translational modes of both chemical units equals 0.05. This will be our hard constraint
zeroth_neighbor.add_modifier( new DoubleADPMode(&cu1_x,&cu1_x,0.05) );
zeroth_neighbor.add_modifier( new DoubleADPMode(&cu1_y,&cu1_y,0.05) );
zeroth_neighbor.add_modifier( new DoubleADPMode(&cu2_x,&cu2_x,0.05) );
zeroth_neighbor.add_modifier( new DoubleADPMode(&cu2_y,&cu2_y,0.05) );
AtomicPairPool first_neighbor;
first_neighbor.add_modifier( new CellShifter(1,0,0) );
vector<double> corr;
corr.push_back(0.572/2);
first_neighbor.add_modifiers( correlators_from_cuns(node,node,corr));
*/
/*
идеально было бы конечно иметь нечто вроде
UnitCell 3 3 1 90 90 90
Symmetry 4mm
Node node1
ChemicalUnit cu1 p=0.5
atom C 0.54 0.54 0 0.05 0.05 0 0 0 0
atom C -0.54 -0.54 0 0.05 0.05 0 0 0 0
ChemicalUnit cu2 p=0.5
atom C -0.54 0.54 0 0.05 0.05 0 0 0 0
atom C 0.54 -0.54 0 0.05 0.05 0 0 0 0
Pool zero
node1 substitutional correlations
cu1 x mode
cu1 y mode
cu2 x mode
cu2 y mode
Pool one (1 0 0)
node1 - node1 substitutional correlation p=0.572
*/
}
void testPoolFindsPairs()
{
AtomicPairPool aPool;
aPool.get_pair(&atom1,&atom1).p()=0;
aPool.get_pair(&atom1,&atom2);
TS_ASSERT_EQUALS(2,aPool.pairs.size());
TS_ASSERT_EQUALS(0,aPool.get_pair(&atom1,&atom1).p());
TS_ASSERT_EQUALS(2,aPool.pairs.size());
}
void testPoolInvokesCorrelators()
{
AtomicPairPool aPool;
aPool.add_modifier(new CellShifter(1,0,0));
aPool.add_modifier(new SubstitutionalCorrelation(p_atom1,p_atom1,0));
aPool.invoke_correlators();
TS_ASSERT_EQUALS(0,aPool.get_pair(p_atom1,p_atom1).p());
TS_ASSERT_EQUALS(vec3<double>(1,0,0),aPool.get_pair(p_atom1,p_atom1).r());
TS_ASSERT_EQUALS(vec3<double>(1,0,0),aPool.get_pair(p_atom1,p_atom1).average_r());
}
void testCellShifter()
{
AtomicPairPool aPool;
aPool.get_pair(&atom1,&atom1);
CellShifter shifter(0,1,2);
shifter.modify_pairs(&aPool);
TS_ASSERT_EQUALS(vec3<double>(0,1,2),aPool.get_pair(&atom1,&atom1).average_r());
TS_ASSERT_EQUALS(vec3<double>(0,1,2),aPool.get_pair(&atom1,&atom1).r());
}
void testSubstitutionalCorrelation()
{
ChemicalUnitNode node;
Atom* atom3 = new Atom("Si",0.5,2,2,2,0,0,0,0,0,0);
AtomicAssembly unit;
unit.set_occupancy(0.5);
unit.add_chemical_unit(p_atom1);
unit.add_chemical_unit(p_atom2);
AtomicPairPool aPool;
SubstitutionalCorrelation corr(&unit,atom3,0.5);
corr.modify_pairs(&aPool);
TS_ASSERT_EQUALS(0.5,aPool.get_pair(p_atom1,atom3).p());
TS_ASSERT_EQUALS(0.25,aPool.get_pair(p_atom1,atom3).average_p());
}
void testADPMode()
{
ADPMode mode1,mode2;
TS_ASSERT_EQUALS(mode1,mode2);
mode1.add_atom(&atom1, vec3<double>(1,2,3));
TS_ASSERT(mode1!=mode2);
mode2.add_atom(&atom1, vec3<double>(1,2,3));
TS_ASSERT_EQUALS(mode1,mode2);
mode1.add_atom(&atom2, vec3<double>(1,2,3));
mode2.add_atom(&atom1, vec3<double>(1,2,3));
TS_ASSERT(mode1!=mode2);
mode2.atomic_displacements[1].atom=&atom2;
TS_ASSERT_EQUALS(mode1,mode2);
mode2.atomic_displacements[1].displacement_vector = vec3<double>(1,3,2);
TS_ASSERT(mode1!=mode2);
}
void testDoubleADPMode()
{
ADPMode mode1,mode2;
mode1.add_atom(p_atom1,vec3<double>(1,0,0));
AtomicPairPool aPool;
DoubleADPMode(&mode1,&mode1,1).modify_pairs(&aPool);
TS_ASSERT_EQUALS(0,aPool.get_pair(p_atom1,p_atom1).U()[0]);
//test equals operator
DoubleADPMode dmode1(&mode1,&mode1,1);
DoubleADPMode dmode2(&mode1,&mode2,1);
DoubleADPMode dmode3(&mode1,&mode1,2);
TS_ASSERT_EQUALS(dmode1,dmode1);
TS_ASSERT(!(dmode1==dmode2));
TS_ASSERT(!(dmode1==dmode3));
}
void testZeroVectorCorrelation()
{
ZeroVectorCorrelation zcor1;
AtomicPairPool aPool;
aPool.get_pair(p_atom1,p_atom1);
aPool.get_pair(p_atom1,p_atom2);
zcor1.modify_pairs(&aPool);
sym_mat3<double> zero_ADP(0,0,0,0,0,0);
sym_mat3<double> nozero_ADP(2,2,2,0,0,0);
TS_ASSERT_EQUALS(zero_ADP,aPool.get_pair(p_atom1,p_atom1).U());
TS_ASSERT_EQUALS(nozero_ADP,aPool.get_pair(p_atom1,p_atom1).average_U());
TS_ASSERT_EQUALS(nozero_ADP,aPool.get_pair(p_atom1,p_atom2).U());
aPool = AtomicPairPool();
aPool.get_pair(p_atom1,p_atom1);
aPool.get_pair(p_atom1,p_atom2);
CellShifter(1,0,0).modify_pairs(&aPool);
zcor1.modify_pairs(&aPool);
TS_ASSERT_EQUALS(nozero_ADP,aPool.get_pair(p_atom1,p_atom1).U());
}
void testMultiplicityCorrelation()
{
AtomicPairPool aPool;
double p=aPool.get_pair(p_atom1,p_atom1).p();
double m=15.6;
MultiplicityCorrelation mcor(m);
mcor.modify_pairs(&aPool);
TS_ASSERT_DELTA(p,aPool.get_pair(p_atom1,p_atom1).p(),0.00001);
TS_ASSERT_DELTA(p,aPool.get_pair(p_atom1,p_atom1).average_p(),0.00001);
TS_ASSERT_DELTA(m,aPool.get_pair(p_atom1,p_atom1).multiplier,0.00001);
}
void testTranslationalMode()
{
UnitCell cell(10,10,10,90,90,90);
AtomicAssembly* cu1 = new AtomicAssembly();
cu1->add_chemical_unit(p_atom1);
cu1->add_chemical_unit(p_atom2);
ADPMode* cu1_x = translational_mode(cu1,0,cell.cell.metrical_matrix());
TS_ASSERT(almost_equal(vec3<double>(0.1,0,0),cu1_x->atomic_displacements[0].displacement_vector));
delete cu1_x;
}
void test_rotational_mode()
{
UnitCell cell(2,2,3,90,90,90);
AtomicAssembly* cu1 = new AtomicAssembly();
cu1->add_chemical_unit(p_atom1);//0 0 0
cu1->add_chemical_unit(p_atom2);//.5 .5 .5
ADPMode* cu1_z = rot_mode(cu1,vec3<double>(0,0,1),vec3<double>(0,0,0),cell.cell.metrical_matrix());//z - rotation
TS_ASSERT_EQUALS(vec3<double>(0,0,0),cu1_z->atomic_displacements[0].displacement_vector);
TS_ASSERT(almost_equal(vec3<double>(-0.5,0.5,0),cu1_z->atomic_displacements[1].displacement_vector));
ADPMode* cu1_hex_z=rot_mode(cu1,vec3<double>(0,0,1),vec3<double>(0,0,0),sym_mat3<double>(1,1,1,0.5,0,0));//z - rotation
TS_ASSERT_DELTA(-0.2887,cu1_hex_z->atomic_displacements[1].displacement_vector[0],0.0001);
TS_ASSERT_DELTA(0.2887,cu1_hex_z->atomic_displacements[1].displacement_vector[1],0.0001);
}
void testCorrelationFromCUNS()
{
p_atom2->occupancy=0.3;
Atom* p_atom3 = new Atom("Si",0.2,2,2,2,0,0,0,0,0,0);
Atom* p_atom21 = new Atom(*p_atom3);
Atom* p_atom22 = new Atom(*p_atom2);
Atom* p_atom23 = new Atom(*p_atom1);
ChemicalUnitNode node1;
node1.add_chemical_unit(p_atom1);
node1.add_chemical_unit(p_atom2);
node1.add_chemical_unit(p_atom3);
ChemicalUnitNode node2;
node2.add_chemical_unit(p_atom21);
node2.add_chemical_unit(p_atom22);
node2.add_chemical_unit(p_atom23);
vector<double> corr;
corr.push_back(0.1);
corr.push_back(0.1);
corr.push_back(0.2);
corr.push_back(0.0);
// Probabilities will be:
// 0.5 0.3 0.2
// 0.2 0.1 0.1 0.0
// 0.3 0.2 0.0 0.1
// 0.5 0.2 0.2 0.1
//
// in an array in row-coloumn order
vector<SubstitutionalCorrelation*> correlations = correlators_from_cuns(&node1,&node2,corr);
TS_ASSERT_EQUALS(9,correlations.size());
SubstitutionalCorrelation corr32(p_atom3, p_atom22, 0.3);
SubstitutionalCorrelation corr33(p_atom3, p_atom23, 0.0);
TS_ASSERT_EQUALS(0.0,correlations[2]->joint_probability);
TS_ASSERT_EQUALS(p_atom3,correlations[2]->chemical_units[0]);
TS_ASSERT_EQUALS(p_atom21,correlations[2]->chemical_units[1]);
TS_ASSERT_DELTA(0.1,correlations[5]->joint_probability,0.000001);
TS_ASSERT_EQUALS(p_atom3,correlations[5]->chemical_units[0]);
TS_ASSERT_EQUALS(p_atom22,correlations[5]->chemical_units[1]);
TS_ASSERT_DELTA(0.1,correlations[8]->joint_probability,0.000001);
TS_ASSERT_EQUALS(p_atom3,correlations[8]->chemical_units[0]);
TS_ASSERT_EQUALS(p_atom23,correlations[8]->chemical_units[1]);
for(int i=0; i<correlations.size(); i++)
delete correlations[i];
}
void testOuterProduct()
{
TS_ASSERT_EQUALS(sym_mat3<double>(0,1,6,0,0,3), outer_product(vec3<double>(0,1,2),vec3<double>(0,1,3)));
}
void testStaticShift(){
StaticShift shift;
ADPMode* atom1_x=translational_mode(&atom1,0,unit_matrix);
ADPMode* atom2_x=translational_mode(&atom2,0,unit_matrix);
ADPMode* atom1_y=translational_mode(&atom1,1,unit_matrix);
ADPMode* atom2_y=translational_mode(&atom2,1,unit_matrix);
shift.add_displacement(VectorStart,atom1_x,0.25);
shift.add_displacement(VectorEnd,atom2_x,-0.25);
shift.add_displacement(VectorStart,atom1_y,0.25);
shift.add_displacement(VectorEnd,atom2_y,-0.25);
AtomicPairPool pool;
shift.modify_pairs(&pool);
TS_ASSERT_DELTA(0,pool.get_pair(&atom1,&atom2).r()[0],0.0001);
TS_ASSERT_DELTA(0,pool.get_pair(&atom1,&atom2).r()[1],0.0001);
}
void testSizeEffect()
{
ADPMode* atom2_x=translational_mode(&atom2,0,unit_matrix);
SizeEffect size_effect_cu_adp(&atom1,atom2_x,0.5);//initially distance is (0.5,0.5,0.5) -> (1,0.5,0.5)
SizeEffect size_effect_adp_cu(atom2_x,&atom1,0.5);// dist is -(0.5,0.5,0.5) -> -(1,0.5,0.5)
AtomicPairPool pool;
size_effect_cu_adp.modify_pairs(&pool);
size_effect_adp_cu.modify_pairs(&pool);
TS_ASSERT(almost_equal( vec3<double>(1,0.5,0.5) , pool.get_pair(&atom1,&atom2).r() ));
TS_ASSERT(almost_equal( vec3<double>(-1,-0.5,-0.5) , pool.get_pair(&atom2,&atom1).r() ));
}
///TODO: make this test
void testGridReciprocal()
{
//still too lazy to write this test
//Grid grid(trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-.5,-.5,-.5)));
}
void test_grid_and_residual()
{
vec3<double> r_res;
vec3<int> r_grid;
grid_and_residual(vec3<double>(2.1,3.8,-0.51),
Grid(trivial_unit_cell,vec3<double>(1,1,0.5),vec3<double>(0,0,0)),
r_grid,r_res);
TS_ASSERT_DELTA(0.1,r_res[0],0.00001);
TS_ASSERT_DELTA(-0.2,r_res[1],0.00001);
TS_ASSERT_DELTA(-0.01,r_res[2],0.00001);
TS_ASSERT_EQUALS(vec3<int>(2,4,-1),r_grid);
grid_and_residual(vec3<double>(2.1,3.8,-0.51),
Grid(trivial_unit_cell,vec3<double>(1,1,0.5),vec3<double>(-1,-1,-1)),
r_grid,r_res);
TS_ASSERT_EQUALS(vec3<int>(3,5,1),r_grid);
}
void test_add_pair_to_appropriate_place()
{
IntensityMap P(20,20,1);
P.set_grid(trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-10,-10,0));
P.at(14,12,0)=0;
IntensityMap part_of_P(4,4,1);
part_of_P.set_grid(trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-2,-2,0));
part_of_P.at(0,0,0)=150;
add_pair_to_appropriate_place(part_of_P,P,vec3<int>(16,14,0),vector<bool> (3,false));
TS_ASSERT_EQUALS(part_of_P.at(0,0,0),P.at(14,12,0));
TS_ASSERT_THROWS_NOTHING(add_pair_to_appropriate_place(part_of_P,P,vec3<int>(20000,20000,0),vector<bool> (3,false)));
}
void test_add_pair_to_appropriate_place_with_periodic_boundary_conditions()
{
IntensityMap P(2,2,1);
P.set_grid(trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-1,-1,0));
P.erase_data();
IntensityMap part_of_P(2,2,1);
part_of_P.set_grid(trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-1,-1,0));
// 1 2
// 3 4
part_of_P.at(0,0,0)=1.0;
part_of_P.at(0,1,0)=2.0;
part_of_P.at(1,0,0)=3.0;
part_of_P.at(1,1,0)=4;
// 0 0
// 0 1
P.erase_data();
add_pair_to_appropriate_place(part_of_P,P,vec3<int>(2,2,0),vector<bool>(3,false));
TS_ASSERT_EQUALS(0,P.at(0,0,0));
TS_ASSERT_EQUALS(0,P.at(0,1,0));
TS_ASSERT_EQUALS(0,P.at(1,0,0));
TS_ASSERT_EQUALS(1.0,P.at(1,1,0));
P.erase_data();
// 4 3
// 2 1
add_pair_to_appropriate_place(part_of_P,P,vec3<int>(2,2,0),vector<bool>(3,true));
TS_ASSERT_EQUALS(4,P.at(0,0,0));
TS_ASSERT_EQUALS(3,P.at(0,1,0));
TS_ASSERT_EQUALS(2,P.at(1,0,0));
TS_ASSERT_EQUALS(1,P.at(1,1,0));
vector<bool> only_y(3,false);
only_y.at(1)=true;
P.erase_data();
// 0 0
// 2 1
add_pair_to_appropriate_place(part_of_P,P,vec3<int>(2,2,0),only_y);
TS_ASSERT_EQUALS(0,P.at(0,0,0));
TS_ASSERT_EQUALS(0,P.at(0,1,0));
TS_ASSERT_EQUALS(2.0,P.at(1,0,0));
TS_ASSERT_EQUALS(1.0,P.at(1,1,0));
}
void test_misc()
{
TS_ASSERT_EQUALS(0,1/2);
TS_ASSERT_EQUALS(vec3<int>(0,1,1),vec3<int>(1,2,3)/2);
TS_ASSERT_EQUALS(0.5-0.5,0);
}
void test_unique()
{
const int SIZE = 10;
int a1[ SIZE ] = { 1, 3, 5, 7, 7, 9, 1, 3, 5, 7 };
std::vector< int > inp( a1, a1 + SIZE ); // copy of a
std::vector< int > res( a1, a1 + 4 ); // Unique values of a
res.push_back(9);
TS_ASSERT_EQUALS(res,unique_elements(inp));
}
void test_apply_symmetry_element_to_atomic_assembly()
{
AtomicAssembly group;
AtomicAssembly* subgroup = new AtomicAssembly();
subgroup->add_chemical_unit(p_atom1);
subgroup->add_chemical_unit(p_atom2);
group.add_chemical_unit(subgroup);
ChemicalUnit* symmetry_equivalent = group.create_symmetric(mat3<double>(1,0,0,0,1,0,0,0,1),vec3<double>(0,0,0));
TS_ASSERT_EQUALS(2,symmetry_equivalent->get_atoms().size());
delete symmetry_equivalent;
//TODO: make the test
//TS_FAIL("check occupancy of AtomicAssembly");
Atom atom = Atom(string("C"),0.5,1,2,3,1,2,3,4,5,6);
Atom* sym_atom = atom.create_symmetric(mat3<double>(-1,0,0,0,1,0,0,0,1), vec3<double>(0,0,100));
TS_ASSERT_EQUALS(vec3<double>(-1,2,103),sym_atom->r);
TS_ASSERT_EQUALS(sym_mat3<double>(1,2,3,-4,-5,6),sym_atom->U);
delete sym_atom;
}
void test_minimizer()
{
Minimizer a_minimizer;
vector<double> params(10,0);
for(int i=0; i<10; i++)
params[i]=(double)(10-i)/10;
TestMinimizerCalculator calc;
IntensityMap exp_data(10,1,1);
for(int i=0; i<10; i++)
exp_data.at(i)=7;
OptionalIntensityMap weights;
report.shut_up();
params = a_minimizer.minimize(params, &exp_data, &calc, &weights);
TS_ASSERT_DELTA(params[0],7,0.001);
}
void test_hdf5_reader()
{
IntensityMap map_123 = ReadHDF5(PATH_TO_YELL_SRC "/test_files/123.h5");
TS_ASSERT_DELTA(1,map_123.at(0),0.01);
TS_ASSERT_DELTA(2,map_123.at(1),0.01);
TS_ASSERT_DELTA(3,map_123.at(2),0.01);
}
void testOptionalIntensityMap()
{
OptionalIntensityMap map(138690);
TS_ASSERT_DELTA(138690, map.at(31), 0.01);
map.load_data(PATH_TO_YELL_SRC "/test_files/123.h5");
TS_ASSERT_DELTA(1,map.at(0),0.01);
TS_ASSERT_DELTA(2,map.at(1),0.01);
TS_ASSERT_DELTA(3,map.at(2),0.01);
//test that unloaded functions do not break
OptionalIntensityMap unloaded_map(0);
TS_ASSERT_DELTA(0, unloaded_map.at(312), 0.01);
unloaded_map.load_data("file_does_not_exist.h5");
TS_ASSERT_DELTA(0,unloaded_map.at(0),0.01);
TS_ASSERT_DELTA(0,unloaded_map.at(1),0.01);
}
void test_file_exists()
{
TS_ASSERT_EQUALS(true, file_exists(PATH_TO_YELL_SRC "/test_files/123.h5"));
TS_ASSERT_EQUALS(false, file_exists("does.not.exist"));
}
void test_R_factor()
{
Model a_model;
IntensityMap I(2,1,1);
I.at(0)=2;
I.at(1)=10;
IntensityMap I0(2,1,1);
I0.at(0)=0;
I0.at(1)=0;
IntensityMap I_half(2,1,1);
I_half.at(0)=1;
I_half.at(1)=5;
a_model.intensity_map = I;
a_model.average_intensity_map = I0;
TS_ASSERT_DELTA(0,a_model.R_factor(I,R1,UNWEIGHTED), 0.001);
TS_ASSERT_DELTA(1, a_model.R_factor(I_half,R1,UNWEIGHTED),0.001);
}
void test_padded_intensity_map()
{
IntensityMap I(2,1,1);
IntensityMap I_padded(4,1,1);
for(int i=0;i<4;++i)
I_padded.at(i)=i;
I.copy_from_padded(vec3<int> (1,0,0),I_padded);
TS_ASSERT_EQUALS(1,I.at(0));
TS_ASSERT_EQUALS(2,I.at(1));
}
void test_create_padded_map()
{
Grid a_grid (trivial_unit_cell,vec3<double>(0.1,0.1,0.1), vec3<double>(-1,-2,-3),vec3<int>(10,10,10));
Grid padded_grid = a_grid.pad(vec3<int>(3,2,1));
TS_ASSERT_EQUALS(vec3<double>(-1.3,-2.2,-3.1),padded_grid.lower_limits);
TS_ASSERT_EQUALS(vec3<int>(16,14,12),padded_grid.grid_size);
}
// the following functions are used to test qi parsers
template<class Attr,class parser_type,class skipper_type>
bool test_parser(Attr expected, string input,parser_type& a_parser,skipper_type skipper)
{
iterator_ start = input.begin();
iterator_ end = input.end();
Attr result;
return qi::phrase_parse(start,end,a_parser,skipper,result) && start==end && result == expected ;
}
template<class parser_type,class Attr>
bool test_parser(Attr expected,string input,parser_type& a_parser)
{
iterator_ start = input.begin();
iterator_ end = input.end();
Attr result;
return qi::parse(start,end,a_parser,result) && start==end && result == expected ;
}
template<class parser_type>
bool test_parser(double expected,string input,parser_type& a_parser)
{
iterator_ start = input.begin();
iterator_ end = input.end();
double result;
return qi::parse(start,end,a_parser,result) && start==end && almost_equal(result, expected) ;
}
template<class parser_type,class skipper_type>
bool test_parser_nores(string input,parser_type& a_parser,skipper_type skipper)
{
iterator_ start = input.begin();
iterator_ end = input.end();
return qi::phrase_parse(start,end,a_parser,skipper) && start==end;
}
template<class parser_type>
bool test_parser_nores(string input,parser_type& a_parser)
{
iterator_ start = input.begin();
iterator_ end = input.end();
return qi::parse(start,end,a_parser) && start==end ;
}
template<class parser_type,class skipper_type,class result_class>
bool run_parser(string input,parser_type a_parser, skipper_type skipper,result_class& result )
{
iterator_ start = input.begin();
iterator_ end = input.end();
bool r = qi::phrase_parse(start,end,a_parser,skipper,result);
TS_ASSERT(r);
TS_ASSERT(start==end);
return r && (start==end);
}
template<class parser_type,class result_class>
bool run_parser(string input,parser_type a_parser, result_class& result )
{
iterator_ start = input.begin();
iterator_ end = input.end();
bool r = qi::parse(start,end,a_parser,result);
TS_ASSERT(r);
TS_ASSERT(start==end);
return r && (start==end);
}
void test_atom_parser() {
Atom * atom;
a_parser.add_model(new Model());
test_parser_nores("Cell 1 1 1 90. 90. 90.",a_parser.program_options,a_skipper);
run_parser("C1 0.3 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0",a_parser.atom,a_skipper,atom);
TS_ASSERT_DELTA(0.3,atom->multiplier,0.01);
TS_ASSERT_DELTA(-0.0107,atom->r[0],0.01);
TS_ASSERT_DELTA(0.066,atom->U[0],0.01);
delete atom;
//check how Uiso parser works
run_parser("C1 0.5 0 0 0 0.1",a_parser.atom,a_skipper,atom);
TS_ASSERT_EQUALS(Atom("C1",0.5,1,0,0,0, 0.1,0.1,0.1,0,0,0),*atom);
delete atom;
}
void test_molecular_form_factor() {
Scatterer *scatterer, *not_initialized_scatterer;
a_parser.add_model(new Model());
test_parser_nores("Cell 1 1 1 90. 90. 90.",a_parser.program_options,a_skipper);
run_parser("[C1 0.5 0 0 0 0.1\n C1 0.5 0 0 0 0.1]",a_parser.molecular_scatterer,a_skipper,scatterer);
TS_ASSERT_DIFFERS(scatterer, not_initialized_scatterer);
vector<boost::tuple<string,Scatterer*> > scatterers;
run_parser("MolecularScatterers[ C_molecule=[C1 0.5 0 0 0 0.1\n C1 0.5 0 0 0 0.1] Nop=[] ]",a_parser.molecular_scatterers,a_skipper,scatterers);
TS_ASSERT_EQUALS(2,scatterers.size());
TS_ASSERT_EQUALS(boost::get<0>(scatterers[0]), "C_molecule");
TS_ASSERT_DIFFERS(boost::get<1>(scatterers[0]), not_initialized_scatterer);
TS_ASSERT_EQUALS(boost::get<1>(scatterers[0]), AtomicTypeCollection::get("C_molecule", XRay)); //it is done by molecular_scatterers do register it
}
void test_atomic_assembly_parser() {
AtomicAssembly* assembly;
run_parser("[ C1 21.0 0 0 0 0 0 0 0 0 0 C2 0 10 0 0 0 0 0 0 0 0 ]",a_parser.atomic_assembly,a_skipper,assembly);
TS_ASSERT_DELTA(21.0,(*assembly)[0]->get_atoms()[0]->multiplier,0.01);
TS_ASSERT_DELTA(10.0,(*assembly)[1]->get_atoms()[0]->r[0],0.01);
delete assembly;
}
void test_chemical_unit_parser() {
ChemicalUnit * unit;
run_parser("C1 0.1238 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0",a_parser.chemical_unit,a_skipper,unit);
TS_ASSERT_DELTA(0.1238,unit->get_atoms()[0]->multiplier,0.0001);//should wrap the atom
delete unit;
run_parser("[ C1 0.3215 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0 ]",a_parser.chemical_unit,a_skipper,unit);
TS_ASSERT_DELTA(0.3215,unit->get_atoms()[0]->multiplier,0.0001);//should wrap the atom atomic assembly
delete unit;
}
void test_identifier_assignement() {
ChemicalUnit* unit;
StructurePartRef assigned_unit;
run_parser("an_atom1 =[ C1 0.3215 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0 ]",a_parser.chemical_unit,a_skipper,unit);
run_parser("an_atom1",a_parser.identifier,assigned_unit);
TS_ASSERT_EQUALS(StructurePartRef(unit),assigned_unit);
delete unit;
}
void test_variant() {
ChemicalUnitNode * a_variant;
run_parser("Variant[ (p=0.9876) an_atom1 =[ C1 0.3215 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0 ] (p=1-0.9876)Void]",a_parser.variant,a_skipper,a_variant);
TS_ASSERT_DELTA(0.9876,a_variant->chemical_units[0].get_atoms()[0]->occupancy,0.0001);
}
void test_variant_assignement() {
ChemicalUnitNode * a_variant;
StructurePartRef assigned_unit;
run_parser("our_variant = Variant[ (p=0.9876) an_atom1 =[ C1 0.3215 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0 ] (p=1-0.9876)[]]",a_parser.variant_assignement,a_skipper,a_variant);
run_parser("our_variant",a_parser.identifier,assigned_unit);
TS_ASSERT_EQUALS(StructurePartRef(a_variant),assigned_unit);
}
void test_symmetry_parser() {
SymmetryElement unity(mat3<double>(1,0,0,0,1,0,0,0,1),vec3<double>(0,0,0));
TS_ASSERT_EQUALS(SymmetryElement(),unity); //check that we implemented operator==
TS_ASSERT_DIFFERS(SymmetryElement(mat3<double>(.9,0,0,0,1,0,0,0,1),vec3<double>(0,0,0)),unity);
TS_ASSERT(test_parser(0,"x",a_parser.basis_vector));
double r[] = {1,-1,1,0.5};
vector<double> correct;
correct.insert(correct.end(),r,r+4);
vector<double> res;
run_parser("x-y+z+1/2",a_parser.permutation_component,a_skipper,res);
TS_ASSERT_EQUALS(correct,res);
// -x; +x; x-y-1/2;x+1/2;
TS_ASSERT(test_parser(unity, "Symmetry(x,y,z)",a_parser.symmetry_element,a_skipper));//unity
mat3<double> xyz(1,0,0,0,1,0,0,0,1);
TS_ASSERT(test_parser(SymmetryElement(xyz,vec3<double>(1,0,0)), "Symmetry(x+1,y,z)",a_parser.symmetry_element,a_skipper));
TS_ASSERT(test_parser(SymmetryElement(xyz,vec3<double>(3,0,0)), "Symmetry(3+x,y,z)",a_parser.symmetry_element,a_skipper));
TS_ASSERT(test_parser(SymmetryElement(xyz,vec3<double>(3,125.0/6,0)), "Symmetry(3+x,125/6+y,z)",a_parser.symmetry_element,a_skipper));
}
void test_symmetric_atomic_assembly() {
ChemicalUnit * unchanged_atom;
run_parser("some_atom = C 0.123 1 2 3 11 22 33 12 13 23",a_parser.chemical_unit,a_skipper,unchanged_atom);
ChemicalUnit * changed_atom;
run_parser("some_atom*Symmetry(y,x,z)",a_parser.chemical_unit,a_skipper,changed_atom);
// some_atom*Symmetry[y,x,z] == C 0.123 2 1 3 22 11 33 12 23 13
TS_ASSERT_EQUALS(Atom("C",0.123,1,2,1,3,22,11,33,12,23,13),*(changed_atom->get_atoms()[0]));
TS_ASSERT(test_parser_nores("Void",a_parser.chemical_unit,a_skipper));
delete unchanged_atom;
delete changed_atom;
}
void test_expression_calculator() {
FormulaParser formula_parser;
TS_ASSERT(test_parser(-12.0,"-12",formula_parser));
TS_ASSERT(test_parser(4.0,"2*2",formula_parser));
TS_ASSERT(test_parser(4.0,"2+2",formula_parser));
TS_ASSERT(test_parser(5.0,"1+2*2",formula_parser));
TS_ASSERT(test_parser(6.0,"(1+2)*2",formula_parser));
TS_ASSERT(test_parser(-12.8749,"ll=-12.8749",formula_parser));
TS_ASSERT(test_parser(-12.8749,"ll",formula_parser));
TS_ASSERT(test_parser(12.8749,"-ll",formula_parser));
TS_ASSERT(test_parser(-12.8749*2,"2*ll",formula_parser));
TS_ASSERT(!test_parser_nores("",formula_parser));
}
void test_expression_calculator_variable_redefinition() {
FormulaParser formula_parser;
TS_ASSERT(test_parser(2,"a=2",formula_parser));
TS_ASSERT(test_parser(2,"a",formula_parser));
TS_ASSERT(test_parser(5.2,"a=5.2",formula_parser));
TS_ASSERT(!test_parser(2,"a",formula_parser));
TS_ASSERT(test_parser(5.2,"a",formula_parser));
}
void test_special_funcitons_in_expression_calculator() {
FormulaParser formula_parser;
//Special funcitons. Tests generated with the following matlab code:
/*functions = {'log','sin','cos','exp','sqrt','abs'};
for i=1:length(functions)
res = eval([functions{i} '(2)']);
fprintf('TS_ASSERT(test_parser(%.10f,"%s(2)",formula_parser));\n',res,functions{i});
end*/
TS_ASSERT(test_parser( 0.6931471806,"log(2)",formula_parser));
TS_ASSERT(test_parser( 0.9092974268,"sin(2)",formula_parser));
TS_ASSERT(test_parser(-0.4161468365,"cos(2)",formula_parser));
TS_ASSERT(test_parser( 7.3890560989,"exp(2)",formula_parser));
TS_ASSERT(test_parser( 1.4142135624,"sqrt(2)",formula_parser));
TS_ASSERT(test_parser( 2.0000000000,"abs(2)",formula_parser));
TS_ASSERT(test_parser(1.5,"mod(1.5,2)",formula_parser));
TS_ASSERT(test_parser(9,"pow(3,2)",formula_parser));
}
void test_crystal_parameters_parser() {
Model a_model;
a_parser.add_model(&a_model);
/*
Cell 14.115 14.115 6.93 90 90 90
ll=-12.8749
gs=-ll*2/104
DiffuseScatteringGrid ll ll -6 gs gs 1 12 12 12
*/
TS_ASSERT(test_parser_nores("Cell 14.115 14.115 6.93 90 90 90\n \nDiffuseScatteringGrid -6 -6 -6 1 1 1 12 12 12",a_parser.program_options,a_skipper));
TS_ASSERT(UnitCell(14.115,14.115,6.93,90,90,90) == a_model.cell);
TS_ASSERT_EQUALS(Grid(UnitCell(14.115,14.115,6.93,90,90,90).cell,vec3<double>(1,1,1),vec3<double>(-6,-6,-6),vec3<int>(12,12,12)),a_model.intensity_map.grid);
TS_ASSERT(test_parser_nores("Cell 14.115 14.115 6.93 90 90 90 gs=1; ll=-6; DiffuseScatteringGrid ll ll ll gs gs gs 12 12 12",a_parser.program_options,a_skipper)); //gs=1
TS_ASSERT(UnitCell(14.115,14.115,6.93,90,90,90) == a_model.cell);
TS_ASSERT_EQUALS(Grid(UnitCell(14.115,14.115,6.93,90,90,90).cell,vec3<double>(1,1,1),vec3<double>(-6,-6,-6),vec3<int>(12,12,12)),a_model.intensity_map.grid);
}
void test_unit_cell_parser() {
Model a_model;
a_model.cell = UnitCell(1,2,3,90,90,90);
a_parser.add_model(&a_model);
/*
UnitCell
[
Var = Variant[
(p=0.5)
C1 0.5 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0
]
]
*/
TS_ASSERT_EQUALS(0,a_model.cell.chemical_unit_nodes.size()); //start with empty model
TS_ASSERT(test_parser_nores(" UnitCell \
[ \
Var = Variant[ \
(p=0.5) \
C1 0.5 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0 \
(p=0.5) \
[] \
] \
]",
a_parser.unit_cell,a_skipper));
TS_ASSERT_EQUALS(1,a_model.cell.chemical_unit_nodes.size()); //check that we now have one unit node
TS_ASSERT_EQUALS(Atom("C1", 0.5,-0.0107,0.8970,0.1319,0.066,0.066/4,0.066/9,-0.033/2,0,0),*a_model.cell.chemical_unit_nodes[0].chemical_units[0].get_atoms()[0]);
}
void test_substitutional_correlation_parser() {
ChemicalUnitNode* var;
vector<SubstitutionalCorrelation*> corrs,expected_corrs;
run_parser("a_variant = Variant[(p=0.5) C1 0.5 -0.0107 0.8970 0.1319 0.066 0.066 0.066 -0.033 0 0 (p=0.5)[] ]",a_parser.variant_assignement,a_skipper,var);
run_parser("SubstitutionalCorrelation(a_variant,a_variant,0.5)",a_parser.substitutional_correlation,a_skipper,corrs);
expected_corrs = correlators_from_cuns(var,var,vector<double>(1,0.5));
for(int i=0; i<expected_corrs.size(); i++)
{
TS_ASSERT_EQUALS(*expected_corrs[i],*corrs[i]);
delete expected_corrs[i];
delete corrs[i];
}
delete var;
}
void test_multiplicity_correlation_parser() {
MultiplicityCorrelation* mlt;
run_parser("Multiplicity 0.5",a_parser.multiplicity_correlation,a_skipper,mlt);
TS_ASSERT_EQUALS(MultiplicityCorrelation(0.5),*mlt);
delete mlt;
}
void test_cell_shifter_parser() {
CellShifter* cell_shifter;
run_parser("(0,1,2)",a_parser.cell_shifter,a_skipper,cell_shifter);
TS_ASSERT_EQUALS(CellShifter(0,1,2),*cell_shifter);
delete cell_shifter;
}
void test_pool_parser() {
AtomicPairPool* pool;
run_parser("[(0,1,2) Multiplicity 0.5]",a_parser.atomic_pair_pool,a_skipper,pool);
// todo test that multiplicity correlations also work
TS_ASSERT_EQUALS(2,pool->modifiers.size());
delete pool;
}
void test_correlations_parser() {
//todo change behavior of run_parser so that it returns true if parsed and false if not, warnings showing what's wrong
vector<AtomicPairPool*> pools;
run_parser("Correlations[ [(1,2,3)] [Multiplicity 0.5 (3,2,1)] ]",a_parser.correlations,a_skipper,pools);
TS_ASSERT_EQUALS(2,pools.size());
for(int i=0; i<pools.size(); i++)
delete pools[i];
}
void test_input_file_parser_grammar() {
Model a_model;
a_parser.add_model(&a_model);
const char* crystal_params =
"Cell 14.115 14.115 6.93 90 90 90 \n\
ll=-12.8749; \n\
gs=-ll*2/104; \n\
DiffuseScatteringGrid ll ll -6 gs gs 1 104 104 12\n\
LaueSymmetry mmm\n";
const char* unit_cell =
"UnitCell \
[ \
Var = Variant[ \
(p=1) \
C1 0.5 -0.010700 -0.103000 0.131900 0.000287 0.000236 0.000770 0.000136 0.000092 0.000031 \
] \
]\n";
const char* modes= "Modes [ ] \n";
const char* correlations =
"Correlations \
[ \
[(0,0,0) \
Multiplicity 0.5] \
]";
string cryst = crystal_params;
cryst += unit_cell ;
cryst += modes;
cryst += correlations;
TS_ASSERT(test_parser_nores(crystal_params,a_parser.program_options,a_skipper));
TS_ASSERT(test_parser_nores(unit_cell,a_parser.unit_cell,a_skipper));
TS_ASSERT(test_parser_nores(correlations,a_parser.correlations,a_skipper));
TS_ASSERT(test_parser_nores(cryst,a_parser,a_skipper));
}
void test_translational_mode_parser() {
Model a_model;
a_parser.add_model(&a_model);
ChemicalUnit* one_atom;
const char cell [] = "Cell 1 1 1 90 90 90 \n\
DiffuseScatteringGrid 0 0 0 0 0 0 0 0 0\n\
LaueSymmetry -1";
test_parser_nores(cell,a_parser.program_options,a_skipper);
run_parser("one_atom = [C1 0.5 -0.010700 -0.103000 0.131900 0.000287 0.000236 0.000770 0.000136 0.000092 0.000031]",a_parser.chemical_unit_assignement,a_skipper,one_atom);
ADPMode* answer = translational_mode(one_atom, 0,unit_matrix);
ADPMode* res;
run_parser("TranslationalMode(one_atom,x)",a_parser.translational_mode,a_skipper,res);
TS_ASSERT_EQUALS(*answer,*res);
}
void test_rotational_mode_parser() {
Model a_model;
double prm[]={1,1,1,90,90,120};
vector<double> unit_cell_params(prm,prm+6);
a_model.initialize_unit_cell(unit_cell_params);
a_parser.add_model(&a_model);
ChemicalUnit* one_atom;
run_parser("atom_rot = [C1 0.5 -0.010700 -0.103000 0.131900 0.000287 0.000236 0.000770 0.000136 0.000092 0.000031]",a_parser.chemical_unit_assignement,a_skipper,one_atom);
ADPMode* answer = rot_mode(one_atom, vec3<double>(0,0,1), vec3<double>(0,0,0),a_model.cell.cell.metrical_matrix());
ADPMode* res;
run_parser("RotationalMode(atom_rot, 0,0,1, 0,0,0)",a_parser.rotational_mode,a_skipper,res);
TS_ASSERT_EQUALS(*answer,*res);
}
void test_modes_parser() {
Model a_model;
a_model.cell = UnitCell(1,1,1,90,90,90);
a_parser.add_model(&a_model);
ChemicalUnit* one_atom;
run_parser("modes_atom = [C1 0.5 -0.010700 -0.103000 0.131900 0.000287 0.000236 0.000770 0.000136 0.000092 0.000031]",a_parser.chemical_unit_assignement,a_skipper,one_atom);
ADPMode* answer = translational_mode(one_atom, 1,unit_matrix);
StructurePartRef res;
TS_ASSERT(test_parser_nores("Modes[ mode1 = TranslationalMode(modes_atom,y) ]",a_parser.modes,a_skipper));
run_parser("mode1",a_parser.identifier,a_skipper,res);
ADPMode* result=boost::get<ADPMode*>(res);
TS_ASSERT_EQUALS(*answer,*result);
TS_ASSERT_EQUALS(1,a_model.modes.size());
TS_ASSERT_EQUALS(boost::get<ADPMode*>(res),&a_model.modes[0]);
}
void test_adp_correlation_parser() {
Model a_model;
a_parser.add_model(&a_model);
test_parser_nores("modes_atom2 = [C1 0.5 -0.010700 -0.103000 0.131900 0.000287 0.000236 0.000770 0.000136 0.000092 0.000031]",a_parser.chemical_unit_assignement,a_skipper);
test_parser_nores("Modes[ mode_x = TranslationalMode(modes_atom,x) mode_y = TranslationalMode(modes_atom,y)]",a_parser.modes,a_skipper);
ADPMode *mol_x = &a_model.modes[0];
ADPMode *mol_y = &a_model.modes[1];
DoubleADPMode correct(mol_x,mol_y,0.123);
DoubleADPMode *res;
TS_ASSERT(run_parser("ADPCorrelation(mode_x,mode_y,0.123)",a_parser.adp_correlation,a_skipper,res));
TS_ASSERT_EQUALS(*res,correct);
}
void test_initialization_of_refinable_variables() {
Model a_model;
a_parser.add_model(&a_model);
vector<boost::fusion::tuple<string,double> > res;
run_parser("RefinableVariables[ a= 1 b=0; c=0 d=0.12(19);]",a_parser.refinable_parameters,a_skipper,res);
TS_ASSERT_EQUALS(4, res.size());
TS_ASSERT_EQUALS("a",boost::fusion::get<0>(res[0]));
TS_ASSERT_EQUALS(1,boost::fusion::get<1>(res[0]));
TS_ASSERT_EQUALS("b",boost::fusion::get<0>(res[1]));
TS_ASSERT_EQUALS(0,boost::fusion::get<1>(res[1]));
TS_ASSERT_EQUALS(0.12,boost::fusion::get<1>(res[3]));
}
void test_size_effect_corrlation_parser() {
Model a_model;
a_parser.add_model(&a_model);
ChemicalUnit* se_atom;
run_parser("se_atom = [C1 0.5 -0.010700 -0.103000 0.131900 0.000287 0.000236 0.000770 0.000136 0.000092 0.000031]",a_parser.chemical_unit_assignement,a_skipper,se_atom);
ADPMode* mode;
run_parser("se_atom_x = TranslationalMode(se_atom,x)",a_parser.mode_assignement,a_skipper,mode);
SizeEffect* res;
TS_ASSERT(run_parser("SizeEffect(se_atom,se_atom_x,0.123)",a_parser.size_effect,a_skipper,res));
TS_ASSERT_EQUALS(SizeEffect(se_atom,mode,0.123),*res);
TS_ASSERT(run_parser("SizeEffect(se_atom_x,se_atom,0.123)",a_parser.size_effect,a_skipper,res)); //other order of operands
TS_ASSERT_EQUALS(SizeEffect(mode,se_atom,0.123),*res);
}
void notest_integrated_minimizer() {
// create model that should be refined
// unit cell 1 1 1 90 90 90
// atoms [0.5 0;-0.5 0;][ 0 0.5;0 -0.5]
string model = "Cell 1 1 1 90 90 90 \n\
DiffuseScatteringGrid -1 -1 -1 0.1 0.1 0.1 20 20 20 \n\
InitialParams 1 0.0 \
UnitCell \
[ \
Var = Variant[ \
(p=0.5) \
[ C1 0.5 0.5 0 0 0 0 0 0 0 0 \
C2 0.5 -0.5 0 0 0 0 0 0 0 0 \
]\
(p=0.5)\
[ C3 0.5 0 0.5 0 0 0 0 0 0 0 \
C4 0.5 0 -0.5 0 0 0 0 0 0 0 \
] \
] \
] \
Correlations \
[ \
[(0,0,0) \
Multiplicity 0.5 \
SubstitutionalCorrelation(Var,Var,0.25+~i)] \
]";
// calculate diffuse scattering from the model with known correlation
Model a_model(model);
//hook to raw internal function of diffuse scattering caclulation
vector<double> params(1,1);
params.push_back(0.25);
a_model.calculate(params);
IntensityMap diffuse_map(a_model.data().size());
for(int i=0; i<diffuse_map.size_1d(); ++i)
diffuse_map.at(i) = a_model.data().at(i);
// run minimizer and compare results
Minimizer a_minimizer;
//vector<double> initial_params(1,0);
vector<double> refined_params(2,0);
OptionalIntensityMap weights;
refined_params = a_minimizer.minimize(a_model.refinement_parameters, &diffuse_map, &a_model, &weights);
TS_ASSERT_DELTA(1.0,refined_params[0],0.01);
TS_ASSERT_DELTA(0.25,refined_params[1],0.01);
}
void test_laue_symmetry_is_compatible_with_lattice() {
TS_ASSERT(LaueSymmetry("-1").is_compatible_with_cell(UnitCell(1,2,3,70,80,99)));
TS_ASSERT_EQUALS(false,LaueSymmetry("2/m").is_compatible_with_cell(UnitCell(1,2,3,70,80,99)));
TS_ASSERT_EQUALS(false,LaueSymmetry("6/m").is_compatible_with_cell(UnitCell(1,1,1,90,90,90)));
TS_ASSERT_EQUALS(true,LaueSymmetry("-3mR").is_compatible_with_cell(UnitCell(1,1,1,90,90,90)));
}
///TODO: write this test, since I destrroyed the old one
void test_laue_symmetry_apply_symmetry_to_pairs()
{
Grid incompatible_grid(trivial_unit_cell, vec3<double> (1,2,3), vec3<double> (1,2,3),vec3<int> (1,2,3));
LaueSymmetry laue("4/m",incompatible_grid);
vector<AtomicPair> pairs;
Atom atom3(string("C2"),1, 0.5,0.25,0, 1,0,0,-1,0,0);
AtomicPair aPair(atom1,atom3);
pairs.push_back(aPair);
pairs = laue.apply_patterson_symmetry(pairs);
TS_ASSERT_EQUALS(8,pairs.size());
pairs.clear();
pairs.push_back(aPair);
incompatible_grid = Grid(trivial_unit_cell, vec3<double> (0.1,0.1,0.1), vec3<double> (-9,-9,0), vec3<int>(180,180,1));
laue = LaueSymmetry("m-3m",incompatible_grid);
pairs = laue.apply_patterson_symmetry(pairs);
TS_ASSERT_EQUALS(3,pairs.size());
//with the following symmetry and grid there is one symmetry element which should be applied to pairs
// namely -y,x-y,z - three fold rotation
incompatible_grid = Grid(trivial_unit_cell,
vec3<double> (1,0.5,1), //centering is all right
vec3<double> (-9,-4.5,0), // but grid steps are different.
vec3<int>(18,18,1));
laue = LaueSymmetry("-3H",incompatible_grid);
pairs.clear();
pairs.push_back(aPair); // coordinates are 0.5 0.25 0
// symmetry equivalent are -0.25,0.25,0 and -0.25,-0.5,0
pairs = laue.apply_patterson_symmetry(pairs);
TS_ASSERT_EQUALS(3,pairs.size());
TS_ASSERT(almost_equal(vec3<double>(-0.25,0.25,0),pairs[1].r()));
TS_ASSERT(almost_equal(vec3<double>(-0.25,-0.5,0),pairs[2].r()));
}
void test_laue_symmetry_apply_matrix_generator()
{
LaueSymmetry laue;
mat3<double> T(-1,0,0,0,1,0,0,0,1); //mirror plane
vector<AtomicPair> pairs;
pairs.push_back(AtomicPair(atom1,atom2));// 0 0 0->0.5 0.5 0
pairs[0].U()=sym_mat3<double>(1,2,3,1,0,0);
pairs=laue.apply_matrix_generator(pairs,T,2);
TS_ASSERT_EQUALS(1,(T*sym_mat3<double>(1,2,3,-1,0,0)*T.transpose())[3]);
TS_ASSERT_EQUALS(2,pairs.size());
TS_ASSERT_EQUALS(vec3<double>(-0.5,0.5,0.5),pairs[1].r());
TS_ASSERT_EQUALS(sym_mat3<double>(1,2,3,-1,0,0),pairs[1].U());
}
void test_Laue_have_same_step() {
LaueSymmetry laue_symmetry;
Grid grid_xy (trivial_unit_cell,vec3<double>(1,1,0.5),vec3<double>(-10,-10,-10),vec3<int>(20,20,20));
TS_ASSERT_EQUALS(true, laue_symmetry.have_same_step_and_ll(grid_xy,"xy"));
TS_ASSERT_EQUALS(false, laue_symmetry.have_same_step_and_ll(grid_xy,"xyxz"));
Grid grid_xy_again (trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-10,-10,-10),vec3<int>(20,20,30));
TS_ASSERT_EQUALS(true, laue_symmetry.have_same_step_and_ll(grid_xy_again,"xy"));
TS_ASSERT_EQUALS(false, laue_symmetry.have_same_step_and_ll(grid_xy_again,"xyxz"));
Grid grid_xyz (trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-10,-10,-10),vec3<int>(20,20,20));
TS_ASSERT_EQUALS(true, laue_symmetry.have_same_step_and_ll(grid_xyz,"xyxz"));
}
void test_Laue_centered_correctly() {
LaueSymmetry laue_symmetry;
Grid grid_xy (trivial_unit_cell,vec3<double>(1,1,0.5),vec3<double>(-10,-10,-10),vec3<int>(20,20,20));
TS_ASSERT_EQUALS(true, laue_symmetry.centered_correctly(grid_xy,"xy"));
TS_ASSERT_EQUALS(false, laue_symmetry.centered_correctly(grid_xy,"z"));
TS_ASSERT_EQUALS(false, laue_symmetry.centered_correctly(grid_xy,"xyz"));
// we do not support grids with uneven lengths
Grid grid_xy_different_step (trivial_unit_cell,vec3<double>(1,0.5,1),vec3<double>(-10,-5,-10),vec3<int>(20,20,21));
TS_ASSERT_EQUALS(true, laue_symmetry.centered_correctly(grid_xy_different_step,"xy"));
TS_ASSERT_EQUALS(false, laue_symmetry.centered_correctly(grid_xy_different_step,"z"));
Grid grid_z (trivial_unit_cell,vec3<double>(1,1,1),vec3<double>(-12,-1,-5),vec3<int>(10,10,10));
TS_ASSERT_EQUALS(true, laue_symmetry.centered_correctly(grid_z,"z"));
}
void test_Laue_generator_initialization() {
Grid grid(trivial_unit_cell,vec3<double>(0.1,0.1,0.1),vec3<double>(-9,-9,0),vec3<int>(180,180,1));
LaueSymmetry laue_symmetry("m-3m",grid);
TS_ASSERT_EQUALS(4, laue_symmetry.generators_on_map.size())
}
//The following block was generated with cctbx
void test_Laue_Symmetry_1bar() {
IntensityMap int_map(10,10,10);
int_map.at(5+3,5+2,5+1)=2; // the group class is 2
LaueSymmetry a_symmetry("-1");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+3,5+2,5+1),1); //xyz
int_map.at(5+3,5+2,5+1)=0;
TS_ASSERT_EQUALS(int_map.at(5-3,5-2,5-1),1); //-x,-y,-z
int_map.at(5-3,5-2,5-1)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_Symmetry_m3m() {
//hall symbol -P 4 2 3
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=48; // the group class
LaueSymmetry a_symmetry("m-3m");
a_symmetry.apply_patterson_symmetry(int_map);
/* this tests are generated with the following cctbx.python script:
from cctbx import sgtbx
import re
sg = sgtbx.space_group("-P 4 2 3")
for i in range(0,sg.order_z()):
line = re.sub(',',',5+',sg(i).as_xyz())
print "TS_ASSERT_EQUALS(int_map.at(5+" + line + "),1); //" + sg(i).as_xyz()
print "int_map.at(5+" + line + ")=0; "
*/
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x,5+z),1); //-y,x,z
int_map.at(5+-y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x,5+z),1); //y,-x,z
int_map.at(5+y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+-z),1); //x,-y,-z
int_map.at(5+x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+-z),1); //y,x,-z
int_map.at(5+y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+-z),1); //-x,y,-z
int_map.at(5+-x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+-z),1); //-y,-x,-z
int_map.at(5+-y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+x,5+y),1); //z,x,y
int_map.at(5+z,5+x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+z,5+y),1); //-x,z,y
int_map.at(5+-x,5+z,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-x,5+y),1); //-z,-x,y
int_map.at(5+-z,5+-x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-z,5+y),1); //x,-z,y
int_map.at(5+x,5+-z,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+-x,5+-y),1); //z,-x,-y
int_map.at(5+z,5+-x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+z,5+-y),1); //x,z,-y
int_map.at(5+x,5+z,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+x,5+-y),1); //-z,x,-y
int_map.at(5+-z,5+x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-z,5+-y),1); //-x,-z,-y
int_map.at(5+-x,5+-z,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+z,5+x),1); //y,z,x
int_map.at(5+y,5+z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-z,5+-x),1); //y,-z,-x
int_map.at(5+y,5+-z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+y,5+-x),1); //z,y,-x
int_map.at(5+z,5+y,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+z,5+-x),1); //-y,z,-x
int_map.at(5+-y,5+z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-y,5+-x),1); //-z,-y,-x
int_map.at(5+-z,5+-y,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-z,5+x),1); //-y,-z,x
int_map.at(5+-y,5+-z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+-y,5+x),1); //z,-y,x
int_map.at(5+z,5+-y,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+y,5+x),1); //-z,y,x
int_map.at(5+-z,5+y,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x,5+-z),1); //y,-x,-z
int_map.at(5+y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z
int_map.at(5+x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x,5+-z),1); //-y,x,-z
int_map.at(5+-y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+z),1); //-x,y,z
int_map.at(5+-x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+z),1); //-y,-x,z
int_map.at(5+-y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+z),1); //x,-y,z
int_map.at(5+x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+z),1); //y,x,z
int_map.at(5+y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-x,5+-y),1); //-z,-x,-y
int_map.at(5+-z,5+-x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-z,5+-y),1); //x,-z,-y
int_map.at(5+x,5+-z,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+x,5+-y),1); //z,x,-y
int_map.at(5+z,5+x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+z,5+-y),1); //-x,z,-y
int_map.at(5+-x,5+z,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+x,5+y),1); //-z,x,y
int_map.at(5+-z,5+x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-z,5+y),1); //-x,-z,y
int_map.at(5+-x,5+-z,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+-x,5+y),1); //z,-x,y
int_map.at(5+z,5+-x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+z,5+y),1); //x,z,y
int_map.at(5+x,5+z,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-z,5+-x),1); //-y,-z,-x
int_map.at(5+-y,5+-z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+z,5+x),1); //-y,z,x
int_map.at(5+-y,5+z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-y,5+x),1); //-z,-y,x
int_map.at(5+-z,5+-y,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-z,5+x),1); //y,-z,x
int_map.at(5+y,5+-z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+y,5+x),1); //z,y,x
int_map.at(5+z,5+y,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+z,5+-x),1); //y,z,-x
int_map.at(5+y,5+z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+y,5+-x),1); //-z,y,-x
int_map.at(5+-z,5+y,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+-y,5+-x),1); //z,-y,-x
int_map.at(5+z,5+-y,5+-x)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_m3bar() {
// hall symbol is -P 2 2 3
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=24; // the group class
LaueSymmetry a_symmetry("m-3");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+-z),1); //x,-y,-z
int_map.at(5+x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+-z),1); //-x,y,-z
int_map.at(5+-x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+x,5+y),1); //z,x,y
int_map.at(5+z,5+x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-x,5+y),1); //-z,-x,y
int_map.at(5+-z,5+-x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+-x,5+-y),1); //z,-x,-y
int_map.at(5+z,5+-x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+x,5+-y),1); //-z,x,-y
int_map.at(5+-z,5+x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+z,5+x),1); //y,z,x
int_map.at(5+y,5+z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-z,5+-x),1); //y,-z,-x
int_map.at(5+y,5+-z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+z,5+-x),1); //-y,z,-x
int_map.at(5+-y,5+z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-z,5+x),1); //-y,-z,x
int_map.at(5+-y,5+-z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z
int_map.at(5+x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+z),1); //-x,y,z
int_map.at(5+-x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+z),1); //x,-y,z
int_map.at(5+x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-x,5+-y),1); //-z,-x,-y
int_map.at(5+-z,5+-x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+x,5+-y),1); //z,x,-y
int_map.at(5+z,5+x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+x,5+y),1); //-z,x,y
int_map.at(5+-z,5+x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+-x,5+y),1); //z,-x,y
int_map.at(5+z,5+-x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-z,5+-x),1); //-y,-z,-x
int_map.at(5+-y,5+-z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+z,5+x),1); //-y,z,x
int_map.at(5+-y,5+z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-z,5+x),1); //y,-z,x
int_map.at(5+y,5+-z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+z,5+-x),1); //y,z,-x
int_map.at(5+y,5+z,5+-x)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_6mmm() {
// hall symbol is -P 6 2
IntensityMap int_map(10,10,10);
int_map.grid.reciprocal_flag=false;
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=24; // the group class
LaueSymmetry a_symmetry("6/mmm");
TS_ASSERT_EQUALS(4,a_symmetry.generators_on_map.size());
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+x,5+z),1); //x-y,x,z
int_map.at(5+x-y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x-y,5+z),1); //-y,x-y,z
int_map.at(5+-y,5+x-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+-x,5+z),1); //-x+y,-x,z
int_map.at(5+-x+y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x+y,5+z),1); //y,-x+y,z
int_map.at(5+y,5+-x+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+-z),1); //-y,-x,-z
int_map.at(5+-y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+-y,5+-z),1); //x-y,-y,-z
int_map.at(5+x-y,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+x-y,5+-z),1); //x,x-y,-z
int_map.at(5+x,5+x-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+-z),1); //y,x,-z
int_map.at(5+y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+y,5+-z),1); //-x+y,y,-z
int_map.at(5+-x+y,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-x+y,5+-z),1); //-x,-x+y,-z
int_map.at(5+-x,5+-x+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+-x,5+-z),1); //-x+y,-x,-z
int_map.at(5+-x+y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x+y,5+-z),1); //y,-x+y,-z
int_map.at(5+y,5+-x+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z //Это как высоченные стены таинственных письмен
int_map.at(5+x,5+y,5+-z)=0; //В комнате стало жарко, как будто одного лаптома достаточно чтобы нагреть всю комнату
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+x,5+-z),1); //x-y,x,-z
int_map.at(5+x-y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x-y,5+-z),1); //-y,x-y,-z
int_map.at(5+-y,5+x-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+z),1); //y,x,z
int_map.at(5+y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+y,5+z),1); //-x+y,y,z
int_map.at(5+-x+y,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-x+y,5+z),1); //-x,-x+y,z
int_map.at(5+-x,5+-x+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+z),1); //-y,-x,z
int_map.at(5+-y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+-y,5+z),1); //x-y,-y,z
int_map.at(5+x-y,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+x-y,5+z),1); //x,x-y,z
int_map.at(5+x,5+x-y,5+z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_6m() {
// hall symbol is -P 6
IntensityMap int_map(10,10,10);
int_map.grid.reciprocal_flag=false;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=12; // the group class
LaueSymmetry a_symmetry("6/m");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+x,5+z),1); //x-y,x,z
int_map.at(5+x-y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x-y,5+z),1); //-y,x-y,z
int_map.at(5+-y,5+x-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+-x,5+z),1); //-x+y,-x,z
int_map.at(5+-x+y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x+y,5+z),1); //y,-x+y,z
int_map.at(5+y,5+-x+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+-x,5+-z),1); //-x+y,-x,-z
int_map.at(5+-x+y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x+y,5+-z),1); //y,-x+y,-z
int_map.at(5+y,5+-x+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z
int_map.at(5+x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+x,5+-z),1); //x-y,x,-z
int_map.at(5+x-y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x-y,5+-z),1); //-y,x-y,-z
int_map.at(5+-y,5+x-y,5+-z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_3barmH() {
// hall symbol is -R 3 2"
IntensityMap int_map(10,10,10);
int_map.grid.reciprocal_flag=false;
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=12; // the group class
LaueSymmetry a_symmetry("-3mH");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x-y,5+z),1); //-y,x-y,z
int_map.at(5+-y,5+x-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+-x,5+z),1); //-x+y,-x,z
int_map.at(5+-x+y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+-z),1); //y,x,-z
int_map.at(5+y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-x+y,5+-z),1); //-x,-x+y,-z
int_map.at(5+-x,5+-x+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+-y,5+-z),1); //x-y,-y,-z
int_map.at(5+x-y,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x+y,5+-z),1); //y,-x+y,-z
int_map.at(5+y,5+-x+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+x,5+-z),1); //x-y,x,-z
int_map.at(5+x-y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+z),1); //-y,-x,z
int_map.at(5+-y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+x-y,5+z),1); //x,x-y,z
int_map.at(5+x,5+x-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+y,5+z),1); //-x+y,y,z
int_map.at(5+-x+y,5+y,5+z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_3barmR() {
// hall symbol is -P 3* 2
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=12; // the group class
LaueSymmetry a_symmetry("-3mR");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+x,5+y),1); //z,x,y
int_map.at(5+z,5+x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+z,5+x),1); //y,z,x
int_map.at(5+y,5+z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+-z),1); //-y,-x,-z
int_map.at(5+-y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-y,5+-x),1); //-z,-y,-x
int_map.at(5+-z,5+-y,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-z,5+-y),1); //-x,-z,-y
int_map.at(5+-x,5+-z,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-x,5+-y),1); //-z,-x,-y
int_map.at(5+-z,5+-x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-z,5+-x),1); //-y,-z,-x
int_map.at(5+-y,5+-z,5+-x)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+z),1); //y,x,z
int_map.at(5+y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+y,5+x),1); //z,y,x
int_map.at(5+z,5+y,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+z,5+y),1); //x,z,y
int_map.at(5+x,5+z,5+y)=0; //Я помню это показалось мне смешной мыслью - если хочешь чтобы все запомнили как тебя зовут, заставь людей вводить твои имя и фамилию чтобы добраться до интернета
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i) //Блин, эту задачу решить совершенно невозможно
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
//Так, надо доделать и уметываться отсюда
//тут слишком много чего отвлекает
//wdtnf цвета конечно крутые
// хаха
}
void test_Laue_symmetry_3barH() {
// hall symbol is -P 3
IntensityMap int_map(10,10,10);
int_map.grid.reciprocal_flag=false;
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=6; // the group class
LaueSymmetry a_symmetry("-3H");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x-y,5+z),1); //-y,x-y,z
int_map.at(5+-y,5+x-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x+y,5+-x,5+z),1); //-x+y,-x,z
int_map.at(5+-x+y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x+y,5+-z),1); //y,-x+y,-z
int_map.at(5+y,5+-x+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x-y,5+x,5+-z),1); //x-y,x,-z
int_map.at(5+x-y,5+x,5+-z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_m3barR() {
// hall symbol is -P 3*
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=6; // the group class
LaueSymmetry a_symmetry("-3R");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+z,5+x,5+y),1); //z,x,y
int_map.at(5+z,5+x,5+y)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+z,5+x),1); //y,z,x
int_map.at(5+y,5+z,5+x)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-z,5+-x,5+-y),1); //-z,-x,-y
int_map.at(5+-z,5+-x,5+-y)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-z,5+-x),1); //-y,-z,-x
int_map.at(5+-y,5+-z,5+-x)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_4mmm() {
// hall symbol is -P 4 2
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=16; // the group class
LaueSymmetry a_symmetry("4/mmm");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x,5+z),1); //-y,x,z
int_map.at(5+-y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x,5+z),1); //y,-x,z
int_map.at(5+y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+-z),1); //x,-y,-z
int_map.at(5+x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+-z),1); //y,x,-z
int_map.at(5+y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+-z),1); //-x,y,-z
int_map.at(5+-x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+-z),1); //-y,-x,-z
int_map.at(5+-y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x,5+-z),1); //y,-x,-z
int_map.at(5+y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z
int_map.at(5+x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x,5+-z),1); //-y,x,-z
int_map.at(5+-y,5+x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+z),1); //-x,y,z
int_map.at(5+-x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+-x,5+z),1); //-y,-x,z
int_map.at(5+-y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+z),1); //x,-y,z
int_map.at(5+x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+x,5+z),1); //y,x,z
int_map.at(5+y,5+x,5+z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_4m() {
// hall symbol is -P 4
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=8; // the group class
LaueSymmetry a_symmetry("4/m");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x,5+z),1); //-y,x,z
int_map.at(5+-y,5+x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x,5+z),1); //y,-x,z
int_map.at(5+y,5+-x,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+y,5+-x,5+-z),1); //y,-x,-z
int_map.at(5+y,5+-x,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z
int_map.at(5+x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-y,5+x,5+-z),1); //-y,x,-z
int_map.at(5+-y,5+x,5+-z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_mmm() {
// hall symbol is -P 2 2
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=8; // the group class
LaueSymmetry a_symmetry("mmm");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+-z),1); //x,-y,-z
int_map.at(5+x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+-z),1); //-x,y,-z
int_map.at(5+-x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z
int_map.at(5+x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+z),1); //-x,y,z
int_map.at(5+-x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+z),1); //x,-y,z
int_map.at(5+x,5+-y,5+z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_2m() {
// hall symbol is -P 2
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=4; // the group class
LaueSymmetry a_symmetry("2/m");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+z),1); //-x,-y,z
int_map.at(5+-x,5+-y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+-z),1); //x,y,-z
int_map.at(5+x,5+y,5+-z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_Laue_symmetry_2mb() {
// hall symbol is -P 2y
IntensityMap int_map(10,10,10);
int x=3,y=2,z=1;
int_map.at(5+x,5+y,5+z)=4; // the group class
LaueSymmetry a_symmetry("2/mb");
a_symmetry.apply_patterson_symmetry(int_map);
TS_ASSERT_EQUALS(int_map.at(5+x,5+y,5+z),1); //x,y,z
int_map.at(5+x,5+y,5+z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+y,5+-z),1); //-x,y,-z
int_map.at(5+-x,5+y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+-x,5+-y,5+-z),1); //-x,-y,-z
int_map.at(5+-x,5+-y,5+-z)=0;
TS_ASSERT_EQUALS(int_map.at(5+x,5+-y,5+z),1); //x,-y,z
int_map.at(5+x,5+-y,5+z)=0;
for(int k=1;k<10;++k)
for(int j=1;j<10;++j)
for(int i=1;i<10;++i)
TS_ASSERT_EQUALS(int_map.at(i,j,k),0); //some unexpected symmetry
}
void test_comment_parser() {
TS_ASSERT(test_parser_nores("#Ruby-type comment\n",a_parser.skipper));
}
void test_filter_asymmetric_unit_m() {
// The symmetry m is a dummy symmetry for the z mirror part of 6/m 4/m 2/m
vector<AtomicPair> pairs;
AtomicPair ethalon(atom1,atom2);
for(int i=0; i<3; ++i)
pairs.push_back(AtomicPair(atom1,atom2));
pairs[1].average_r()=vec3<double>(10,20,0); //occupancy should be 1/2
pairs[2].average_r()=-pairs[2].average_r(); //pair should be deleted
LaueSymmetry a_symmetry("6/m");
pairs=a_symmetry.filter_pairs_from_asymmetric_unit(pairs);
TS_ASSERT_DIFFERS(ethalon,pairs[1]);
TS_ASSERT_EQUALS(ethalon.average_p()/2,pairs[1].average_p()); // x y 0 should decrease occupancy
TS_ASSERT_EQUALS(2,pairs.size());
}
void test_filter_asymmetric_unit_mmm() {
vector<AtomicPair> pairs;
for(int i=0; i<12; ++i)
pairs.push_back(AtomicPair(atom1,atom2));
pairs[0].average_r()=vec3<double>(0,0,0); //occupancy should be 1/8
pairs[1].average_r()=vec3<double>(10,20,0); //occupancy should be 1/2
pairs[2].average_r()=vec3<double>(10,0,13); //occupancy should be 1/2
pairs[3].average_r()=vec3<double>(0,10,20); //occupancy should be 1/2
pairs[4].average_r()=vec3<double>(1,2,3); //This one stays
AtomicPair ethalon=pairs[4];
pairs[5].average_r()=vec3<double>(1,2,-3); //pair should be deleted
pairs[6].average_r()=vec3<double>(1,-2,3); //pair should be deleted
pairs[7].average_r()=vec3<double>(1,-2,-3); //pair should be deleted
pairs[8].average_r()=vec3<double>(-1,2,3); //pair should be deleted
pairs[9].average_r()=vec3<double>(-1,2,-3); //pair should be deleted
pairs[10].average_r()=vec3<double>(-1,-2,3); //pair should be deleted
pairs[11].average_r()=vec3<double>(-1,-2,-3); //pair should be deleted
LaueSymmetry a_symmetry("mmm");
pairs=a_symmetry.filter_pairs_from_asymmetric_unit(pairs);
TS_ASSERT_EQUALS(ethalon.average_p()/8,pairs[0].average_p());
for(int i=1; i<4; ++i)
TS_ASSERT_EQUALS(ethalon.average_p()/2,pairs[i].average_p());
TS_ASSERT_EQUALS(5,pairs.size()); // all the rest are deleted
}
void test_filter_asymmetric_unit_4mmm() {
vector<AtomicPair> pairs;
for(int i=0; i<4; ++i)
pairs.push_back(AtomicPair(atom1,atom2));
pairs[0].average_r()=vec3<double>(0,0,0); //occupancy should be 1/16
pairs[1].average_r()=vec3<double>(10,10,12); //occupancy should be 1/2
pairs[2].average_r()=vec3<double>(3,2,1); //This one stays
AtomicPair ethalon=pairs[2];
pairs[3].average_r()=vec3<double>(2,3,1); //pair should be deleted
LaueSymmetry a_symmetry("4/mmm");
pairs=a_symmetry.filter_pairs_from_asymmetric_unit(pairs);
TS_ASSERT_EQUALS(ethalon.average_p()/16,pairs[0].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/2,pairs[1].average_p());
// TS_ASSERT_EQUALS(ethalon,pairs[2]); // does not change
TS_ASSERT_EQUALS(3,pairs.size());
}
void test_filter_asymmetric_unit_m3m() {
vector<AtomicPair> pairs;
for(int i=0; i<5; ++i)
pairs.push_back(AtomicPair(atom1,atom2));
pairs[0].average_r()=vec3<double>(0,0,0); //occupancy should be 1/48
pairs[1].average_r()=vec3<double>(10,0,0); //occupancy should be 1/8
pairs[2].average_r()=vec3<double>(3,2,1); //This one does not change
AtomicPair ethalon=pairs[2];
pairs[3].average_r()=vec3<double>(2,3,1); //pair should be deleted
pairs[4].average_r()=vec3<double>(2,1,3); //pair should also be deleted
LaueSymmetry a_symmetry("m-3m");
pairs=a_symmetry.filter_pairs_from_asymmetric_unit(pairs);
TS_ASSERT_EQUALS(ethalon.average_p()/48,pairs[0].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/8,pairs[1].average_p());
// TS_ASSERT_EQUALS(ethalon,pairs[2]); // does not change
TS_ASSERT_EQUALS(3,pairs.size());
}
void test_filter_asymmetric_unit_6mmm() {
vector<AtomicPair> pairs;
for(int i=0; i<4; ++i)
pairs.push_back(AtomicPair(atom1,atom2));
pairs[0].average_r()=vec3<double>(0,0,0); //occupancy should be 1/24
pairs[1].average_r()=vec3<double>(10,0,0); //occupancy should be 1/4
pairs[2].average_r()=vec3<double>(5,2,1); //This one does not change
AtomicPair ethalon=pairs[2];
pairs[3].average_r()=vec3<double>(3,2,1); //pair should be deleted
LaueSymmetry a_symmetry("6/mmm");
pairs=a_symmetry.filter_pairs_from_asymmetric_unit(pairs);
TS_ASSERT_EQUALS(ethalon.average_p()/24,pairs[0].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/4,pairs[1].average_p());
// TS_ASSERT_EQUALS(ethalon,pairs[2]); // does not change
TS_ASSERT_EQUALS(3,pairs.size());
}
void test_filter_asymmetric_unit_3barmH() {
vector<AtomicPair> pairs;
for(int i=0; i<7; ++i)
pairs.push_back(AtomicPair(atom1,atom2));
pairs[0].average_r()=vec3<double>(0,0,0); //occupancy should be 1/6! Even though the group class is 12
pairs[1].average_r()=vec3<double>(0,0,7); //occupancy should be 1/6
pairs[2].average_r()=vec3<double>(5,-5,1); //occupancy should be 1/2
pairs[3].average_r()=vec3<double>(6,3,2); //occupancy should be 1/2
pairs[4].average_r()=vec3<double>(4,0,0); //This one does not change even though this is a two fold rotation axis
AtomicPair ethalon=pairs[4];
pairs[5].average_r()=vec3<double>(4,4,0); //pair should be deleted
pairs[6].average_r()=vec3<double>(0,4,0); //pair should be deleted
LaueSymmetry a_symmetry("-3mH");
pairs=a_symmetry.filter_pairs_from_asymmetric_unit(pairs);
TS_ASSERT_EQUALS(ethalon.average_p()/6,pairs[0].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/6,pairs[1].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/2,pairs[2].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/2,pairs[3].average_p());
// TS_ASSERT_EQUALS(ethalon,pairs[4]); // does not change
TS_ASSERT_EQUALS(5,pairs.size());
}
void test_filter_asymmetric_unit_3barmR() {
vector<AtomicPair> pairs;
for(int i=0; i<7; ++i)
pairs.push_back(AtomicPair(atom1,atom2));
pairs[0].average_r()=vec3<double>(0,0,0); //occupancy should be 1/6! Even though the group class is 12
pairs[1].average_r()=vec3<double>(1,1,1); //occupancy should be 1/6
pairs[2].average_r()=vec3<double>(5,5,1); //occupancy should be 1/2
pairs[3].average_r()=vec3<double>(6,3,3); //occupancy should be 1/2
pairs[4].average_r()=vec3<double>(4,0,-4); //This one does not change even though this is a two fold rotation axis
AtomicPair ethalon=pairs[4];
pairs[5].average_r()=vec3<double>(-4,4,0); //pair should be deleted
pairs[6].average_r()=vec3<double>(0,-4,4); //pair should be deleted
LaueSymmetry a_symmetry("-3mR");
pairs=a_symmetry.filter_pairs_from_asymmetric_unit(pairs);
TS_ASSERT_EQUALS(ethalon.average_p()/6,pairs[0].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/6,pairs[1].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/2,pairs[2].average_p());
TS_ASSERT_EQUALS(ethalon.average_p()/2,pairs[3].average_p());
// TS_ASSERT_EQUALS(ethalon,pairs[4]); // does not change
TS_ASSERT_EQUALS(5,pairs.size());
}
void test_format_esd()
{
TS_ASSERT_EQUALS("1(2)", format_esd(1,2));
TS_ASSERT_EQUALS("0.1(2)", format_esd(0.1,0.2));
TS_ASSERT_EQUALS("0.1(2)", format_esd(0.133162,0.2123154));
TS_ASSERT_EQUALS("0.13(12)", format_esd(0.133162,0.12123154));
TS_ASSERT_EQUALS("0.0003(7)", format_esd(0.00033175,0.000717));
TS_ASSERT_EQUALS("0.0000003(7)", format_esd(0.00000033175,0.000000717));
TS_ASSERT_EQUALS("0.0000000003(71)", format_esd(0.00000000033175,0.00000000717));
TS_ASSERT_EQUALS("0.0000000003(7)", format_esd(0.00000000033175,0.000000000717));
TS_ASSERT_EQUALS("0.123456(0)", format_esd(0.123456,0));
}
void nottestTODO()
{
TS_FAIL("Test SetUp contains memory leak");
TS_FAIL("Rewrite grid with hkl-prefix for all vals which are in HKL - coordinates to separate them from reciprocal coordinates");
TS_FAIL("Rewrite symmetry check and multiplication");
TS_FAIL("Rewrite modifiers so they will have priority to make possible to create zero vector modifier");
}
};
| Unknown |
3D | YellProgram/Yell | src/basic_io.h | .h | 1,036 | 34 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __diffuser_y__basic_io__
#define __diffuser_y__basic_io__
#include <iostream>
#include <string>
using std::string;
using std::ifstream;
/// checks if file file exists
bool file_exists(string filename);
/// reads the whole file in a string
string read_input_file(string filename);
#endif /* defined(__diffuser_y__basic_io__) */
| Unknown |
3D | YellProgram/Yell | src/InputFileParserIII.cpp | .cpp | 3,797 | 82 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InputFileParser.h"
void add_symbol( qi::symbols<char,std::string>& molecular_type, vector<boost::tuple<string,Scatterer*> > inp) {
for(int i=0; i<inp.size(); ++i) {
std::string label = boost::get<0>(inp[i]);
molecular_type.add(label.c_str(),label);
}
}
void InputParser::InputParserIII()
{
using namespace qi;
using phoenix::bind;
using phoenix::ref;
chemical_unit %=
lit("Void")[_val = phoenix::new_<AtomicAssembly>()]
| chemical_unit_assignement
| atomic_assembly
| symmetric_chemical_unit
| atom
;
symmetric_chemical_unit = (identifier >> '*' >> symmetry_element)[_val = bind(create_symmetric_chemical_unit,_1,_2)];
chemical_unit_assignement =
valid_identifier[_a=_1]
>> "="
>> chemical_unit[_val = _1]
>> eps[bind(InputParser::add_reference,phoenix::ref(references),_a,phoenix::construct<StructurePartRef>(_val))]
;
atomic_assembly = ('[' >> *chemical_unit >> ']')[_val = phoenix::new_<AtomicAssembly>(_1)] ;
atom =
(atom_name >> repeat(10)[lexeme[formula]]) [_val = bind(&Model::construct_atom,*ref(model),_1,_2)] //Uaniso and p
| (atom_name > repeat(5)[lexeme[formula]]) [_val = bind(&Model::construct_atom_isotropic_adp,*ref(model),_1,_2)]
;
molecular_scatterer =
chemical_unit[_val = phoenix::new_<MolecularScatterer>(_1)]
;
molecular_scatterers %=
lit("MolecularScatterers")
> "["
>> *(valid_identifier
>> "="
>> molecular_scatterer)
> "]"
> eps[bind(&Model::register_molecular_scatterers,_val)]
> eps[bind(&add_symbol,phoenix::ref(molecular_type),_val)]
;
atom_type.add("H","H")("He","He")("Li","Li")("Be","Be")("B","B")("C","C")("N","N")("O","O")("F","F")("Ne","Ne")("Na","Na")("Mg","Mg")("Al","Al")("Si","Si")("P","P")("S","S")("Cl","Cl")("Ar","Ar")("K","K")("Ca","Ca")("Sc","Sc")("Ti","Ti")("V","V")("Cr","Cr")("Mn","Mn")("Fe","Fe")("Co","Co")("Ni","Ni")("Cu","Cu")("Zn","Zn")("Ga","Ga")("Ge","Ge")("As","As")("Se","Se")("Br","Br")("Kr","Kr")("Rb","Rb")("Sr","Sr")("Y","Y")("Zr","Zr")("Nb","Nb")("Mo","Mo")("Tc","Tc")("Ru","Ru")("Rh","Rh")("Pd","Pd")("Ag","Ag")("Cd","Cd")("In","In")("Sn","Sn")("Sb","Sb")("Te","Te")("I","I")("Xe","Xe")("Cs","Cs")("Ba","Ba")("La","La")("Ce","Ce")("Pr","Pr")("Nd","Nd")("Pm","Pm")("Sm","Sm")("Eu","Eu")("Gd","Gd")("Tb","Tb")("Dy","Dy")("Ho","Ho")("Er","Er")("Tm","Tm")("Yb","Yb")("Lu","Lu")("Hf","Hf")("Ta","Ta")("W","W")("Re","Re")("Os","Os")("Ir","Ir")("Pt","Pt")("Au","Au")("Hg","Hg")("Tl","Tl")("Pb","Pb")("Bi","Bi")("Po","Po")("At","At")("Rn","Rn")("Fr","Fr")("Ra","Ra")("Ac","Ac")("Th","Th")("Pa","Pa")("U","U")("Np","Np")("Pu","Pu")("Am","Am")("Cm","Cm")("Bk","Bk")("Cf","Cf")("Es","Es")("Fm","Fm")("Md","Md")("No","No")("Lr","Lr")("Rf","Rf")("Db","Db")("Sg","Sg")("Bh","Bh")("Hs","Hs")("Mt","Mt")("Ds","Ds")("Rg","Rg")("Cn","Cn")("Uut","Uut")("Fl","Fl")("Uup","Uup")("Lv","Lv")("Uus","Uus")("Uuo","Uuo");
atom_name %=
molecular_type
| atom_type >> *alnum
;
identifier %= references >> !alnum;
rest_of_the_line = *(qi::char_ - qi::eol) >> qi::eol;
}; | C++ |
3D | YellProgram/Yell | src/OutputHandler.h | .h | 2,874 | 116 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __diffuser_y__OutputHandler__
#define __diffuser_y__OutputHandler__
#include <iostream>
#include <string>
using std::string;
using std::ostream;
using std::cout;
#define REPORT(when) if(report(when)) cout
enum WhenToPrint { FIRST_RUN, AFTER_REFINEMENT, MAIN, ERROR };
/**
* Class to output the messages in a standardized way. For now just outputs a bool which tells whether to print or not the message. The class atm is used through macros
*/
class OutputHandler {
public:
OutputHandler()
{
first_run_flag=false;
last_run_flag=false;
shut_up_flag=false;
}
/**
Flag to output the information from the first model construction
this includes echoing the information on say the number of pairs
created.
*/
bool first_run_flag;
/**
Flag to output the information about model after the refinement is finished.
eg. print out values of variables
*/
bool last_run_flag;
/**
Flag for test purposes. Suppresses any output
*/
bool shut_up_flag;
void last_run() {
last_run_flag = true;
}
/**
Supresses any further output.
*/
void shut_up() {
shut_up_flag=true;
}
void expect_first_calculation() {
first_run_flag=true;
}
void calculation_is_finished() {
first_run_flag = false;
last_run_flag = false;
}
/** The function that handles all the output from the program.
The program execution is not extremely nice at the moment, since most of the logic is executed while the input file gets parsed (which happens for every calculation). This class helps to keep track on what kind of output should be printed when.
*/
bool operator()(WhenToPrint when) {
if (when==ERROR)
{
cout << "\n ERROR: ";
return true;
}
if (shut_up_flag)
return false;
switch (when) {
case FIRST_RUN:
return first_run_flag;
break;
case AFTER_REFINEMENT:
return last_run_flag;
break;
case MAIN:
return true;
break;
case ERROR:
return true;
break;
}
return true;
}
};
#endif /* defined(__diffuser_y__OutputHandler__) */
| Unknown |
3D | YellProgram/Yell | src/InputFileParser.h | .h | 5,667 | 134 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef InputFileParser_H
#define InputFileParser_H
#include "basic_classes.h"
#include "precompiled_header.h"
#include "FormulaParser.h"
#include "model.h"
#include <boost/fusion/tuple.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
typedef boost::variant<ChemicalUnit*,ChemicalUnitNode*,ADPMode*> StructurePartRef;
typedef iterator_ Iterator;
struct InputParser : qi::grammar<Iterator, void(), qi::rule<Iterator,void()> >{
//public:
InputParser();
void InputParserI();
void InputParserII();
void InputParserIII();
//
//typedef ChemicalUnit* StructurePartRef;
typedef qi::rule<Iterator,void()> skipper_type;
qi::rule<Iterator, void(), skipper_type> start;
qi::rule<Iterator, Atom*(), skipper_type> atom;
qi::rule<Iterator, Atom*(), skipper_type> isotropic_atom;
qi::rule<Iterator,string()> atom_name;
qi::rule<Iterator,ChemicalUnit*(), skipper_type > chemical_unit;
qi::rule<Iterator,qi::locals<string>,ChemicalUnit*(), skipper_type > chemical_unit_assignement;
qi::rule<Iterator,AtomicAssembly*(), skipper_type> atomic_assembly;
qi::rule<Iterator,string()> valid_identifier;
typedef qi::symbols<char,StructurePartRef> ReferenceTable;
ReferenceTable references;
qi::rule<Iterator,StructurePartRef()> identifier;
qi::rule<Iterator,ChemicalUnitNode*(), skipper_type > variant;
qi::rule<Iterator,ChemicalUnitNode*(), skipper_type > variant_assignement;
qi::rule<Iterator,SymmetryElement(),skipper_type> symmetry_element;
qi::symbols<char,int> basis_vector;
qi::rule<Iterator,vector<double>(),skipper_type> permutation_component;
qi::rule<Iterator,ChemicalUnit*(), skipper_type> symmetric_chemical_unit;
qi::rule<Iterator,double()> number;
FormulaParser formula;
qi::rule<Iterator,void()> rest_of_the_line;
qi::rule<Iterator,void(),skipper_type> unit_cell; //this parser does not return anything because it adds the variants directly to model->cell
qi::rule<Iterator,vector<SubstitutionalCorrelation*>(), skipper_type> substitutional_correlation;
qi::rule<Iterator,MultiplicityCorrelation*(),skipper_type> multiplicity_correlation;
qi::rule<Iterator,CellShifter*(),skipper_type> cell_shifter;
qi::rule<Iterator,AtomicPairPool*(),skipper_type> atomic_pair_pool;
qi::rule<Iterator,vector<AtomicPairPool*>(),skipper_type> correlations;
qi::rule<Iterator,vector<boost::fusion::tuple<string,double> >(),skipper_type> refinable_parameters;
skipper_type skipper;
skipper_type skipper_no_assignement; //< this is a skipper which does not parse arithmetic assignements. Used in
qi::rule<Iterator,void()> comment;
qi::rule<Iterator,ADPMode*(),skipper_type> translational_mode;
qi::rule<Iterator,ADPMode*(),skipper_type> rotational_mode;
qi::rule<Iterator,void(),skipper_type> modes;
qi::rule<Iterator,ADPMode*(),skipper_type> mode_assignement;
qi::rule<Iterator,DoubleADPMode*(),skipper_type> adp_correlation;
qi::rule<Iterator,SizeEffect*(),skipper_type> size_effect;
qi::symbols<char,string> point_group_symbol;
qi::symbols<char,string> atom_type;
qi::symbols<char,string> molecular_type;
qi::symbols<char,bool> calculation_methods;
qi::symbols<char,ScatteringType> scattering_type;
qi::rule<Iterator,void(),skipper_type> print_command_parser;
qi::rule<Iterator,string()> string_in_quotes;
qi::rule<Iterator,void(),skipper_type> program_option;
qi::rule<Iterator,void(),skipper_type> program_option1;
qi::rule<Iterator,void(),skipper_type> program_option2;
qi::rule<Iterator,void(),skipper_type> program_options;
qi::rule<Iterator,void(),skipper_type> maybe_assignments;
qi::rule<Iterator,Scatterer*(),skipper_type> molecular_scatterer;
qi::rule<Iterator,vector<boost::tuple<string,Scatterer*> >(),skipper_type> molecular_scatterers;
static ChemicalUnit* create_symmetric_chemical_unit(StructurePartRef _unit,SymmetryElement symm)
{
ChemicalUnit* res = boost::get<ChemicalUnit*>(_unit)->create_symmetric(symm.permutation_matrix,symm.displacement);
return res;
}
static void add_reference(ReferenceTable& reference_table, string name,StructurePartRef references)
{
reference_table.add(name,references);
}
static SymmetryElement update_symmetry_component(SymmetryElement symm,vector<double> update, int component)
{
for(int i=0; i<3; i++)
symm.permutation_matrix[i+component*3] = update[i];
symm.displacement[component] = update[3];
return symm;
}
void add_model(Model* _model)
{
model = _model;
}
Model* model;
};
/* TODO
Make script for model bind functions and rewrite all functions in model so that they are not static. maybe destroy all inline functions
May be it should be done in following way: all parsers return the objects. and objects are translated to their references only when they are registered
*/
#endif | Unknown |
3D | YellProgram/Yell | src/FormulaParser.cpp | .cpp | 3,594 | 95 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#include "FormulaParser.h"
#include "OutputHandler.h"
extern OutputHandler report;
// for the reasons explained here http://www.boost.org/doc/libs/1_53_0/libs/bind/bind.html it is impossible to bind templated funcitons to spirit semantic actions. Thus, we will have to make adapter to all the arithmetic functions.
double adopted_exp(double x) { return exp(x); }
double adopted_log(double x) { return log(x); }
double adopted_sin(double x) { return sin(x); }
double adopted_cos(double x) { return cos(x); }
double adopted_sqrt(double x) { return sqrt(x); }
double adopted_abs(double x) { return abs(x); }
double adopted_mod(double x,double y) { return fmod(x,y); }
double adopted_pow(double x,double y) { return pow(x,y); }
bool log_is_ok(double x) {
if(x>0)
return true;
else
{
REPORT(ERROR) << "Calculation of logarithm failed, current argument is " << x << "\n";
return false;
}
}
bool sqrt_is_ok(double x) {
if(x>=0)
return true;
else
{
REPORT(ERROR) << "Calculation of square root failed, current argument is " << x << "\n";
return false;
}
}
FormulaParser::FormulaParser() : FormulaParser::base_type(start),current_array_value(0)
{
using namespace qi;
using phoenix::bind;
using phoenix::ref;
fact %= double_ | '(' >> expr >> ')' | identifier | assignment | array_element | special_function; //
special_function =
("exp(" >> expr >> ')') [_val = bind(&adopted_exp,_1)]
| ("log(" >> expr >> ')') [_pass = bind(&log_is_ok,_1)][_val = bind(&adopted_log,_1)]
| ("sin(" >> expr >> ')') [_val = bind(&adopted_sin,_1)]
| ("cos(" >> expr >> ')') [_val = bind(&adopted_cos,_1)]
| ("sqrt(">> expr >> ')') [_pass = bind(&sqrt_is_ok,_1)][_val = bind(&adopted_sqrt,_1)]
| ("abs(" >> expr >> ')') [_val = bind(&adopted_abs,_1)]
| ("mod(" >> expr >> ',' >> expr >> ')') [_val = bind(&adopted_mod,_1,_2)]
| ("pow(" >> expr >> ',' >> expr >> ')') [_val = bind(&adopted_pow,_1,_2)]
;
term %= fact[_val = _1]
>> *( ('*' >> fact)[_val *= _1]
| ('/' >> fact)[_val/=_1] )
;
expr = ( (-lit('+') >> term)[_val=_1]
| ('-' >> term)[_val=- _1] )
>> *(
('+' >> term)[_val+=_1]
| ('-' >> term)[_val-=_1])
;
// Deprecated
//array_element =
//lit("~i")[_val = bind(&extract_array_value,ref(array),ref(current_array_value)++)]
//;
// copypaste from InputParser better make a separate grammar for this
// added minus to the charecters
valid_identifier %= alpha >> *char_("a-zA-Z0-9_");
identifier %= references >> !(alnum | '=');
assignment = (valid_identifier >> '=' >> expr[_val = _1])[bind(add_key,ref(references),_1,_2)];//
start %= expr;
} | C++ |
3D | YellProgram/Yell | src/model.h | .h | 12,529 | 413 | /*
Copyright Arkadiy Simonov, Thomas Weber, ETH Zurich 2014
This file is part of Yell.
Yell is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Yell is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Yell. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODEL_H
#define MODEL_H
#include "basic_classes.h"
#include "precompiled_header.h"
#include "FormulaParser.h"
#include <boost/fusion/tuple.hpp>
//COPYPASTE from InputFileParser.h
typedef boost::variant<ChemicalUnit*,ChemicalUnitNode*,ADPMode*> StructurePartRef;
//#include "InputFileParser.h"
enum R_FACTORS {R1, R2};
enum WEIGHTED_OPTIONS {WEIGHTED, UNWEIGHTED};
class Model : public MinimizerCalculator {
private:
static double sq(double x) {
return x*x;
}
public:
static void register_molecular_scatterers(vector<boost::tuple<string,Scatterer*> > scatterers) {
for(int i=0; i<scatterers.size();++i)
AtomicTypeCollection::add(boost::get<0>(scatterers[i]),boost::get<1>(scatterers[i]));
}
bool unit_cell_is_initialized() {
if(!cell_is_initialized)
REPORT(ERROR) << "Unit cell is not defined\n";
if(!grid_initialized)
REPORT(ERROR) << "Diffuse scattering grid is not defined\n";
if(cell.laue_symmetry.label=="")
{
REPORT(ERROR) << "Point group is not defined\n";
return false;
}
bool symmetry_is_ok = cell.laue_symmetry.is_compatible_with_cell(cell);
if(!symmetry_is_ok)
REPORT(ERROR) << "Point group " << cell.laue_symmetry.label << " is incomatible with unit cell " << cell.to_string() << "\n";
return cell_is_initialized && grid_initialized && symmetry_is_ok;
}
void set_calculate_jacobians(bool inp) {
calculate_jacobians=inp;
}
void set_print_covariance_matrix(bool inp){
print_covariance_matrix=inp;
}
void set_padding(vector<int> inp) {
for(int i=0; i<3; ++i)
padding[i]=inp[i];
}
void set_report_pairs_outside_pdf_grid(bool inp)
{
report_pairs_outside_pdf_grid = inp;
}
void set_max_number_of_iterations(int inp)
{
refinement_options.max_number_of_iterations=inp;
}
void set_tau(double inp)
{
refinement_options.tau = inp;
}
void set_diff(double inp)
{
refinement_options.difference = inp;
}
void set_thresholds(vector<double> inp)
{
assert(inp.size()==3);
for(int i=0;i<3;++i)
refinement_options.thresholds[i]=inp[i];
}
double R_factor(IntensityMap& exp, R_FACTORS r,WEIGHTED_OPTIONS weighted)
{
double scale = refinement_parameters[0];
double nom=0,denom=0,result;
if(r==R1)
if(weighted==UNWEIGHTED)
{
for(int i=0; i<intensity_map.size_1d(); ++i)
{
nom += abs(exp.at(i)-scale*(intensity_map.at(i)-average_intensity_map.at(i)));
denom += abs(exp.at(i));
}
result = nom/denom;
}
else // WEIGHTED not used
{
for(int i=0; i<intensity_map.size_1d(); ++i)
{
nom += abs( (exp.at(i)-scale*(intensity_map.at(i)-average_intensity_map.at(i)))*weights.at(i) );
denom += abs(exp.at(i)*weights.at(i));
}
result = nom/denom;
}
else //R2
if(weighted==WEIGHTED)
{
for(int i=0; i<intensity_map.size_1d(); ++i)
{
nom += sq( (exp.at(i)-scale*(intensity_map.at(i)-average_intensity_map.at(i))) )*weights.at(i) ;
denom += sq(exp.at(i))*weights.at(i);
}
result = sqrt(nom/denom);
}
else // UNWEIGHTED not used
{
for(int i=0; i<intensity_map.size_1d(); ++i)
{
nom += sq(exp.at(i)-scale*(intensity_map.at(i)-average_intensity_map.at(i)));
denom += sq(exp.at(i));
}
result = sqrt(nom/denom);
}
return result;
}
static void throw_error() {
throw "error";
}
void set_periodic_boundaries(vector<bool> inp) {
periodic_boundaries = inp;
}
/**
* Creates an atom with isotropic ADP
*/
Atom* construct_atom_isotropic_adp(string name,vector<double> params) {
return new Atom(name,params[0],
1,//we assign probability to 1 because it will be changed by Variant afterwards anyway
params[1],params[2],params[3],params[4],cell.cell.reciprocal_metrical_matrix(),scattering_type);
}
/**
* This function creates an atom from atom name and a vector of atomic parameters. The atom should be deleted elsewhere (normally its pointer should be given to AtomicAssembly which will take care of it)
*/
Atom* construct_atom(string name,vector<double> params) {
double a=cell.cell.parameters()[0];
double b=cell.cell.parameters()[1];
double c=cell.cell.parameters()[2];
//Also transforms input adps from angstroems^2 into fractional values
return new Atom(name,params[0],
1, //we assign probability to 1 because it will be changed by Variant afterwards anyway
params[1],params[2],params[3],
params[4]/a/a,
params[5]/b/b,
params[6]/c/c,
params[7]/a/b,
params[8]/a/c,
params[9]/b/c,
scattering_type);
}
void set_scale(double inp) {
refinement_parameters[0]=inp;
}
void set_refinable_parameters(FormulaParser& formula,vector<boost::fusion::tuple<string,double> > inp) {
refinement_parameters.resize(inp.size()+1);
refined_variable_names.resize(inp.size()+1);
for(int i=0; i<inp.size(); ++i)
{
refined_variable_names[i+1]=boost::fusion::get<0>(inp[i]);
refinement_parameters[i+1]=boost::fusion::get<1>(inp[i]);
}
// If this is a first parser run
formula.initialize_refinable_variables(refined_variable_names,refinement_parameters);
}
void initialize_unit_cell(vector<double> params) {
cell_is_initialized = true;
cell = UnitCell(params[0],params[1],params[2],params[3],params[4],params[5]);
}
void set_fft_grid_size(vector<int> params) {
fft_grid_size=vec3<int>(params[0],params[1],params[2]);
}
void set_dump_pairs(bool inp) {
dump_pairs=inp;
}
void set_refinement_flag(bool inp) {
refinement_flag=inp;
}
///\TODO: rename point group and laue_symmetry to PDF_symmetry consistently thwougout the code
void set_point_group(string point_goup_symbol) {
cell.laue_symmetry = LaueSymmetry(point_goup_symbol,intensity_map.grid);
}
void set_calculation_method(bool method) {
direct_diffuse_scattering_calculation=method;
}
void set_scattering_type(ScatteringType t) {
scattering_type = t;
}
void set_recalculation_flag(bool flag) {
recalculate_average=flag;
}
/// Initialize a the grid from ... DiffuseScatteringGrid -6 -6 -6 1 1 1 12 12 12 (lower limits, step sizes,number of pixels)
void initialize_intensity_grid(vector<double> params) {
if(!grid_initialized)
{
vec3<double> steps(params[3],params[4],params[5]);
vec3<double> lower_limits(params[0],params[1],params[2]);
vec3<int> grid_size(params[6],params[7],params[8]);
grid =Grid(cell.cell,steps,lower_limits,grid_size,true);
intensity_map = IntensityMap(grid);
average_intensity_map = IntensityMap(grid);
data_ = IntensityMap(grid);
grid_initialized = true;
}
}
void add_variant(ChemicalUnitNode* var) {
cell.add_node(var);
}
static vector<SubstitutionalCorrelation*> correlators_from_cuns_(StructurePartRef _var1,StructurePartRef _var2,vector<double> params) {
ChemicalUnitNode* var1= boost::get<ChemicalUnitNode*>(_var1);
ChemicalUnitNode* var2= boost::get<ChemicalUnitNode*>(_var2);
return correlators_from_cuns(var1,var2,params);
}
void init_flags() {
calculate_jacobians=false;
direct_diffuse_scattering_calculation = true;
print_covariance_matrix=false;
cell_is_initialized=false;
average_is_calculated = false;
grid_initialized = false;
refinement_flag = true;
recalculate_average=true;
fft_grid_size=vec3<int>(16,16,16);
dump_pairs=false;
scattering_type = XRay;
refinement_parameters = vector<double>(1,1);
refined_variable_names = vector<string>(1,"Scale");
periodic_boundaries = vector<bool>(3,true);
refinement_options = RefinementOptions::default_refinement_options();
report_pairs_outside_pdf_grid = false;
padding = vec3<int>(0,0,0);
}
///\TODO: test the following part of Model
Model(string _model) : model(_model)
{
init_flags();
}
///used for tests
Model() {
init_flags();
}
void add_correlations(const vector<AtomicPairPool*>& _pools) {
pools = _pools;
}
ADPMode* create_translational_mode(StructurePartRef chem_unit,int direction) {
return translational_mode(boost::get<ChemicalUnit*>(chem_unit),direction,cell.cell.metrical_matrix());
}
ADPMode* create_rotational_mode(StructurePartRef chem_unit,vector<double> params) {
return rot_mode(boost::get<ChemicalUnit*>(chem_unit),vec3<double>(params[0],params[1],params[2]),
vec3<double>(params[3],params[4],params[5]),cell.cell.metrical_matrix());
}
void add_modes(vector<ADPMode*> _modes) {
modes.concat(_modes);
}
static DoubleADPMode* create_double_adp_mode(StructurePartRef mode1,StructurePartRef mode2,double amplitude)
{
return new DoubleADPMode(boost::get<ADPMode*> (mode1),boost::get<ADPMode*>(mode2),amplitude);
}
static SizeEffect* create_size_effect(StructurePartRef el1,StructurePartRef el2, double amplitude)
{
if(boost::get<ChemicalUnit*>(&el1)) //check that first element is ChemicalUnit
return new SizeEffect(boost::get<ChemicalUnit*>(el1),boost::get<ADPMode*>(el2), amplitude);
else
return new SizeEffect(boost::get<ADPMode*>(el1),boost::get<ChemicalUnit*>(el2), amplitude);
}
static const bool AVERAGE = true;
static const bool FULL = false;
void apply_resolution_function_if_possible(IntensityMap& map) {
if(pdf_multiplier.is_loaded)
{
map.to_real();
for(int i=0; i<map.size_1d(); ++i)
map.at(i) *= pdf_multiplier.at(i);
}
}
void apply_reciprocal_space_multipliers_if_possible(IntensityMap& map) {
if(reciprocal_space_multiplier.is_loaded)
{
map.to_reciprocal();
for(int i=0; i<map.size_1d(); ++i)
map.at(i) *= reciprocal_space_multiplier.at(i);
}
}
/// function for minimizer
void calculate(vector<double> params) {
double scale = params[0];
if(!average_is_calculated || recalculate_average)
{
calculate(params,AVERAGE);
average_is_calculated = true;
}
calculate(params,FULL);
for(int i=0; i<data_.size_1d(); ++i)
data_.at(i) = scale*(intensity_map.at(i)-average_intensity_map.at(i));
}
IntensityMap& model_scaled_to_experiment() {
return data_;
}
void calculate(vector<double> params,bool);
UnitCell cell;
IntensityMap intensity_map, average_intensity_map;
string model;
vector<AtomicPairPool*> pools;
vector<double> refinement_parameters;
vector<string> refined_variable_names;
p_vector<ADPMode> modes;
RefinementOptions refinement_options;
vec3<int> fft_grid_size;
vector<bool> periodic_boundaries;
// int number_of_parameters;
bool cell_is_initialized;
bool grid_initialized;
bool average_is_calculated;
bool recalculate_average;
bool direct_diffuse_scattering_calculation;
bool refinement_flag;
bool dump_pairs;
bool report_pairs_outside_pdf_grid;
bool print_covariance_matrix;
bool calculate_jacobians;
ScatteringType scattering_type;
IntensityMap& data() { return data_; }
IntensityMap data_;
OptionalIntensityMap weights;
OptionalIntensityMap reciprocal_space_multiplier;
OptionalIntensityMap pdf_multiplier;
vector<AtomicPair> atomic_pairs;
vec3<int> padding;
Grid grid;
};
#endif | Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/omptbx/omp_or_stubs.h | .h | 214 | 13 | #ifndef OMPTBX_WRAPPER_H
#define OMPTBX_WRAPPER_H
#if defined(_OPENMP)
# define OMPTBX_HAVE_OMP_H
# include <omp.h>
#else
# define OMPTBX_HAVE_STUBS_H
# include <omptbx/stubs.h>
#endif
#endif // OMPTBX_WRAPPER_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/omptbx/stubs.h | .h | 1,124 | 92 | #ifndef OMPTBX_STUBS_H
#define OMPTBX_STUBS_H
#if !defined(_OPENMP)
#ifdef __cplusplus
extern "C"
{
#endif
typedef int omp_lock_t;
typedef struct
{
int owner;
int count;
} omp_nest_lock_t;
void
omp_set_num_threads(int num_threads);
int
omp_get_num_threads(void);
int
omp_get_max_threads(void);
int
omp_get_thread_num(void);
int
omp_get_num_procs(void);
void
omp_set_dynamic(int dynamic_threads);
int
omp_get_dynamic(void);
int
omp_in_parallel(void);
void
omp_set_nested(int nested);
int
omp_get_nested(void);
void
omp_init_lock(omp_lock_t* lock);
void
omp_destroy_lock(omp_lock_t* lock);
void
omp_set_lock(omp_lock_t* lock);
void
omp_unset_lock(omp_lock_t* lock);
int
omp_test_lock(omp_lock_t* lock);
void
omp_init_nest_lock(omp_nest_lock_t* nlock);
void
omp_destroy_nest_lock(omp_nest_lock_t* nlock);
void
omp_set_nest_lock(omp_nest_lock_t* nlock);
void
omp_unset_nest_lock(omp_nest_lock_t* nlock);
int
omp_test_nest_lock(omp_nest_lock_t* nlock);
double
omp_get_wtime(void);
double
omp_get_wtick(void);
#ifdef __cplusplus
}
#endif
#endif /* !defined(_OPENMP) */
#endif /* OMPTBX_STUBS_H */
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/omptbx/stubs.cpp | .cpp | 3,693 | 217 | #if !defined(_OPENMP)
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <omptbx/stubs.h>
extern "C" {
void
omp_set_num_threads(int num_threads)
{
}
int
omp_get_num_threads(void)
{
return 1;
}
int
omp_get_max_threads(void)
{
return 1;
}
int
omp_get_thread_num(void)
{
return 0;
}
int
omp_get_num_procs(void)
{
return 1;
}
void
omp_set_dynamic(int dynamic_threads)
{
}
int
omp_get_dynamic(void)
{
return 0;
}
int
omp_in_parallel(void)
{
return 0;
}
void
omp_set_nested(int nested)
{
}
int
omp_get_nested(void)
{
return 0;
}
enum { omptbx_stubs_UNLOCKED = -1, omptbx_stubs_INIT, omptbx_stubs_LOCKED };
void
omp_init_lock(omp_lock_t* lock)
{
*lock = omptbx_stubs_UNLOCKED;
}
void
omp_destroy_lock(omp_lock_t* lock)
{
*lock = omptbx_stubs_INIT;
}
void
omp_set_lock(omp_lock_t* lock)
{
if (*lock == omptbx_stubs_UNLOCKED) {
*lock = omptbx_stubs_LOCKED;
}
else if (*lock == omptbx_stubs_LOCKED) {
fprintf(stderr, "omptbx error: deadlock in using lock variable\n");
exit(1);
}
else {
fprintf(stderr, "omptbx error: lock not initialized\n");
exit(1);
}
}
void
omp_unset_lock(omp_lock_t* lock)
{
if (*lock == omptbx_stubs_LOCKED) {
*lock = omptbx_stubs_UNLOCKED;
}
else if (*lock == omptbx_stubs_UNLOCKED) {
fprintf(stderr, "omptbx error: lock not set\n");
exit(1);
}
else {
fprintf(stderr, "omptbx error: lock not initialized\n");
exit(1);
}
}
int
omp_test_lock(omp_lock_t* lock)
{
if (*lock == omptbx_stubs_UNLOCKED)
{
*lock = omptbx_stubs_LOCKED;
return 1;
}
else if (*lock != omptbx_stubs_LOCKED)
{
fprintf(stderr, "omptbx error: lock not initialized\n");
exit(1);
}
return 0;
}
enum { omptbx_stubs_NOOWNER = -1, omptbx_stubs_MASTER = 0 };
void
omp_init_nest_lock(omp_nest_lock_t* nlock)
{
nlock->owner = omptbx_stubs_NOOWNER;
nlock->count = 0;
}
void
omp_destroy_nest_lock(omp_nest_lock_t* nlock)
{
nlock->owner = omptbx_stubs_NOOWNER;
nlock->count = omptbx_stubs_UNLOCKED;
}
void
omp_set_nest_lock(omp_nest_lock_t* nlock)
{
if (nlock->owner == omptbx_stubs_MASTER && nlock->count >= 1) {
nlock->count++;
}
else if (nlock->owner == omptbx_stubs_NOOWNER && nlock->count == 0) {
nlock->owner = omptbx_stubs_MASTER;
nlock->count = 1;
}
else {
fprintf(stderr, "omptbx error: lock corrupted or not initialized\n");
exit(1);
}
}
void
omp_unset_nest_lock(omp_nest_lock_t* nlock)
{
if (nlock->owner == omptbx_stubs_NOOWNER && nlock->count >= 1) {
nlock->count--;
if (nlock->count == 0) {
nlock->owner = omptbx_stubs_NOOWNER;
}
}
else if (nlock->owner == omptbx_stubs_NOOWNER && nlock->count == 0) {
fprintf(stderr, "omptbx error: lock not set\n");
exit(1);
}
else {
fprintf(stderr, "omptbx error: lock corrupted or not initialized\n");
exit(1);
}
}
int
omp_test_nest_lock(omp_nest_lock_t* nlock)
{
omp_set_nest_lock(nlock);
return nlock->count;
}
#if defined(_MSC_VER)
// warning C4297: function assumed not to throw an exception but does
# pragma warning(disable:4297)
#endif
double
omp_get_wtime(void)
{
/* This function does not provide a working
wallclock timer. Replace it with a version
customized for the target machine.
*/
//return 0.0;
throw std::runtime_error("omptbx: omp_get_wtime() not implemented.");
}
double
omp_get_wtick(void)
{
/* This function does not provide a working
clock tick function. Replace it with
a version customized for the target machine.
*/
// return 365. * 86400.;
throw std::runtime_error("omptbx: omp_get_wtick() not implemented.");
}
} // extern "C"
#endif /* !defined(_OPENMP) */
| C++ |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/vec3.h | .h | 16,941 | 737 | #ifndef SCITBX_VEC3_H
#define SCITBX_VEC3_H
#include <scitbx/array_family/tiny.h>
#include <scitbx/array_family/operator_traits_builtin.h>
#include <boost/optional.hpp>
namespace scitbx {
//! Three-dimensional vector.
/*! This class can be used to represent points, vectors, normals
or even colors. The usual vector operations are available.
C++ version of the python vec3 class by
Matthias Baas (baas@ira.uka.de). See
http://cgkit.sourceforge.net/
for more information.
*/
template <typename NumType>
class vec3 : public af::tiny_plain<NumType, 3>
{
public:
typedef typename af::tiny_plain<NumType, 3> base_type;
//! Default constructor. Elements are not initialized.
vec3() {}
//! All elements are initialized with e.
vec3(NumType const& e)
: base_type(e, e, e)
{}
//! Constructor.
vec3(NumType const& e0, NumType const& e1, NumType const& e2)
: base_type(e0, e1, e2)
{}
//! Constructor.
vec3(base_type const& a)
: base_type(a)
{}
//! Constructor.
explicit
vec3(const NumType* a)
{
for(std::size_t i=0;i<3;i++) this->elems[i] = a[i];
}
//! Test if all elements are 0.
bool is_zero() const
{
return !(this->elems[0] || this->elems[1] || this->elems[2]);
}
//! Minimum of vector elements.
NumType
min() const
{
NumType result = this->elems[0];
if (result > this->elems[1]) result = this->elems[1];
if (result > this->elems[2]) result = this->elems[2];
return result;
}
//! Maximum of vector elements.
NumType
max() const
{
NumType result = this->elems[0];
if (result < this->elems[1]) result = this->elems[1];
if (result < this->elems[2]) result = this->elems[2];
return result;
}
//! In-place minimum of this and other for each element.
void
each_update_min(vec3 const& other)
{
for(std::size_t i=0;i<3;i++) {
if (this->elems[i] > other[i]) this->elems[i] = other[i];
}
}
//! In-place maximum of this and other for each element.
void
each_update_max(vec3 const& other)
{
for(std::size_t i=0;i<3;i++) {
if (this->elems[i] < other[i]) this->elems[i] = other[i];
}
}
//! Sum of vector elements.
NumType
sum() const
{
return this->elems[0] + this->elems[1] + this->elems[2];
}
//! Product of vector elements.
NumType
product() const
{
return this->elems[0] * this->elems[1] * this->elems[2];
}
//! Cross product.
vec3 cross(vec3 const& other) const
{
vec3 const& a = *this;
vec3 const& b = other;
return vec3(
a[1] * b[2] - b[1] * a[2],
a[2] * b[0] - b[2] * a[0],
a[0] * b[1] - b[0] * a[1]);
}
//! Element-wise multiplication.
template <typename NumTypeRhs>
vec3<
typename af::binary_operator_traits<NumType, NumTypeRhs>::arithmetic>
each_mul(
vec3<NumTypeRhs> const& rhs) const
{
vec3<
typename af::binary_operator_traits<NumType, NumTypeRhs>::arithmetic>
result;
for(std::size_t i=0;i<3;i++) {
result[i] = (*this)[i] * rhs[i];
}
return result;
}
//! Return the length squared of the vector.
NumType length_sq() const
{
return (*this) * (*this);
}
//! Return the length of the vector.
NumType length() const
{
return NumType(std::sqrt(length_sq()));
}
//! Return normalized vector.
/*! length() == 0 will lead to a division-by-zero exception.
Explicit checks are avoided to maximize performance.
A maximally robust (but slower) calculation of the
||.||_2 norm is implemented in
scitbx::math::accumulator::norm_accumulator .
*/
vec3 normalize() const
{
return (*this) / length();
}
//! Return angle (in radians) between this and other.
/*! This implementation is unsafe as it does not check
if both vector lengths are different from zero.
*/
NumType
angle(
vec3 const& other) const
{
return NumType(
std::acos(((*this) * other) / (length() * other.length())));
}
//! Return angle (in radians) between this and other.
/*! Safe implementation guarding against division-by-zero
and rounding errors.
*/
boost::optional<NumType>
angle_rad(
vec3 const& other) const
{
NumType den = length() * other.length();
if (den == 0) return boost::optional<NumType>();
NumType c = ((*this) * other) / den;
if (c < -1) c = -1;
else if (c > 1) c = 1;
return boost::optional<NumType>(NumType(std::acos(c)));
}
//! Return the reflection vector.
/*! @param n is the surface normal which has to be of unit length.
*/
vec3 reflect(vec3 const& n) const
{
return (*this) - NumType(2) * ((*this) * n) * n;
}
//! Return the transmitted vector.
/*! @param n is the surface normal which has to be of unit length.
@param eta is the relative index of refraction. If the returned
vector is zero then there is no transmitted light because
of total internal reflection.
*/
vec3 refract(vec3 const& n, NumType const& eta) const
{
NumType dot = (*this) * n;
NumType k = 1. - eta*eta*(1. - dot*dot);
if (k < NumType(0)) return vec3(0,0,0);
return eta * (*this) - (eta * dot + std::sqrt(k)) * n;
}
//! Returns a vector that is orthogonal to this.
/*! If normalize is true, given the null vector (within
floating-point precision) the result is (0,0,1).
*/
vec3 ortho(bool normalize=false) const;
//! Copies the vector to a tiny instance.
af::tiny<NumType, 3>
as_tiny() const { return af::tiny<NumType, 3>(*this); }
//! Rotate the vector.
/*! Use the rotation formula to rotate the vector around the direction
vector through an angle given in radians. The direction vector is
normalized so need not be given as a vector of unit length.
*/
vec3
rotate_around_origin(vec3 const& direction, NumType const& angle) const {
vec3 unit = direction.normalize();
return unit_rotate_around_origin(unit,angle);
}
//! Rotate the vector.
/*! Use the rotation formula to rotate the vector around the unit
direction through an angle given in radians. The caller
guarantees that the direction vector is of unit length.
*/
vec3
unit_rotate_around_origin(vec3 const& unit, NumType const& angle) const {
NumType cosang = std::cos(angle);
return (*this)*cosang +
unit*(unit*(*this))*(1.0-cosang)+
(unit.cross(*this))*std::sin(angle);
}
private:
static NumType abs_(NumType const& x)
{
if (x < NumType(0)) return -x;
return x;
}
};
//! Test equality.
template <typename NumType>
inline
bool
operator==(
vec3<NumType> const& lhs,
vec3<NumType> const& rhs)
{
for(std::size_t i=0;i<3;i++) {
if (lhs[i] != rhs[i]) return false;
}
return true;
}
//! Test equality. True if all elements of lhs == rhs.
template <typename NumType>
inline
bool
operator==(
vec3<NumType> const& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<3;i++) {
if (lhs[i] != rhs ) return false;
}
return true;
}
//! Test equality. True if all elements of rhs == lhs.
template <typename NumType>
inline
bool
operator==(
NumType const& lhs,
vec3<NumType> const& rhs)
{
for(std::size_t i=0;i<3;i++) {
if (lhs != rhs[i]) return false;
}
return true;
}
//! Test inequality.
template <typename NumType>
inline
bool
operator!=(
vec3<NumType> const& lhs,
vec3<NumType> const& rhs)
{
return !(lhs == rhs);
}
//! Test inequality. True if any element of lhs != rhs.
template <typename NumType>
inline
bool
operator!=(
vec3<NumType> const& lhs,
NumType const& rhs)
{
return !(lhs == rhs);
}
//! Test inequality. True if any element of rhs != lhs.
template <typename NumType>
inline
bool
operator!=(
NumType const& lhs,
vec3<NumType> const& rhs)
{
return !(lhs == rhs);
}
//! Element-wise addition.
template <typename NumType>
inline
vec3<NumType>
operator+(
vec3<NumType> const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] + rhs[i];
}
return result;
}
//! Element-wise addition.
template <typename NumType>
inline
vec3<NumType>
operator+(
vec3<NumType> const& lhs,
NumType const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] + rhs ;
}
return result;
}
//! Element-wise addition.
template <typename NumType>
inline
vec3<NumType>
operator+(
NumType const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs + rhs[i];
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
vec3<NumType>
operator-(
vec3<NumType> const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] - rhs[i];
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
vec3<NumType>
operator-(
vec3<NumType> const& lhs,
NumType const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] - rhs ;
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
vec3<NumType>
operator-(
NumType const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs - rhs[i];
}
return result;
}
//! Dot product.
template <typename NumTypeLhs, typename NumTypeRhs>
inline
typename af::binary_operator_traits<NumTypeLhs, NumTypeRhs>::arithmetic
operator*(
vec3<NumTypeLhs> const& lhs,
vec3<NumTypeRhs> const& rhs)
{
typename af::binary_operator_traits<NumTypeLhs, NumTypeRhs>::arithmetic
result(0);
for(std::size_t i=0;i<3;i++) {
result += lhs[i] * rhs[i];
}
return result;
}
//! Element-wise multiplication.
template <typename NumType>
inline
vec3<NumType>
operator*(
vec3<NumType> const& lhs,
NumType const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] * rhs ;
}
return result;
}
//! Element-wise multiplication.
template <typename NumType>
inline
vec3<NumType>
operator*(
NumType const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs * rhs[i];
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
vec3<NumType>
operator/(
vec3<NumType> const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] / rhs[i];
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
vec3<NumType>
operator/(
vec3<NumType> const& lhs,
NumType const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] / rhs ;
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
vec3<NumType>
operator/(
vec3<NumType> const& lhs,
std::size_t const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] / rhs ;
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
vec3<NumType>
operator/(
NumType const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs / rhs[i];
}
return result;
}
//! Element-wise modulus operation.
template <typename NumType>
inline
vec3<NumType>
operator%(
vec3<NumType> const& lhs,
NumType const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs[i] % rhs ;
}
return result;
}
//! Element-wise modulus operation.
template <typename NumType>
inline
vec3<NumType>
operator%(
NumType const& lhs,
vec3<NumType> const& rhs)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = lhs % rhs[i];
}
return result;
}
//! Element-wise in-place addition.
template <typename NumType>
inline
vec3<NumType>&
operator+=(
vec3<NumType>& lhs,
vec3<NumType> const& rhs)
{
for(std::size_t i=0;i<3;i++) {
lhs[i] += rhs[i];
}
return lhs;
}
//! Element-wise in-place addition.
template <typename NumType>
inline
vec3<NumType>&
operator+=(
vec3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<3;i++) {
lhs[i] += rhs ;
}
return lhs;
}
//! Element-wise in-place difference.
template <typename NumType>
inline
vec3<NumType>&
operator-=(
vec3<NumType>& lhs,
vec3<NumType> const& rhs)
{
for(std::size_t i=0;i<3;i++) {
lhs[i] -= rhs[i];
}
return lhs;
}
//! Element-wise in-place difference.
template <typename NumType>
inline
vec3<NumType>&
operator-=(
vec3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<3;i++) {
lhs[i] -= rhs ;
}
return lhs;
}
//! Element-wise in-place multiplication.
template <typename NumType>
inline
vec3<NumType>&
operator*=(
vec3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<3;i++) {
lhs[i] *= rhs ;
}
return lhs;
}
//! Element-wise in-place division.
template <typename NumType>
inline
vec3<NumType>&
operator/=(
vec3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<3;i++) {
lhs[i] /= rhs ;
}
return lhs;
}
//! Element-wise in-place modulus operation.
template <typename NumType>
inline
vec3<NumType>&
operator%=(
vec3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<3;i++) {
lhs[i] %= rhs ;
}
return lhs;
}
//! Element-wise unary minus.
template <typename NumType>
inline
vec3<NumType>
operator-(
vec3<NumType> const& v)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = -v[i];
}
return result;
}
//! Element-wise unary plus.
template <typename NumType>
inline
vec3<NumType>
operator+(
vec3<NumType> const& v)
{
vec3<NumType> result;
for(std::size_t i=0;i<3;i++) {
result[i] = +v[i];
}
return result;
}
//! Return the length of the vector.
template <typename NumType>
inline
NumType
abs(
vec3<NumType> const& v)
{
return v.length();
}
template <typename NumType>
vec3<NumType>
vec3<NumType>::ortho(bool normalize) const
{
const NumType* e = this->elems;
NumType x = abs_(e[0]);
NumType y = abs_(e[1]);
NumType z = abs_(e[2]);
NumType u, v, w;
// Is z the smallest element? Then use x and y.
if (z <= x && z <= y) {
u = e[1]; v = -e[0]; w = 0;
if (normalize) {
NumType d = std::sqrt(x*x + y*y);
if (d != 0) { u /= d; v /= d; }
else { u = 0; v = 0; w = 1; }
}
}
// Is y smallest element? Then use x and z.
else if (y <= x && y <= z) {
u = -e[2]; v = 0; w = e[0];
if (normalize) {
NumType d = std::sqrt(x*x + z*z);
if (d != 0) { u /= d; w /= d; }
else { u = 0; v = 0; w = 1; }
}
}
// x is smallest.
else {
u = 0; v = e[2]; w = -e[1];
if (normalize) {
NumType d = std::sqrt(y*y + z*z);
if (d != 0) { v /= d; w /= d; }
else { u = 0; v = 0; w = 1; }
}
}
return vec3<NumType>(u,v,w);
}
} // namespace scitbx
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
namespace boost {
template <typename NumType>
struct has_trivial_destructor<scitbx::vec3<NumType> > {
static const bool value = ::boost::has_trivial_destructor<NumType>::value;
};
}
#endif
#endif // SCITBX_VEC3_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/type_holder.h | .h | 197 | 11 | #ifndef SCITBX_TYPE_HOLDER_H
#define SCITBX_TYPE_HOLDER_H
namespace scitbx {
template <class T> struct type_holder { typedef T type; };
} // namespace scitbx
#endif // SCITBX_TYPE_HOLDER_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/error_utils.h | .h | 4,754 | 170 | #ifndef SCITBX_ERROR_UTILS_H
#define SCITBX_ERROR_UTILS_H
#include <sstream>
#include <string>
#include <exception>
#include <stdexcept>
#ifdef _MSC_VER
# pragma warning(disable:4355)
#endif
namespace scitbx {
//! Exception which can plug into the SCITBX_ERROR_UTILS_ASSERT trickery
/*!
This class is aimed at being inherited from:
class error : public std::exception, protected scitbx::error_base<error>
{
// define constructors
}
*/
template<class DerivedError>
class error_base : public std::exception
{
public:
DerivedError &SCITBX_ERROR_UTILS_ASSERT_A, &SCITBX_ERROR_UTILS_ASSERT_B;
DerivedError& derived_this() throw();
error_base(std::string const& prefix, std::string const& msg) throw();
error_base(
std::string const& prefix,
const char* file, long line,
std::string const& msg = "",
bool internal = true) throw();
error_base(error_base const& e) throw();
virtual ~error_base() throw();
virtual const char*
what() const throw();
template<typename T>
DerivedError&
with_current_value(const T& value, const char* label);
protected:
std::string msg_;
};
template<class DerivedError>
DerivedError& error_base<DerivedError>
::derived_this() throw()
{
return static_cast<DerivedError&>(*this);
}
template<class DerivedError>
error_base<DerivedError>
::error_base(
std::string const& prefix,
std::string const& msg) throw()
:
SCITBX_ERROR_UTILS_ASSERT_A(derived_this()),
SCITBX_ERROR_UTILS_ASSERT_B(derived_this())
{
std::ostringstream o;
o << prefix << " Error: " << msg;
msg_ = o.str();
}
template<class DerivedError>
error_base<DerivedError>
::error_base(
std::string const& prefix,
const char* file, long line,
std::string const& msg,
bool internal) throw()
:
SCITBX_ERROR_UTILS_ASSERT_A(derived_this()),
SCITBX_ERROR_UTILS_ASSERT_B(derived_this())
{
std::ostringstream o;
o << prefix;
if (internal) o << " Internal";
o << " Error: " << file << "(" << line << ")";
if (msg.size()) o << ": " << msg;
msg_ = o.str();
}
template<class DerivedError>
error_base<DerivedError>
::error_base(error_base const& e) throw()
:
std::exception(e),
SCITBX_ERROR_UTILS_ASSERT_A(derived_this()),
SCITBX_ERROR_UTILS_ASSERT_B(derived_this())
{
msg_ += e.msg_;
}
template<class DerivedError>
error_base<DerivedError>
::~error_base() throw() {}
template<class DerivedError>
const char*
error_base<DerivedError>
::what() const throw() { return msg_.c_str(); }
template<class DerivedError>
template<typename T>
DerivedError& error_base<DerivedError>
::with_current_value(
const T& value,
const char* label)
{
std::ostringstream o;
o << "\n" << " " << label << " = " << value;
msg_ += o.str();
return derived_this();
}
} // namespace scitbx
//! For throwing an error exception with file name, line number, and message.
#define SCITBX_ERROR_UTILS_REPORT(error_class, msg) \
error_class(__FILE__, __LINE__, msg, false)
//! For throwing an "Internal Error" exception.
#define SCITBX_ERROR_UTILS_REPORT_INTERNAL(error_class) \
error_class(__FILE__, __LINE__)
//! For throwing a "Not implemented" exception.
#define SCITBX_ERROR_UTILS_REPORT_NOT_IMPLEMENTED(error_class) \
error_class(__FILE__, __LINE__, "Not implemented.")
//! Custom assertion.
/*!
Here is an example of use:
\code
SCITBX_ERROR_UTILS_ASSERT(error_class, n > 0 && m < n)(m)(n);
\endcode
The first parenthesis contains the expression to assert whereas the subsequent
parentheses contain the variables whose values will be reported upon failure of
the assertion. The C++ stream system must know how to handle the type of m and
n through the operator <<.
If the condition is violated, an instance of error_class is thrown. That
class should inherit from error_format<namespace::error> as explained in the
documentation of error_format.
The implementation uses the tricks described in [1].
[1] A. Alexandrescu and J. Torjo, "Enhancing Assertions",
C/C++ Users Journal, August 2003
*/
#define SCITBX_ERROR_UTILS_ASSERT_A(x) SCITBX_ERROR_UTILS_ASSERT_OP(x, B)
#define SCITBX_ERROR_UTILS_ASSERT_B(x) SCITBX_ERROR_UTILS_ASSERT_OP(x, A)
#define SCITBX_ERROR_UTILS_ASSERT_OP(x, next) \
SCITBX_ERROR_UTILS_ASSERT_A.with_current_value( \
(x), #x).SCITBX_ERROR_UTILS_ASSERT_ ## next
#define SCITBX_ERROR_UTILS_ASSERT(error_class, assert_macro, assertion) \
if (!(assertion)) throw error_class(__FILE__, __LINE__, \
#assert_macro"(" # assertion ") failure.").SCITBX_ERROR_UTILS_ASSERT_A
#endif // SCITBX_ERROR_UTILS_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/rational.h | .h | 1,732 | 74 | #ifndef SCITBX_RATIONAL_H
#define SCITBX_RATIONAL_H
#include <boost/rational.hpp>
#include <string>
#include <cstdio>
namespace scitbx {
//! Formatting of rational numbers.
template <typename IntType>
std::string
format(
boost::rational<IntType> const& v,
bool decimal=false)
{
if (v.numerator() == 0) return std::string("0");
char buf[128];
if (decimal) {
std::sprintf(buf, "%.6g", double(v.numerator()) / v.denominator());
char* cp = buf;
if (*cp == '-') cp++;
if (*cp == '0') {
char* cpp = cp + 1; while (*cp) *cp++ = *cpp++;
}
}
else if (v.denominator() == 1) {
std::sprintf(buf, "%ld", static_cast<long>(v.numerator()));
}
else {
std::sprintf(buf, "%ld/%ld", static_cast<long>(v.numerator()),
static_cast<long>(v.denominator()));
}
return std::string(buf);
}
template <typename IntType>
std::string
format(
boost::rational<IntType> const* values,
std::size_t values_size,
char const* seperator=",",
bool decimal=false)
{
std::string result;
if (values_size != 0) {
result.reserve(8*values_size);
for(std::size_t i=0;;) {
result += format(values[i++], decimal);
if (i == values_size) break;
result += seperator;
}
}
return result;
}
template <typename ArrayType>
typename ArrayType::value_type
array_lcm(ArrayType const& a)
{
typename ArrayType::value_type result;
if (a.size() > 0) {
result = a[0];
for(std::size_t i=1;i<a.size();i++) {
result = boost::lcm(result, a[i]);
}
}
return result;
}
} // namespace scitbx
#endif // SCITBX_RATIONAL_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/constants.h | .h | 1,867 | 60 | /*! \file
General purpose mathematical or physical %constants.
*/
#ifndef SCITBX_CONSTANTS_H
#define SCITBX_CONSTANTS_H
#include <cmath>
namespace scitbx {
//! General purpose mathematical or physical %constants.
namespace constants {
//! mathematical constant pi
static const double pi = 4. * std::atan(1.);
//! mathematical constant pi*pi
static const double pi_sq = pi * pi;
//! mathematical constant 2*pi
static const double two_pi = 8. * std::atan(1.);
//! mathematical constant 2*pi*pi
static const double two_pi_sq = 2. * pi_sq;
//! mathematical constant 4*pi
static const double four_pi = 16. * std::atan(1.);
//! mathematical constant 4*pi*pi
static const double four_pi_sq = two_pi * two_pi;
//! mathematical constant 8*pi*pi
static const double eight_pi_sq = 2. * four_pi_sq;
//! mathematical constant pi/2
static const double pi_2 = 2. * std::atan(1.);
//! mathematical constant pi/180
static const double pi_180 = std::atan(1.) / 45.;
//! Factor for keV <-> Angstrom conversion.
/*!
http://physics.nist.gov/PhysRefData/codata86/table2.html
h = Plank's Constant = 6.6260755e-34 J s
c = speed of light = 2.99792458e+8 m/s
1 keV = 1.e+3 * 1.60217733e-19 J
1 A = Angstrom = 1.e-10 m
E = (h * c) / lamda;
Exponents: (-34 + 8) - (3 - 19 - 10) = 0
*/
static const double
factor_kev_angstrom = 6.6260755 * 2.99792458 / 1.60217733;
static const double
factor_ev_angstrom = 6626.0755 * 2.99792458 / 1.60217733;
}
//! Conversions from degrees to radians.
inline double deg_as_rad(double deg) { return deg * constants::pi_180;}
//! Conversions from radians to degrees.
inline double rad_as_deg(double rad) { return rad / constants::pi_180;}
} // namespace scitbx
#endif // SCITBX_CONSTANTS_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/mat3.h | .h | 25,139 | 989 | #ifndef SCITBX_MAT3_H
#define SCITBX_MAT3_H
#include <utility>
#include <scitbx/error.h>
#include <scitbx/vec3.h>
#include <scitbx/array_family/tiny_reductions.h>
namespace scitbx {
// forward declaration
template <typename NumType>
class sym_mat3;
//! Matrix class (3x3).
/*! This class represents a 3x3 matrix that can be used to store
linear transformations.
Enhanced version of the python mat3 class by
Matthias Baas (baas@ira.uka.de). See
http://cgkit.sourceforge.net/
for more information.
*/
template <typename NumType>
class mat3 : public af::tiny_plain<NumType, 9>
{
public:
typedef typename af::tiny_plain<NumType, 9> base_type;
//! Default constructor. Elements are not initialized.
mat3() {}
//! Constructor.
mat3(NumType const& e00, NumType const& e01, NumType const& e02,
NumType const& e10, NumType const& e11, NumType const& e12,
NumType const& e20, NumType const& e21, NumType const& e22)
: base_type(e00, e01, e02, e10, e11, e12, e20, e21, e22)
{}
//! Constructor.
mat3(base_type const& a)
: base_type(a)
{}
//! Constructor.
explicit
mat3(const NumType* a)
{
for(std::size_t i=0;i<9;i++) this->elems[i] = a[i];
}
//! Constructor for diagonal matrix.
explicit
mat3(NumType const& diag)
: base_type(diag,0,0,0,diag,0,0,0,diag)
{}
//! Constructor for diagonal matrix.
explicit
mat3(NumType const& diag0, NumType const& diag1, NumType const& diag2)
: base_type(diag0,0,0,0,diag1,0,0,0,diag2)
{}
//! Constructor for diagonal matrix.
explicit
mat3(af::tiny_plain<NumType,3> const& diag)
: base_type(diag[0],0,0,0,diag[1],0,0,0,diag[2])
{}
//! Construction from symmetric matrix.
explicit
inline
mat3(sym_mat3<NumType> const& m);
//! Access elements with 2-dimensional indices.
NumType const&
operator()(std::size_t r, std::size_t c) const
{
return this->elems[r * 3 + c];
}
//! Access elements with 2-dimensional indices.
NumType&
operator()(std::size_t r, std::size_t c)
{
return this->elems[r * 3 + c];
}
//! Return a row.
vec3<NumType>
get_row(std::size_t i) const
{
return vec3<NumType>(&this->elems[i * 3]);
}
//! Set a row.
void
set_row(std::size_t i, af::tiny_plain<NumType,3> const& v)
{
std::copy(v.begin(), v.end(), &this->elems[i * 3]);
}
//! Swap two rows in place.
void
swap_rows(std::size_t i1, std::size_t i2)
{
std::swap_ranges(&(*this)(i1,0), &(*this)(i1+1,0), &(*this)(i2,0));
}
//! Return a column.
vec3<NumType>
get_column(std::size_t i) const
{
vec3<NumType> result;
for(std::size_t j=0;j<3;j++) result[j] = this->elems[j * 3 + i];
return result;
}
//! Set a column.
void
set_column(std::size_t i, af::tiny_plain<NumType,3> const& v)
{
for(std::size_t j=0;j<3;j++) this->elems[j * 3 + i] = v[j];
}
//! Swap two columns in place.
void
swap_columns(std::size_t i1, std::size_t i2)
{
for(std::size_t i=0;i<9;i+=3) {
std::swap(this->elems[i + i1], this->elems[i + i2]);
}
}
//! Return diagonal elements.
vec3<NumType>
diagonal() const
{
mat3 const& m = *this;
return vec3<NumType>(m[0], m[4], m[8]);
}
//! Return the transposed matrix.
mat3
transpose() const
{
mat3 const& m = *this;
return mat3(m[0], m[3], m[6],
m[1], m[4], m[7],
m[2], m[5], m[8]);
}
//! Return trace (sum of diagonal elements).
NumType
trace() const
{
mat3 const& m = *this;
return m[0] + m[4] + m[8];
}
//! Return determinant.
NumType
determinant() const
{
mat3 const& m = *this;
return m[0] * (m[4] * m[8] - m[5] * m[7])
- m[1] * (m[3] * m[8] - m[5] * m[6])
+ m[2] * (m[3] * m[7] - m[4] * m[6]);
}
//! Maximum of the absolute values of the elements of this matrix.
NumType
max_abs() const
{
return af::max_absolute(this->const_ref());
}
//! Test for symmetric matrix.
/*! Returns false if the absolute value of the difference between
any pair of off-diagonal elements is different from zero.
*/
bool
is_symmetric() const
{
mat3 const& m = *this;
return m[1] == m[3]
&& m[2] == m[6]
&& m[5] == m[7];
}
//! Test for symmetric matrix.
/*! Returns false if the absolute value of the difference between
any pair of off-diagonal elements is larger than
max_abs()*relative_tolerance.
*/
bool
is_symmetric(NumType const& relative_tolerance) const
{
mat3 const& m = *this;
NumType tolerance = max_abs() * relative_tolerance;
return fn::approx_equal(m[1], m[3], tolerance)
&& fn::approx_equal(m[2], m[6], tolerance)
&& fn::approx_equal(m[5], m[7], tolerance);
}
bool
is_diagonal() const
{
mat3 const& m = *this;
return ( m[1]==0 && m[2]==0
&& m[3]==0 && m[5]==0
&& m[6]==0 && m[7]==0);
}
//! Return the transposed of the co-factor matrix.
/*! The inverse matrix is obtained by dividing the result
by the determinant().
*/
mat3
co_factor_matrix_transposed() const
{
mat3 const& m = *this;
return mat3(
m[4] * m[8] - m[5] * m[7],
-m[1] * m[8] + m[2] * m[7],
m[1] * m[5] - m[2] * m[4],
-m[3] * m[8] + m[5] * m[6],
m[0] * m[8] - m[2] * m[6],
-m[0] * m[5] + m[2] * m[3],
m[3] * m[7] - m[4] * m[6],
-m[0] * m[7] + m[1] * m[6],
m[0] * m[4] - m[1] * m[3]);
}
//! Return the inverse matrix.
/*! An exception is thrown if the matrix is not invertible,
i.e. if the determinant() is zero.
*/
mat3
inverse() const
{
NumType d = determinant();
if (d == NumType(0)) throw error("Matrix is not invertible.");
return co_factor_matrix_transposed() / d;
}
//! Returns the inverse matrix, after minimizing the error numerically.
/*! Here's the theory:
M*M^-1 = I-E, where E is the error
M*M^-1*(I+E) = (I-E)*(I+E)
M*(M^-1*(I+E)) = I^2-E^2
M*(M^-1*(I+E)) = I-E^2
let M^-1*(I+E) = M1
let E^2 = E2
M*M1*(I+E2) = (I-E2)*(I+E2)
M*M2 = I-E4
M*Mi = I-E2^i
Supposedly this will drive the error pretty low after
only a few repetitions. The error rate should be ~E^(2^iterations),
which I think is pretty good. This assumes that E is "<< 1",
whatever that means. Attributed to Judah I. Rosenblatt.
2*I - (I-E) ==> 2*I - I + E = I + E
*/
mat3
error_minimizing_inverse ( std::size_t iterations ) const
{
mat3 inverse = this->inverse();
if ( 0 == iterations )
return inverse;
mat3 two_diagonal(2);
for ( std::size_t i=0; i<iterations; ++i )
inverse = inverse * (two_diagonal - this*inverse);
return inverse;
}
//! Scale matrix in place.
/*! Each row of this is multiplied element-wise with v.
*/
mat3&
scale(af::tiny_plain<NumType,3> const& v)
{
for(std::size_t i=0;i<9;) {
for(std::size_t j=0;j<3;j++,i++) {
this->elems[i] *= v[j];
}
}
return *this;
}
//! Return a matrix with orthogonal base vectors.
mat3 ortho() const;
//! Decomposes the matrix into a rotation and scaling part.
std::pair<mat3, vec3<NumType> >
decompose() const;
//! (*this) * this->transpose().
inline
sym_mat3<NumType>
self_times_self_transpose() const;
//! this->transpose() * (*this).
inline
sym_mat3<NumType>
self_transpose_times_self() const;
//! Sum of element-wise products.
inline
NumType
dot(mat3 const& other) const
{
mat3 const& m = *this;
return m[0] * other[0]
+ m[1] * other[1]
+ m[2] * other[2]
+ m[3] * other[3]
+ m[4] * other[4]
+ m[5] * other[5]
+ m[6] * other[6]
+ m[7] * other[7]
+ m[8] * other[8];
}
//! Matrix associated with vector cross product.
/*! a.cross(b) is equivalent to cross_product_matrix(a) * b.
Useful for simplification of equations. Used frequently in
robotics and classical mechanics literature.
*/
static
mat3
cross_product_matrix(
vec3<NumType> const& v)
{
return mat3(
0, -v[2], v[1],
v[2], 0, -v[0],
-v[1], v[0], 0);
}
//! Returns the outer product, or tensor product of one and other
static
mat3
outer_product( vec3<NumType> const& one, vec3<NumType> const& other )
{
return mat3 ( one[0]*other[0], one[0]*other[1], one[0]*other[2],
one[1]*other[0], one[1]*other[1], one[1]*other[2],
one[2]*other[0], one[2]*other[1], one[2]*other[2]
);
}
/// Matrix associated with symmetric rank-2 tensor transform
/** The change of basis of such a tensor U reads
\f[ U' = R U R^T \f]
where \f$U, U'\f$ are represented as symmetric matrices.
If, on the other hand, \f$U\f$ is represented as a vector
\f[ u = (u_{11}, u_{22}, u_{33}, u_{12}, u_{13}, u_{23}) \f]
and similarly \f$U'\f$, then the change of basis may be written
as a linear transformation
\f[ u' = P u \]
where \f$P\f$ reads
\f[ P = \begin{bmatrix}
r_{11}^2 & r_{12}^2 & r_{13}^2 &
2 r_{11} r_{12} & 2 r_{11} r_{13} & 2 r_{12} r_{13} \\
r_{21}^2 & r_{22}^2 & r_{23}^2 &
2 r_{21} r_{22} & 2 r_{21} r_{23} & 2 r_{22} r_{23} \\
r_{31}^2 & r_{32}^2 & r_{33}^2 &
2 r_{31} r_{32} & 2 r_{31} r_{33} & 2 r_{32} r_{33} \\
r_{11} r_{21} & r_{12} r_{22} & r_{13} r_{23} &
r_{12} r_{21} + r_{11} r_{22} &
r_{13} r_{21} + r_{11} r_{23} &
r_{13} r_{22} + r_{12} r_{23} \\
r_{11} r_{31} & r_{12} r_{32} & r_{13} r_{33} &
r_{12} r_{31} + r_{11} r_{32} &
r_{13} r_{31} + r_{11} r_{33} &
r_{13} r_{32} + r_{12} r_{33} \\
r_{21} r_{31} & r_{22} r_{32} & r_{23} r_{33} &
r_{22} r_{31} + r_{21} r_{32} &
r_{23} r_{31} + r_{21} r_{33} &
r_{23} r_{32} + r_{22} r_{33}
\end{bmatrix}
C.f. scitbx/matrix/tensor_transform_as_linear_map.nb
for the Mathematica code used to obtain this result.
The result is a matrix stored by row.
*/
af::tiny<NumType, 6*6> tensor_transform_matrix() const {
af::tiny<NumType, 6*6> result;
NumType *p = result.begin();
mat3 const &m = *this;
NumType r11 = m[0], r12 = m[1], r13 = m[2],
r21 = m[3], r22 = m[4], r23 = m[5],
r31 = m[6], r32 = m[7], r33 = m[8];
// 1st row
*p++ = r11*r11;
*p++ = r12*r12;
*p++ = r13*r13;
*p++ = 2*r11*r12;
*p++ = 2*r11*r13;
*p++ = 2*r12*r13;
// 2nd row
*p++ = r21*r21;
*p++ = r22*r22;
*p++ = r23*r23;
*p++ = 2*r21*r22;
*p++ = 2*r21*r23;
*p++ = 2*r22*r23;
// 3rd row
*p++ = r31*r31;
*p++ = r32*r32;
*p++ = r33*r33;
*p++ = 2*r31*r32;
*p++ = 2*r31*r33;
*p++ = 2*r32*r33;
// 4th row
*p++ = r11*r21;
*p++ = r12*r22;
*p++ = r13*r23;
*p++ = r12*r21 + r11*r22;
*p++ = r13*r21 + r11*r23;
*p++ = r13*r22 + r12*r23;
// 5th row
*p++ = r11*r31;
*p++ = r12*r32;
*p++ = r13*r33;
*p++ = r12*r31 + r11*r32;
*p++ = r13*r31 + r11*r33;
*p++ = r13*r32 + r12*r33;
// 6th row
*p++ = r21*r31;
*p++ = r22*r32;
*p++ = r23*r33;
*p++ = r22*r31 + r21*r32;
*p++ = r23*r31 + r21*r33;
*p++ = r23*r32 + r22*r33;
return result;
}
};
// non-inline member function
template <typename NumType>
mat3<NumType>
mat3<NumType>::ortho() const
{
vec3<NumType> x = get_column(0);
vec3<NumType> y = get_column(1);
vec3<NumType> z = get_column(2);
NumType xl = x.length_sq();
y = y - ((x * y) / xl) * x;
z = z - ((x * z) / xl) * x;
NumType yl = y.length_sq();
z = z - ((y * z) / yl) * y;
return mat3(x[0], y[0], z[0],
x[1], y[1], z[1],
x[2], y[2], z[2]);
}
// non-inline member function
template <typename NumType>
std::pair<mat3<NumType>, vec3<NumType> >
mat3<NumType>::decompose() const
{
mat3 ro = ortho();
vec3<NumType> x = ro.get_column(0);
vec3<NumType> y = ro.get_column(1);
vec3<NumType> z = ro.get_column(2);
NumType xl = x.length();
NumType yl = y.length();
NumType zl = z.length();
vec3<NumType> sc(xl, yl, zl);
x /= xl;
y /= yl;
z /= zl;
ro.set_column(0, x);
ro.set_column(1, y);
ro.set_column(2, z);
if (ro.determinant() < NumType(0)) {
ro.set_column(0, -x);
sc[0] = -sc[0];
}
return std::make_pair(ro, sc);
}
//! Test equality.
template <typename NumType>
inline
bool
operator==(
mat3<NumType> const& lhs,
mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<9;i++) {
if (lhs[i] != rhs[i]) return false;
}
return true;
}
//! Test equality. True if all elements of lhs == rhs.
template <typename NumType>
inline
bool
operator==(
mat3<NumType> const& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<9;i++) {
if (lhs[i] != rhs ) return false;
}
return true;
}
//! Test equality. True if all elements of rhs == lhs.
template <typename NumType>
inline
bool
operator==(
NumType const& lhs,
mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<9;i++) {
if (lhs != rhs[i]) return false;
}
return true;
}
//! Test inequality.
template <typename NumType>
inline
bool
operator!=(
mat3<NumType> const& lhs,
mat3<NumType> const& rhs)
{
return !(lhs == rhs);
}
//! Test inequality. True if any element of lhs != rhs.
template <typename NumType>
inline
bool
operator!=(
mat3<NumType> const& lhs,
NumType const& rhs)
{
return !(lhs == rhs);
}
//! Test inequality. True if any element of rhs != lhs.
template <typename NumType>
inline
bool
operator!=(
NumType const& lhs,
mat3<NumType> const& rhs)
{
return !(lhs == rhs);
}
//! Element-wise addition.
template <typename NumType>
inline
mat3<NumType>
operator+(
mat3<NumType> const& lhs,
mat3<NumType> const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs[i] + rhs[i];
}
return result;
}
//! Element-wise addition.
template <typename NumType>
inline
mat3<NumType>
operator+(
mat3<NumType> const& lhs,
NumType const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs[i] + rhs ;
}
return result;
}
//! Element-wise addition.
template <typename NumType>
inline
mat3<NumType>
operator+(
NumType const& lhs,
mat3<NumType> const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs + rhs[i];
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
mat3<NumType>
operator-(
mat3<NumType> const& lhs,
mat3<NumType> const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs[i] - rhs[i];
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
mat3<NumType>
operator-(
mat3<NumType> const& lhs,
NumType const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs[i] - rhs ;
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
mat3<NumType>
operator-(
NumType const& lhs,
mat3<NumType> const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs - rhs[i];
}
return result;
}
//! Matrix * matrix product.
template <typename NumTypeLhs, typename NumTypeRhs>
inline
mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>
operator*(
mat3<NumTypeLhs> const& lhs,
mat3<NumTypeRhs> const& rhs)
{
return mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>(
lhs[0]*rhs[0]+lhs[1]*rhs[3]+lhs[2]*rhs[6],
lhs[0]*rhs[1]+lhs[1]*rhs[4]+lhs[2]*rhs[7],
lhs[0]*rhs[2]+lhs[1]*rhs[5]+lhs[2]*rhs[8],
lhs[3]*rhs[0]+lhs[4]*rhs[3]+lhs[5]*rhs[6],
lhs[3]*rhs[1]+lhs[4]*rhs[4]+lhs[5]*rhs[7],
lhs[3]*rhs[2]+lhs[4]*rhs[5]+lhs[5]*rhs[8],
lhs[6]*rhs[0]+lhs[7]*rhs[3]+lhs[8]*rhs[6],
lhs[6]*rhs[1]+lhs[7]*rhs[4]+lhs[8]*rhs[7],
lhs[6]*rhs[2]+lhs[7]*rhs[5]+lhs[8]*rhs[8]);
}
//! lhs.transpose() * rhs
template <typename NumTypeLhs, typename NumTypeRhs>
inline
mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>
transpose_mul(
mat3<NumTypeLhs> const& lhs,
mat3<NumTypeRhs> const& rhs)
{
return mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>(
lhs[0]*rhs[0]+lhs[3]*rhs[3]+lhs[6]*rhs[6],
lhs[0]*rhs[1]+lhs[3]*rhs[4]+lhs[6]*rhs[7],
lhs[0]*rhs[2]+lhs[3]*rhs[5]+lhs[6]*rhs[8],
lhs[1]*rhs[0]+lhs[4]*rhs[3]+lhs[7]*rhs[6],
lhs[1]*rhs[1]+lhs[4]*rhs[4]+lhs[7]*rhs[7],
lhs[1]*rhs[2]+lhs[4]*rhs[5]+lhs[7]*rhs[8],
lhs[2]*rhs[0]+lhs[5]*rhs[3]+lhs[8]*rhs[6],
lhs[2]*rhs[1]+lhs[5]*rhs[4]+lhs[8]*rhs[7],
lhs[2]*rhs[2]+lhs[5]*rhs[5]+lhs[8]*rhs[8]);
}
//! lhs * rhs.transpose()
template <typename NumTypeLhs, typename NumTypeRhs>
inline
mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>
mul_transpose(
mat3<NumTypeLhs> const& lhs,
mat3<NumTypeRhs> const& rhs)
{
return mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>(
lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2],
lhs[0]*rhs[3]+lhs[1]*rhs[4]+lhs[2]*rhs[5],
lhs[0]*rhs[6]+lhs[1]*rhs[7]+lhs[2]*rhs[8],
lhs[3]*rhs[0]+lhs[4]*rhs[1]+lhs[5]*rhs[2],
lhs[3]*rhs[3]+lhs[4]*rhs[4]+lhs[5]*rhs[5],
lhs[3]*rhs[6]+lhs[4]*rhs[7]+lhs[5]*rhs[8],
lhs[6]*rhs[0]+lhs[7]*rhs[1]+lhs[8]*rhs[2],
lhs[6]*rhs[3]+lhs[7]*rhs[4]+lhs[8]*rhs[5],
lhs[6]*rhs[6]+lhs[7]*rhs[7]+lhs[8]*rhs[8]);
}
//! Matrix * vector product.
template <typename NumTypeMatrix,
typename NumTypeVector>
inline
vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>
operator*(
mat3<NumTypeMatrix> const& lhs,
af::tiny_plain<NumTypeVector,3> const& rhs)
{
return vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>(
lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2],
lhs[3]*rhs[0]+lhs[4]*rhs[1]+lhs[5]*rhs[2],
lhs[6]*rhs[0]+lhs[7]*rhs[1]+lhs[8]*rhs[2]);
}
//! Vector * matrix product.
template <typename NumTypeVector,
typename NumTypeMatrix>
inline
vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>
operator*(
af::tiny_plain<NumTypeVector,3> const& lhs,
mat3<NumTypeMatrix> const& rhs)
{
return vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>(
lhs[0]*rhs[0]+lhs[1]*rhs[3]+lhs[2]*rhs[6],
lhs[0]*rhs[1]+lhs[1]*rhs[4]+lhs[2]*rhs[7],
lhs[0]*rhs[2]+lhs[1]*rhs[5]+lhs[2]*rhs[8]);
}
//! Element-wise multiplication.
template <typename NumType>
inline
mat3<NumType>
operator*(
mat3<NumType> const& lhs,
NumType const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs[i] * rhs ;
}
return result;
}
//! Element-wise multiplication.
template <typename NumType>
inline
mat3<NumType>
operator*(
NumType const& lhs,
mat3<NumType> const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs * rhs[i];
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
mat3<NumType>
operator/(
mat3<NumType> const& lhs,
NumType const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs[i] / rhs ;
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
mat3<NumType>
operator/(
NumType const& lhs,
mat3<NumType> const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs / rhs[i];
}
return result;
}
//! Element-wise modulus operation.
template <typename NumType>
inline
mat3<NumType>
operator%(
mat3<NumType> const& lhs,
NumType const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs[i] % rhs ;
}
return result;
}
//! Element-wise modulus operation.
template <typename NumType>
inline
mat3<NumType>
operator%(
NumType const& lhs,
mat3<NumType> const& rhs)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = lhs % rhs[i];
}
return result;
}
//! Element-wise in-place addition.
template <typename NumType>
inline
mat3<NumType>&
operator+=(
mat3<NumType>& lhs,
mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<9;i++) {
lhs[i] += rhs[i];
}
return lhs;
}
//! Element-wise in-place addition.
template <typename NumType>
inline
mat3<NumType>&
operator+=(
mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<9;i++) {
lhs[i] += rhs ;
}
return lhs;
}
//! Element-wise in-place difference.
template <typename NumType>
inline
mat3<NumType>&
operator-=(
mat3<NumType>& lhs,
mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<9;i++) {
lhs[i] -= rhs[i];
}
return lhs;
}
//! Element-wise in-place difference.
template <typename NumType>
inline
mat3<NumType>&
operator-=(
mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<9;i++) {
lhs[i] -= rhs ;
}
return lhs;
}
//! Element-wise in-place multiplication.
template <typename NumType>
inline
mat3<NumType>&
operator*=(
mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<9;i++) {
lhs[i] *= rhs ;
}
return lhs;
}
//! Element-wise in-place division.
template <typename NumType>
inline
mat3<NumType>&
operator/=(
mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<9;i++) {
lhs[i] /= rhs ;
}
return lhs;
}
//! Element-wise in-place modulus operation.
template <typename NumType>
inline
mat3<NumType>&
operator%=(
mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<9;i++) {
lhs[i] %= rhs ;
}
return lhs;
}
//! Element-wise unary minus.
template <typename NumType>
inline
mat3<NumType>
operator-(
mat3<NumType> const& v)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = -v[i];
}
return result;
}
//! Element-wise unary plus.
template <typename NumType>
inline
mat3<NumType>
operator+(
mat3<NumType> const& v)
{
mat3<NumType> result;
for(std::size_t i=0;i<9;i++) {
result[i] = +v[i];
}
return result;
}
} // namespace scitbx
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
namespace boost {
template <typename NumType>
struct has_trivial_destructor<scitbx::mat3<NumType> > {
static const bool value = ::boost::has_trivial_destructor<NumType>::value;
};
}
#endif
#endif // SCITBX_MAT3_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/auto_array.h | .h | 2,517 | 108 | #ifndef SCITBX_AUTO_ARRAY_H
#define SCITBX_AUTO_ARRAY_H
// Modified (Ralf W. Grosse-Kunstleve) copy of boost/scoped_array.hpp
// Original copyright:
// (C) Copyright Greg Colvin and Beman Dawes 1998, 1999.
// Copyright (c) 2001, 2002 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0. (See
// http://www.boost.org/LICENSE_1_0.txt)
//
// http://www.boost.org/libs/smart_ptr/scoped_array.htm
#include <boost/config.hpp> // in case ptrdiff_t not in std
#include <boost/detail/workaround.hpp>
#include <cstddef> // for std::ptrdiff_t
namespace scitbx {
//! Like std::auto_ptr, but with delete[].
template<typename T>
class auto_array
{
private:
typedef auto_array<T> this_type;
protected:
mutable T* ptr;
public:
typedef T element_type;
explicit
auto_array(T* p=0) : ptr(p) {}
// This should be non-const, but that would require serious gymnastics.
auto_array(auto_array const& other)
:
ptr(const_cast<auto_array*>(&other)->release())
{}
// This should be non-const, but that would require serious gymnastics.
auto_array&
operator=(auto_array const& other)
{
reset(const_cast<auto_array*>(&other)->release());
return *this;
}
~auto_array() { delete[] ptr; }
void
reset(T* p=0) { if (p != ptr) this_type(p).swap(*this); }
T*
release()
{
T* result = ptr;
ptr = 0;
return result;
}
T&
operator[](std::ptrdiff_t i) const { return ptr[i]; }
T*
get() const { return ptr; }
#if defined(__SUNPRO_CC) && BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530)
operator bool () const { return ptr != 0; }
#elif defined(__MWERKS__) \
&& BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003))
typedef T* (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const
{
return ptr == 0? 0: &this_type::get;
}
#else
typedef T* this_type::*unspecified_bool_type;
operator unspecified_bool_type() const
{
return ptr == 0? 0: &this_type::ptr;
}
#endif
bool
operator!() const { return ptr == 0; }
void swap(auto_array & other)
{
T* tmp = other.ptr;
other.ptr = ptr;
ptr = tmp;
}
};
template<typename T>
inline void
swap(auto_array<T>& a, auto_array<T>& b) { a.swap(b); }
} // namespace scitbx
#endif // SCITBX_AUTO_ARRAY_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/sym_mat3.h | .h | 22,179 | 846 | #ifndef SCITBX_SYM_MAT3_H
#define SCITBX_SYM_MAT3_H
#include <scitbx/mat3.h>
namespace scitbx {
static const std::size_t sym_mat3_storage_mapping[] = {0,3,4,
3,1,5,
4,5,2};
//! Symmetric 3x3 matrix class.
template <typename NumType>
class sym_mat3 : public af::tiny_plain<NumType, 6>
{
public:
typedef typename af::tiny_plain<NumType, 6> base_type;
//! Default constructor. Elements are not initialized.
sym_mat3() {}
//! Constructor.
sym_mat3(NumType const& e00, NumType const& e11, NumType const& e22,
NumType const& e01, NumType const& e02, NumType const& e12)
: base_type(e00, e11, e22, e01, e02, e12)
{}
//! Constructor.
sym_mat3(base_type const& a)
: base_type(a)
{}
//! Constructor.
explicit
sym_mat3(const NumType* a)
{
for(std::size_t i=0;i<6;i++) this->elems[i] = a[i];
}
//! Constructor for diagonal matrix.
explicit
sym_mat3(NumType const& diag)
: base_type(diag,diag,diag,0,0,0)
{}
//! Constructor for diagonal matrix.
explicit
sym_mat3(af::tiny_plain<NumType,3> const& diag)
: base_type(diag[0],diag[1],diag[2],0,0,0)
{}
//! Construction from full 3x3 matrix.
/*! The off-diagonal elements of the new sym_mat3 are copied from
the upper-right triangle of m.
<p>
An exception is thrown if the absolute value of the
difference between any pair of off-diagonal elements is
different from zero.
<p>
See also: mat3<>::is_symmetric()
*/
explicit
sym_mat3(mat3<NumType> const& m)
: base_type(m[0],m[4],m[8],m[1],m[2],m[5])
{
SCITBX_ASSERT(m.is_symmetric());
}
//! Construction from full 3x3 matrix.
/*! The off-diagonal elements of the new sym_mat3 are determined
as the averages of the corresponding off-diagonal elements
of the input matrix m.
<p>
If relative_tolerance is greater than or equal to zero, it is
used to check the input matrix m. An exception is thrown if
the absolute value of the difference between any pair of
off-diagonal elements is larger than
max_abs*relative_tolerance, where max_abs is the maximum of
the absolute values of the elements of m.
<p>
See also: mat3<>::is_symmetric()
*/
explicit
sym_mat3(mat3<NumType> const& m, NumType const& relative_tolerance)
: base_type(m[0],m[4],m[8],
(m[1]+m[3])/2,
(m[2]+m[6])/2,
(m[5]+m[7])/2)
{
SCITBX_ASSERT(relative_tolerance < 0
|| m.is_symmetric(relative_tolerance));
}
//! Access elements with 2-dimensional indices.
NumType const&
operator()(std::size_t r, std::size_t c) const
{
return this->begin()[sym_mat3_storage_mapping[r * 3 + c]];
}
//! Access elements with 2-dimensional indices.
NumType&
operator()(std::size_t r, std::size_t c)
{
return this->begin()[sym_mat3_storage_mapping[r * 3 + c]];
}
//! Return diagonal elements.
vec3<NumType>
diagonal() const
{
return vec3<NumType>(this->begin());
}
//! Return the transposed matrix.
/*! In analogy with mat3, return a new instance.
*/
sym_mat3
transpose()
{
return *this;
}
//! Return trace (sum of diagonal elements).
NumType
trace() const
{
return af::sum(diagonal());
}
//! Return determinant.
NumType
determinant() const
{
sym_mat3 const& m = *this;
return m(0,0) * (m(1,1) * m(2,2) - m(1,2) * m(2,1))
- m(0,1) * (m(1,0) * m(2,2) - m(1,2) * m(2,0))
+ m(0,2) * (m(1,0) * m(2,1) - m(1,1) * m(2,0));
}
//! Return the transposed of the co-factor matrix.
/*! The inverse matrix is obtained by dividing the result
by the determinant().
*/
sym_mat3
co_factor_matrix_transposed() const
{
sym_mat3 const& m = *this;
sym_mat3 result;
result(0,0) = m(1,1) * m(2,2) - m(1,2) * m(2,1);
result(1,1) = m(0,0) * m(2,2) - m(0,2) * m(2,0);
result(2,2) = m(0,0) * m(1,1) - m(0,1) * m(1,0);
result(0,1) = -m(0,1) * m(2,2) + m(0,2) * m(2,1);
result(0,2) = m(0,1) * m(1,2) - m(0,2) * m(1,1);
result(1,2) = -m(0,0) * m(1,2) + m(0,2) * m(1,0);
return result;
}
//! Return the inverse matrix.
/*! An exception is thrown if the matrix is not invertible,
i.e. if the determinant() is zero.
*/
sym_mat3
inverse() const
{
NumType d = determinant();
if (d == NumType(0)) throw error("Matrix is not invertible.");
return co_factor_matrix_transposed() / d;
}
//! Tensor transform: c * (*this) * c.transpose()
template <typename OtherNumType>
sym_mat3
tensor_transform(mat3<OtherNumType> const& c) const;
//! Antisymmetric tensor transform: c * (*this) * c.transpose()
/*! c is the antisymmetric matrix
{{ 0, v0, v1},
{-v0, 0, v2}
{-v1, -v2, 0}}
*/
sym_mat3
antisymmetric_tensor_transform(
NumType const& v0,
NumType const& v1,
NumType const& v2) const;
//! Antisymmetric tensor transform: c * (*this) * c.transpose()
/*! c is the antisymmetric matrix
{{ 0, v[0], v[1]},
{-v[0], 0, v[2]}
{-v[1], -v[2], 0 }}
*/
sym_mat3
antisymmetric_tensor_transform(vec3<NumType> const& v) const
{
return antisymmetric_tensor_transform(v[0], v[1], v[2]);
}
//! Tensor transform: c.transpose() * (*this) * c
sym_mat3
tensor_transpose_transform(mat3<NumType> const& c) const;
//! Sum of 9 element-wise products.
inline
NumType
dot(sym_mat3 const& other) const
{
sym_mat3 const& m = *this;
return m[0] * other[0]
+ m[1] * other[1]
+ m[2] * other[2]
+ 2 * ( m[3] * other[3]
+ m[4] * other[4]
+ m[5] * other[5]);
}
};
// Constructor for mat3.
template <typename NumType>
inline
mat3<NumType>::mat3(sym_mat3<NumType> const& m)
: base_type(m[0], m[3], m[4],
m[3], m[1], m[5],
m[4], m[5], m[2])
{}
template <typename NumType>
inline
sym_mat3<NumType>
mat3<NumType>::self_times_self_transpose() const
{
mat3<NumType> const& m = *this;
return sym_mat3<NumType>(
m[0]*m[0]+m[1]*m[1]+m[2]*m[2],
m[3]*m[3]+m[4]*m[4]+m[5]*m[5],
m[6]*m[6]+m[7]*m[7]+m[8]*m[8],
m[0]*m[3]+m[1]*m[4]+m[2]*m[5],
m[0]*m[6]+m[1]*m[7]+m[2]*m[8],
m[3]*m[6]+m[4]*m[7]+m[5]*m[8]);
}
template <typename NumType>
inline
sym_mat3<NumType>
mat3<NumType>::self_transpose_times_self() const
{
mat3<NumType> const& m = *this;
return sym_mat3<NumType>(
m[0]*m[0]+m[3]*m[3]+m[6]*m[6],
m[1]*m[1]+m[4]*m[4]+m[7]*m[7],
m[2]*m[2]+m[5]*m[5]+m[8]*m[8],
m[0]*m[1]+m[3]*m[4]+m[6]*m[7],
m[0]*m[2]+m[3]*m[5]+m[6]*m[8],
m[1]*m[2]+m[4]*m[5]+m[7]*m[8]);
}
// non-inline member function
template <typename NumType>
sym_mat3<NumType>
sym_mat3<NumType>
::antisymmetric_tensor_transform(
NumType const& v0,
NumType const& v1,
NumType const& v2) const
{
sym_mat3<NumType> const& t = *this;
NumType v00 = v0 * v0;
NumType v11 = v1 * v1;
NumType v22 = v2 * v2;
NumType v01 = v0 * v1;
NumType v02 = v0 * v2;
NumType v12 = v1 * v2;
// The result is guaranteed to be a symmetric matrix.
return sym_mat3<NumType>(
t[2]*v11 + 2*t[5]*v01 + t[1]*v00,
t[2]*v22 - 2*t[4]*v02 + t[0]*v00,
t[1]*v22 + 2*t[3]*v12 + t[0]*v11,
t[2]*v12 + t[5]*v02 - t[4]*v01 - t[3]*v00,
-t[5]*v12 - t[1]*v02 - t[4]*v11 - t[3]*v01,
-t[5]*v22 - t[4]*v12 + t[3]*v02 + t[0]*v01);
}
// non-inline member function
template <typename NumType>
template <typename OtherNumType>
sym_mat3<NumType>
sym_mat3<NumType>
::tensor_transform(mat3<OtherNumType> const& c) const
{
mat3<NumType> ct = c * (*this);
// The result is guaranteed to be a symmetric matrix.
return sym_mat3<NumType>(
ct[0]*c[0]+ct[1]*c[1]+ct[2]*c[2],
ct[3]*c[3]+ct[4]*c[4]+ct[5]*c[5],
ct[6]*c[6]+ct[7]*c[7]+ct[8]*c[8],
ct[0]*c[3]+ct[1]*c[4]+ct[2]*c[5],
ct[0]*c[6]+ct[1]*c[7]+ct[2]*c[8],
ct[3]*c[6]+ct[4]*c[7]+ct[5]*c[8]);
}
// non-inline member function
template <typename NumType>
sym_mat3<NumType>
sym_mat3<NumType>
::tensor_transpose_transform(mat3<NumType> const& c) const
{
sym_mat3<NumType> const& t = *this;
mat3<NumType> ctt( // c.transpose() * (*this)
c[0]*t[0]+c[3]*t[3]+c[6]*t[4],
c[3]*t[1]+c[0]*t[3]+c[6]*t[5],
c[6]*t[2]+c[0]*t[4]+c[3]*t[5],
c[1]*t[0]+c[4]*t[3]+c[7]*t[4],
c[4]*t[1]+c[1]*t[3]+c[7]*t[5],
c[7]*t[2]+c[1]*t[4]+c[4]*t[5],
c[2]*t[0]+c[5]*t[3]+c[8]*t[4],
c[5]*t[1]+c[2]*t[3]+c[8]*t[5],
c[8]*t[2]+c[2]*t[4]+c[5]*t[5]);
// The result is guaranteed to be a symmetric matrix.
return sym_mat3<NumType>(
ctt[0]*c[0]+ctt[1]*c[3]+ctt[2]*c[6],
ctt[3]*c[1]+ctt[4]*c[4]+ctt[5]*c[7],
ctt[6]*c[2]+ctt[7]*c[5]+ctt[8]*c[8],
ctt[0]*c[1]+ctt[1]*c[4]+ctt[2]*c[7],
ctt[0]*c[2]+ctt[1]*c[5]+ctt[2]*c[8],
ctt[3]*c[2]+ctt[4]*c[5]+ctt[5]*c[8]);
}
//! Test equality.
template <typename NumType>
inline
bool
operator==(
sym_mat3<NumType> const& lhs,
sym_mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<6;i++) {
if (lhs[i] != rhs[i]) return false;
}
return true;
}
//! Test equality. True if all elements of lhs == rhs.
template <typename NumType>
inline
bool
operator==(
sym_mat3<NumType> const& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<6;i++) {
if (lhs[i] != rhs ) return false;
}
return true;
}
//! Test equality. True if all elements of rhs == lhs.
template <typename NumType>
inline
bool
operator==(
NumType const& lhs,
sym_mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<6;i++) {
if (lhs != rhs[i]) return false;
}
return true;
}
//! Test inequality.
template <typename NumType>
inline
bool
operator!=(
sym_mat3<NumType> const& lhs,
sym_mat3<NumType> const& rhs)
{
return !(lhs == rhs);
}
//! Test inequality. True if any element of lhs != rhs.
template <typename NumType>
inline
bool
operator!=(
sym_mat3<NumType> const& lhs,
NumType const& rhs)
{
return !(lhs == rhs);
}
//! Test inequality. True if any element of rhs != lhs.
template <typename NumType>
inline
bool
operator!=(
NumType const& lhs,
sym_mat3<NumType> const& rhs)
{
return !(lhs == rhs);
}
//! Element-wise addition.
template <typename NumType>
inline
sym_mat3<NumType>
operator+(
sym_mat3<NumType> const& lhs,
sym_mat3<NumType> const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs[i] + rhs[i];
}
return result;
}
//! Element-wise addition.
template <typename NumType>
inline
sym_mat3<NumType>
operator+(
sym_mat3<NumType> const& lhs,
NumType const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs[i] + rhs ;
}
return result;
}
//! Element-wise addition.
template <typename NumType>
inline
sym_mat3<NumType>
operator+(
NumType const& lhs,
sym_mat3<NumType> const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs + rhs[i];
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
sym_mat3<NumType>
operator-(
sym_mat3<NumType> const& lhs,
sym_mat3<NumType> const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs[i] - rhs[i];
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
sym_mat3<NumType>
operator-(
sym_mat3<NumType> const& lhs,
NumType const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs[i] - rhs ;
}
return result;
}
//! Element-wise difference.
template <typename NumType>
inline
sym_mat3<NumType>
operator-(
NumType const& lhs,
sym_mat3<NumType> const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs - rhs[i];
}
return result;
}
//! Symmetric * symmetric matrix product.
template <typename NumTypeLhs, typename NumTypeRhs>
inline
mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>
operator*(
sym_mat3<NumTypeLhs> const& lhs,
sym_mat3<NumTypeRhs> const& rhs)
{
typedef
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic
result_element_type;
result_element_type lhs_3__rhs_3_ = lhs[3]*rhs[3];
result_element_type lhs_4__rhs_4_ = lhs[4]*rhs[4];
result_element_type lhs_5__rhs_5_ = lhs[5]*rhs[5];
return mat3<result_element_type>(
lhs[0]*rhs[0]+lhs_3__rhs_3_+lhs_4__rhs_4_,
lhs[3]*rhs[1]+lhs[0]*rhs[3]+lhs[4]*rhs[5],
lhs[4]*rhs[2]+lhs[0]*rhs[4]+lhs[3]*rhs[5],
lhs[3]*rhs[0]+lhs[1]*rhs[3]+lhs[5]*rhs[4],
lhs[1]*rhs[1]+lhs_3__rhs_3_+lhs_5__rhs_5_,
lhs[5]*rhs[2]+lhs[3]*rhs[4]+lhs[1]*rhs[5],
lhs[4]*rhs[0]+lhs[5]*rhs[3]+lhs[2]*rhs[4],
lhs[5]*rhs[1]+lhs[4]*rhs[3]+lhs[2]*rhs[5],
lhs[2]*rhs[2]+lhs_4__rhs_4_+lhs_5__rhs_5_);
}
//! Square * symmetric matrix product.
template <typename NumTypeLhs, typename NumTypeRhs>
inline
mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>
operator*(
mat3<NumTypeLhs> const& lhs,
sym_mat3<NumTypeRhs> const& rhs)
{
return mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>(
lhs[0]*rhs[0]+lhs[1]*rhs[3]+lhs[2]*rhs[4],
lhs[1]*rhs[1]+lhs[0]*rhs[3]+lhs[2]*rhs[5],
lhs[2]*rhs[2]+lhs[0]*rhs[4]+lhs[1]*rhs[5],
lhs[3]*rhs[0]+lhs[4]*rhs[3]+lhs[5]*rhs[4],
lhs[4]*rhs[1]+lhs[3]*rhs[3]+lhs[5]*rhs[5],
lhs[5]*rhs[2]+lhs[3]*rhs[4]+lhs[4]*rhs[5],
lhs[6]*rhs[0]+lhs[7]*rhs[3]+lhs[8]*rhs[4],
lhs[7]*rhs[1]+lhs[6]*rhs[3]+lhs[8]*rhs[5],
lhs[8]*rhs[2]+lhs[6]*rhs[4]+lhs[7]*rhs[5]);
}
//! Symmetric * square matrix product.
template <typename NumTypeLhs, typename NumTypeRhs>
inline
mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>
operator*(
sym_mat3<NumTypeLhs> const& lhs,
mat3<NumTypeRhs> const& rhs)
{
return mat3<
typename af::binary_operator_traits<
NumTypeLhs, NumTypeRhs>::arithmetic>(
rhs[0]*lhs[0]+rhs[3]*lhs[3]+rhs[6]*lhs[4],
rhs[1]*lhs[0]+rhs[4]*lhs[3]+rhs[7]*lhs[4],
rhs[2]*lhs[0]+rhs[5]*lhs[3]+rhs[8]*lhs[4],
rhs[3]*lhs[1]+rhs[0]*lhs[3]+rhs[6]*lhs[5],
rhs[4]*lhs[1]+rhs[1]*lhs[3]+rhs[7]*lhs[5],
rhs[5]*lhs[1]+rhs[2]*lhs[3]+rhs[8]*lhs[5],
rhs[6]*lhs[2]+rhs[0]*lhs[4]+rhs[3]*lhs[5],
rhs[7]*lhs[2]+rhs[1]*lhs[4]+rhs[4]*lhs[5],
rhs[8]*lhs[2]+rhs[2]*lhs[4]+rhs[5]*lhs[5]);
}
//! Matrix * vector product.
template <typename NumTypeMatrix,
typename NumTypeVector>
inline
vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>
operator*(
sym_mat3<NumTypeMatrix> const& lhs,
af::tiny_plain<NumTypeVector,3> const& rhs)
{
return vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>(
lhs[0]*rhs[0]+lhs[3]*rhs[1]+lhs[4]*rhs[2],
lhs[3]*rhs[0]+lhs[1]*rhs[1]+lhs[5]*rhs[2],
lhs[4]*rhs[0]+lhs[5]*rhs[1]+lhs[2]*rhs[2]);
}
//! Vector * matrix product.
template <typename NumTypeVector,
typename NumTypeMatrix>
inline
vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>
operator*(
af::tiny_plain<NumTypeVector,3> const& lhs,
sym_mat3<NumTypeMatrix> const& rhs)
{
return vec3<
typename af::binary_operator_traits<
NumTypeMatrix, NumTypeVector>::arithmetic>(
lhs[0]*rhs[0]+lhs[1]*rhs[3]+lhs[2]*rhs[4],
lhs[1]*rhs[1]+lhs[0]*rhs[3]+lhs[2]*rhs[5],
lhs[2]*rhs[2]+lhs[0]*rhs[4]+lhs[1]*rhs[5]);
}
/// Linear form * (matrix as 6-vector)
template <typename NumTypeVector,
typename NumTypeMatrix>
inline
typename af::binary_operator_traits<NumTypeVector,
NumTypeMatrix>::arithmetic
operator*(af::tiny_plain<NumTypeVector, 6> const &form,
sym_mat3<NumTypeMatrix> const &matrix_as_vec6)
{
typename af::binary_operator_traits<NumTypeVector,
NumTypeMatrix>::arithmetic
result = 0;
for (int i=0; i<6; ++i) result += form[i]*matrix_as_vec6[i];
return result;
}
//! Element-wise multiplication.
template <typename NumType>
inline
sym_mat3<NumType>
operator*(
sym_mat3<NumType> const& lhs,
NumType const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs[i] * rhs ;
}
return result;
}
//! Element-wise multiplication.
template <typename NumType>
inline
sym_mat3<NumType>
operator*(
NumType const& lhs,
sym_mat3<NumType> const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs * rhs[i];
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
sym_mat3<NumType>
operator/(
sym_mat3<NumType> const& lhs,
NumType const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs[i] / rhs ;
}
return result;
}
//! Element-wise division.
template <typename NumType>
inline
sym_mat3<NumType>
operator/(
NumType const& lhs,
sym_mat3<NumType> const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs / rhs[i];
}
return result;
}
//! Element-wise modulus operation.
template <typename NumType>
inline
sym_mat3<NumType>
operator%(
sym_mat3<NumType> const& lhs,
NumType const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs[i] % rhs ;
}
return result;
}
//! Element-wise modulus operation.
template <typename NumType>
inline
sym_mat3<NumType>
operator%(
NumType const& lhs,
sym_mat3<NumType> const& rhs)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = lhs % rhs[i];
}
return result;
}
//! Element-wise in-place addition.
template <typename NumType>
inline
sym_mat3<NumType>&
operator+=(
sym_mat3<NumType>& lhs,
sym_mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<6;i++) {
lhs[i] += rhs[i];
}
return lhs;
}
//! Element-wise in-place addition.
template <typename NumType>
inline
sym_mat3<NumType>&
operator+=(
sym_mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<6;i++) {
lhs[i] += rhs ;
}
return lhs;
}
//! Element-wise in-place difference.
template <typename NumType>
inline
sym_mat3<NumType>&
operator-=(
sym_mat3<NumType>& lhs,
sym_mat3<NumType> const& rhs)
{
for(std::size_t i=0;i<6;i++) {
lhs[i] -= rhs[i];
}
return lhs;
}
//! Element-wise in-place difference.
template <typename NumType>
inline
sym_mat3<NumType>&
operator-=(
sym_mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<6;i++) {
lhs[i] -= rhs ;
}
return lhs;
}
//! Element-wise in-place multiplication.
template <typename NumType>
inline
sym_mat3<NumType>&
operator*=(
sym_mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<6;i++) {
lhs[i] *= rhs ;
}
return lhs;
}
//! Element-wise in-place division.
template <typename NumType>
inline
sym_mat3<NumType>&
operator/=(
sym_mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<6;i++) {
lhs[i] /= rhs ;
}
return lhs;
}
//! Element-wise in-place modulus operation.
template <typename NumType>
inline
sym_mat3<NumType>&
operator%=(
sym_mat3<NumType>& lhs,
NumType const& rhs)
{
for(std::size_t i=0;i<6;i++) {
lhs[i] %= rhs ;
}
return lhs;
}
//! Element-wise unary minus.
template <typename NumType>
inline
sym_mat3<NumType>
operator-(
sym_mat3<NumType> const& v)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = -v[i];
}
return result;
}
//! Element-wise unary plus.
template <typename NumType>
inline
sym_mat3<NumType>
operator+(
sym_mat3<NumType> const& v)
{
sym_mat3<NumType> result;
for(std::size_t i=0;i<6;i++) {
result[i] = +v[i];
}
return result;
}
} // namespace scitbx
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
namespace boost {
template <typename NumType>
struct has_trivial_destructor<scitbx::sym_mat3<NumType> > {
static const bool value = ::boost::has_trivial_destructor<NumType>::value;
};
}
#endif
#endif // SCITBX_SYM_MAT3_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/error.h | .h | 2,350 | 80 | /* *****************************************************
THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT.
*****************************************************
Generated by:
scitbx.generate_error_h
*/
/*! \file
Declarations and macros for exception handling.
*/
#ifndef SCITBX_ERROR_H
#define SCITBX_ERROR_H
#include <scitbx/error_utils.h>
#include <iostream>
#define SCITBX_CHECK_POINT \
std::cout << __FILE__ << "(" << __LINE__ << ")" << std::endl << std::flush
#define SCITBX_CHECK_POINT_MSG(msg) \
std::cout << msg << " @ " __FILE__ << "(" << __LINE__ << ")" \
<< std::endl << std::flush
#define SCITBX_EXAMINE(A) \
std::cout << "variable " << #A << ": " << A << std::endl << std::flush
//! Common scitbx namespace.
namespace scitbx {
//! All scitbx exceptions are derived from this class.
class error : public ::scitbx::error_base<error>
{
public:
//! General scitbx error message.
explicit
error(std::string const& msg) throw()
: ::scitbx::error_base<error>("scitbx", msg)
{}
//! Error message with file name and line number.
/*! Used by the macros below.
*/
error(const char* file, long line, std::string const& msg = "",
bool internal = true) throw()
: ::scitbx::error_base<error>("scitbx", file, line, msg, internal)
{}
};
//! Special class for "Index out of range." exceptions.
/*! These exceptions are propagated to Python as IndexError.
*/
class error_index : public error
{
public:
//! Default constructor. The message may be customized.
explicit
error_index(std::string const& msg = "Index out of range.") throw()
: error(msg)
{}
};
} // namespace scitbx
//! For throwing an error exception with file name, line number, and message.
#define SCITBX_ERROR(msg) \
SCITBX_ERROR_UTILS_REPORT(scitbx::error, msg)
//! For throwing an "Internal Error" exception.
#define SCITBX_INTERNAL_ERROR() \
SCITBX_ERROR_UTILS_REPORT_INTERNAL(scitbx::error)
//! For throwing a "Not implemented" exception.
#define SCITBX_NOT_IMPLEMENTED() \
SCITBX_ERROR_UTILS_REPORT_NOT_IMPLEMENTED(scitbx::error)
//! Custom scitbx assertion.
#define SCITBX_ASSERT(assertion) \
SCITBX_ERROR_UTILS_ASSERT(scitbx::error, SCITBX_ASSERT, assertion)
#endif // SCITBX_ERROR_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/utils.h | .h | 3,883 | 162 | #ifndef SCITBX_MATH_UTILS_H
#define SCITBX_MATH_UTILS_H
#include <cmath>
#include <algorithm>
#include <limits>
#include <complex>
namespace scitbx { namespace math {
template <typename NumType1, typename NumType2>
inline
NumType1&
update_min(NumType1& m, NumType2 const& x)
{
if (m > x) m = x;
return m;
}
template <typename NumType1, typename NumType2>
inline
NumType1&
update_max(NumType1& m, NumType2 const& x)
{
if (m < x) m = x;
return m;
}
/// Overflow-proof sqrt(x*x + y*y)
template <typename NumType>
inline
NumType norm(NumType x, NumType y) {
x = std::abs(x);
y = std::abs(y);
if (x > y) std::swap(x, y);
// 0 < x < y from here on
if (x == 0) return y;
NumType t = x/y;
return y*std::sqrt(NumType(1) + t*t);
}
template <typename FloatType>
FloatType
round(FloatType x, int n_digits=0)
{
// based on Python/bltinmodule.c: builtin_round()
FloatType f = 1;
int i = n_digits;
if (i < 0) i = -i;
while (--i >= 0) f *= 10;
if (n_digits < 0) x /= f;
else x *= f;
if (x >= 0) x = std::floor(x + 0.5);
else x = std::ceil(x - 0.5);
if (n_digits < 0) x *= f;
else x /= f;
return x;
}
template <typename FloatType,
typename SignedIntType>
struct float_int_conversions
{
static
inline
SignedIntType
iround(FloatType const& x)
{
if (x < 0) return static_cast<SignedIntType>(x-0.5);
return static_cast<SignedIntType>(x+.5);
}
static
inline
SignedIntType
iceil(FloatType const& x) { return iround(std::ceil(x)); }
static
inline
SignedIntType
ifloor(FloatType const& x) { return iround(std::floor(x)); }
static
inline
SignedIntType
nearest_integer(FloatType const& x)
{
SignedIntType i = static_cast<SignedIntType>(x);
FloatType dxi = x - static_cast<FloatType>(i);
if (x >= 0) {
if (dxi > 0.5) i++;
else if (dxi == 0.5 && (i & 1)) i++;
}
else {
if (x - static_cast<FloatType>(i) < -0.5) i--;
else if (dxi == -0.5 && (i & 1)) i--;
}
return i;
}
};
inline
int
iround(double x) { return float_int_conversions<double,int>::iround(x); }
inline
int
iceil(double x) { return float_int_conversions<double,int>::iceil(x); }
inline
int
ifloor(double x) { return float_int_conversions<double,int>::ifloor(x); }
inline
int
nearest_integer(double x)
{
return float_int_conversions<double,int>::nearest_integer(x);
}
template <typename UnsignedIntType, typename SizeType>
bool
unsigned_product_leads_to_overflow(UnsignedIntType* a, SizeType n) {
double product = 1;
for (int i=0; i<n; i++) {
product *= a[i];
}
return product > std::numeric_limits<UnsignedIntType>::max();
}
/// Quotient and remainder of x/y for floating point x and y
/** The static function divmod returns n,r such that:
- n is the nearest integer to x/y
- r = x - n*y
*/
template<typename FloatType, typename SignedIntType>
struct remainder_and_quotient {
static inline
std::pair<SignedIntType, FloatType>
divmod(FloatType x, FloatType y) {
SignedIntType quo
= float_int_conversions<FloatType, SignedIntType>::nearest_integer(x/y);
FloatType rem = x - quo*y;
return std::make_pair(quo, rem);
}
};
inline std::pair<int, double> divmod(double x, double y) {
return remainder_and_quotient<double, int>::divmod(x,y);
}
// Returns a complex number with magnitude equal to 1, and phase theta
template<typename FloatType>
std::complex<FloatType> unit_complex(FloatType const& theta){
return std::complex<FloatType>(std::cos(theta), std::sin(theta));
}
}} // namespace scitbx::math
#endif // SCITBX_MATH_UTILS_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/traits.h | .h | 292 | 21 | #ifndef SCITBX_MATH_ABS_H
#define SCITBX_MATH_ABS_H
#include <complex>
namespace scitbx { namespace math {
template <class T>
struct abs_traits {
typedef T result_type;
};
template <class T>
struct abs_traits< std::complex<T> > {
typedef T result_type;
};
}}
#endif
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/gcd.h | .h | 4,361 | 196 | #ifndef SCITBX_MATH_GCD_H
#define SCITBX_MATH_GCD_H
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) \
&& (!defined(__clang__)) \
&& (defined(__APPLE_CC__) && __APPLE_CC__ >= 5465) // OS X 10.5
# define SCITBX_MATH_GCD_USING_ASM
#endif
namespace scitbx { namespace math {
inline
int
gcd_int_simple(
int a,
int b)
{
for(;;) {
if (b == 0) return (a < 0 ? -a : a);
int next_b = a % b;
a = b;
b = next_b;
}
}
inline
long
gcd_long_simple(
long a,
long b)
{
for(;;) {
if (b == 0) return (a < 0 ? -a : a);
long next_b = a % b;
a = b;
b = next_b;
}
}
#if defined(SCITBX_MATH_GCD_USING_ASM)
/* gcc 3.2 32-bit: ca. 30% faster than gcd_int_simple()
gcc 4.0 32-bit: ca. 10% faster
gcc 4.1 64-bit: ca. 15% faster
gcc 4.4, icc 9.1 64-bit: practically same speed
*/
inline
int
gcd_int32_asm(
int a,
int b)
{
__asm__(
" movl %2, %%ecx\n"
".L_for_%=:\n"
" cmpl $0, %%ecx\n" // if b == 0
" je .L_return_a_or_minus_a_%=\n"
" movl %0, %%edx\n"
" sarl $31, %%edx\n"
" idivl %%ecx\n" // next_b = a % b
" movl %%ecx, %0\n" // a = b
" movl %%edx, %%ecx\n" // b = next_b
" jmp .L_for_%=\n"
".L_return_a_or_minus_a_%=:\n"
// next five lines: slightly faster than compare & jump
" movl %0, %%ecx\n"
" cltd\n"
" xorl %%edx, %%ecx\n"
" subl %%edx, %%ecx\n"
" movl %%ecx, %0\n"
: "=a"(a) /* output */
: "0"(a), "r"(b) /* input */
: "cc", "%ecx", "%edx"); /* clobbered registers */
return a;
}
#endif
#if defined(SCITBX_MATH_GCD_USING_ASM) && defined(__x86_64__)
inline
long
gcd_int64_asm(
long a,
long b)
{
__asm__(
" movq %2, %%rcx\n"
".L_for_%=:\n"
" cmpq $0, %%rcx\n" // if b == 0
" je .L_return_a_or_minus_a_%=\n"
" movq %0, %%rdx\n"
" sarq $63, %%rdx\n"
" idivq %%rcx\n" // next_b = a % b
" movq %%rcx, %0\n" // a = b
" movq %%rdx, %%rcx\n" // b = next_b
" jmp .L_for_%=\n"
".L_return_a_or_minus_a_%=:\n"
// next five lines: slightly faster than compare & jump
" movq %0, %%rcx\n"
" cqto\n"
" xorq %%rdx, %%rcx\n"
" subq %%rdx, %%rcx\n"
" movq %%rcx, %0\n"
: "=a"(a) /* output */
: "0"(a), "r"(b) /* input */
: "cc", "%rcx", "%rdx"); /* clobbered registers */
return a;
}
#endif
// from boost/math/common_factor_rt.hpp, svn trunk rev. 47847
inline
unsigned long
gcd_unsigned_long_binary(
unsigned long u,
unsigned long v)
{
if ( u && v ) {
// Shift out common factors of 2
unsigned shifts = 0;
while ( !(u & 1u) && !(v & 1u) ) {
++shifts;
u >>= 1;
v >>= 1;
}
// Start with the still-even one, if any
unsigned long r[] = { u, v };
unsigned which = static_cast<bool>( u & 1u );
// Whittle down the values via their differences
do {
// Remove factors of two from the even one
while ( !(r[ which ] & 1u) ) {
r[ which ] >>= 1;
}
// Replace the larger of the two with their difference
if ( r[!which] > r[which] ) {
which ^= 1u;
}
r[ which ] -= r[ !which ];
}
while ( r[which] );
// Shift-in the common factor of 2 to the residues' GCD
return r[ !which ] << shifts;
}
else {
// At least one input is zero, return the other
// (adding since zero is the additive identity)
// or zero if both are zero.
return u + v;
}
}
inline
long
gcd_long_binary(
long u,
long v)
{
return static_cast<long>(
gcd_unsigned_long_binary(
u < 0 ? -u : u,
v < 0 ? -v : v));
}
inline
int
gcd_int(
int a,
int b)
{
#if defined(SCITBX_MATH_GCD_USING_ASM)
return gcd_int32_asm(a, b);
#else
return gcd_int_simple(a, b);
#endif
}
inline
long
gcd_long(
long a,
long b)
{
#if defined(SCITBX_MATH_GCD_USING_ASM)
# if defined(__x86_64__)
return gcd_int64_asm(a, b);
# else
return gcd_int32_asm(a, b);
# endif
#else
return gcd_long_simple(a, b);
#endif
}
}} // namespace scitbx::math
#endif // GUARD
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/modulo.h | .h | 771 | 44 | #ifndef SCITBX_MATH_MOD_H
#define SCITBX_MATH_MOD_H
#include <cmath>
namespace scitbx { namespace math {
template <typename IntType>
inline
IntType
mod_positive(IntType ix, IntType const& iy)
{
if (iy > 0) {
ix %= iy;
if (ix < 0) ix += iy;
}
return ix;
}
template <typename IntType>
inline
IntType
mod_short(IntType ix, IntType const& iy)
{
ix = mod_positive(ix, iy);
if (ix > iy / 2)
ix -= iy;
return ix;
}
template <typename FloatType>
inline FloatType
fmod_short(FloatType const& x, FloatType const& y)
{
FloatType result = std::fmod(x, y);
if (result < 0) result += y;
if (result > y/2) result -= y;
return result;
}
}} // namespace scitbx::math
#endif // GUARD
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/erf.h | .h | 1,326 | 61 | #ifndef SCITBX_MATH_ERF_H
#define SCITBX_MATH_ERF_H
#include <scitbx/math/erf/engine.h>
#include <scitbx/array_family/shared.h>
#include <scitbx/array_family/ref.h>
namespace scitbx { namespace math {
//! Approximate values for erf(x).
/*! See also: scitbx::math::erf_engine
*/
template <typename FloatType>
inline
FloatType
erf(FloatType const& x)
{
return erf_engine<FloatType>().compute(x, 0);
}
template <typename FloatType>
inline
af::shared<FloatType>
erf(af::const_ref<FloatType> const& x)
{
af::shared<FloatType> result(x.size(),
af::init_functor_null<FloatType>());
erf_engine<FloatType> engine;
for( unsigned ii=0;ii<x.size();ii++){
result[ii]=engine.compute(x[ii], 0);
}
return ( result );
}
//! Approximate values for erfc(x).
/*! See also: scitbx::math::erf_engine
*/
template <typename FloatType>
inline
FloatType
erfc(FloatType const& x)
{
return erf_engine<FloatType>().compute(x, 1);
}
//! Approximate values for exp(x*x) * erfc(x).
/*! See also: scitbx::math::erf_engine
*/
template <typename FloatType>
inline
FloatType
erfcx(FloatType const& x)
{
return erf_engine<FloatType>().compute(x, 2);
}
}} // namespace scitbx::math
#endif // SCITBX_MATH_ERF_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/approx_equal.h | .h | 2,548 | 79 | #ifndef SCITBX_MATH_APPROX_EQUAL_H
#define SCITBX_MATH_APPROX_EQUAL_H
#include <algorithm>
#include <cmath>
#include <scitbx/math/traits.h>
#include <limits>
namespace scitbx { namespace math {
/** \brief A functor testing whether the relative error
between two floating point values is smaller than some tolerance.
This is recommended a method to compare two values which should only
differ because of rounding errors. The generic type NumType may be
a scalar floating point type, a complex number type or even some vector of
floating point values, providing that std::abs(x) exists
and that abs_traits<NumType> has the correct specialisation.
The implementation first tests whether the two values are very small,
in which case their relative difference is deemed to be zero.
*/
template <class NumType>
struct approx_equal_relatively
{
typedef NumType num_type;
typedef typename abs_traits<num_type>::result_type amplitude_type;
amplitude_type relative_error, near_zero_threshold;
approx_equal_relatively(amplitude_type relative_error)
:
relative_error(relative_error),
near_zero_threshold(std::numeric_limits<amplitude_type>::min())
{}
approx_equal_relatively(amplitude_type relative_error,
amplitude_type near_zero_threshold)
:
relative_error(relative_error),
near_zero_threshold(near_zero_threshold)
{}
bool operator()(num_type const &x, num_type const &y) const {
amplitude_type a = std::abs(x), b = std::abs(y), m = std::max(a, b);
if (m < near_zero_threshold) return true;
if (std::abs(x - y) <= relative_error*m) return true;
return false;
}
};
/** \brief A functor testing whether the relative error
between two floating point values is smaller than some tolerance.
The generic type NumType may be
a scalar floating point type, a complex number type or even some vector of
floating point values, providing that std::abs(x) exists
and that abs_traits<NumType> has the correct specialisation.
*/
template <class NumType>
struct approx_equal_absolutely
{
typedef NumType num_type;
typedef typename abs_traits<num_type>::result_type amplitude_type;
amplitude_type absolute_error;
approx_equal_absolutely(amplitude_type absolute_error)
: absolute_error(absolute_error)
{}
bool operator()(num_type const &x, num_type const &y) const {
return std::abs(x - y) <= absolute_error;
}
};
}}
#endif
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/compile_time.h | .h | 562 | 27 | #ifndef SCITBX_MATH_COMPILE_TIME_H
#define SCITBX_MATH_COMPILE_TIME_H
#include <cstddef>
namespace scitbx { namespace math { namespace compile_time {
template <std::size_t N>
struct product
{
template <typename IndexType>
static std::size_t
get(IndexType const& i) { return i[N-1] * product<N-1>::get(i); }
};
template <>
struct product<1>
{
template <typename IndexType>
static std::size_t
get(IndexType const& i) { return i[0]; }
};
}}} // namespace scitbx::math::compile_time
#endif // SCITBX_MATH_COMPILE_TIME_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/unimodular_generator.h | .h | 3,378 | 123 | #ifndef SCITBX_MATH_UNIMODULAR_GENERATOR_H
#define SCITBX_MATH_UNIMODULAR_GENERATOR_H
#include <scitbx/mat3.h>
namespace scitbx { namespace math {
template <typename IntType>
class unimodular_generator
{
private:
IntType range_;
bool at_end_;
unsigned return_target_id_;
IntType i0, i1, i2, i3, i4, i5, i6, i7, i8;
IntType i37, i38, i48, i4857, i3746, i3856, i04857;
IntType i04857_one, one_i04857_13856;
public:
unimodular_generator() {}
unimodular_generator(IntType const& range)
:
range_(range),
at_end_(false),
return_target_id_(0)
{
incr();
}
bool
at_end() const { return at_end_; }
scitbx::mat3<IntType>
next()
{
SCITBX_ASSERT(!at_end_);
scitbx::mat3<IntType> result(i0,i1,i2,i3,i4,i5,i6,i7,i8);
incr();
return result;
}
std::size_t
count()
{
std::size_t result = 0;
while (!at_end_) {
result++;
incr();
}
return result;
}
private:
void
incr()
{
if (return_target_id_ == 1) goto return_target_1;
if (return_target_id_ == 2) goto return_target_2;
if (return_target_id_ == 3) goto return_target_3;
// 0 1 2
// 3 4 5
// 6 7 8
// Manually optimized search for matrices with determinant 1.
for(i4=-range_;i4<=range_;i4++) {
for(i8=-range_;i8<=range_;i8++) { i48 = i4*i8;
for(i5=-range_;i5<=range_;i5++) {
for(i7=-range_;i7<=range_;i7++) { i4857 = i48-i5*i7;
for(i3=-range_;i3<=range_;i3++) { i38 = i3*i8;
i37 = i3*i7;
for(i6=-range_;i6<=range_;i6++) { i3746 = i37-i4*i6;
i3856 = i38-i5*i6;
if (i3746 == 0) {
if (i3856 == 0) {
if (i4857 == -1 || i4857 == 1) {
return_target_id_ = 1;
i0 = i4857;
for(i1=-range_;i1<=range_;i1++) {
for(i2=-range_;i2<=range_;i2++) {
return;
return_target_1:;
}
}
}
}
else {
return_target_id_ = 2;
for(i0=-range_;i0<=range_;i0++) {
i04857_one = i0*i4857 - 1;
i1 = i04857_one / i3856;
if (-range_ <= i1 && i1 <= range_ && i1*i3856 == i04857_one) {
for(i2=-range_;i2<=range_;i2++) {
return;
return_target_2:;
}
}
}
}
}
else {
return_target_id_ = 3;
for(i0=-range_;i0<=range_;i0++) {
i04857 = i0*i4857;
for(i1=-range_;i1<=range_;i1++) {
one_i04857_13856 = 1 - i04857 + i1*i3856;
i2 = one_i04857_13856 / i3746;
if (-range_ <= i2 && i2 <= range_
&& i2*i3746 == one_i04857_13856) {
return;
return_target_3:;
}
}
}
}
}}}}}}
at_end_ = true;
}
};
}} // namespace scitbx::math
#endif // SCITBX_MATH_UNIMODULAR_GENERATOR_H
| Unknown |
3D | YellProgram/Yell | lib/cctbx_stubs/scitbx/math/gaussian/term.h | .h | 2,657 | 106 | #ifndef SCITBX_MATH_GAUSSIAN_TERM_H
#define SCITBX_MATH_GAUSSIAN_TERM_H
#include <scitbx/math/erf.h>
#include <scitbx/constants.h>
#include <cmath>
namespace scitbx { namespace math { namespace gaussian {
//! Gaussian term: a Exp[-b x^2]
template <typename FloatType=double>
struct term
{
//! Default constructor. Some data members are not initialized!
term() {}
//! Definition of coefficients a and b.
term(FloatType const& a_, FloatType const& b_)
:
a(a_),
b(b_)
{}
//! Gaussian at the point x, given x^2.
FloatType
at_x_sq(FloatType const& x_sq) const
{
return a * std::exp(-b * x_sq);
}
//! Gaussian at the point x.
FloatType
at_x(FloatType const& x) const
{
return at_x_sq(x * x);
}
//! Analytical gradient w.r.t. x at the point x.
FloatType
gradient_dx_at_x(FloatType const& x) const
{
return -2*a*b*x/std::exp(b*x*x);
}
//! Analytical integral dx from 0 to the point x.
FloatType
integral_dx_at_x(
FloatType const& x,
FloatType const& b_min_for_erf_based_algorithm=1e-3)
{
using scitbx::math::erf;
static const FloatType sqrt_pi = std::sqrt(scitbx::constants::pi);
if (b == 0) return a * x;
if (b > b_min_for_erf_based_algorithm) {
/* Mathematica:
f = a Exp[-b x^2]
Integrate[f,x]
*/
FloatType sqrt_b = std::sqrt(b);
return a*sqrt_pi*erf(sqrt_b*x)/(2*sqrt_b);
}
/* Mathematica:
f = a Exp[-b x^2]
Series[Integrate[f,x], {x,0,20}]
Formula for the denominator of the series expansion: (2n+1)*n!
Encyclopedia of Integer Sequences ID Number: A007680
*/
FloatType bxx = b * x * x;
FloatType part = 1;
FloatType result = 1;
FloatType prev_result = result;
unsigned n = 0;
unsigned tnp1 = 1;
while (true) {
n++;
tnp1 += 2;
part *= bxx / n;
result -= part / tnp1;
if (result == prev_result) break;
prev_result = result;
n++;
tnp1 += 2;
part *= bxx / n;
result += part / tnp1;
if (result == prev_result) break;
prev_result = result;
}
return a * x * result;
}
//! Analytical gradients w.r.t. a and b at the point x, given x^2.
term
gradients_d_ab_at_x_sq(FloatType const& x_sq) const
{
FloatType gr_a = std::exp(-b * x_sq);
return term(gr_a, -a * x_sq * gr_a);
}
FloatType a;
FloatType b;
};
}}} // scitbx::math::gaussian
#endif // SCITBX_MATH_GAUSSIAN_TERM_H
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.