From 749002e0837a65df6626ab156fe5216d811defff Mon Sep 17 00:00:00 2001 From: Koishi <david.diepelt@gmx.net> Date: Wed, 3 Apr 2024 14:19:10 +0200 Subject: [PATCH] adding initial commit of repository --- README.md | 94 +------- main_elasticity_bare_metal.py | 402 ++++++++++++++++++++++++++++++++++ notes.md | 4 + setup.sh | 5 + 4 files changed, 415 insertions(+), 90 deletions(-) create mode 100644 main_elasticity_bare_metal.py create mode 100644 notes.md create mode 100755 setup.sh diff --git a/README.md b/README.md index eb3c5d3..c021426 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,7 @@ # dune-python-tnnmg +## Goal of this Repository - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.mn.tu-dresden.de/jodi058b/dune-python-tnnmg.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.mn.tu-dresden.de/jodi058b/dune-python-tnnmg/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +* An Easy Show of implementing the TNNMG Algorithm on similar examples (hopefully) +* currently working on primal plasticity +* also shows some capabilities of dune-functions on the python side. \ No newline at end of file diff --git a/main_elasticity_bare_metal.py b/main_elasticity_bare_metal.py new file mode 100644 index 0000000..6db527b --- /dev/null +++ b/main_elasticity_bare_metal.py @@ -0,0 +1,402 @@ +import numpy as np + +from dune.grid import cartesianDomain, gridFunction +from dune.alugrid import aluConformGrid as grid +from dune.alugrid import aluCubeGrid as cubeGrid +from dune.geometry import quadratureRule + +from dune.istl import BuildMode, bcrsMatrix, blockVector, CGSolver, SeqJacobi +import dune.geometry +import dune.grid +import dune.functions as functions +from dune.functions import defaultGlobalBasis, subspaceBasis, Lagrange, Power, Composite + + + +# Wie viele Dimensionen? +dim = 2 +# Wie viele plastic Strains? +plastic_dim = 2 +# Was für eine Belastung? +def force(directionNum,position): + if directionNum == 0: + return 0 + if directionNum == 1: # Y-Richtung + return 9.81 + +# Basis der Plastic Strains: +# Ist eine Basis der symmetrischen spurfreien (dim x dim) Matrizen +# Hier für dim = 2 +def plastic_strain_basis(num_basis): + scale = 1.0/np.sqrt(2) + b = np.zeros((dim,dim)) + if num_basis == 0: + b[0,0] = 1 + b[1,1] = -1 + if num_basis == 1: + b[0,1] = 1 + b[1,0] = 1 + return scale * b + + +###### Hilfsfunktionen + +# von elastischen Dehnungen zu Spannungen (mittels Materialgesetz) +def stresses(elasStrainTensor,firstLameConstant,secondLameConstant): + + # druckanteil herausgerechnet + pressure = np.trace(elasStrainTensor) + + # die spannungen + stresses = np.zeros((dim,dim)) + + # Kugelanteil + np.fill_diagonal(stresses,pressure*firstLameConstant) + + # Deviatoranteil + stresses = stresses + 2.0 * secondLameConstant * elasStrainTensor + + return stresses + +# Compute Strains +def strains(directionNum,node,shapeGradient): + + real_strains = np.zeros((dim,dim)) + if directionNum == 0: + real_strains[0,0] = shapeGradient[node][0] + real_strains[0,1] = 0.5*(shapeGradient[node][0] + shapeGradient[node][1]) + if directionNum == 1: + real_strains[1,0] = 0.5*(shapeGradient[node][1] + shapeGradient[node][0]) + real_strains[1,1] = shapeGradient[node][1] + + return real_strains + + + + +# Encapsulation of the local stiffnesses +def local_assembler_elasticity(element,localDisplacementTree): + #help(localView) + n = len(localDisplacementTree) + + #help(localDisplacementTree[0].localIndex(0)) + # Der ist hier, weil local functions keine Bäume auf der Python Seite zulassen. + # num_local_dofs = 2 + + print(n) + #help(localBasis) + + quadOrder = 2 + + # TODO Local Matrix assemblieren + + localStiffnessMatrix = np.zeros((n,n)) + + for gaussPoint in quadratureRule(elem.type, quadOrder): + x = gaussPoint.position + w = gaussPoint.weight + #help(x) + + jacobianInverseTransposed = elem.geometry.jacobianInverseTransposed(x) + # Wert der Jacobi Determinante? + determinant = elem.geometry.integrationElement(x) + + # Funktionswerte und Ableitungen der Basisfunktionen + #phi = localBasis.evaluateFunction(x) + + #phiRefGradient = localBasis.evaluateJacobian(x) + # Das sind die Ableitungen der Shape Functions in Globalen Koordinaten + #phiGradient = [ np.dot(jacobianInverseTransposed, np.array(g)[0]) for g in phiRefGradient ] + # Welche jetzt für x und y verwendet werden + # Berechnen der Dehnungen () + posGlobal = element.geometry.toGlobal(x) + + help(localDisplacementTree.child(0).finiteElement(localDisplacementTree)) + + # Jaap Paper, Equation 20 + # In welchem Block befinden wir uns? -> [(x,x),(x,y)],[(y,x),(y,y)] + # Das fühlt sich immens ineffizient an, aber naja. + for i in range(dim): + localRealBasis = localDisplacementTree.child(i).finiteElement.localBasis + #help(localRealBasis) + + # Local Shape Functions + phi = localRealBasis.evaluateFunction(x) + phiRefGradient = localRealBasis.evaluateJacobian(x) + # Das sind die Ableitungen der Shape Functions in Globalen Koordinaten + phiGradient = [ np.dot(jacobianInverseTransposed, np.array(g)[0]) for g in phiRefGradient ] + + for j in range(dim): + localVirtBasis = localDisplacementTree.child(j).finiteElement.localBasis + #help(localRealBasis) + + # Local Shape Functions + phiVirt = localVirtBasis.evaluateFunction(x) + phiVirtRefGradient = localVirtBasis.evaluateJacobian(x) + # Das sind die Ableitungen der Shape Functions in Globalen Koordinaten + phiVirtGradient = [ np.dot(jacobianInverseTransposed, np.array(g)[0]) for g in phiVirtRefGradient ] + + for k in range(len(localRealBasis)): + localRealIndex = localDisplacementTree.child(i).localIndex(k) + # Strains + Stresses + realStrains = strains(directionNum=i,node=k,shapeGradient=phiGradient) + realStresses = stresses(elasStrainTensor=realStrains,firstLameConstant=1e7,secondLameConstant=6.5e6) + for l in range(len(localVirtBasis)): + localVirtIndex = localDisplacementTree.child(j).localIndex(l) + + virtStrains = strains(directionNum=j,node=l,shapeGradient=phiVirtGradient) + + #print(localRealIndex,localVirtIndex) + + #here we will assemble! + localStiffnessMatrix[localRealIndex,localVirtIndex] += determinant * np.tensordot(realStresses,virtStrains) * w + + print(localStiffnessMatrix) + return localStiffnessMatrix + +# Interaktionsterme (Jaap Gleichung ) +# +def local_assembler_elasticity_plasticity_interaction(element,localBasisDisp,localBasisPlastic): + + nDisp = len(localBasisDisp) + nPlast = len(localBasisPlastic) + + quadOrder = 2 + # Local Interaction Matrix + # Without isotropic hardening (else it would be ((dim_plastic+1)*nPlast) ) + local_interaction_matrix = np.zeros((dim*nDisp,plastic_dim*nPlast)) + + # Starting the Integration Loop + for gaussPoint in quadratureRule(elem.type, quadOrder): + x = gaussPoint.position + w = gaussPoint.weight + + phiDisp = localBasisDisp.evaluateFunction(x) + phiDispRefGradient = localBasisDisp.evaluateJacobian(x) + jacobianInverseTransposed = elem.geometry.jacobianInverseTransposed(x) + # Betrag der Jacobi Determinante? + determinant = elem.geometry.integrationElement(x) + + # Das sind die Ableitungen der Shape Functions in Globalen Koordinaten + phiDispGradient = [ np.dot(jacobianInverseTransposed, np.array(g)[0]) for g in phiDispRefGradient ] + # Jetzt noch die Basis der plastischen Strains + + thetaStrain = localBasisPlastic.evaluateFunction(x) + + # Welche jetzt für x und y verwendet werden + # posGlobal = element.geometry.toGlobal(x) + # Welcher reale Freiheitsgrad? + for i in range(nDisp): + # Welche reale Richtung? + for k in range(dim): + real_strains = strains(k,i,phiDispGradient) + + stress = stresses(real_strains, lamb, mu) + # Jetzt die Frage, welche plastic Strains verwendet werden. + # Wie viele n-plastische? + for j in range(nPlast): + # wie viele plastische basen? + for l in range(plastic_dim): + plastic_strain = plastic_strain_basis(l) # basis abholen + + local_interaction_matrix[i*dim+k,j*plastic_dim+l] += - determinant * np.tensordot(stress,plastic_strain*thetaStrain) * w + + #print(local_interaction_matrix) + return local_interaction_matrix + +def local_assembler_plasticity(element,localBasisPlastic): + + nPlast = len(localBasisPlastic) + + quadOrder = 2 + # Local Interaction Matrix + # Without isotropic hardening (else it would be ((dim_plastic+1)*nPlast) ) + local_plastic_matrix = np.zeros((plastic_dim*nPlast,plastic_dim*nPlast)) + + # Starting the Integration Loop + for gaussPoint in quadratureRule(elem.type, quadOrder): + x = gaussPoint.position + w = gaussPoint.weight + + phiDisp = localBasisDisp.evaluateFunction(x) + # phiDispRefGradient = localBasisDisp.evaluateJacobian(x) + # jacobianInverseTransposed = elem.geometry.jacobianInverseTransposed(x) + # Betrag der Jacobi Determinante? + determinant = elem.geometry.integrationElement(x) + + # Das sind die Ableitungen der Shape Functions in Globalen Koordinaten + # phiDispGradient = [ np.dot(jacobianInverseTransposed, np.array(g)[0]) for g in phiDispRefGradient ] + # Jetzt noch die Basis der plastischen Strains + + thetaStrain = localBasisPlastic.evaluateFunction(x) + + # Welche jetzt für x und y verwendet werden + # posGlobal = element.geometry.toGlobal(x) + # Welcher reale Freiheitsgrad? + for i in range(nPlast): + # Welche reale Richtung? + for k in range(plastic_dim): + plastic_strain = plastic_strain_basis(k) + + stress = stresses(plastic_strain, lamb, mu) + # Jetzt die Frage, welche plastic Strains verwendet werden. + # Wie viele n-plastische? + for j in range(nPlast): + # wie viele plastische basen? + for l in range(plastic_dim): + plastic_strain = plastic_strain_basis(l) # basis abholen + + local_plastic_matrix[i*plastic_dim+k,j*plastic_dim+l] += determinant * np.tensordot(stress,plastic_strain*thetaStrain) * w + + #print(local_plastic_matrix) + return local_plastic_matrix + + + +###### Hilfsfunktionen Ende + + +# https://gitlab.dune-project.org/staging/dune-functions/-/blob/master/dune/python/test/poisson.py?ref_type=heads + +# Gebe mir ein Gitter +domain = {'vertices': np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]), 'simplices': np.array([(0, 1, 2), (0, 2, 3)])} +gridView = grid(domain) +gridView.hierarchicalGrid.globalRefine(0) + +# Und eine Basis (Da der Dune-Functions Baum auf der Python Seite nicht traversierbar ist, werden 2 Bäume verwendet.) +# lagBasis_displacement = Lagrange(order = 1, dimRange = 2) +lagBasis_displacement = Power(Lagrange(order = 1),exponent=dim) # Verschiebungen (Die n Dimensionen werden manuell gemacht) +lagBasis_plasticStrains = Power(Lagrange(order = 0),exponent=plastic_dim) # Plastische Dehnungen (Die k Dimensionen werde manuell gemacht) + +lagBasis = Composite(lagBasis_displacement,lagBasis_plasticStrains) + +# Lamé Konstanten +lamb = 1e7 +mu = 6.5e6 + +# Und jetzt besitzen wir eine Globale Basis auf dem Gitter +# in diesem Fall eine LagrangeBasis +# Gitter und Basis sind jetzt verheiratet +globalBasis = defaultGlobalBasis(gridView,lagBasis) +globalBasisDisplacement = defaultGlobalBasis(gridView,lagBasis_displacement) +globalBasisPlasticStrains = defaultGlobalBasis(gridView,lagBasis_plasticStrains) +#print(globalBasis) +#help(globalBasis) + +localView = globalBasis.localView() +localViewDisplacement = globalBasisDisplacement.localView() +localViewPlastic = globalBasisPlasticStrains.localView() +#help(localView) +#https://gitlab.dune-project.org/dune-course/iwr-course-2021/-/tree/master/doc?ref_type=heads + +#help(gridView.grid) +# Jetzt erstmal die globale Steifigkeitsmatrix +numNodes = len(globalBasis) +numNodesDisp = len(globalBasisDisplacement) +numNodesPlast = len(globalBasisPlasticStrains) +print(globalBasis.dimRange) +print(numNodes,numNodesDisp,numNodesPlast) + +# Frage: Globale Steifigkeit für alle Teilmatrizen? Direkt den E, C und P Block aufschreiben? +globalStiffness = np.zeros((numNodesDisp*dim+numNodesPlast*plastic_dim,numNodesDisp*dim+numNodesPlast*plastic_dim)) + +for elem in gridView.elements: + # Hier komm ein Typ raus + # print(elem.type) + + # Hier verbinden wir die lokale Ansicht des Baums mit der Geometrischen Information + # Erst ab hier können wir shape functions und ähnliches abfragen + localView.bind(elem) + localViewDisplacement.bind(elem) + localViewPlastic.bind(elem) + #help(localViewDisplacement) + + localViewTree = localView.tree() + + #help(localViewTree) + + localViewDispTree = localViewTree.child(0) + localViewPlastTree = localViewTree.child(1) + + #help(localViewDispTree) + print(len(localView.tree())) + print(len(localViewDispTree),len(localViewPlastTree)) + + print(localViewDispTree.localIndex(1)) + + for i in range(len(localView)): + multiIndex = localView.index(i)[0] # in der liste steht der globale index der zum lokalen gehört + print("G - L:",multiIndex, i) + + for i in range(len(localViewDispTree)): + indexQuestion = localViewDispTree.localIndex(i) # Die lokalen Verschiebungsfreiheitsgrade gehören zu den lokalen FE Freiheitsgraden + print("L - D:",indexQuestion,i) + + for i in range(len(localViewPlastTree)): + indexQuestion = localViewPlastTree.localIndex(i) # genauso wie hier. + print("L - P:",indexQuestion,i) + + #localViewDispTree[0].finiteElement + + #help(localViewDispTree) + + # das funktioniert irgendwie??? + localStiffnessMatrix = local_assembler_elasticity(element=elem,localDisplacementTree=localViewDispTree) + + #print(localStiffnessMatrix) + + #help(localViewDispTree[0].finiteElement) + + #localViewDisplacement.tree() + + localBasisDisp = localViewDisplacement.tree()[0].finiteElement + + #help(localBasisDisp) + localBasisStrain = localViewPlastic.tree()[0].finiteElement.localBasis + + localN = len(localBasisDisp) + # E Matrix + #localStiffnessMatrix = local_assembler_elasticity(element=elem,localBasis=localBasisDisp) + # print(localStiffnessMatrix) + # C Matrix + #localInteractionMatrix = local_assembler_elasticity_plasticity_interaction(element=elem,localBasisDisp=localBasisDisp,localBasisPlastic=localBasisStrain) + + # P Matrix + #localPlasticityMatrix = local_assembler_plasticity(element=elem,localBasisPlastic=localBasisStrain) + + #print("---") + for i in range(localN): + + #print(localViewDisplacement.index(i)) + gi = localViewDisplacement.index(i)[0] + + #help(localBasis) + # Das Geometry object: https://dune-project.org/doxygen/master/classDune_1_1Geometry.html + # elemgeom = elem.geometry + # elemtype = elem.type + + #print(refElement) + # über das ding was aus quadratureRule rauskommt kann ich nur iterieren, + # scheint kein Objekt zu sein + # for p in quadratureRule(elemtype, 2): + # x = p.position + # + +#print(globalStiffness) + +''' +print("Assembling...") +matrix, rhs = assemble(gridView, lambda v: sum(2.0 * x * (1 - x) for x in v)) + +print("Solving...") +u = blockVector(gridView.indexSet.size(2)) +CGSolver(matrix.asLinearOperator(), SeqJacobi(matrix), 1e-10)(u, rhs) + +print("Visualizing...") +dim = gridView.dimension +basis = P1ShapeFunctionSet(dim) +@gridFunction(gridView,"u_h") +def u_h(e, x): + return [sum(phi.evaluate(x) * u[i][0] for phi, i in zip(basis, gridView.indexSet.subIndices(e, dim)))] +gridView.writeVTK("fem2d", pointdata=[u_h]) +''' diff --git a/notes.md b/notes.md new file mode 100644 index 0000000..af88850 --- /dev/null +++ b/notes.md @@ -0,0 +1,4 @@ +# An Engineers Guide to DUNE + +## Python-DUNE + diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..0511554 --- /dev/null +++ b/setup.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +# python3 -m venv ~/dune-env +#.${HOME}/dune-modules/dune-common/build-cmake/run-in-dune-env python +source ../dune-common/build-cmake/dune-env/bin/activate -- GitLab