-
Notifications
You must be signed in to change notification settings - Fork 298
/
ForceFieldTestCreation.h
300 lines (251 loc) · 13.8 KB
/
ForceFieldTestCreation.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture *
* (c) 2006 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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 2 of the License, or (at your option) *
* any later version. *
* *
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#pragma once
#include <sofa/testing/BaseSimulationTest.h>
using sofa::testing::BaseSimulationTest;
#include <sofa/testing/NumericTest.h>
using sofa::testing::NumericTest;
#include <sofa/simulation/graph/DAGSimulation.h>
#include <sofa/simulation/MechanicalVisitor.h>
#include <sofa/linearalgebra/EigenBaseSparseMatrix.h>
#include <sofa/core/behavior/SingleMatrixAccessor.h>
#include <SceneCreator/SceneCreator.h>
#include <SceneCreator/SceneUtils.h>
#include <sofa/defaulttype/VecTypes.h>
#include <sofa/component/statecontainer/MechanicalObject.h>
#include <sofa/core/behavior/BaseForceField.h>
#include <sofa/simulation/mechanicalvisitor/MechanicalComputeDfVisitor.h>
using sofa::simulation::mechanicalvisitor::MechanicalComputeDfVisitor;
#include <sofa/simulation/mechanicalvisitor/MechanicalResetForceVisitor.h>
using sofa::simulation::mechanicalvisitor::MechanicalResetForceVisitor;
#include <sofa/simulation/mechanicalvisitor/MechanicalComputeForceVisitor.h>
using sofa::simulation::mechanicalvisitor::MechanicalComputeForceVisitor;
namespace sofa {
/** @brief Helper for writing ForceField tests.
* The constructor creates a root node and adds it a State and a ForceField (of the paremeter type of this template class).
* Pointers to node, state and force are available.
* Deriving the ForceField test from this class makes it easy to write: just call function run_test with positions, velocities and the corresponding expected forces.
* This function automatically checks not only the forces (function addForce), but also the stiffness (methods addDForce and addKToMatrix), using finite differences.
* @author François Faure, 2014
*
*/
template <typename _ForceFieldType>
struct ForceField_test : public BaseSimulationTest, NumericTest<typename _ForceFieldType::DataTypes::Real>
{
typedef _ForceFieldType ForceField;
typedef typename ForceField::DataTypes DataTypes;
typedef typename DataTypes::VecCoord VecCoord;
typedef typename DataTypes::VecDeriv VecDeriv;
typedef typename DataTypes::Coord Coord;
typedef typename DataTypes::Deriv Deriv;
typedef typename Coord::value_type Real;
typedef component::statecontainer::MechanicalObject<DataTypes> DOF;
/// @name Scene elements
/// {
typename DOF::SPtr dof;
typename ForceField::SPtr force;
simulation::Node::SPtr node;
/// }
/// @name Precision and control parameters
/// {
SReal errorMax; ///< tolerance in precision test. The actual value is this one times the epsilon of the Real numbers (typically float or double)
SReal errorFactorPotentialEnergy; ///< The test for potential energy is successfull if the (infinite norm of the) difference is less than errorFactorPotentialEnergy * errorMax *epsilon (default = 1)
/**
* @brief Minimum/Maximum amplitudes of the random perturbation used to check the stiffness using finite differences
* @warning Should be more than errorMax/stiffness. This is not checked automatically.
*/
std::pair<Real,Real> deltaRange;
bool checkStiffness; ///< If false, stops the test after checking the force, without checking the stiffness. Default value is true.
bool debug; ///< Print debug messages. Default is false.
/// }
/// @name Tested API
/// {
static const unsigned char TEST_POTENTIAL_ENERGY = 1; ///< testing getPotentialEnergy function. The tests will only work with conservative forces (if dissipative forces such as viscosity or damping are computed, the test is wrong)
static const unsigned char TEST_ALL = UCHAR_MAX; ///< testing everything
unsigned char flags; ///< testing options. (all by default). To be used with precaution.
/// }
/** Create a scene with a node, a state and a forcefield.;
*
*/
ForceField_test()
: errorMax( 100 )
, errorFactorPotentialEnergy(1)
, deltaRange( 1, 1000 )
, checkStiffness( true )
, debug( false )
, flags( TEST_ALL )
{
using modeling::addNew;
simulation::Simulation* simu = sofa::simulation::getSimulation();
assert(simu);
/// node 1
node = simu->createNewGraph("root");
dof = addNew<DOF>(node);
force = addNew<ForceField>(node);
}
/** Create a scene from a xml file.
*
*/
ForceField_test(std::string filename)
: errorMax( 100 )
, errorFactorPotentialEnergy(1)
, deltaRange( 1, 1000 )
, checkStiffness( true )
, debug( false )
, flags( TEST_ALL )
{
using modeling::addNew;
simulation::Simulation* simu = sofa::simulation::getSimulation();
assert(simu);
/// Load the scene
node = simu->createNewGraph("root");
node = sofa::simulation::node::load(filename.c_str());
/// Get mechanical object
dof = node->get<DOF>(node->SearchDown);
// Add force field
force = addNew<ForceField>(node);
}
/**
* @brief Given positions and velocities, checks that the expected forces are obtained, and that a small change of positions generates the corresponding change of forces.
* @param x positions
* @param v velocities
* @param ef expected forces
* This function first checks that the expected forces are obtained. Then, it checks getPotentialEnergy.
* And then, it checks the stiffness, unless member checkStiffness is set to false.
* A new position is created using a small random change, and the new force is computed.
* The change of potential energy is compared to the dot product between displacement and force.
* The change of force is compared to the change computed by function addDForce, and to the product of the position change with the stiffness matrix.
*/
void run_test( const VecCoord& x, const VecDeriv& v, const VecDeriv& ef, bool initScene = true )
{
if( !(flags & TEST_POTENTIAL_ENERGY) ) msg_warning("ForceFieldTest") << "Potential energy is not tested";
if( deltaRange.second / errorMax <= sofa::testing::g_minDeltaErrorRatio )
ADD_FAILURE() << "The comparison threshold is too large for the finite difference delta";
ASSERT_EQ(x.size(), v.size());
ASSERT_EQ(x.size(), ef.size());
std::size_t n = x.size();
// copy the position and velocities to the scene graph
this->dof->resize(static_cast<sofa::Size>(n));
typename DOF::WriteVecCoord xdof = this->dof->writePositions();
sofa::testing::copyToData( xdof, x );
typename DOF::WriteVecDeriv vdof = this->dof->writeVelocities();
sofa::testing::copyToData( vdof, v );
// init scene and compute force
if (initScene)
{
sofa::simulation::node::initRoot(this->node.get());
}
core::MechanicalParams mparams;
mparams.setKFactor(1.0);
MechanicalResetForceVisitor resetForce(&mparams, core::VecDerivId::force());
node->execute(resetForce);
MechanicalComputeForceVisitor computeForce( &mparams, core::VecDerivId::force() );
this->node->execute(computeForce);
// check force
typename DOF::ReadVecDeriv f= this->dof->readForces();
if(debug){
std::cout << "run_test, x = " << x << std::endl;
std::cout << " v = " << v << std::endl;
std::cout << " expected f = " << ef << std::endl;
std::cout << " actual f = " << f.ref() << std::endl;
}
ASSERT_LT( this->vectorMaxDiff(f,ef), errorMax*this->epsilon() );
if( !checkStiffness ) return;
// to check the stiffness, generate a change of position, to check the change of force
// store current force
VecDeriv curF;
sofa::testing::copyFromData( curF, dof->readForces() );
// Get potential Energy before applying a displacement to dofs
SReal potentialEnergyBeforeDisplacement = (flags & TEST_POTENTIAL_ENERGY) ? ((const core::behavior::BaseForceField*)force.get())->getPotentialEnergy(&mparams) : 0;
// change position
VecDeriv dX(n);
for( unsigned i=0; i<n; i++ ){
dX[i] = DataTypes::randomDeriv( deltaRange.first * this->epsilon(), deltaRange.second * this->epsilon() ); // todo: better random, with negative values
xdof[i] += dX[i];
}
// compute new force and difference between previous force
node->execute(resetForce);
node->execute(computeForce);
VecDeriv newF;
sofa::testing::copyFromData( newF, dof->readForces() );
VecDeriv changeOfForce(curF);
for( unsigned i=0; i<curF.size(); ++i){
changeOfForce[i] = newF[i] - curF[i];
}
if( flags & TEST_POTENTIAL_ENERGY )
{
// Get potential energy after displacement of dofs
SReal potentialEnergyAfterDisplacement = ((const core::behavior::BaseForceField*)force.get())->getPotentialEnergy(&mparams);
// Check getPotentialEnergy() we should have dE = -dX.F
// Compute dE = E(x+dx)-E(x)
SReal differencePotentialEnergy = potentialEnergyAfterDisplacement-potentialEnergyBeforeDisplacement;
// Compute the expected difference of potential energy: -dX.F (dot product between applied displacement and Force)
SReal expectedDifferencePotentialEnergy = 0;
for( unsigned i=0; i<n; ++i){
expectedDifferencePotentialEnergy = expectedDifferencePotentialEnergy - dot(dX[i],curF[i]);
}
SReal absoluteErrorPotentialEnergy = std::abs(differencePotentialEnergy - expectedDifferencePotentialEnergy);
if( absoluteErrorPotentialEnergy> errorFactorPotentialEnergy*errorMax*this->epsilon() ){
ADD_FAILURE()<<"dPotentialEnergy differs from -dX.F (threshold=" << errorFactorPotentialEnergy*errorMax*this->epsilon() << ")" << std::endl
<< "dPotentialEnergy is " << differencePotentialEnergy << std::endl
<< "-dX.F is " << expectedDifferencePotentialEnergy << std::endl
<< "Failed seed number = " << this->seed << std::endl;
}
}
// check computeDf: compare its result to actual change
node->execute(resetForce);
dof->vRealloc( &mparams, core::VecDerivId::dx()); // dx is not allocated by default
typename DOF::WriteVecDeriv wdx = dof->writeDx();
sofa::testing::copyToData ( wdx, dX );
MechanicalComputeDfVisitor computeDf( &mparams, core::VecDerivId::force() );
node->execute(computeDf);
VecDeriv dF;
sofa::testing::copyFromData( dF, dof->readForces() );
if( this->vectorMaxDiff(changeOfForce,dF)> errorMax*this->epsilon() ){
ADD_FAILURE()<<"dF differs from change of force" << std::endl << "Failed seed number = " << this->seed << std::endl;
}
// check stiffness matrix: compare its product with dx to actual force change
typedef sofa::linearalgebra::EigenBaseSparseMatrix<SReal> Sqmat;
const sofa::SignedIndex matrixSize = static_cast<sofa::SignedIndex>(n * DataTypes::deriv_total_size);
Sqmat K( matrixSize, matrixSize);
sofa::core::behavior::SingleMatrixAccessor accessor( &K );
mparams.setKFactor(1.0);
force->addKToMatrix( &mparams, &accessor);
K.compress();
// cout << "stiffness: " << K << endl;
modeling::Vector dx;
sofa::testing::data_traits<DataTypes>::VecDeriv_to_Vector( dx, dX );
modeling::Vector Kdx = K * dx;
if( debug ){
std::cout << " dX = " << dX << std::endl;
std::cout << " newF = " << newF << std::endl;
std::cout << " change of force = " << changeOfForce << std::endl;
std::cout << " addDforce = " << dF << std::endl;
std::cout << " Kdx = " << Kdx.transpose() << std::endl;
}
modeling::Vector df;
sofa::testing::data_traits<DataTypes>::VecDeriv_to_Vector( df, changeOfForce );
if( this->vectorMaxDiff(Kdx,df)> errorMax*this->epsilon() )
ADD_FAILURE()<<"Kdx differs from change of force"<< std::endl << "Failed seed number = " << this->seed << std::endl;
}
};
} // namespace sofa