OOFEM  2.4
OOFEM.org - Object Oriented Finite Element Solver
structuralpythonmaterial.C
Go to the documentation of this file.
1 /*
2  *
3  * ##### ##### ###### ###### ### ###
4  * ## ## ## ## ## ## ## ### ##
5  * ## ## ## ## #### #### ## # ##
6  * ## ## ## ## ## ## ## ##
7  * ## ## ## ## ## ## ## ##
8  * ##### ##### ## ###### ## ##
9  *
10  *
11  * OOFEM : Object Oriented Finite Element Code
12  *
13  * Copyright (C) 1993 - 2013 Borek Patzak
14  *
15  *
16  *
17  * Czech Technical University, Faculty of Civil Engineering,
18  * Department of Structural Mechanics, 166 29 Prague, Czech Republic
19  *
20  * This library is free software; you can redistribute it and/or
21  * modify it under the terms of the GNU Lesser General Public
22  * License as published by the Free Software Foundation; either
23  * version 2.1 of the License, or (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28  * Lesser General Public License for more details.
29  *
30  * You should have received a copy of the GNU Lesser General Public
31  * License along with this library; if not, write to the Free Software
32  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
33  */
34 
35 #include <Python.h>
36 
38 #include "gausspoint.h"
39 #include "classfactory.h"
40 #include "dynamicinputrecord.h"
41 
42 namespace oofem {
43 REGISTER_Material(StructuralPythonMaterial);
44 
46  StructuralMaterial(n, d)
47 #if 0
48  smallDef(NULL),
49  smallDefTangent(NULL),
50  largeDef(NULL),
51  largeDefTangent(NULL)
52 #endif
53 {}
54 
56 {
58 }
59 
61 {
62  IRResultType result;
63 
65  if ( result != IRRT_OK ) return result;
66 
68 
69  module=bp::import(moduleName.c_str());
70  if(!module){ OOFEM_WARNING("Module %s not importable.",moduleName.c_str()); return IRRT_BAD_FORMAT; }
71  // lambda for finding function and checking that it is callable
72  // returns true (OK) if the function was not found, or was found and it callable
73  // returns false (not OK) if the function was found but is not callable
74  auto tryDef=[&](const std::string& attr, bp::object& callable)->bool{
75  if(PyObject_HasAttrString(module.ptr(),attr.c_str())){
76  callable=module.attr(attr.c_str());
77  if(!PyCallable_Check(callable.ptr())){ OOFEM_WARNING("Object %s is not callable",attr.c_str()); return false; }
78  } else callable=bp::object();
79  return true;
80  };
81  // try to find all necessary functions; false means the function is not callable, in which case warning was already printed above
82  if(!(tryDef("computeStress",smallDef) && tryDef("computePK1Stress",largeDef) && tryDef("computeStressTangent",smallDefTangent) && tryDef("computePK1StressTangent",largeDefTangent))){ return IRRT_BAD_FORMAT; }
83  if(!smallDefTangent && !!smallDef){ OOFEM_WARNING("Using numerical tangent for small deformations."); }
84  if(!largeDefTangent && !!largeDef){ OOFEM_WARNING("Using numerical tangent for large deformations."); }
85  if(!smallDef && !largeDef){ OOFEM_WARNING("No functions for small/large deformations found."); return IRRT_BAD_FORMAT; }
86 
87 
88 
89 
90 #if 0
91  // Import Python file
92  PyObject *mpName = PyString_FromString( this->moduleName.c_str() );
93  this->mpModule = PyImport_Import(mpName);
94  Py_DECREF(mpName);
95 
96  if ( mpModule != NULL ) {
97  // Load and call Python function
98  smallDef = PyObject_GetAttrString(mpModule, "computeStress");
99  largeDef = PyObject_GetAttrString(mpModule, "computePK1Stress");
100  smallDefTangent = PyObject_GetAttrString(mpModule, "computeStressTangent");
101  largeDefTangent = PyObject_GetAttrString(mpModule, "computePK1StressTangent");
102  if ( smallDefTangent == NULL && smallDef != NULL) {
103  OOFEM_WARNING("Using numerical tangent for small deformations");
104  }
105  if ( largeDefTangent == NULL && largeDef != NULL) {
106  OOFEM_WARNING("Using numerical tangent for large deformations");
107  }
108  if ( smallDef == NULL && largeDef == NULL ) {
109  OOFEM_WARNING("No functions for either small or large deformations supplied. Are you sure the functions are named correctly?");
110  return IRRT_BAD_FORMAT;
111  }
112  } else {
113  OOFEM_WARNING("mpModule == NULL for module name %s", this->moduleName.c_str());
114  return IRRT_BAD_FORMAT;
115  }
116 #endif
117  pert = 1e-12;
118 
119  return IRRT_OK;
120 }
121 
123 {
125 
127 }
128 
130 {
131  return new StructuralPythonMaterialStatus(this->giveDomain(), gp);
132 }
133 
134 void StructuralPythonMaterial :: callStressFunction(bp::object func, const FloatArray &oldStrain, const FloatArray &oldStress, const FloatArray &strain, FloatArray &stress, bp::object stateDict, bp::object tempStateDict, TimeStep *tStep) const
135 {
136  // pass mutable args via bp::ref
137  // pass "const" args without, which by default results in a new copy, ensuring the original won't be modified
138  func(oldStrain,oldStress,strain,stress,stateDict,tempStateDict,tStep->giveTargetTime());
139 
140 #if 0
141  if ( !PyCallable_Check(func) ) {
142  OOFEM_ERROR("Python function is not callable.");
143  }
144 
145  // Build the argument list;
146  double size = strain.giveSize();
147  PyObject *pArgs = PyTuple_New(5);
148 
149  PyObject *pArgOldStrain = PyList_New(size);
150  PyObject *pArgOldStress = PyList_New(size);
151  PyObject *pArgStrain = PyList_New(size);
152 
153  for ( int i = 0; i < size; i++ ) {
154  PyList_SET_ITEM( pArgOldStrain, i, PyFloat_FromDouble( oldStrain[i] ) );
155  PyList_SET_ITEM( pArgOldStress, i, PyFloat_FromDouble( oldStress[i] ) );
156  PyList_SET_ITEM( pArgStrain, i, PyFloat_FromDouble( strain[i] ) );
157  }
158 
159  // PyTuple_SetItem takes over responsibility for objects passed to it -> no DECREF
160  PyTuple_SetItem(pArgs, 0, pArgOldStrain);
161  PyTuple_SetItem(pArgs, 1, pArgOldStress);
162  PyTuple_SetItem(pArgs, 2, pArgStrain);
163  // Internal state variables
164  Py_INCREF(stateDict);
165  PyTuple_SetItem(pArgs, 3, stateDict);
166  Py_INCREF(tempStateDict);
167  PyTuple_SetItem(pArgs, 4, tempStateDict);
168  // Time
169  PyTuple_SetItem(pArgs, 5, PyFloat_FromDouble( tStep->giveTargetTime() ));
170  // Call the function;
171  PyObject *retVal = PyObject_CallObject(func, pArgs);
172 
173  // Convert function output back to C++ form:
174  stress.resize(size);
175  for ( int i = 0; i < size; i++ ) {
176  PyObject *val = PyList_GET_ITEM(retVal, i);
177  stress[i] = PyFloat_AS_DOUBLE(val);
178  //Py_DECREF(val);
179  }
180 
181  Py_DECREF(retVal);
182  Py_DECREF(pArgs);
183 #endif
184 }
185 
186 void StructuralPythonMaterial :: callTangentFunction(FloatMatrix &answer, bp::object func, const FloatArray &strain, const FloatArray &stress, bp::object stateDict, bp::object tempStateDict, TimeStep *tStep) const
187 {
188  answer=bp::extract<FloatMatrix>(func(strain,stress,stateDict,tempStateDict,tStep->giveTargetTime()));
189 #if 0
190  if ( !PyCallable_Check(func) ) {
191  OOFEM_ERROR("Python function is not callable.");
192  }
193 
194  // Build the argument list;
195  double size = strain.giveSize();
196  PyObject *pArgs = PyTuple_New(4);
197 
198  PyObject *pArgStrain = PyList_New(size);
199  PyObject *pArgStress = PyList_New(size);
200 
201  for ( int i = 0; i < size; i++ ) {
202  PyList_SET_ITEM( pArgStrain, i, PyFloat_FromDouble( strain[i] ) );
203  PyList_SET_ITEM( pArgStress, i, PyFloat_FromDouble( stress[i] ) );
204  }
205  // PyTuple_SetItem takes over responsibility for objects passed to it -> no DECREF
206  PyTuple_SetItem(pArgs, 0, pArgStrain);
207  PyTuple_SetItem(pArgs, 1, pArgStress);
208  // Internal state variables
209  Py_INCREF(stateDict);
210  PyTuple_SetItem(pArgs, 2, stateDict);
211  Py_INCREF(tempStateDict);
212  PyTuple_SetItem(pArgs, 3, tempStateDict);
213  // Time
214  PyTuple_SetItem(pArgs, 4, PyFloat_FromDouble( tStep->giveTargetTime() ));
215  // Call the function;
216  PyObject *retVal = PyObject_CallObject(func, pArgs);
217 
218  if ( retVal == NULL ) {
219  OOFEM_ERROR("bad return value (null) from PyObject_CallObject");
220  }
221  // Convert function output back to C++ form:
222  answer.resize(size, size);
223  for ( int i = 0; i < size; i++ ) {
224  PyObject *row = PyList_GET_ITEM(retVal, i); // Get item just borrows the reference, don't DECREF
225  for ( int j = 0; j < size; j++ ) {
226  PyObject *val = PyList_GET_ITEM(row, j);
227  answer(i, j) = PyFloat_AS_DOUBLE(val);
228  }
229  }
230 
231  Py_DECREF(retVal);
232  Py_DECREF(pArgs);
233 #endif
234 }
235 
237 {
238  StructuralPythonMaterialStatus *ms = dynamic_cast< StructuralPythonMaterialStatus * >( this->giveStatus(gp) );
239 
240  if ( this->smallDefTangent ) {
242  } else {
243  FloatArray vE, vE_h, stress, stressh;
244  vE = ms->giveTempStrainVector();
245  stress = ( ( StructuralMaterialStatus * ) gp->giveMaterialStatus() )->giveTempStressVector();
246  answer.resize(6, 6);
247  for ( int i = 1; i <= 6; ++i ) {
248  vE_h = vE;
249  vE_h.at(i) += pert;
250  this->giveRealStressVector_3d(stressh, gp, vE_h, tStep);
251  stressh.subtract(stress);
252  stressh.times(1.0 / pert);
253  answer.setColumn(stressh, i);
254  }
255 
256  // Reset the stress internal variables
257  this->giveRealStressVector_3d(stress, gp, vE, tStep);
258  }
259 }
260 
261 
263 {
264  StructuralPythonMaterialStatus *ms = dynamic_cast< StructuralPythonMaterialStatus * >( this->giveStatus(gp) );
265 
266  if ( this->largeDefTangent ) {
268  } else {
269  FloatArray vF, vF_h, stress, stressh;
270  vF = ms->giveTempFVector();
271  stress = ( ( StructuralMaterialStatus * ) gp->giveMaterialStatus() )->giveTempPVector();
272  answer.resize(9, 9);
273  for ( int i = 1; i <= 9; ++i ) {
274  vF_h = vF;
275  vF_h.at(i) += pert;
276  this->giveFirstPKStressVector_3d(stressh, gp, vF_h, tStep);
277  stressh.subtract(stress);
278  stressh.times(1.0 / pert);
279  answer.setColumn(stressh, i);
280  }
281 
282  // Reset the internal variables
283  this->giveFirstPKStressVector_3d(stress, gp, vF, tStep);
284  }
285 }
286 
287 
289  const FloatArray &strain, TimeStep *tStep)
290 {
292 
294 
295  this->callStressFunction(this->smallDef,
296  ms->giveStrainVector(), ms->giveStressVector(),
297  strain, answer,
298  ms->giveStateDictionary(), ms->giveTempStateDictionary(), tStep);
299 
300  ms->letTempStrainVectorBe(strain);
301  ms->letTempStressVectorBe(answer);
302 }
303 
304 
306  const FloatArray &vF, TimeStep *tStep)
307 {
309 
310  ms->reinitTempStateDictionary(); // Resets the temp dictionary to the equilibrated values
311 
312  this->callStressFunction(this->smallDef,
313  ms->giveFVector(), ms->givePVector(),
314  vF, answer,
315  ms->giveStateDictionary(), ms->giveTempStateDictionary(), tStep);
316 
317  FloatArray vE, vS;
318  FloatMatrix F, Finv, E, S;
319  F.beMatrixForm(vF);
320  Finv.beInverseOf(F);
321  // Compute Green-Lagrange strain
322  E.beTProductOf(F, F);
323  E.at(1, 1) -= 1.0;
324  E.at(2, 2) -= 1.0;
325  E.at(3, 3) -= 1.0;
326  E.times(0.5);
327  vE.beSymVectorFormOfStrain(E);
328  // Convert from P to S
329  S.beProductOf(Finv, answer);
330  vS.beSymVectorForm(S);
331 
332  ms->letTempStrainVectorBe(vE);
333  ms->letTempStressVectorBe(vS);
334  ms->letTempPVectorBe(answer);
335  ms->letTempFVectorBe(vF);
336 }
337 
338 
340 {
342  bp::object val=ms->giveStateDictionary()[std::to_string(type).c_str()];
343  // call parent if we don't have this type in our records
344  if(!val) return StructuralMaterial::giveIPValue(answer,gp,type,tStep);
345  bp::extract<double> exNum(val);
346  bp::extract<FloatArray> exMat(val);
347  if(exNum.check()){ answer=FloatArray{exNum()}; return 1; }
348  else if(exMat.check()){ answer=exMat(); return 1;}
349  OOFEM_WARNING("Dictionary entry of material state not float or something convertible to FloatArray");
350  return 0;
351 #if 0
352  std :: string s = std :: to_string( type );
353  PyObject *val = PyDict_GetItemString(ms->giveStateDictionary(), s.c_str());
354  if ( val ) {
355 
356  if ( PyFloat_Check(val) != 0 ) {
357  answer = FloatArray{PyFloat_AS_DOUBLE(val)};
358  } else if ( PyList_Check(val) != 0 ) {
359  // Convert function output back to C++ form:
360  int size = PyList_Size(val);
361  answer.resize(size);
362  for ( int i = 0; i < size; i++ ) {
363  PyObject *val = PyList_GET_ITEM(val, i);
364  answer[i] = PyFloat_AS_DOUBLE(val);
365  //Py_DECREF(val);
366  }
367  return 1;
368  } else {
369  OOFEM_WARNING("Dictionary entry of material state is not a list (only lists supported for now)");
370  return 0;
371  }
372  }
373  return StructuralMaterial :: giveIPValue(answer, gp, type, tStep);
374 #endif
375 }
376 
377 
378 
379 
380 
382 {
385 }
386 
387 
389  StructuralMaterialStatus(0, d, gp)
390 {
391 #if 0
392  this->stateDict = PyDict_New();
393  this->tempStateDict = PyDict_New();
394 #endif
395 }
396 
398 {
399 #if 0
400  Py_DECREF(this->stateDict);
401  Py_DECREF(this->tempStateDict);
402 #endif
403 }
404 
406 {
408  // Copy the temp dict to the equilibrated one
409  this->stateDict = this->tempStateDict.copy();
410 #if 0
411  Py_DECREF(oldDict);
412 #endif
413 }
414 
415 
417 {
418  //Py_DECREF(this->tempStateDict);
419  //this->tempStateDict = PyDict_Copy(this->stateDict);
420  tempStateDict=stateDict.copy();
421 }
422 
423 
424 } // end namespace oofem
virtual void initTempStatus()
Initializes the temporary internal variables, describing the current state according to previously re...
virtual void updateYourself(TimeStep *tStep)
Update equilibrium history variables according to temp-variables.
Definition: structuralms.C:96
InternalStateType
Type representing the physical meaning of element or constitutive model internal variable.
void setField(int item, InputFieldType id)
void subtract(const FloatArray &src)
Subtracts array src to receiver.
Definition: floatarray.C:258
void letTempStrainVectorBe(const FloatArray &v)
Assigns tempStrainVector to given vector v.
Definition: structuralms.h:137
virtual MaterialStatus * giveStatus(GaussPoint *gp) const
Returns material status of receiver in given integration point.
Definition: material.C:244
Class and object Domain.
Definition: domain.h:115
void letTempFVectorBe(const FloatArray &v)
Assigns tempFVector to given vector v.
Definition: structuralms.h:143
_object PyObject
virtual void giveFirstPKStressVector_3d(FloatArray &answer, GaussPoint *gp, const FloatArray &reducedF, TimeStep *tStep)
Default implementation relies on giveRealStressVector for second Piola-Kirchoff stress.
const FloatArray & givePVector() const
Returns the const pointer to receiver&#39;s first Piola-Kirchhoff stress vector.
Definition: structuralms.h:109
virtual void giveInputRecord(DynamicInputRecord &input)
Setups the input record string of receiver.
virtual int giveIPValue(FloatArray &answer, GaussPoint *gp, InternalStateType type, TimeStep *tStep)
Returns the integration point corresponding value in Reduced form.
double & at(int i)
Coefficient access function.
Definition: floatarray.h:131
This class implements a structural material status information.
Definition: structuralms.h:65
bp::object module
module containing functions (created from moduleName)
bp::dict stateDict
Internal state variables.
double giveTargetTime()
Returns target time.
Definition: timestep.h:146
#define S(p)
Definition: mdm.C:481
bp::object smallDef
callable for small deformations
MatResponseMode
Describes the character of characteristic material matrix.
StructuralPythonMaterial(int n, Domain *d)
Constructor.
void callTangentFunction(FloatMatrix &answer, bp::object func, const FloatArray &strain, const FloatArray &stress, bp::object stateDict, bp::object tempStateDict, TimeStep *tStep) const
void beMatrixForm(const FloatArray &aArray)
Definition: floatmatrix.C:1657
virtual IRResultType initializeFrom(InputRecord *ir)
Initializes receiver according to object description stored in input record.
#define E(p)
Definition: mdm.C:368
const FloatArray & giveTempPVector() const
Returns the const pointer to receiver&#39;s temporary first Piola-Kirchhoff stress vector.
Definition: structuralms.h:119
#define OOFEM_ERROR(...)
Definition: error.h:61
void times(double f)
Multiplies receiver by factor f.
Definition: floatmatrix.C:1594
const FloatArray & giveTempStrainVector() const
Returns the const pointer to receiver&#39;s temporary strain vector.
Definition: structuralms.h:115
#define _IFT_StructuralPythonMaterial_moduleName
double at(int i, int j) const
Coefficient access function.
Definition: floatmatrix.h:176
virtual ~StructuralPythonMaterial()
Destructor.
virtual void give3dMaterialStiffnessMatrix_dPdF(FloatMatrix &answer, MatResponseMode mode, GaussPoint *gp, TimeStep *tStep)
Abstract base class representing a material status information.
Definition: matstatus.h:84
virtual MaterialStatus * CreateStatus(GaussPoint *gp) const
Creates new copy of associated status and inserts it into given integration point.
void callStressFunction(bp::object func, const FloatArray &oldStrain, const FloatArray &oldStress, const FloatArray &strain, FloatArray &stress, bp::object stateDict, bp::object tempStateDict, TimeStep *tStep) const
Class representing vector of real numbers.
Definition: floatarray.h:82
Implementation of matrix containing floating point numbers.
Definition: floatmatrix.h:94
IRResultType
Type defining the return values of InputRecord reading operations.
Definition: irresulttype.h:47
virtual void giveRealStressVector_3d(FloatArray &answer, GaussPoint *gp, const FloatArray &reducedStrain, TimeStep *tStep)
Default implementation relies on giveRealStressVector for second Piola-Kirchoff stress.
void letTempStressVectorBe(const FloatArray &v)
Assigns tempStressVector to given vector v.
Definition: structuralms.h:135
const FloatArray & giveStressVector() const
Returns the const pointer to receiver&#39;s stress vector.
Definition: structuralms.h:107
IntegrationPointStatus * giveMaterialStatus()
Returns reference to associated material status (NULL if not defined).
Definition: gausspoint.h:205
const FloatArray & giveFVector() const
Returns the const pointer to receiver&#39;s deformation gradient vector.
Definition: structuralms.h:113
void resize(int rows, int cols)
Checks size of receiver towards requested bounds.
Definition: floatmatrix.C:1358
Class representing the general Input Record.
Definition: inputrecord.h:101
void beTProductOf(const FloatMatrix &a, const FloatMatrix &b)
Assigns to the receiver product of .
Definition: floatmatrix.C:367
const FloatArray & giveTempFVector() const
Returns the const pointer to receiver&#39;s temporary deformation gradient vector.
Definition: structuralms.h:123
void setColumn(const FloatArray &src, int c)
Sets the values of the matrix in specified column.
Definition: floatmatrix.C:648
Class representing the a dynamic Input Record.
void times(double s)
Multiplies receiver with scalar.
Definition: floatarray.C:818
Abstract base class for all "structural" constitutive models.
virtual void initTempStatus()
Initializes the temporary internal variables, describing the current state according to previously re...
Definition: structuralms.C:108
Domain * giveDomain() const
Definition: femcmpnn.h:100
virtual void giveInputRecord(DynamicInputRecord &input)
Setups the input record string of receiver.
REGISTER_Material(DummyMaterial)
void beProductOf(const FloatMatrix &a, const FloatMatrix &b)
Assigns to the receiver product of .
Definition: floatmatrix.C:337
const FloatArray & giveTempStressVector() const
Returns the const pointer to receiver&#39;s temporary stress vector.
Definition: structuralms.h:117
int giveSize() const
Returns the size of receiver.
Definition: floatarray.h:218
the oofem namespace is to define a context or scope in which all oofem names are defined.
virtual IRResultType initializeFrom(InputRecord *ir)
Initializes receiver according to object description stored in input record.
std::string moduleName
Name of the file that contains the python function.
#define IR_GIVE_FIELD(__ir, __value, __id)
Macro facilitating the use of input record reading methods.
Definition: inputrecord.h:69
void beInverseOf(const FloatMatrix &src)
Modifies receiver to become inverse of given parameter.
Definition: floatmatrix.C:835
const FloatArray & giveStrainVector() const
Returns the const pointer to receiver&#39;s strain vector.
Definition: structuralms.h:105
Class representing integration point in finite element program.
Definition: gausspoint.h:93
#define OOFEM_WARNING(...)
Definition: error.h:62
Class representing solution step.
Definition: timestep.h:80
StructuralPythonMaterialStatus(Domain *d, GaussPoint *gp)
Constructor.
double pert
Numerical pertubation for numerical tangents.
virtual void give3dMaterialStiffnessMatrix(FloatMatrix &answer, MatResponseMode mode, GaussPoint *gp, TimeStep *tStep)
Computes full 3d material stiffness matrix at given integration point, time, respecting load history ...
virtual int giveIPValue(FloatArray &answer, GaussPoint *gp, InternalStateType type, TimeStep *tStep)
Returns the integration point corresponding value in Reduced form.
virtual void updateYourself(TimeStep *tStep)
Update equilibrium history variables according to temp-variables.
void letTempPVectorBe(const FloatArray &v)
Assigns tempPVector to given vector v.
Definition: structuralms.h:139
void resize(int s)
Resizes receiver towards requested size.
Definition: floatarray.C:631

This page is part of the OOFEM documentation. Copyright (c) 2011 Borek Patzak
Project e-mail: info@oofem.org
Generated at Tue Jan 2 2018 20:07:31 for OOFEM by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2011