diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index eaeb583..28ee977 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,20 +1,30 @@ name: docs + on: push: branches: [main] pull_request: + permissions: contents: write + jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 # the authors page is generated from the git history + - uses: actions/setup-python@v5 with: python-version: "3.12" + - run: pip install -r docs/requirements.txt - - run: sphinx-build -b html docs/source docs/build/html + + # Builds English, Spanish, Portuguese and Italian; warnings are errors (-W). + - run: python docs/tools/build_docs.py + - uses: peaceiris/actions-gh-pages@v4 if: github.ref == 'refs/heads/main' with: diff --git a/.github/workflows/tests-all.yml b/.github/workflows/tests-all.yml new file mode 100644 index 0000000..1dc0d97 --- /dev/null +++ b/.github/workflows/tests-all.yml @@ -0,0 +1,33 @@ +name: tests-all + +# The slow tests build the complete beam model of the example (about 167,000 +# nodes). They are run on demand, not on every push. +on: + workflow_dispatch: + +jobs: + matlab: + name: All tests (including slow) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Set up MATLAB + uses: matlab-actions/setup-matlab@v2 + with: + release: R2023b + + - name: Run the build (static analysis + all tests) + uses: matlab-actions/run-build@v2 + with: + tasks: check testAll + + - name: Keep the reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: reports-all + path: | + test-results/ + code-coverage/ + if-no-files-found: ignore diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5d772f8..c8c70f0 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,11 +1,35 @@ name: tests -on: [push, pull_request] + +on: + push: + pull_request: + jobs: matlab: + name: Code Analyzer and tests runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: matlab-actions/setup-matlab@v2 - - uses: matlab-actions/run-command@v2 + + - name: Set up MATLAB + uses: matlab-actions/setup-matlab@v2 with: - command: addpath('tests'); run_tests + # The code uses name=value arguments, the arguments block, buildtool and + # dictionary, so R2022b is the oldest release that can run it. + release: R2023b + + - name: Run the build (static analysis + fast tests with coverage) + uses: matlab-actions/run-build@v2 + with: + tasks: check test + + - name: Keep the reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: reports + path: | + test-results/ + code-coverage/ + code-issues/ + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 8892ef0..420c346 100644 --- a/.gitignore +++ b/.gitignore @@ -1,225 +1,41 @@ -# Byte-compiled / optimized / DLL files +# MATLAB +*.asv +*.m~ +*.mex* +slprj/ +codegen/ +*.autosave +resources/project/ + +# LDEM simulation outputs (written to the working directory / output folder) +output/ +LET.CON +LET.DIS +LET.POS +LET.ENE +LET.RES +Lei_Barra.TXT +Energia_Barra.TXT +BARI.txt +ANSYS*.MAC +*.vtu +*.pvd + +# Test artifacts +test-results/ +code-coverage/ + +# Python / Sphinx (docs) +docs/locale/**/*.mo __pycache__/ -*.py[codz] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py.cover -*.lcov -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation +.venv/ +docs/build/ docs/_build/ +BARR_ROMP.dat +SIM01.DAT +code-issues/ +.buildtool/ -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -# Pipfile.lock - -# uv -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -# poetry.lock -# poetry.toml - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. -# https://pdm-project.org/en/latest/usage/project/#working-with-version-control -# pdm.lock -# pdm.toml -.pdm-python -.pdm-build/ - -# pixi -# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. -# pixi.lock -# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one -# in the .venv directory. It is recommended not to include this directory in version control. -.pixi/* -!.pixi/config.toml - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule* -celerybeat.pid - -# Redis -*.rdb -*.aof -*.pid - -# RabbitMQ -mnesia/ -rabbitmq/ -rabbitmq-data/ - -# ActiveMQ -activemq-data/ - -# SageMath parsed files -*.sage.py - -# Environments -.env -.envrc -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs/Zensical documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -# .idea/ - -# Abstra -# Abstra is an AI-powered process automation framework. -# Ignore directories containing user credentials, local state, and settings. -# Learn more at https://abstra.io/docs -.abstra/ - -# Visual Studio Code -# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that -# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore -# and can be added to the global gitignore or merged into this file. However, if you prefer, you -# could uncomment the following to ignore the entire vscode folder -# .vscode/ -# Temporary file for partial code execution -tempCodeRunnerFile.py - -# Ruff stuff: -.ruff_cache/ - -# PyPI configuration file -.pypirc - -# Marimo -marimo/_static/ -marimo/_lsp/ -__marimo__/ - -# Streamlit -.streamlit/secrets.toml - -# MATLAB / LDEM -*.asv -*.m~ +# Documentation build docs/build/ +docs/source/_generated/ diff --git a/.mailmap b/.mailmap new file mode 100644 index 0000000..7a8164a --- /dev/null +++ b/.mailmap @@ -0,0 +1,4 @@ +# Merges the different identities of one person so that AUTHORS is correct. +Boris Rojo Tanzi <71112604+borisrojotanzi@users.noreply.github.com> +Boris Rojo Tanzi <71112604+borisrojotanzi@users.noreply.github.com> +Rodrigo Cavasotto Oscar Montanha diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000..246bfaf --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,9 @@ +# Authors + +Generated from the git history and `CITATION.cff` by `docs/tools/generate_authors.py`. Do not edit by hand. + +| Name | Commits | +|------|---------| +| Boris Rojo Tanzi | 19 | +| Rodrigo Cavasotto Oscar Montanha | 7 | +| Ignacio Iturrioz | - | diff --git a/CHANGELOG.md b/CHANGELOG.md index 77d6d26..df4d7f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,176 @@ ## [Unreleased] ### Added +- Documentation of the examples (user guide page *Examples*, in the four languages): the model, files, + how to run and what to expect of the bi-clamped beam (`example1_clamped_beam`), the uniaxial prism + (`tension_101`) and the four-point bending beam (`beam_102`), with figures and numbers taken from + running them with the current code; `examples/README.md` brought up to date. The three examples run + from start to finish (about 35 s, 6 s and 30 s for its first 50 steps). +- Documentation in one language and translated: the English pages in `docs/source/` are + the only source, and Spanish, Portuguese and Italian are gettext catalogs + (`docs/locale//LC_MESSAGES/.po`) instead of copies of every page, so a + translation cannot drift from the English text (it had: some Portuguese and Italian + sentences differed from the English ones). `docs/tools/build_docs.py` builds each language + as its own site in `docs/build/html//` with a root page that opens the English + one; every page has a language selector in the sidebar; untranslated text falls back to + English. `docs/tools/update_translations.py` updates the catalogs after the English text + changes (changed sentences are marked fuzzy) and `--status` reports what is left. The tables + of case-file keys are translated too. The "Made with Sphinx and Furo" line of the footer is + removed. `buildtool docs`, the CI workflow and `make html` use the new script. +- Case files (`.ldem`): a readable, commented input file that replaces + `DATA0.DAT` and describes the whole model (mesh, material, random scatter, + time, damping, scenario, control nodes, output). Keys are read by name, numbers + carry units (`3.87 GPa`, `0.35 us`), `time.step = auto` takes 0.9 times the + critical step, output cadence can be given in steps or in time, control nodes + can be given by position, and every error names the file, line, section and key + (with "did you mean ...?"). JSON with the same structure is also read. + `ldem.io.readCase`, `ldem.io.writeCase`, `ldem.io.writeTemplate`, + `ldem.io.convertLegacyInput` (DATA0.DAT to `.ldem`, same `Parameters`), + `ldem.run`, `ldem.check` (dry run: size of the model, stability margin, random + field file, snapshot memory), and `ldem.Parameters.fromFile` reads `.ldem` and + `.json` too. The keys live in one table, `ldem.schema.caseSchema`, with + `ldem.schema.parseQuantity` / `formatQuantity` for the units. +- `ldem.run` makes every run reproducible: `results.info.case` keeps the SHA-256 + of the case file, its text and the resolved case (all defaults and overrides), + and the resolved case is saved as `case.ldem` in the output folder + (`ldem.runSimulation` has a new `CaseInfo` option for this). +- Pluggable constitutive law and damping model, chosen by name in the case file + (`[material] law`, `[damping] type`) and in `ldem.Parameters` + (`constitutiveLaw`, `dampingModel`). `ldem.material.MaterialLaw` is the + interface of a law (force, energies, damage energy of a bar, viscous + stiffness); `bilinear` (the legacy law, results unchanged) and the new + `linear_elastic` implement it, registered in `ldem.material.lawRegistry`. + `ldem.solver.DampingModel` is the interface of a damping model; `mass_proportional` + (legacy) and the new `none` are in `ldem.solver.dampingRegistry`. The solver + functions take the law and the model as optional last arguments. +- Case files can inherit: `extends = "base.ldem"` (or a list) starts from other files; keys + replace the inherited ones, repeated tables replace the whole list, a change of scenario, + scatter or damping type drops the keys of the old type, relative paths follow the file + that writes them, and errors name that file. Loops and missing parents are errors. +- Parameter sweeps: `[[sweep]]` blocks (`key`, `values`; `sweep_mode = "product"` or + `"zip"`) and `ldem.sweep`, which validates every run first, runs each in + `run_NNN` with its resolved `case.ldem`, and returns a table (also written as + `sweep_summary.csv`) with the varied values, status, time and damaged and broken bars. + `ldem.io.readCase` has an `Overrides` option and `ldem.run` too; `results.info.case` also + keeps `parents` (with hashes) and `overrides`. +- The key reference of the user guide (`docs/source/case-keys.inc`) is generated from + `ldem.schema.caseSchema` by `ldem.schema.writeKeyReference`; a test fails if it is out of date. +- Tests defined in the case file, without a class: `[scenario] type = "custom"` with + `[[support]]` and `[[load]]` blocks. Nodes are selected by kind (all, grid, centre), + by number and by coordinate ranges in modules with `min`, `max` and `mid`; a load is a + force or a prescribed displacement following `constant`, `linear`, `ramp` or `table`; + blocks can join the reaction of the test. `ldem.scenarios.Declarative` (test 900) is + the class behind it, with `selectNodes`, `parseCoordinate`, `coordinateText` and + `timeFunction`. The three built-in tests written as blocks give exactly the same + results. `Scenario.prepare` lets a scenario compute its node lists once; they are + stored in `mesh.scenarioData`. New unit `force` (N, kN, MN). +- `ldem.scenarios.registry` is the single list of scenarios; + `ldem.scenarios.fromTestId` reads it and `ldem.scenarios.fromName` is new. +- `case.ldem` next to the `DATA0.DAT` of `examples/beam_102` and + `examples/example1_clamped_beam`; user guide (EN/ES/IT/PT) and API pages. - Repository structure: README, LICENSE, CITATION, CONTRIBUTING. - Sphinx documentation (English/Spanish) with API generated from `.m` files. - `matlab.unittest` test suite and GitHub Actions workflows. +- Golden-master regression infrastructure (`tests/tools`, `tests/fixtures`, + `tests/regression`): three small reference simulations generated from the + original code. +- `docs/known-issues/KNOWN_ISSUES.md` (and `.es.md`): bugs found in the original + code and how each one was resolved. + +- New package `src/+ldem` (refactoring in progress), validated against the + legacy fixtures: `ldem.Parameters` (validated input), `ldem.io.readInputFile`, + `ldem.mesh.*` (nodes, bars, masses, geometry, optional perturbation), + `ldem.scenarios.*` (test cases 101 and 102) and `ldem.solver.checkStability`. +- Material model in `ldem.material`: lattice coefficients, bar stiffness by bar + type, critical strain with optional random field (`ldem.io.readRandomField`), + and the bilinear constitutive law as a pure function (`bilinearLaw`). + `ldem.mesh.buildBars` now also returns the bar type and boundary faces. +- Solver in `ldem.solver`: `simulate` (time loop), `computeBarForces`, + `integrateStep` (central differences with damping), `computeEnergies`, + `dampingCoefficient` and `initialState`. `Scenario` now also defines the + loading (`applyLoads`, with a configurable `loadingVelocity`) and the + reaction force (`reactions`). +- `TestSolverAgainstLegacy`: the new solver reproduces the corrected legacy + simulation (displacements, velocities, damage, energies, reactions) in the + three reference cases; unit tests with analytical solutions (damped + oscillator, energy balance, Newton's third law). +- `ldem.runSimulation`: complete simulation returning one `results` struct and + writing `results.mat`, ANSYS macro files (`ldem.io.exportAnsys`, equal to the + legacy files except for two intended fixes) and a VTK series for ParaView + (`ldem.io.exportVtk`, `ldem.io.writePvd`), driven by `ldem.io.SnapshotWriter`. +- `ldem.post.plotEnergy` and `ldem.post.plotReaction`; `ldem.Parameters.toStruct`. +- Runnable examples: `examples/tension_101/runTension.m` and + `examples/beam_102/runBeam.m`; user guides rewritten (EN/ES). +- `buildfile.m` (`buildtool`): `check` (Code Analyzer, any warning fails), `test` + (fast tests, JUnit report, Cobertura coverage), `testAll`, `docs` and `clean`. + Coverage of the `ldem` package is 99.9 %. +- CI: `tests` runs `check` and `test` on R2023b and keeps the reports; `tests-all` + (manual) also runs the slow tests; `docs` builds Sphinx with warnings as errors. +- External work and energy balance: `energy.external` is the work done on the degrees + of freedom held by the scenario and `energy.balance = external - internal` + (0.01-0.5 % of the external work in the reference tests, also with softening + and rupture). +- Kinetic energy of every node (`ldem.solver.nodalKineticEnergy`, stored in + `results.final` and in the snapshots) besides the total of the model. +- `results.model` and `results.material`: counts, mass, material data, lattice + coefficients and statistics of the critical strain (what `WRICON` printed). +- `FourPointBending(supportPosition=, loadPosition=)`: the positions of the beam + test are parameters (the legacy values are the defaults); an error is raised when + a position matches no node. +- Spanish translation of the known issues: `docs/known-issues/KNOWN_ISSUES.es.md`. +- Example 1, `examples/example1_clamped_beam`: the beam clamped at both ends and + loaded with a force at mid-span, by Rodrigo (branch `dev_rodrigo`). It adds + `ldem.scenarios.ClampedBeam` (test 103), the first scenario loaded with a force: + a scenario can now set `state.appliedForce`, which the solver adds to the bar + forces and whose work is counted in the external energy. The new code + reproduces the original routines of the branch with no difference + (`tests/regression/TestClampedBeamAgainstLegacy`). +- ANSYS files list the displacement imposed on the loaded nodes + (`D,node,direction,value`) in the applied-loads section. +- `Parameters.meshPerturbation`: one number that switches the mesh perturbation + off (`0`, the default) or on with that coefficient of variation (`> 0`). +- Unit tests (`tests/unit`) and a regression test that compares the new mesh + with the legacy one (`tests/regression/TestMeshAgainstLegacy`). +- `ldem.io.exportAnsys` writes the applied forces (`F,node,FX|FY|FZ,value`) of force-controlled + scenarios (test 103); before, the ANSYS files of that test had no load. +- Documentation brought in line with the code: the introductions (EN/ES) describe the `ldem` package + instead of the legacy routines, `Parameters.testId` and `Scenario` mention test 103, the results tables + include `brokenBars` and the reaction of test 103, and the Portuguese and Spanish READMEs translate the + `buildtool` comments. +- Random field generated in memory: `ldem.material.generateRandomField` ports the + external script `Aleat_novo4.m` (Weibull values on a grid of poles, trilinear + interpolation to the bar centres), vectorised and without toolboxes. It is + switched on with `Parameters.randomFieldCv > 0`, with + `randomFieldCorrelationLength` (in module lengths, default 3) and + `randomFieldSeed` (default 515); no text file is needed. The multiplier of each + bar is stored in `results.barProps.randomField` and its origin and statistics in + `results.material.randomField`, also for a field read from a file. + +### Changed +- Example inputs moved to `examples/beam_102/`. +- `.gitignore` now targets MATLAB and LDEM output files. +- `run_tests` searches subfolders and skips tests tagged `Slow` by default. +- The generated API documentation covers the `ldem` package only. + +### Fixed in the original code (kept in the git tag `legacy-reference`) +- `legacy/main1.m`: removed scratch lines; fixed the end-of-run file closing + (undefined `fid12/fid15/fid19/fid20`) and the ANSYS output call. +- `legacy/BOUND.m`: `TEST 101` failed because `ini` was not assigned, and its + right-end support had a misplaced parenthesis (the loaded nodes were not held, + so the tension test did not conserve energy). +- `legacy/CALOAD.m`: the second load point of the beam test was never loaded. +- `legacy/IGN012.m`: the acceleration in y used a wrong index. +- `legacy/IGN012.m`: the time integration was never executed (the nested function + `ign012` was not called), so free nodes never moved. Fixed; the golden-master + fixtures were regenerated and the damage case re-tuned (1000 steps, Gf = 0.1). + +### Removed +- The original routines (`legacy/`) and the scratch scripts (`sandbox/`), with the + tools and tests that ran them (`generateReference`, `runLegacyCase`, + `TestLegacyReproducibility`, `TestLdemPath`). They remain in the git history + under the tag `legacy-reference`; the reference results they produced are kept + in `tests/fixtures/`. +- `examples/beam_102/LET.AN1`, which only the original driver read. +- Duplicate files (`* - Copia.m`, `Copy_of_*`), empty `initialization_DEM`, and + generated output files that were tracked by mistake (`LET.*`, `*.TXT`, + `SIM01.DAT`, `BARR_ROMP.dat`). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4578723..8cf55d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,23 +2,74 @@ ## Docstring convention The API docs are generated from the comments of the `.m` files -(`sphinxcontrib-matlabdomain`). The docstring must be the comment block -placed **immediately after the `function` line** (before `global` blocks): +(`sphinxcontrib-matlabdomain`). The docstring is the comment block placed +**immediately after the `function` line** (no blank line in between): ```matlab -function ini = CALOAD() -% CALOAD One-line summary (Portuguese). -% Longer description of what the routine does. -global ... +function [barLength, barCentres] = computeBarGeometry(nodes, bars) +%COMPUTEBARGEOMETRY One-line summary. +% +% [barLength, barCentres] = ldem.mesh.computeBarGeometry(nodes, bars) +% explains in a few lines what the function does. +% +% Inputs: +% nodes nNodes-by-3 coordinates [m]. +% bars nBars-by-2 node numbers. +% +% Outputs: +% barLength nBars-by-1 vector of lengths [m]. +% barCentres nBars-by-3 matrix of midpoints [m]. +% +% Example: +% [len, mid] = ldem.mesh.computeBarGeometry(nodes, bars); +% +% Legacy: CALAUX. +% +% See also ldem.mesh.buildBars. ``` -Comments in the source code are written in Portuguese. +Rules that keep the Sphinx build free of warnings: +- Write each entry of *Inputs/Outputs* on **one line**; put longer + explanations in a paragraph after the list. +- Leave a blank comment line before an indented block (list, example, table). + +Comments are written in English. Names: `lowerCamelCase` for functions and variables, +`UpperCamelCase` for classes. Validate inputs with an `arguments` block and throw +errors with an identifier of the form `ldem::`. ## Workflow 1. Branch from `dev`. -2. Add/adjust tests in `tests/` (`Test*.m`, `matlab.unittest`). -3. Run `run_tests` in MATLAB and build the docs (`docs/`) locally. -4. Open a pull request. +2. Add or adjust tests in `tests/` (`Test*.m`, `matlab.unittest`): `tests/unit` + for the behaviour of each function, `tests/regression` for comparisons with + the golden-master results of the original code. +3. Run `buildtool` in MATLAB from the repository root. It runs the Code + Analyzer (`check`, which must report nothing) and the fast tests with + coverage (`test`). Before opening the pull request also run + `buildtool testAll` and `buildtool docs`. +4. Open a pull request. CI runs `check` and `test` on every push and builds the + documentation with warnings as errors. + +| Command | What it does | +|---------|--------------| +| `buildtool` | `check` and `test` (default) | +| `buildtool check` | Code Analyzer on `src/`, `tests/` and `examples/`; any warning fails | +| `buildtool test` | Fast tests; writes `test-results/results.xml` and `code-coverage/coverage.xml` | +| `buildtool testAll` | Also the slow tests (complete beam model) | +| `buildtool docs` | Sphinx HTML in every language, in `docs/build/html/` (needs Python and `docs/requirements.txt`) | +| `buildtool clean` | Delete the generated files | + +`run_tests` (in `tests/`) is a lighter alternative that only runs the tests. + +Files excluded from docs/tests: backups (`*.asv`). -Files excluded from docs/tests: backups (`*.asv`), copies (`*Copia*`, -`Copy_of_*`) and scratch scripts (`Teste_*`, `main1`, ...). +## Repository layout +- `src/+ldem/` is the `ldem` package. All the code goes here. +- `tests/fixtures/*.mat` are golden-master results produced by the original + (Fortran-derived) MATLAB code, after correcting its obvious bugs. The original + code is not in the working tree; it is in the git history under the tag + `legacy-reference` (`git checkout legacy-reference`, which also contains the + tools that generated the fixtures). The problems found in it are listed in + `docs/known-issues/KNOWN_ISSUES.md`. Change a fixture only on purpose, and + say in the pull request why the reference result changed. +- Slow tests (tag `Slow`) are skipped by `buildtool test` and `run_tests`; use + `buildtool testAll` or `run_tests(IncludeSlow=true)`. diff --git a/README.md b/README.md index 922f4a3..f36eb9b 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ quasi-brittle materials (concrete, rocks). | Path | Content | |------|---------| -| `src/ldem/` | LDEM source code (`.m`) | +| `src/+ldem/` | The `ldem` package (refactored code) | | `tests/` | `matlab.unittest` test suite | | `docs/` | Sphinx documentation (English and Spanish), API generated from the `.m` files | | `examples/` | How to run the example simulations | @@ -24,15 +24,16 @@ quasi-brittle materials (concrete, rocks). ### Quick start ```matlab ->> setup_path % adds src/ldem to the MATLAB path ->> main % runs the default simulation +>> setup_path % adds src/ to the MATLAB path +>> run('examples/tension_101/runTension.m') % small example, output in examples/tension_101/output +>> run('examples/example1_clamped_beam/runClampedBeam.m') % beam clamped at both ends ``` Run the tests: ```matlab ->> addpath tests ->> run_tests +>> buildtool % static analysis + fast tests (needs R2022b or newer) +>> buildtool testAll % also the slow tests ``` ### Documentation @@ -43,11 +44,11 @@ The API reference is generated automatically from the comments of the ```bash pip install -r docs/requirements.txt -sphinx-build -b html docs/source docs/build/html +python docs/tools/build_docs.py ``` -Source-code comments are written in Portuguese; the guides are available in -English and Spanish. See [CONTRIBUTING.md](CONTRIBUTING.md) for the docstring +Comments are written in English (the original code is in the git history under +the tag `legacy-reference`); the guides are available in English and Spanish. See [CONTRIBUTING.md](CONTRIBUTING.md) for the docstring convention. ### Citation @@ -68,7 +69,7 @@ quase-frágeis (concreto, rochas). | Caminho | Conteúdo | |---------|----------| -| `src/ldem/` | Código-fonte LDEM (`.m`) | +| `src/+ldem/` | O pacote `ldem` (código refatorado) | | `tests/` | Suíte de testes com `matlab.unittest` | | `docs/` | Documentação Sphinx (espanhol e inglês), API gerada a partir dos `.m` | | `examples/` | Como executar as simulações de exemplo | @@ -76,15 +77,16 @@ quase-frágeis (concreto, rochas). ### Início rápido ```matlab ->> setup_path % adiciona src/ldem ao path do MATLAB ->> main % executa a simulação padrão +>> setup_path % adiciona src/ ao path do MATLAB +>> run('examples/tension_101/runTension.m') % exemplo pequeno, saída em examples/tension_101/output +>> run('examples/example1_clamped_beam/runClampedBeam.m') % viga biengastada ``` Executar os testes: ```matlab ->> addpath tests ->> run_tests +>> buildtool % análise estática + testes rápidos (requer R2022b ou superior) +>> buildtool testAll % inclui também os testes lentos ``` ### Documentação @@ -94,11 +96,11 @@ A referência da API é gerada automaticamente a partir dos comentários dos ```bash pip install -r docs/requirements.txt -sphinx-build -b html docs/source docs/build/html +python docs/tools/build_docs.py ``` -Os comentários do código estão em português; os guias estão em espanhol e -inglês. Veja [CONTRIBUTING.md](CONTRIBUTING.md) para a convenção de docstrings. +Os comentários estão em inglês (o código original está no histórico do git, na +tag `legacy-reference`); os guias estão em espanhol e inglês. Veja [CONTRIBUTING.md](CONTRIBUTING.md) para a convenção de docstrings. ### Citação @@ -118,7 +120,7 @@ cuasi-frágiles (hormigón, rocas). | Ruta | Contenido | |------|-----------| -| `src/ldem/` | Código fuente LDEM (`.m`) | +| `src/+ldem/` | El paquete `ldem` (código refactorizado) | | `tests/` | Suite de tests con `matlab.unittest` | | `docs/` | Documentación Sphinx (español e inglés), API generada desde los `.m` | | `examples/` | Cómo ejecutar las simulaciones de ejemplo | @@ -126,15 +128,16 @@ cuasi-frágiles (hormigón, rocas). ### Inicio rápido ```matlab ->> setup_path % agrega src/ldem al path de MATLAB ->> main % ejecuta la simulación por defecto +>> setup_path % agrega src/ al path de MATLAB +>> run('examples/tension_101/runTension.m') % ejemplo pequeño, salida en examples/tension_101/output +>> run('examples/example1_clamped_beam/runClampedBeam.m') % viga empotrada en ambos extremos ``` Ejecutar los tests: ```matlab ->> addpath tests ->> run_tests +>> buildtool % análisis estático + tests rápidos (requiere R2022b o posterior) +>> buildtool testAll % incluye también los tests lentos ``` ### Documentación @@ -144,11 +147,11 @@ los `.m` con Sphinx y `sphinxcontrib-matlabdomain`: ```bash pip install -r docs/requirements.txt -sphinx-build -b html docs/source docs/build/html +python docs/tools/build_docs.py ``` -Los comentarios del código están en portugués; las guías están en español e -inglés. Ver [CONTRIBUTING.md](CONTRIBUTING.md) para la convención de docstrings. +Los comentarios están en inglés (el código original está en el historial de git, +etiqueta `legacy-reference`); las guías están en español e inglés. Ver [CONTRIBUTING.md](CONTRIBUTING.md) para la convención de docstrings. ### Cita diff --git a/buildfile.m b/buildfile.m new file mode 100644 index 0000000..1eeb030 --- /dev/null +++ b/buildfile.m @@ -0,0 +1,117 @@ +function plan = buildfile +%BUILDFILE Build plan of the repository, run with MATLAB's buildtool. +% +% From the repository root: +% +% >> buildtool % default: check + test +% >> buildtool check % static analysis (Code Analyzer) +% >> buildtool test % fast tests, with coverage and JUnit report +% >> buildtool testAll % also the slow tests (full beam model) +% >> buildtool docs % Sphinx documentation (needs Python) +% >> buildtool clean % remove generated files +% >> buildtool -tasks % list the tasks +% +% Tasks +% check Fails if the Code Analyzer reports any warning or error in +% src/, tests/ or examples/. +% test Runs every test not tagged "Slow", writes +% test-results/results.xml (JUnit) and code-coverage/coverage.xml +% (Cobertura) and prints the coverage of the ldem package. +% testAll Same as test but including the slow tests (they build the +% complete beam model of the example, about 167,000 nodes). +% docs Builds the HTML documentation, in every language, in docs/build/html. +% clean Deletes test-results/, code-coverage/ and docs/build/. +% +% See also run_tests, buildplan. + +import matlab.buildtool.tasks.CodeIssuesTask + +plan = buildplan(localfunctions); + +plan("check") = CodeIssuesTask(["src", "tests", "examples"], ... + IncludeSubfolders = true, ... + ErrorThreshold = 0, ... + WarningThreshold = 0, ... + Results = "code-issues/results.sarif"); + +plan("test").Dependencies = "check"; +plan("testAll").Dependencies = "check"; + +plan.DefaultTasks = ["check", "test"]; +end + +function testTask(context) +% Fast tests, coverage and JUnit report. +runTests(context, false); +end + +function testAllTask(context) +% All tests, including the slow ones. +runTests(context, true); +end + +function docsTask(context) +% Build the Sphinx documentation. +root = context.Plan.RootFolder; +script = fullfile(root, 'docs', 'tools', 'build_docs.py'); +target = fullfile(root, 'docs', 'build', 'html'); +command = sprintf('python "%s"', script); +[status, output] = system(command); +if status ~= 0 + error('build:docs', ['Sphinx failed (is Python with docs/requirements.txt installed?):' newline '%s'], output); +end +fprintf('Documentation written to %s\n', target); +end + +function cleanTask(context) +% Remove the generated files. +root = context.Plan.RootFolder; +for folder = {'test-results', 'code-coverage', 'code-issues', fullfile('docs', 'build')} + target = fullfile(root, folder{1}); + if isfolder(target) + rmdir(target, 's'); + fprintf('Deleted %s\n', target); + end +end +end + +function runTests(context, includeSlow) +%RUNTESTS Run the test suite with a JUnit report and code coverage. +import matlab.unittest.TestRunner +import matlab.unittest.TestSuite +import matlab.unittest.plugins.XMLPlugin +import matlab.unittest.plugins.CodeCoveragePlugin +import matlab.unittest.plugins.codecoverage.CoberturaFormat +import matlab.unittest.selectors.HasTag + +root = context.Plan.RootFolder; + +% Source code and tests on the path for this run. +originalPath = path; +restorePath = onCleanup(@() path(originalPath)); +addpath(fullfile(root, 'src'), fullfile(root, 'tests')); + +resultsFolder = fullfile(root, 'test-results'); +coverageFolder = fullfile(root, 'code-coverage'); +for folder = {resultsFolder, coverageFolder} + if ~isfolder(folder{1}) + mkdir(folder{1}); + end +end + +suite = TestSuite.fromFolder(fullfile(root, 'tests'), 'IncludingSubfolders', true); +if ~includeSlow + suite = suite.selectIf(~HasTag('Slow')); +end + +runner = TestRunner.withTextOutput; +runner.addPlugin(XMLPlugin.producingJUnitFormat(fullfile(resultsFolder, 'results.xml'))); +runner.addPlugin(CodeCoveragePlugin.forPackage('ldem', 'IncludingSubpackages', true, ... + 'Producing', CoberturaFormat(fullfile(coverageFolder, 'coverage.xml')))); + +results = runner.run(suite); + +fprintf('\n%d tests: %d passed, %d failed, %d incomplete.\n', ... + numel(results), nnz([results.Passed]), nnz([results.Failed]), nnz([results.Incomplete])); +assertSuccess(results); +end diff --git a/docs/Makefile b/docs/Makefile index a8cc387..255f049 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -3,7 +3,7 @@ SOURCEDIR = source BUILDDIR = build html: - $(SPHINXBUILD) -b html $(SOURCEDIR) $(BUILDDIR)/html + python tools/build_docs.py clean: rm -rf $(BUILDDIR) diff --git a/docs/known-issues/KNOWN_ISSUES.es.md b/docs/known-issues/KNOWN_ISSUES.es.md new file mode 100644 index 0000000..737faaf --- /dev/null +++ b/docs/known-issues/KNOWN_ISSUES.es.md @@ -0,0 +1,139 @@ +# Problemas conocidos del código original + +*English version: [KNOWN_ISSUES.md](KNOWN_ISSUES.md).* + +Las rutinas originales de MATLAB (la carpeta `legacy/`, traducidas del programa +en Fortran) fueron la implementación de referencia de los tests de regresión. +Se quitaron del árbol de trabajo cuando el código refactorizado las reprodujo; +siguen en el historial de git bajo la etiqueta `legacy-reference` +(`git checkout legacy-reference`). Los resultados de referencia que produjeron +están en `tests/fixtures/`. + +Los problemas encontrados en el código original se listan aquí con la decisión +tomada. Cuando un problema era un error evidente de programación se **corrigió +también en el código original**, y los fixtures se regeneraron con la versión +corregida (la etiqueta guarda esa versión). + +Estado de cada ítem: **Corregido** (en el código original y en el nuevo), +**Resuelto** (en el código nuevo; el original conservaba el comportamiento +anterior), **Revisado** (comprobado, sin cambios) o **Aceptado** (se mantiene el +comportamiento original). No queda ningún ítem abierto. + +## Corregido en el código original + +| Archivo | Problema | Corrección | +|---------|----------|------------| +| `main1.m` | Líneas de prueba `a=1, b=2, c=3` al comienzo | Eliminadas | +| `main1.m` | La sección final usaba identificadores sin definir (`fid12/fid15/fid19/fid20`) y fallaba al terminar cada corrida | Cierra los identificadores de archivo que realmente se abrieron | +| `main1.m` | `ARMANS(I3)` (paréntesis) y `[...] = ini==ANSYS(...)` fallaban al activar la salida ANSYS | `ARMANS{I3}` y llamada simple | +| `BOUND.m` | `ini` solo se asignaba con `TEST == 102`, por lo que `TEST 101` fallaba | Se asigna siempre | +| `IGN012.m` | **Crítico.** La integración por diferencias centrales estaba en una función anidada `ign012` que nunca se llamaba, así que ningún nodo se movía salvo los de desplazamiento impuesto (velocidades y aceleraciones exactamente 0) | Se agregó la llamada `ign012;` | +| `IGN012.m` | La aceleración en y usaba `V(2,I)` (un escalar sobrante del bucle de nodos) en lugar de `V(2,:)` (ítem 11) | `V(2,:)` | +| `BOUND.m` | `TEST 101`: paréntesis mal puesto en el apoyo del extremo derecho (ítems 3 y 19) | `(M1 - 0.51)*LCO` | +| `CALOAD.m` | `TEST 102`: condición incorrecta, el segundo punto de carga nunca se cargaba (ítem 15) | `LOGIC2 && LOGIC3` | + +## Ítems + +1. **`ENERG2.m`, líneas 172-174: la energía cinética no se suma.** `ENCN` era un + vector por nodo en lugar de un escalar. **Resuelto.** El código nuevo da las + dos cosas: la energía cinética de cada nodo (`results.final.kineticEnergy`, + y `results.snapshots.kineticEnergy` en los pasos de snapshot) y el total del + modelo (`results.energy.kinetic`). +2. **`WRIENE.m`, línea 35: formato inválido `%25.12` (falta la `e`).** `LET.ENE` + quedaba truncado y desordenado. **Resuelto.** El historial de energías forma + parte del archivo de resultados (`results.energy`); ya no hay archivo de + texto. +3. **`BOUND.m`, `TEST == 101`: precedencia de operadores.** `mask2` usaba + `U0 > (M1 - 0.51*LCO)` en lugar de `(M1 - 0.51)*LCO` y no seleccionaba + ningún nodo. **Corregido.** La columna de nodos centrales del extremo + derecho es la cargada, y ahora está fija en x (es el mismo error que el + ítem 19). +4. **`CABAR.m` / `ENERG2.m`: barra rastreada fija en 7014.** **Resuelto**: + `params.trackedBar`. +5. **`TEST == 102`: geometría escrita en unidades de módulo** (`33.49`, `4.51`, + `50.5`...), por lo que el ensayo solo funcionaba con `M >= ~70`. + **Resuelto**: `FourPointBending(supportPosition=, loadPosition=)`, con los + valores originales por defecto, y un error cuando una posición no coincide + con ningún nodo. +6. **`IMPERF.m`: `LABELN` se pone en 1 y enseguida en 0,** de modo que la + perturbación de la malla nunca se aplica y la semilla no tiene efecto. + **Resuelto** en el código nuevo: el usuario la define con un solo número, + `meshPerturbation`: 0 (el valor por defecto) deja el reticulado regular y + cualquier valor positivo activa la perturbación con ese coeficiente de + variación (por ejemplo `0.02` para el 2 % de la longitud del módulo). Ya no + es un indicador que se edita en el código. La comprobación de estabilidad + del paso de tiempo usa las longitudes reales (perturbadas) de las barras. +7. **`CALCOEV.m`: el coeficiente de variación nunca se guarda** (`COEF` en lugar + de `COEV`). **Resuelto**: `results.barProps.criticalStrainCv` y + `results.material`, que además guarda E, Gf, los coeficientes del reticulado + y la deformación crítica media, mínima y máxima (lo que imprimía `WRICON`). +8. **`DEFEP.m`: verificación de seguridad sin uso** (`KR < 1.01`). **Resuelto**: + `buildBarProperties` lanza `ldem:material:criticalLengthTooShort`. +9. **El campo aleatorio es obligatorio.** **Resuelto**: `params.randomFieldFile` + es opcional (vacío = todos los multiplicadores valen 1). +10. **La prealocación `INT = 168000`, `INB = 2300000`** limitaba el tamaño de la + malla. **Resuelto**: todos los tamaños se deducen del número de módulos. +11. **`ign012`: la aceleración en y usa un índice incorrecto.** **Corregido** + en el código original y en el nuevo (`ldem.solver.integrateStep`); el test de + regresión ahora compara las tres componentes. +12. **`ign012`: la energía de amortiguamiento mezcla vectores y escalares.** + **Resuelto**: `state.dampingEnergy` es un escalar. (Los casos de referencia + tienen `CON = 0`, donde las dos definiciones coinciden.) +13. **`ENERG2.m` / `IGN012.m`: `KL` siempre vale 2.** La condición `B > NBA` que + daría `KL = 4` a las diagonales nunca se cumple porque + `NBA = NBS = NBT`. **Revisado.** El tipo de barra se conoce por cómo se + construye el modelo (arista de la malla, barra entre centros o diagonal, + `mesh.barType`), pero `KL = 2` es correcto para todos los tipos: da la + energía de la barra `E*deformación^2*L/2`, coherente con la ley de fuerza. + Con `KL = 4` en las diagonales el balance de energía se desviaría 13.5 % + (viga elástica; las diagonales guardan el 36 % de la energía elástica) y + 4.6 % (viga con daño), contra 0.05-0.1 % con `KL = 2`. +14. **`ENEX` (trabajo externo) nunca se calcula.** **Resuelto**: + `energy.external` es el trabajo realizado sobre los grados de libertad que + el escenario mantiene fijos y `energy.balance = external - internal`. El + balance es menor al 1 % del trabajo externo (0.01-0.5 % en los tests de + referencia), también con ablandamiento y rotura (tests en `TestSimulate` y + `TestSolver`). +15. **`CALOAD.m`, `TEST == 102`: el segundo punto de carga nunca se carga.** La + condición `LOGIC1 && LOGIC2` no puede cumplirse. **Corregido**: los dos + puntos de carga se mueven (`LOGIC2 && LOGIC3`). +16. **Un `TDAF` menor que medio paso de tiempo nunca cambia el amortiguamiento.** + **Aceptado** (`ldem.solver.dampingCoefficient` lo reproduce). +17. **Convención de signo de `TEST == 101`.** Los nodos cargados se mueven a + `x0 - VF2*TIME`, lo que comprime el prisma para `VF2 > 0` aunque el + comentario dice "tracción". **Aceptado**: misma convención, documentada en + `UniaxialTension`; usar un `loadingVelocity` negativo para traccionar. +18. **`ANSYS.m`: tres problemas en los archivos de macro.** (a) La línea + `ET,IFILE,4` es un comando de ANSYS inválido (un descuido por `ET,3,4`); + (b) las restricciones (`D,nodo,UX`...) solo se escriben para + `TEST == 102`; (c) la sección de "cargas aplicadas" escribe + `F,nodo,Fx,-10` para nodos elegidos con coordenadas fijas en el código + (`50.5*LCO`...) que no coinciden con ningún nodo de la viga. **Resuelto.** + `ldem.io.exportAnsys` escribe `ET,3,4` (a) y las restricciones de valor + cero de todos los escenarios (b). Para (c) la sección de cargas lista el + desplazamiento impuesto a los nodos cargados como `D,nodo,UY,valor`, + medido desde su posición inicial (nada en el tiempo cero). ANSYS conserva + la última restricción de cada grado de libertad, así que estas líneas + reemplazan a las de valor cero. Las coordenadas de los nodos del archivo + siguen siendo las posiciones actuales, por lo que el archivo muestra el + estado de la simulación; no es un reinicio desde el reticulado sin + deformar. +19. **`CALOAD.m`, `TEST == 101`: los nodos cargados no estaban fijos** (el mismo + error que el ítem 3): su posición se sobrescribía en cada paso y luego se + movían libremente, así que ninguna fuerza hacía trabajo sobre ellos y el + balance de energía no podía cerrar. **Corregido** junto con el ítem 3. +20. **`Aleat_novo4.m` (generador externo del archivo de campo aleatorio): la + media no es 1 y la interpolación tiene dos erratas.** La escala de la + Weibull es `Gamma(1+1/k)` en lugar de `1/Gamma(1+1/k)`, así que la media del + campo es `Gamma(1+1/k)^2` (0,957 para `Cv = 0.05`, la media de + `arquivo_3lc_rnao_cv05`). En la interpolación trilineal el término x-z usa + `V6-V5-V3+V1` en lugar de `V6-V5-V2+V1` y `ZZp(ii)` en lugar de `ZZp(iip)`, + lo que agrega dispersión: el archivo incluido tiene un CV de 0,054 aunque + los polos tenían 0,05, mientras que una interpolación correcta siempre lo + reduce. El script además necesitaba `BARI.txt` (centros de las barras), que + ningún código del repositorio escribe. **Resuelto**: + `ldem.material.generateRandomField` (se activa con `params.randomFieldCv`) + usa media 1 y la interpolación trilineal exacta, y toma los centros de las + barras de la malla. Por eso sus campos no son iguales a los archivos + legacy; para reproducir una corrida legacy hay que seguir usando + `randomFieldFile`. diff --git a/docs/known-issues/KNOWN_ISSUES.md b/docs/known-issues/KNOWN_ISSUES.md new file mode 100644 index 0000000..bcfed9b --- /dev/null +++ b/docs/known-issues/KNOWN_ISSUES.md @@ -0,0 +1,130 @@ +# Known issues of the legacy code + +*Versión en español: [KNOWN_ISSUES.es.md](KNOWN_ISSUES.es.md).* + +The original MATLAB routines (the `legacy/` folder, translated from the +Fortran program) were the reference implementation of the regression tests. +They were removed from the working tree once the refactored code reproduced +them; they remain in the git history under the tag `legacy-reference` +(`git checkout legacy-reference`). The golden-master results they produced are +stored in `tests/fixtures/`. + +Problems found in the original code are listed here with the decision taken. +Where a problem was an obvious programming error it was **corrected in the +original code as well**, and the fixtures were regenerated from the corrected +version (the tag holds that version). + +Status of each item: **Corrected** (in the original code and in the new code), +**Resolved** (in the new code; the original kept the old behaviour), +**Reviewed** (checked, no change needed) or **Accepted** (the original +behaviour is kept). No item is open. + +## Corrected in the original code + +| File | Problem | Fix | +|------|---------|-----| +| `main1.m` | Scratch lines `a=1, b=2, c=3` at the top | Removed | +| `main1.m` | Closing section used undefined `fid12/fid15/fid19/fid20` and crashed at the end of every run | Closes the file ids that were really opened | +| `main1.m` | `ARMANS(I3)` (parentheses) and `[...] = ini==ANSYS(...)` crashed when ANSYS output was enabled | `ARMANS{I3}`, plain call | +| `BOUND.m` | `ini` only assigned when `TEST == 102`, so `TEST 101` failed | Assigned unconditionally | +| `IGN012.m` | **Critical.** The central-difference integration was in a nested function `ign012` that was never called, so no node moved except those with a prescribed displacement (velocities and accelerations were exactly 0) | Added the call `ign012;` | +| `IGN012.m` | Acceleration in y used `V(2,I)` (a scalar left over from the node loop) instead of `V(2,:)` (item 11) | `V(2,:)` | +| `BOUND.m` | `TEST 101`: misplaced parenthesis in the right-end support (items 3 and 19) | `(M1 - 0.51)*LCO` | +| `CALOAD.m` | `TEST 102`: wrong condition, the second load point was never loaded (item 15) | `LOGIC2 && LOGIC3` | + +## Items + +1. **`ENERG2.m` lines 172-174: kinetic energy is not summed.** `ENCN` is a + per-node vector instead of a scalar. **Resolved.** The new code gives both: + the kinetic energy of every node (`results.final.kineticEnergy`, and + `results.snapshots.kineticEnergy` at the snapshot steps) and the total of + the model (`results.energy.kinetic`). +2. **`WRIENE.m` line 35: invalid format `%25.12` (missing `e`).** `LET.ENE` was + truncated and garbled. **Resolved.** The energy history is part of the + results file (`results.energy`); there is no text file. +3. **`BOUND.m`, `TEST == 101`: operator precedence.** `mask2` used + `U0 > (M1 - 0.51*LCO)` instead of `(M1 - 0.51)*LCO` and selected no node. + **Corrected.** The right-end column of centre nodes is the loaded one, and it + is now held in x (same bug as item 19). +4. **`CABAR.m` / `ENERG2.m`: tracked bar hardcoded to 7014.** **Resolved**: + `params.trackedBar`. +5. **`TEST == 102`: geometry hardcoded in module units** (`33.49`, `4.51`, + `50.5`...), so the test only worked for `M >= ~70`. **Resolved**: + `FourPointBending(supportPosition=, loadPosition=)`, with the legacy values + as defaults, and an error when a position matches no node. +6. **`IMPERF.m`: `LABELN` is set to 1 and then immediately to 0,** so the mesh + perturbation is never applied and the seed has no effect. **Resolved** in + the new code: the user sets it with one number, `meshPerturbation`: 0 (the + default) leaves the lattice regular, and any positive value activates the + perturbation with that coefficient of variation (for example `0.02` for 2 % + of the module length). It is no longer a flag edited in the code. The time-step + stability check uses the real (perturbed) bar lengths. +7. **`CALCOEV.m`: the coefficient of variation is never stored** (`COEF` instead + of `COEV`). **Resolved**: `results.barProps.criticalStrainCv` and + `results.material`, which also stores E, Gf, the lattice coefficients and + the mean, minimum and maximum critical strain (what `WRICON` printed). +8. **`DEFEP.m`: unused safety check** (`KR < 1.01`). **Resolved**: + `buildBarProperties` raises `ldem:material:criticalLengthTooShort`. +9. **Random field is mandatory.** **Resolved**: `params.randomFieldFile` is + optional (empty = all multipliers equal to 1). +10. **Preallocation `INT = 168000`, `INB = 2300000`** limited the mesh size. + **Resolved**: every size follows from the number of modules. +11. **`ign012`: acceleration in y uses a wrong index.** **Corrected** in + the original code and in the new code (`ldem.solver.integrateStep`); the regression + test now compares the three components. +12. **`ign012`: damping energy mixes vectors and scalars.** **Resolved**: + `state.dampingEnergy` is a scalar. (The reference cases have `CON = 0`, + where both definitions coincide.) +13. **`ENERG2.m` / `IGN012.m`: `KL` is always 2.** The test `B > NBA` that + would give `KL = 4` to the diagonals never holds because `NBA = NBS = NBT`. + **Reviewed.** The bar type is known from how the model is built (grid + edge, centre-to-centre bar or diagonal, `mesh.barType`), but `KL = 2` is + right for every type: it gives the bar energy `E*strain^2*L/2`, consistent + with the force law. With `KL = 4` for the diagonals the energy balance + would be off by 13.5 % (elastic beam test; the diagonals hold 36 % of the + elastic energy) and 4.6 % (beam with damage), against 0.05-0.1 % with + `KL = 2`. +14. **`ENEX` (external work) is never computed.** **Resolved**: + `energy.external` is the work done on the degrees of freedom held by the + scenario and `energy.balance = external - internal`. The balance is below + 1 % of the external work (0.01-0.5 % in the reference tests), also with + softening and rupture (tests in `TestSimulate` and `TestSolver`). +15. **`CALOAD.m`, `TEST == 102`: the second load point is never loaded.** The + condition `LOGIC1 && LOGIC2` cannot hold. **Corrected**: both load points + move (`LOGIC2 && LOGIC3`). +16. **`TDAF` shorter than half a time step never switches the damping.** + **Accepted** (`ldem.solver.dampingCoefficient` reproduces it). +17. **`TEST == 101` sign convention.** The loaded nodes move to `x0 - VF2*TIME`, + which compresses the prism for `VF2 > 0` although the comment says + "tension". **Accepted**: same convention, documented in `UniaxialTension`; + use a negative `loadingVelocity` to pull. +18. **`ANSYS.m`: three problems in the macro files.** (a) The line `ET,IFILE,4` + is an invalid ANSYS command (a slip for `ET,3,4`); (b) constraints + (`D,node,UX`...) are only written for `TEST == 102`; (c) the "applied + loads" section writes `F,node,Fx,-10` for nodes selected with hardcoded + coordinates (`50.5*LCO`...) that match no node of the beam. + **Resolved.** `ldem.io.exportAnsys` writes `ET,3,4` (a) and the zero-valued + constraints of every scenario (b). For (c) the loads section lists the + displacement imposed on the loaded nodes as `D,node,UY,value`, measured + from their initial position (nothing at time zero). ANSYS keeps the last + constraint of a degree of freedom, so these lines replace the zero ones. + The node coordinates of the file are still the current positions, so the + file shows the state of the simulation; it is not a restart from the + undeformed lattice. +19. **`CALOAD.m`, `TEST == 101`: the loaded nodes were not held** (the same bug + as item 3): their position was overwritten at every step and then moved + freely, so no force did work on them and the energy balance could not + close. **Corrected** together with item 3. +20. **`Aleat_novo4.m` (external generator of the random field file): the mean is + not 1 and the interpolation has two typos.** The Weibull scale is + `Gamma(1+1/k)` instead of `1/Gamma(1+1/k)`, so the mean of the field is + `Gamma(1+1/k)^2` (0.957 for `Cv = 0.05`, the mean of + `arquivo_3lc_rnao_cv05`). In the trilinear interpolation the x-z term uses + `V6-V5-V3+V1` instead of `V6-V5-V2+V1` and `ZZp(ii)` instead of `ZZp(iip)`, + which adds scatter: the bundled file has a CV of 0.054 although the poles + had 0.05, while a correct interpolation always lowers it. The script also + needed `BARI.txt` (bar centres), which no code of the repository writes. + **Resolved**: `ldem.material.generateRandomField` (enabled with + `params.randomFieldCv`) uses mean 1 and the exact trilinear interpolation + and takes the bar centres from the mesh. Its fields are therefore not equal + to the legacy files; to reproduce a legacy run keep `randomFieldFile`. diff --git a/docs/locale/es/LC_MESSAGES/api/index.po b/docs/locale/es/LC_MESSAGES/api/index.po new file mode 100644 index 0000000..50f4774 --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/api/index.po @@ -0,0 +1,55 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "API reference" +msgstr "Referencia de la API" + +msgid "Generated automatically from the comments of the ``.m`` files." +msgstr "Generada automáticamente desde los comentarios de los ``.m``." + +msgid "" +"The ``ldem`` package (``src/+ldem``) is the refactored code. It replaces the original" +" routines, which are kept in the git history (tag ``legacy-reference``); the problems" +" found in them are listed in ``docs/known-issues/KNOWN_ISSUES.md``." +msgstr "" +"El paquete ``ldem`` (``src/+ldem``) es el código refactorizado. Reemplaza a las " +"rutinas originales, que se conservan en el historial de git (etiqueta ``legacy-" +"reference``); los problemas encontrados en ellas se listan en ``docs/known-" +"issues/KNOWN_ISSUES.md``." + +msgid "Running a simulation" +msgstr "Ejecutar una simulación" + +msgid "Input and output" +msgstr "Entrada y salida" + +msgid "Mesh" +msgstr "Malla" + +msgid "Material" +msgstr "Material" + +msgid "Scenarios" +msgstr "Escenarios de ensayo" + +msgid "Case-file schema" +msgstr "Esquema de los archivos de caso" + +msgid "Solver" +msgstr "" + +msgid "Post-processing" +msgstr "Postproceso" + diff --git a/docs/locale/es/LC_MESSAGES/authors.po b/docs/locale/es/LC_MESSAGES/authors.po new file mode 100644 index 0000000..fdb6d4f --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/authors.po @@ -0,0 +1,59 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Authors" +msgstr "Autores" + +msgid "" +"This list is generated automatically from the commits of the git history (people with" +" the same name or e-mail are merged through ``.mailmap``) and from the authors of " +"``CITATION.cff``. Authors without commits in this repository appear with ``-``. The " +"same list is in ``AUTHORS.md``." +msgstr "" +"Esta lista se genera automáticamente desde los commits del historial de git (las " +"personas con el mismo nombre o correo se unifican con ``.mailmap``) y desde los " +"autores de ``CITATION.cff``. Los autores sin commits en este repositorio aparecen con" +" ``-``. La misma lista está en ``AUTHORS.md``." + +msgid "Name" +msgstr "Nombre" + +msgid "Commits" +msgstr "" + +msgid "Boris Rojo Tanzi" +msgstr "" + +msgid "26" +msgstr "" + +msgid "Rodrigo Cavasotto Oscar Montanha" +msgstr "" + +msgid "7" +msgstr "" + +msgid "Ignacio Iturrioz" +msgstr "" + +msgid "To update it after new commits, build the documentation or run:" +msgstr "Para actualizarla después de nuevos commits, construir la documentación o ejecutar:" + +msgid "python docs/tools/generate_authors.py" +msgstr "" + +msgid "If a person appears twice, add a line to ``.mailmap``." +msgstr "Si una persona aparece dos veces, agregar una línea a ``.mailmap``." + diff --git a/docs/locale/es/LC_MESSAGES/contributing.po b/docs/locale/es/LC_MESSAGES/contributing.po new file mode 100644 index 0000000..7ae6ad0 --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/contributing.po @@ -0,0 +1,43 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Contributing" +msgstr "Contribuir" + +msgid "" +"The API documentation is generated from the ``.m`` comments. The docstring must be " +"the comment block placed **immediately after** the ``function`` line (before any " +"``global`` declaration). Source comments are written in English." +msgstr "" +"La documentación de la API se genera desde los comentarios de los ``.m``. El " +"docstring debe ser el bloque de comentarios ubicado **inmediatamente después** de la " +"línea ``function`` (antes de cualquier ``global``). Los comentarios del código se " +"escriben en inglés." + +#, python-format +msgid "" +"function ini = CALOAD()\n" +"% CALOAD One-line summary.\n" +"% Longer description.\n" +"global ..." +msgstr "" +"function ini = CALOAD()\n" +"% CALOAD Resumen en una línea.\n" +"% Descripción más larga.\n" +"global ..." + +msgid "See ``CONTRIBUTING.md`` in the repository root." +msgstr "Ver ``CONTRIBUTING.md`` en la raíz del repositorio." + diff --git a/docs/locale/es/LC_MESSAGES/docs.po b/docs/locale/es/LC_MESSAGES/docs.po new file mode 100644 index 0000000..40e780b --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/docs.po @@ -0,0 +1,183 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Building this documentation" +msgstr "Construir esta documentación" + +msgid "" +"The documentation is written in English, which is the only set of source pages, and " +"translated into Spanish, Portuguese and Italian with gettext catalogs (``.po`` files " +"in ``docs/locale/``). Each language is built as its own site and the sidebar has a " +"language selector. A text that is not translated yet is shown in English. The API " +"reference is generated from the comments of the ``.m`` files and is in English only." +msgstr "" +"La documentación está escrita en inglés, que es el único conjunto de páginas fuente, " +"y traducida al español, portugués e italiano con catálogos gettext (archivos ``.po`` " +"en ``docs/locale/``). Cada idioma se construye como un sitio propio y la barra " +"lateral tiene un selector de idioma. Un texto que aún no está traducido se muestra en" +" inglés. La referencia de la API se genera desde los comentarios de los archivos " +"``.m`` y está solo en inglés." + +msgid "Requirements" +msgstr "Requisitos" + +msgid "Python 3.9 or newer." +msgstr "Python 3.9 o superior." + +msgid "" +"``git`` (the list of authors is generated from the commit history; with a shallow " +"clone use ``git fetch --unshallow`` first)." +msgstr "" +"``git`` (la lista de autores se genera desde el historial de commits; con un clon " +"superficial ejecutar antes ``git fetch --unshallow``)." + +msgid "No MATLAB is needed; the API is read from the source text." +msgstr "No se necesita MATLAB; la API se lee del texto de las fuentes." + +msgid "pip install -r docs/requirements.txt" +msgstr "" + +msgid "Build" +msgstr "Construcción" + +msgid "From the repository root, with any of these:" +msgstr "Desde la raíz del repositorio, con cualquiera de estas opciones:" + +msgid "python docs/tools/build_docs.py" +msgstr "" + +msgid "cd docs && make html" +msgstr "" + +msgid ">> buildtool docs" +msgstr "" + +msgid "" +"This builds the four languages into ``docs/build/html/en``, ``es``, ``pt`` and " +"``it``; ``docs/build/html/index.html`` sends the reader to the English site. Open it " +"in a browser. To build only some languages use for example ``python " +"docs/tools/build_docs.py --languages en es``. Warnings are errors: the documentation " +"must build without any. ``buildtool clean`` deletes the result." +msgstr "" +"Esto construye los cuatro idiomas en ``docs/build/html/en``, ``es``, ``pt`` e ``it``;" +" ``docs/build/html/index.html`` lleva al lector al sitio en inglés. Ábralo en un " +"navegador. Para construir solo algunos idiomas use, por ejemplo, ``python " +"docs/tools/build_docs.py --languages en es``. Las advertencias son errores: la " +"documentación debe construirse sin ninguna. ``buildtool clean`` borra el resultado." + +msgid "Where things are" +msgstr "Dónde está cada cosa" + +msgid "``docs/source/``" +msgstr "" + +msgid "The pages, in English." +msgstr "Las páginas, en inglés." + +msgid "``docs/locale/es/``, ``pt/``, ``it/``" +msgstr "" + +msgid "" +"Translations: one ``.po`` file per page in ``LC_MESSAGES/``, with each English text " +"and its translation." +msgstr "" +"Traducciones: un archivo ``.po`` por página en ``LC_MESSAGES/``, con cada texto en " +"inglés y su traducción." + +msgid "``docs/source/api/``" +msgstr "" + +msgid "API reference, generated from the ``.m`` comments." +msgstr "Referencia de la API, generada desde los comentarios de los ``.m``." + +msgid "``docs/tools/build_docs.py``" +msgstr "" + +msgid "Builds every language and the page that sends the reader to the English site." +msgstr "Construye cada idioma y la página que lleva al lector al sitio en inglés." + +msgid "``docs/tools/update_translations.py``" +msgstr "" + +msgid "" +"Updates the ``.po`` files after the English text changes, and reports what is left to" +" translate." +msgstr "" +"Actualiza los archivos ``.po`` cuando cambia el texto en inglés e informa lo que " +"falta traducir." + +msgid "``docs/tools/generate_authors.py``" +msgstr "" + +msgid "Writes the authors page and ``AUTHORS.md`` (run by the build)." +msgstr "Escribe la página de autores y ``AUTHORS.md`` (lo ejecuta la construcción)." + +msgid "``docs/source/case-keys.inc``" +msgstr "" + +msgid "" +"Reference of the case-file keys, generated from the schema. After changing " +"``ldem.schema.caseSchema`` regenerate it from MATLAB with " +"``ldem.schema.writeKeyReference(\"docs/source/case-keys.inc\")``; a test fails if it " +"is out of date." +msgstr "" +"Referencia de las claves del archivo de caso, generada desde el esquema. Tras cambiar" +" ``ldem.schema.caseSchema`` se regenera desde MATLAB con " +"``ldem.schema.writeKeyReference(\"docs/source/case-keys.inc\")``; un test falla si " +"está desactualizada." + +msgid "Write or change a page" +msgstr "Escribir o cambiar una página" + +msgid "" +"Edit the English page in ``docs/source/``. A new page also goes in the list of " +"``index.rst``." +msgstr "" +"Edite la página en inglés en ``docs/source/``. Una página nueva también se agrega a " +"la lista de ``index.rst``." + +msgid "" +"Run ``python docs/tools/update_translations.py``. It extracts the texts and updates " +"the ``.po`` files: new texts appear untranslated and changed texts are marked as " +"fuzzy, both shown in English until they are translated." +msgstr "" +"Ejecute ``python docs/tools/update_translations.py``. Extrae los textos y actualiza " +"los archivos ``.po``: los textos nuevos aparecen sin traducir y los textos cambiados " +"se marcan como fuzzy; ambos se muestran en inglés hasta que se traduzcan." + +msgid "" +"Translate the new entries in ``docs/locale//LC_MESSAGES/.po`` (with " +"any text editor or a tool such as Poedit) and remove the fuzzy marks you have " +"reviewed. ``python docs/tools/update_translations.py --status`` shows how much is " +"left in each language." +msgstr "" +"Traduzca las entradas nuevas en ``docs/locale//LC_MESSAGES/.po`` (con" +" cualquier editor de texto o una herramienta como Poedit) y quite las marcas fuzzy " +"que haya revisado. ``python docs/tools/update_translations.py --status`` muestra " +"cuánto falta en cada idioma." + +msgid "Build with ``python docs/tools/build_docs.py`` and fix any warning." +msgstr "Construya con ``python docs/tools/build_docs.py`` y corrija cualquier advertencia." + +msgid "Publishing" +msgstr "Publicación" + +msgid "" +"The workflow ``.github/workflows/docs.yml`` builds the documentation on every pull " +"request and publishes the four languages to GitHub Pages when ``main`` changes." +msgstr "" +"El workflow ``.github/workflows/docs.yml`` construye la documentación en cada pull " +"request y publica los cuatro idiomas en GitHub Pages cuando cambia ``main``." + diff --git a/docs/locale/es/LC_MESSAGES/examples.po b/docs/locale/es/LC_MESSAGES/examples.po new file mode 100644 index 0000000..a46c964 --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/examples.po @@ -0,0 +1,587 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Examples" +msgstr "Ejemplos" + +msgid "" +"The folder ``examples/`` has three models that run from start to finish, each with " +"its inputs and a script that runs it and plots the results. The numbers in this page " +"come from running them with the current code." +msgstr "" +"La carpeta ``examples/`` tiene tres modelos que se ejecutan de principio a fin, cada " +"uno con sus datos de entrada y un script que lo ejecuta y grafica los resultados. Los" +" números de esta página salen de ejecutarlos con el código actual." + +msgid "Folder" +msgstr "Carpeta" + +msgid "What it shows" +msgstr "Qué muestra" + +msgid "Size" +msgstr "Tamaño" + +msgid "Time" +msgstr "Tiempo" + +msgid "``example1_clamped_beam/``" +msgstr "" + +msgid "A beam clamped at both ends and loaded with a force at mid-span" +msgstr "Una viga empotrada en ambos extremos y cargada con una fuerza en el centro del vano" + +msgid "3,086 nodes" +msgstr "3,086 nodos" + +msgid "about 35 s" +msgstr "unos 35 s" + +msgid "``tension_101/``" +msgstr "" + +msgid "A small prism under a uniaxial load, with damage and every output format" +msgstr "Un prisma pequeño bajo carga uniaxial, con daño y todos los formatos de salida" + +msgid "74 nodes" +msgstr "74 nodos" + +msgid "about 6 s" +msgstr "unos 6 s" + +msgid "``beam_102/``" +msgstr "" + +msgid "The four-point bending beam of the paper (a demo of its first 50 steps)" +msgstr "" +"La viga a flexión en cuatro puntos del artículo (una demostración de sus primeros 50 " +"pasos)" + +msgid "166,961 nodes" +msgstr "166,961 nodos" + +msgid "about 30 s for 50 steps" +msgstr "unos 30 s para 50 pasos" + +msgid "" +"Start with ``tension_101`` to learn the interface and with ``example1_clamped_beam`` " +"to see a model loaded with a force, described by a case file and checked against the " +"original code." +msgstr "" +"Comience con ``tension_101`` para aprender la interfaz y con " +"``example1_clamped_beam`` para ver un modelo cargado con una fuerza, descrito con un " +"archivo de caso y verificado contra el código original." + +msgid "Running an example" +msgstr "Ejecutar un ejemplo" + +msgid "From MATLAB, from any folder:" +msgstr "Desde MATLAB, desde cualquier carpeta:" + +#, python-format +msgid "" +">> run('examples/example1_clamped_beam/runClampedBeam.m') % script: run and" +" plot\n" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % from the case " +"file" +msgstr "" +">> run('examples/example1_clamped_beam/runClampedBeam.m') % script: ejecuta" +" y grafica\n" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % desde el " +"archivo de caso" + +msgid "" +"The two beam examples also have a ``case.ldem``: the same model in the readable case-" +"file format (see :doc:`usage`), generated from the ``DATA0.DAT`` of the original " +"program and giving the same parameters. ``ldem.check`` shows what a case file would " +"simulate without running it." +msgstr "" +"Los dos ejemplos de viga también tienen un ``case.ldem``: el mismo modelo en el " +"formato legible de archivo de caso (ver :doc:`usage`), generado a partir del " +"``DATA0.DAT`` del programa original y que da los mismos parámetros. ``ldem.check`` " +"muestra qué simularía un archivo de caso sin ejecutarlo." + +msgid "" +"The scripts write their files to a folder ``output`` next to the script (ignored by " +"git), or to ``outputFolder`` if that variable already exists:" +msgstr "" +"Los scripts escriben sus archivos en una carpeta ``output`` junto al script (ignorada" +" por git), o en ``outputFolder`` si esa variable ya existe:" + +msgid "" +"``results.mat``: one struct, ``results``, with everything that was recorded. Load it " +"with ``data = load('results.mat'); results = data.results;``." +msgstr "" +"``results.mat``: una estructura, ``results``, con todo lo que se registró. Se carga " +"con ``data = load('results.mat'); results = data.results;``." + +msgid "``snapshot_0000.mac``, ...: ANSYS macro files of the deformed lattice." +msgstr "``snapshot_0000.mac``, ...: archivos macro de ANSYS de la malla deformada." + +msgid "" +"``snapshot_0000.vtu``, ... and ``snapshots.pvd``: open ``snapshots.pvd`` in `ParaView" +" `_ to see the damage evolve in time." +msgstr "" +"``snapshot_0000.vtu``, ... y ``snapshots.pvd``: abra ``snapshots.pvd`` en `ParaView " +"`_ para ver cómo evoluciona el daño en el tiempo." + +msgid "Example 1: beam clamped at both ends" +msgstr "Ejemplo 1: viga empotrada en ambos extremos" + +msgid "" +"A small beam of 5 x 5 x 50 modules of 1 mm, clamped at both ends and loaded at mid-" +"span with a force that grows during 0.35 ms and then stays constant. It is the model " +"of Rodrigo (branch ``dev_rodrigo``) and the first test loaded with a force instead of" +" a displacement (``ldem.scenarios.ClampedBeam``, test 103)." +msgstr "" +"Una viga pequeña de 5 x 5 x 50 módulos de 1 mm, empotrada en ambos extremos y cargada" +" en el centro del vano con una fuerza que crece durante 0.35 ms y luego se mantiene " +"constante. Es el modelo de Rodrigo (rama ``dev_rodrigo``) y el primer ensayo cargado " +"con una fuerza en lugar de un desplazamiento (``ldem.scenarios.ClampedBeam``, ensayo " +"103)." + +msgid "The model" +msgstr "El modelo" + +msgid "Part" +msgstr "Parte" + +msgid "Value" +msgstr "Valor" + +msgid "Geometry" +msgstr "Geometría" + +msgid "" +"5 x 5 x 50 modules of 1 mm (a prism of 5 x 5 x 50 mm, axis along z), with 3,086 " +"nodes, 18,085 bars and a mass of 1.875 g" +msgstr "" +"5 x 5 x 50 módulos de 1 mm (un prisma de 5 x 5 x 50 mm, eje a lo largo de z), con " +"3,086 nodos, 18,085 barras y una masa de 1.875 g" + +msgid "Supports" +msgstr "Apoyos" + +msgid "" +"The centre nodes of the first and of the last layer of modules (z = 0.5 and z = 49.5 " +"modules) are clamped: x, y and z held" +msgstr "" +"Los nodos centrales de la primera y de la última capa de módulos (z = 0.5 y z = 49.5 " +"módulos) están empotrados: x, y y z fijos" + +msgid "Load" +msgstr "Carga" + +msgid "" +"The 5 centre nodes of the line at mid-span (z = 24.5 modules, y = 0.5 modules) carry " +"a force in +y of ``1000 N/s * min(t, 0.35 ms)`` each: 0.35 N per node, 1.75 N in " +"total" +msgstr "" +"Los 5 nodos centrales de la línea en el centro del vano (z = 24.5 módulos, y = 0.5 " +"módulos) llevan cada uno una fuerza en +y de ``1000 N/s * min(t, 0.35 ms)``: 0.35 N " +"por nodo, 1.75 N en total" + +msgid "Material" +msgstr "Material" + +msgid "" +"E = 3.87 GPa, Poisson's ratio 0.25, density 1500 kg/m\\ :sup:`3`, fracture energy 0.5" +" N/m, critical distance 4.5 mm; mass-proportional damping of 2500 1/s" +msgstr "" +"E = 3.87 GPa, coeficiente de Poisson 0.25, densidad 1500 kg/m\\ :sup:`3`, energía de " +"fractura 0.5 N/m, distancia crítica 4.5 mm; amortiguamiento proporcional a la masa de" +" 2500 1/s" + +msgid "Scatter" +msgstr "Dispersión" + +msgid "" +"One multiplier of the critical strain per bar, read from a file (shared with " +"``beam_102``)" +msgstr "" +"Un multiplicador de la deformación crítica por barra, leído de un archivo (compartido" +" con ``beam_102``)" + +#, python-format +msgid "2.8 ms in 8000 steps of 0.35 us (65 % of the critical step)" +msgstr "2.8 ms en 8000 pasos de 0.35 us (65 % del paso crítico)" + +msgid "Recorded" +msgstr "Registrado" + +msgid "" +"Control nodes 2441 (a loaded node) and 884 (a grid node at mid-span); tracked bar " +"14398" +msgstr "" +"Nodos de control 2441 (un nodo cargado) y 884 (un nodo de esquina en el centro del " +"vano); barra seguida 14398" + +msgid "" +"The original input file listed five control nodes, but nodes 6870 and 14398 do not " +"exist in this 3,086-node mesh, so the input keeps 2441 and 884. The tracked bar is " +"14398, as in the original." +msgstr "" +"El archivo de entrada original listaba cinco nodos de control, pero los nodos 6870 y " +"14398 no existen en esta malla de 3,086 nodos, así que la entrada conserva 2441 y " +"884. La barra seguida es la 14398, como en el original." + +msgid "Files" +msgstr "Archivos" + +msgid "File" +msgstr "Archivo" + +msgid "Purpose" +msgstr "Propósito" + +msgid "``case.ldem``" +msgstr "" + +msgid "The model as a case file: run it with ``ldem.run``" +msgstr "El modelo como archivo de caso: se ejecuta con ``ldem.run``" + +msgid "``runClampedBeam.m``" +msgstr "" + +msgid "" +"Reads ``DATA0.DAT``, runs the simulation and plots the force on the clamped ends, the" +" vertical displacement of the control nodes and the energies" +msgstr "" +"Lee ``DATA0.DAT``, ejecuta la simulación y grafica la fuerza en los extremos " +"empotrados, el desplazamiento vertical de los nodos de control y las energías" + +msgid "``DATA0.DAT``" +msgstr "" + +msgid "The parameters in the format of the original program (``TEST 103``)" +msgstr "Los parámetros en el formato del programa original (``TEST 103``)" + +msgid "" +"The scenario and the load are the lines of the ``[scenario]`` section of " +"``case.ldem``:" +msgstr "El escenario y la carga son las líneas de la sección ``[scenario]`` de ``case.ldem``:" + +msgid "" +"[scenario]\n" +"type = \"clamped_beam\"\n" +"force_rate = 1000 N/s\n" +"ramp_time = 0.35 ms\n" +"load_position = \"midspan\"\n" +"load_height = 0.5 modules" +msgstr "" + +msgid "" +"The same test can be written without a scenario class, with supports and loads. It " +"gives the same results as ``ldem.scenarios.ClampedBeam`` (the tests check it):" +msgstr "" +"El mismo ensayo se puede escribir sin una clase de escenario, con apoyos y cargas. Da" +" los mismos resultados que ``ldem.scenarios.ClampedBeam`` (los tests lo comprueban):" + +msgid "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"first end\"\n" +"z = 0.5\n" +"fix = [\"x\", \"y\", \"z\"]\n" +"reaction = true\n" +"\n" +"[[support]]\n" +"name = \"last end\"\n" +"z = \"max - 0.5\"\n" +"fix = [\"x\", \"y\", \"z\"]\n" +"reaction = true\n" +"\n" +"[[load]]\n" +"name = \"line at mid-span\"\n" +"y = 0.5\n" +"z = \"mid - 0.5\"\n" +"direction = \"y\"\n" +"type = \"force\"\n" +"time_function = \"ramp\"\n" +"rate = 1000 N/s\n" +"until = 0.35 ms" +msgstr "" + +msgid "Reading the results" +msgstr "Leer los resultados" + +#, python-format +msgid "" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem', " +"OutputFolder=tempname);\n" +">> y0 = results.mesh.nodes0(results.params.controlNodes, 2).';\n" +">> dy = results.controlNodes.displacement(:, :, 2) - y0; % vertical displacement " +"[m]\n" +">> results.reactions.force(end, :) % force on the clamped " +"ends [N]\n" +">> ldem.post.plotReaction(results);\n" +">> ldem.post.plotEnergy(results);" +msgstr "" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem', " +"OutputFolder=tempname);\n" +">> y0 = results.mesh.nodes0(results.params.controlNodes, 2).';\n" +">> dy = results.controlNodes.displacement(:, :, 2) - y0; % desplazamiento vertical " +"[m]\n" +">> results.reactions.force(end, :) % fuerza en los extremos" +" empotrados [N]\n" +">> ldem.post.plotReaction(results);\n" +">> ldem.post.plotEnergy(results);" + +msgid "What you should see" +msgstr "Qué se debería ver" + +msgid "" +"Force carried by the clamped ends. It rises with the load, overshoots to 1.94 N and " +"settles at the total applied force." +msgstr "" +"Fuerza que soportan los extremos empotrados. Crece con la carga, sobrepasa hasta 1.94" +" N y se estabiliza en la fuerza total aplicada." + +msgid "" +"Vertical displacement of the two control nodes: a peak of 6.7 um at 0.46 ms and about" +" 6.3 um at the end." +msgstr "" +"Desplazamiento vertical de los dos nodos de control: un pico de 6.7 um a los 0.46 ms " +"y unos 6.3 um al final." + +msgid "Energies. The external work equals the sum of the internal energies." +msgstr "Energías. El trabajo externo es igual a la suma de las energías internas." + +msgid "" +"The reaction settles at 1.75 N, the 1.75 N applied in total: the beam is in " +"equilibrium at the end. The overshoot (1.94 N) and the oscillation are the dynamic " +"response, which the damping removes." +msgstr "" +"La reacción se estabiliza en 1.75 N, los 1.75 N aplicados en total: la viga está en " +"equilibrio al final. El sobrepaso (1.94 N) y la oscilación son la respuesta dinámica," +" que el amortiguamiento elimina." + +msgid "" +"With these values the beam stays elastic: at the end 18,085 bars are intact and none " +"is damaged or broken." +msgstr "" +"Con estos valores la viga se mantiene elástica: al final 18,085 barras están intactas" +" y ninguna está dañada ni rota." + +msgid "" +"The energy balance closes: the external work of 5.76 uJ is the elastic energy (5.48 " +"uJ) plus the energy dissipated by damping (0.28 uJ); the kinetic energy is about zero" +" and the balance is below 1e-13 J." +msgstr "" +"El balance de energía cierra: el trabajo externo de 5.76 uJ es la energía elástica " +"(5.48 uJ) más la energía disipada por amortiguamiento (0.28 uJ); la energía cinética " +"es casi cero y el balance es menor que 1e-13 J." + +msgid "Try other values" +msgstr "Probar otros valores" + +msgid "" +"Every key of the case file can be changed, or swept without editing the file (see " +":doc:`usage`):" +msgstr "" +"Cada clave del archivo de caso se puede cambiar, o barrer sin editar el archivo (ver " +":doc:`usage`):" + +#, python-brace-format +msgid "" +">> summary = ldem.sweep('examples/example1_clamped_beam/case.ldem', ...\n" +" Vary = {'scenario.force_rate', [\"10 kN/s\" \"30 kN/s\" \"100 kN/s\"]}, " +"Formats = \"mat\");" +msgstr "" + +msgid "" +"With the original value (1 kN/s) no bar is damaged. Ten times more force already " +"breaks the beam; each run takes about 50 s:" +msgstr "" +"Con el valor original (1 kN/s) ninguna barra se daña. Con diez veces más fuerza la " +"viga ya se rompe; cada corrida tarda unos 50 s:" + +msgid "Force rate" +msgstr "Tasa de fuerza" + +msgid "Damaged bars (including broken)" +msgstr "Barras dañadas (incluidas las rotas)" + +msgid "Broken bars" +msgstr "Barras rotas" + +msgid "10 kN/s" +msgstr "" + +msgid "5,630" +msgstr "" + +msgid "3,584" +msgstr "" + +msgid "30 kN/s" +msgstr "" + +msgid "6,074" +msgstr "" + +msgid "3,579" +msgstr "" + +msgid "100 kN/s" +msgstr "" + +msgid "4,760" +msgstr "" + +msgid "2,783" +msgstr "" + +msgid "" +"After the failure the loaded nodes keep being pushed by the force and move freely, so" +" the displacements of these runs are not meaningful; the damage counts are. Each run " +"has its own folder (``run_001``, ...) with its results and its resolved " +"``case.ldem``, and the table is also saved as ``sweep_summary.csv``." +msgstr "" +"Después de la falla, los nodos cargados siguen siendo empujados por la fuerza y se " +"mueven libremente, así que los desplazamientos de estas corridas no tienen " +"significado; los conteos de daño sí. Cada corrida tiene su propia carpeta " +"(``run_001``, ...) con sus resultados y su ``case.ldem`` resuelto, y la tabla también" +" se guarda como ``sweep_summary.csv``." + +msgid "" +"Other changes to try in ``case.ldem``: ``law = \"linear_elastic\"`` (no damage at " +"all), ``type = \"generated\"`` with a ``cv`` in ``[material.scatter]`` to generate " +"the random field in memory instead of reading it, or ``type = \"none\"`` to remove " +"the scatter." +msgstr "" +"Otros cambios para probar en ``case.ldem``: ``law = \"linear_elastic\"`` (sin ningún " +"daño), ``type = \"generated\"`` con un ``cv`` en ``[material.scatter]`` para generar " +"el campo aleatorio en memoria en lugar de leerlo, o ``type = \"none\"`` para quitar " +"la dispersión." + +msgid "Example: uniaxial prism" +msgstr "Ejemplo: prisma uniaxial" + +msgid "" +"``examples/tension_101/runTension.m`` runs a prism of 5 x 2 x 2 modules of 3 mm (74 " +"nodes, 313 bars) under the uniaxial test (test 101): the centre nodes of the last " +"column move along x with a prescribed velocity of 4 mm/s while those of the first " +"column are held. It is the best place to start: it has no input file, the model is " +"described in the script with ``ldem.Parameters``, and it writes every kind of output." +msgstr "" +"``examples/tension_101/runTension.m`` ejecuta un prisma de 5 x 2 x 2 módulos de 3 mm " +"(74 nodos, 313 barras) bajo el ensayo uniaxial (ensayo 101): los nodos centrales de " +"la última columna se mueven en x con una velocidad impuesta de 4 mm/s mientras que " +"los de la primera columna están fijos. Es el mejor lugar para empezar: no tiene " +"archivo de entrada, el modelo se describe en el script con ``ldem.Parameters`` y " +"escribe todos los tipos de salida." + +msgid "" +"E = 32 GPa, Poisson's ratio 0.25, density 2000 kg/m\\ :sup:`3`; a low fracture energy" +" of 0.1 N/m on purpose, so that bars soften and break" +msgstr "" +"E = 32 GPa, coeficiente de Poisson 0.25, densidad 2000 kg/m\\ :sup:`3`; una energía " +"de fractura baja de 0.1 N/m a propósito, para que las barras se ablanden y se rompan" + +msgid "0.2 ms in 1000 steps of 0.2 us" +msgstr "0.2 ms en 1000 pasos de 0.2 us" + +msgid "Output" +msgstr "Salida" + +msgid "" +"Snapshots (ANSYS and VTK) every 250 steps, control nodes and energies every 10 steps," +" no tracked bar" +msgstr "" +"Instantáneas (ANSYS y VTK) cada 250 pasos, nodos de control y energías cada 10 pasos," +" sin barra seguida" + +#, python-format +msgid "" +"At the end 251 bars are intact, 58 are damaged and 4 are broken. The external work is" +" 24.7 uJ: 22.5 uJ of elastic energy, 2.2 uJ dissipated by damage and 0.03 uJ by " +"damping; the balance is 0.01 % of the external work." +msgstr "" +"Al final 251 barras están intactas, 58 dañadas y 4 rotas. El trabajo externo es de " +"24.7 uJ: 22.5 uJ de energía elástica, 2.2 uJ disipados por el daño y 0.03 uJ por el " +"amortiguamiento; el balance es el 0.01 % del trabajo externo." + +msgid "Energies of the uniaxial prism." +msgstr "Energías del prisma uniaxial." + +msgid "" +"With the sign convention of the original code a positive ``loadingVelocity`` moves " +"the loaded face toward the fixed one, that is, it compresses the prism; use a " +"negative value to pull it (see ``ldem.scenarios.UniaxialTension``)." +msgstr "" +"Con el criterio de signos del código original, un ``loadingVelocity`` positivo mueve " +"la cara cargada hacia la fija, es decir, comprime el prisma; use un valor negativo " +"para traccionarlo (ver ``ldem.scenarios.UniaxialTension``)." + +msgid "Example: four-point bending beam" +msgstr "Ejemplo: viga a flexión en cuatro puntos" + +msgid "" +"``examples/beam_102/runBeam.m`` reads the input of the beam of the paper (test 102, " +"``ldem.scenarios.FourPointBending``): 100 x 40 x 20 modules of 3 mm (300 x 120 x 60 " +"mm), 166,961 nodes and 1,126,960 bars. The beam rests on two supports 4.5 modules " +"from its ends and two load points 33.5 modules from its ends push its top face down " +"with a prescribed velocity of 4 mm/s. The material is E = 32 GPa, density 2000 kg/m\\" +" :sup:`3`, fracture energy 50 N/m, critical distance 28 mm, with a random field of " +"the critical strain read from a file." +msgstr "" +"``examples/beam_102/runBeam.m`` lee la entrada de la viga del artículo (ensayo 102, " +"``ldem.scenarios.FourPointBending``): 100 x 40 x 20 módulos de 3 mm (300 x 120 x 60 " +"mm), 166,961 nodos y 1,126,960 barras. La viga se apoya en dos apoyos a 4.5 módulos " +"de sus extremos y dos puntos de carga a 33.5 módulos de sus extremos empujan su cara " +"superior hacia abajo con una velocidad impuesta de 4 mm/s. El material tiene E = 32 " +"GPa, densidad 2000 kg/m\\ :sup:`3`, energía de fractura 50 N/m, distancia crítica 28 " +"mm, con un campo aleatorio de la deformación crítica leído de un archivo." + +msgid "" +"The real simulation has 150,000 steps (0.03 s in steps of 0.2 us) and needs roughly " +"20 hours on a laptop (about 0.5 s per step). The script therefore runs only the first" +" 50 steps: it builds the complete model (about 20 s) and shows that the input is read" +" and the model runs; the plotted reaction is only that of the start of the test. " +"Change ``nStepsDemo`` at the top of the script, or remove the ``totalTime`` override," +" for the full run." +msgstr "" +"La simulación real tiene 150,000 pasos (0.03 s en pasos de 0.2 us) y necesita unas 20" +" horas en una laptop (unos 0.5 s por paso). Por eso el script ejecuta solo los " +"primeros 50 pasos: construye el modelo completo (unos 20 s) y muestra que la entrada " +"se lee y el modelo corre; la reacción graficada es solo la del comienzo del ensayo. " +"Cambie ``nStepsDemo`` al principio del script, o quite el reemplazo de ``totalTime``," +" para la ejecución completa." + +msgid "The same parameters as a case file (``ldem.io.readCase``, ``ldem.run``)" +msgstr "Los mismos parámetros como archivo de caso (``ldem.io.readCase``, ``ldem.run``)" + +msgid "Parameters in the format of the original program (``ldem.Parameters.fromFile``)" +msgstr "Parámetros en el formato del programa original (``ldem.Parameters.fromFile``)" + +msgid "``arquivo_3lc_rnao_cv05``" +msgstr "" + +msgid "" +"Random field applied to the critical strain of each bar (11 MB); it is also used by " +"``example1_clamped_beam``" +msgstr "" +"Campo aleatorio aplicado a la deformación crítica de cada barra (11 MB); también lo " +"usa ``example1_clamped_beam``" + +msgid "``runBeam.m``" +msgstr "" + +msgid "Reads the input, runs the first 50 steps and plots the reaction force" +msgstr "Lee la entrada, ejecuta los primeros 50 pasos y grafica la fuerza de reacción" + diff --git a/docs/locale/es/LC_MESSAGES/index.po b/docs/locale/es/LC_MESSAGES/index.po new file mode 100644 index 0000000..c183d90 --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/index.po @@ -0,0 +1,34 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "User guide" +msgstr "Guía de usuario" + +msgid "API" +msgstr "" + +msgid "LDEM-MATLAB" +msgstr "" + +msgid "Lattice Discrete Element Method (LDEM) in MATLAB." +msgstr "Método de Elementos Discretos tipo Lattice (LDEM) en MATLAB." + +msgid "" +"The documentation is written in English and translated into Spanish, Portuguese and " +"Italian. Choose the language in the sidebar of any page." +msgstr "" +"La documentación está escrita en inglés y traducida al español, portugués e italiano." +" Elija el idioma en la barra lateral de cualquier página." + diff --git a/docs/locale/es/LC_MESSAGES/installation.po b/docs/locale/es/LC_MESSAGES/installation.po new file mode 100644 index 0000000..e06642e --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/installation.po @@ -0,0 +1,70 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Installation" +msgstr "Instalación" + +msgid "" +"Requirements: MATLAB R2022b or newer (developed and tested on R2023b). The package " +"itself uses the ``arguments`` block and name=value syntax; the test suite and " +"``buildtool`` need R2022b. No toolbox is required." +msgstr "" +"Requisitos: MATLAB R2022b o superior (desarrollado y probado en R2023b). El paquete " +"usa el bloque ``arguments`` y la sintaxis nombre=valor; la suite de tests y " +"``buildtool`` requieren R2022b. No hace falta ningún toolbox." + +msgid "" +"git clone ldem-matlab\n" +"cd ldem-matlab" +msgstr "" +"git clone ldem-matlab\n" +"cd ldem-matlab" + +msgid ">> setup_path" +msgstr "" + +msgid "Check the installation with the fast tests:" +msgstr "Comprobar la instalación con los tests rápidos:" + +msgid ">> buildtool test" +msgstr "" + +msgid "Developer tasks (``buildtool`` is run from the repository root):" +msgstr "Tareas para desarrolladores (``buildtool`` se ejecuta desde la raíz del repositorio):" + +#, python-format +msgid "" +">> buildtool % static analysis + fast tests (the default)\n" +">> buildtool check % Code Analyzer only\n" +">> buildtool testAll % all tests, including the slow ones\n" +">> buildtool docs % build this documentation (needs Python)\n" +">> buildtool clean % delete generated files" +msgstr "" +">> buildtool % análisis estático + tests rápidos (por defecto)\n" +">> buildtool check % solo el analizador de código\n" +">> buildtool testAll % todos los tests, incluidos los lentos\n" +">> buildtool docs % construir esta documentación (requiere Python)\n" +">> buildtool clean % borrar los archivos generados" + +msgid "" +"``buildtool test`` writes ``test-results/results.xml`` (JUnit) and ``code-" +"coverage/coverage.xml`` (Cobertura)." +msgstr "" +"``buildtool test`` escribe ``test-results/results.xml`` (JUnit) y ``code-" +"coverage/coverage.xml`` (Cobertura)." + +msgid "To build this documentation without MATLAB see :doc:`docs`." +msgstr "Para construir esta documentación sin MATLAB ver :doc:`docs`." + diff --git a/docs/locale/es/LC_MESSAGES/introduction.po b/docs/locale/es/LC_MESSAGES/introduction.po new file mode 100644 index 0000000..91a4bbf --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/introduction.po @@ -0,0 +1,77 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Introduction" +msgstr "Introducción" + +msgid "" +"The **Lattice Discrete Element Method (LDEM)** models a continuum as a regular " +"lattice of nodes connected by bars arranged in cubic modules (edges plus diagonals). " +"Nodal masses are lumped, bar constitutive laws include damage/fracture, and the " +"equations of motion are integrated with an explicit central-difference scheme. " +"Energies (external, kinetic, elastic, dissipated) are tracked at every step." +msgstr "" +"El **Método de Elementos Discretos tipo Reticulado (LDEM)** modela un continuo como " +"un reticulado regular de nodos conectados por barras dispuestas en módulos cúbicos " +"(aristas más diagonales). Las masas son concentradas en los nodos, las leyes " +"constitutivas de las barras incluyen daño/fractura y las ecuaciones de movimiento se " +"integran con un esquema explícito de diferencias centrales. Las energías (externa, " +"cinética, elástica, disipada) se controlan en cada paso." + +msgid "Main parts of the ``ldem`` package (see :doc:`api/index`):" +msgstr "Partes principales del paquete ``ldem`` (ver :doc:`api/index`):" + +msgid "" +"``ldem.Parameters`` / ``ldem.io.readCase`` / ``ldem.io.readInputFile`` – validated " +"input data (case files and the legacy ``DATA0.DAT``)." +msgstr "" +"``ldem.Parameters`` / ``ldem.io.readCase`` / ``ldem.io.readInputFile`` – datos de " +"entrada validados (archivos de caso y el ``DATA0.DAT`` original)." + +msgid "``ldem.run`` / ``ldem.sweep`` / ``ldem.check`` – run, sweep and check a case file." +msgstr "" +"``ldem.run`` / ``ldem.sweep`` / ``ldem.check`` – ejecutar, barrer y comprobar un " +"archivo de caso." + +msgid "``ldem.mesh`` – nodes, bars, masses and bar geometry." +msgstr "``ldem.mesh`` – nodos, barras, masas y geometría de las barras." + +msgid "``ldem.material`` – bar stiffness, critical strain and the bilinear damage law." +msgstr "``ldem.material`` – rigidez de las barras, deformación crítica y ley bilineal de daño." + +msgid "``ldem.scenarios`` – supports, loads and reactions of each test." +msgstr "``ldem.scenarios`` – apoyos, cargas y reacciones de cada ensayo." + +msgid "``ldem.solver`` – time integration and energy balance." +msgstr "``ldem.solver`` – integración en el tiempo y balance de energía." + +msgid "" +"``ldem.runSimulation`` – the whole simulation, with ``results.mat``, ANSYS and VTK " +"output." +msgstr "" +"``ldem.runSimulation`` – la simulación completa, con salida ``results.mat``, ANSYS y " +"VTK." + +msgid "" +"The routines of the original program (``ini_DEM3``, ``read_dat0``, ``RMEC``, " +"``BOUND``, ``CALOAD``, ``ENERG2``, ...) are kept in the git history under the tag " +"``legacy-reference``; the ``Legacy:`` line of each help text names the routine it " +"replaces." +msgstr "" +"Las rutinas del programa original (``ini_DEM3``, ``read_dat0``, ``RMEC``, ``BOUND``, " +"``CALOAD``, ``ENERG2``, ...) se conservan en el historial de git, con la etiqueta " +"``legacy-reference``; la línea ``Legacy:`` de cada ayuda nombra la rutina que " +"reemplaza." + diff --git a/docs/locale/es/LC_MESSAGES/model.po b/docs/locale/es/LC_MESSAGES/model.po new file mode 100644 index 0000000..1b1705e --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/model.po @@ -0,0 +1,240 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Building a different model" +msgstr "Construir un modelo distinto" + +msgid "" +"A model is defined by three things: the **geometry** of the lattice, the **material**" +" and the **test** (supports and loads). The first two are parameters; the third is a " +"*scenario* class. You can change any of them without touching the solver." +msgstr "" +"Un modelo se define con tres cosas: la **geometría** del reticulado, el **material** " +"y el **ensayo** (apoyos y cargas). Las dos primeras son parámetros; la tercera es una" +" clase *escenario*. Se puede cambiar cualquiera sin tocar el solver." + +msgid "1. Change the geometry and the material" +msgstr "1. Cambiar la geometría y el material" + +msgid "Everything is a property of ``ldem.Parameters``:" +msgstr "Todo es una propiedad de ``ldem.Parameters``:" + +#, python-format +msgid "" +">> params = ldem.Parameters(testId=101, ...\n" +" moduleLength=0.002, ... % edge of the cubic module [m]\n" +" nModules=[21 6 6], ... % nodes along x, y and z\n" +" youngModulus=30e9, density=2400, poissonRatio=0.2, ...\n" +" fractureEnergy=80, criticalDistance=0.02, ...\n" +" meshPerturbation=0.02); % optional irregular mesh" +msgstr "" +">> params = ldem.Parameters(testId=101, ...\n" +" moduleLength=0.002, ... % arista del módulo cúbico [m]\n" +" nModules=[21 6 6], ... % nodos en x, y y z\n" +" youngModulus=30e9, density=2400, poissonRatio=0.2, ...\n" +" fractureEnergy=80, criticalDistance=0.02, ...\n" +" meshPerturbation=0.02); % malla irregular (opcional)" + +msgid "" +"``nModules = [M N L]`` is the number of grid nodes along each axis, so the prism has " +"``(M-1)*(N-1)*(L-1)`` modules." +msgstr "" +"``nModules = [M N L]`` es el número de nodos de la grilla en cada eje, de modo que el" +" prisma tiene ``(M-1)*(N-1)*(L-1)`` módulos." + +msgid "" +"``randomFieldFile`` multiplies the critical strain of each bar by a value read from a" +" text file (a random field of the material strength)." +msgstr "" +"``randomFieldFile`` multiplica la deformación crítica de cada barra por un valor " +"leído de un archivo de texto (campo aleatorio de la resistencia)." + +msgid "" +"``randomFieldCv`` generates that random field in memory instead, with no file: " +"Weibull values with mean 1 and that coefficient of variation on a grid of poles " +"spaced ``randomFieldCorrelationLength`` module lengths apart (default 3), " +"interpolated to each bar; ``randomFieldSeed`` fixes the random numbers. The value of " +"each bar is kept in ``results.barProps.randomField``." +msgstr "" +"``randomFieldCv`` genera ese campo aleatorio en memoria, sin archivo: valores Weibull" +" con media 1 y ese coeficiente de variación en una grilla de polos separados " +"``randomFieldCorrelationLength`` longitudes de módulo (3 por defecto), interpolados a" +" cada barra; ``randomFieldSeed`` fija los números aleatorios. El valor de cada barra " +"queda en ``results.barProps.randomField``." + +msgid "" +"``dt`` must be below ``params.criticalTimeStep``; ``Parameters`` rejects an unstable " +"value and says so." +msgstr "" +"``dt`` debe ser menor que ``params.criticalTimeStep``; ``Parameters`` rechaza un " +"valor inestable y lo explica." + +msgid "" +"The same data can come from a case file (``ldem.io.readCase``, see :doc:`usage`) or " +"from an input file in the format of the original program with " +"``ldem.Parameters.fromFile(\"DATA0.DAT\", ...)``; extra name=value pairs override the" +" file. The mesh can be built and inspected before running anything:" +msgstr "" +"Los mismos datos pueden venir de un archivo de caso (``ldem.io.readCase``, ver " +":doc:`usage`) o de un archivo de entrada con el formato del programa original: " +"``ldem.Parameters.fromFile(\"DATA0.DAT\", ...)``; los pares nombre=valor adicionales " +"reemplazan a los del archivo. La malla se puede construir e inspeccionar antes de " +"ejecutar nada:" + +#, python-format +msgid "" +">> mesh = ldem.mesh.buildMesh(params);\n" +">> fprintf(\"%d nodes, %d bars\\n\", size(mesh.nodes0, 1), size(mesh.bars, 1));" +msgstr "" +">> mesh = ldem.mesh.buildMesh(params);\n" +">> fprintf(\"%d nodos, %d barras\\n\", size(mesh.nodes0, 1), size(mesh.bars, 1));" + +msgid "2. Change the test: write a scenario" +msgstr "2. Cambiar el ensayo: escribir un escenario" + +msgid "" +"A *scenario* says which degrees of freedom are fixed, how the load is applied at " +"every time step and which reaction is reported. The solver never checks the test " +"number, it only asks the scenario. To model a new test, create a subclass of " +"``ldem.scenarios.Scenario`` in ``src/+ldem/+scenarios/``." +msgstr "" +"Un *escenario* dice qué grados de libertad están fijos, cómo se aplica la carga en " +"cada paso de tiempo y qué reacción se informa. El solver nunca consulta el número del" +" ensayo; se lo pregunta al escenario. Para modelar un ensayo nuevo se crea una " +"subclase de ``ldem.scenarios.Scenario`` en ``src/+ldem/+scenarios/``." + +msgid "" +"The example below is a cantilever beam along :math:`z`: the first layer of centre " +"nodes is clamped and a force that grows linearly is applied in :math:`y` at the free " +"end." +msgstr "" +"El ejemplo es una viga en voladizo según :math:`z`: la primera capa de nodos " +"centrales está empotrada y en el extremo libre se aplica en :math:`y` una fuerza que " +"crece linealmente." + +#, python-format +msgid "" +"classdef Cantilever < ldem.scenarios.Scenario\n" +" properties (Constant)\n" +" testId = 104 % new number, unique\n" +" end\n" +" properties\n" +" forceRate (1,1) double = 500 % [N/s] on each loaded node\n" +" end\n" +" methods\n" +" function fixed = fixedDofs(~, nodes0, params)\n" +" z = nodes0(:, 3);\n" +" atStart = abs(z - 0.5*params.moduleLength) < 0.01*params.moduleLength;\n" +" fixed = false(size(nodes0));\n" +" fixed(atStart, :) = true; % x, y and z held\n" +" end\n" +" function state = applyLoads(obj, state, mesh, params)\n" +" L1 = params.nModules(3) - 1;\n" +" z = mesh.nodes0(:, 3);\n" +" atEnd = abs(z - (L1 - 0.5)*params.moduleLength) < " +"0.01*params.moduleLength;\n" +" state.appliedForce(:) = 0;\n" +" state.appliedForce(atEnd, 2) = obj.forceRate * state.time;\n" +" end\n" +" end\n" +"end" +msgstr "" +"classdef Cantilever < ldem.scenarios.Scenario\n" +" properties (Constant)\n" +" testId = 104 % número nuevo, único\n" +" end\n" +" properties\n" +" forceRate (1,1) double = 500 % [N/s] en cada nodo cargado\n" +" end\n" +" methods\n" +" function fixed = fixedDofs(~, nodes0, params)\n" +" z = nodes0(:, 3);\n" +" atStart = abs(z - 0.5*params.moduleLength) < 0.01*params.moduleLength;\n" +" fixed = false(size(nodes0));\n" +" fixed(atStart, :) = true; % x, y y z fijos\n" +" end\n" +" function state = applyLoads(obj, state, mesh, params)\n" +" L1 = params.nModules(3) - 1;\n" +" z = mesh.nodes0(:, 3);\n" +" atEnd = abs(z - (L1 - 0.5)*params.moduleLength) < " +"0.01*params.moduleLength;\n" +" state.appliedForce(:) = 0;\n" +" state.appliedForce(atEnd, 2) = obj.forceRate * state.time;\n" +" end\n" +" end\n" +"end" + +msgid "Rules to follow:" +msgstr "Reglas:" + +msgid "" +"``fixedDofs`` returns an ``nNodes``-by-3 logical matrix, true where the node cannot " +"move (``1 = x``, ``2 = y``, ``3 = z``)." +msgstr "" +"``fixedDofs`` devuelve una matriz lógica de ``nNodes`` por 3, verdadera donde el nodo" +" no puede moverse (``1 = x``, ``2 = y``, ``3 = z``)." + +msgid "" +"``applyLoads`` runs once per step. A **displacement-controlled** test sets " +"``state.displacement`` of the loaded nodes (see ``UniaxialTension``); a **force-" +"controlled** test sets ``state.appliedForce`` in newtons (see ``ClampedBeam``) and " +"the solver counts its work in the external energy." +msgstr "" +"``applyLoads`` se ejecuta en cada paso. Un ensayo **controlado por desplazamiento** " +"asigna ``state.displacement`` de los nodos cargados (ver ``UniaxialTension``); uno " +"**controlado por fuerza** asigna ``state.appliedForce`` en newtons (ver " +"``ClampedBeam``) y el solver cuenta su trabajo en la energía externa." + +msgid "Override ``reactions`` if the test reports a reaction force (default: ``NaN``)." +msgstr "" +"Se redefine ``reactions`` si el ensayo informa una fuerza de reacción (por defecto: " +"``NaN``)." + +msgid "" +"The centre nodes of the modules lie at half-integer multiples of ``moduleLength``; " +"select nodes with a small tolerance, never with ``==``." +msgstr "" +"Los nodos centrales de los módulos están en múltiplos semienteros de " +"``moduleLength``; los nodos se seleccionan con una tolerancia pequeña, nunca con " +"``==``." + +msgid "3. Register and run it" +msgstr "3. Registrarlo y ejecutarlo" + +msgid "Either pass the object directly, with no registration:" +msgstr "Se puede pasar el objeto directamente, sin registrar nada:" + +msgid "" +">> scenario = ldem.scenarios.Cantilever(forceRate=1000);\n" +">> results = ldem.runSimulation(params, Scenario=scenario, ...\n" +" OutputFolder=\"output\", Formats=[\"mat\" \"vtk\"]);" +msgstr "" + +msgid "" +"or add one line to ``ldem.scenarios.registry`` so that ``testId = 104`` finds it and " +"a case file can name it with ``type``. Then add a test in ``tests/unit`` and, if it " +"is a reference case, an example in ``examples/`` (see " +"``examples/example1_clamped_beam``)." +msgstr "" +"o agregar una línea a ``ldem.scenarios.registry`` para que ``testId = 104`` lo " +"encuentre y un archivo de caso pueda nombrarlo con ``type``. Después se agrega un " +"test en ``tests/unit`` y, si es un caso de referencia, un ejemplo en ``examples/`` " +"(ver ``examples/example1_clamped_beam``)." + +msgid "The result is the same ``results`` struct as for any other test, see :doc:`usage`." +msgstr "" +"El resultado es la misma estructura ``results`` de cualquier otro ensayo, ver " +":doc:`usage`." + diff --git a/docs/locale/es/LC_MESSAGES/sphinx.po b/docs/locale/es/LC_MESSAGES/sphinx.po new file mode 100644 index 0000000..7a8f7f7 --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/sphinx.po @@ -0,0 +1,45 @@ +# User-interface texts of the theme (Furo) in es: buttons, search and page navigation. +# Kept by hand: docs/tools/update_translations.py does not touch this file. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Skip to content" +msgstr "Saltar al contenido" + +msgid "Back to top" +msgstr "Volver arriba" + +msgid "Next" +msgstr "Siguiente" + +msgid "Previous" +msgstr "Anterior" + +msgid "Home" +msgstr "Inicio" + +msgid "On this page" +msgstr "En esta página" + +msgid "Search" +msgstr "Buscar" + +msgid "Index" +msgstr "Índice" + +msgid "Error" +msgstr "Error" + +msgid "Please activate JavaScript to enable the search functionality." +msgstr "Active JavaScript para habilitar la función de búsqueda." + diff --git a/docs/locale/es/LC_MESSAGES/usage.po b/docs/locale/es/LC_MESSAGES/usage.po new file mode 100644 index 0000000..50d9bc0 --- /dev/null +++ b/docs/locale/es/LC_MESSAGES/usage.po @@ -0,0 +1,1346 @@ +# Translation of the LDEM-MATLAB documentation (es). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: es\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Usage" +msgstr "Uso" + +msgid "Run a simulation" +msgstr "Ejecutar una simulación" + +msgid "" +">> setup_path % adds src/ to the MATLAB path\n" +">> params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4, ...\n" +" fractureEnergy=0.1, ...\n" +" output=struct('snapshotEvery', 250, 'controlNodesEvery', 10, ...\n" +" 'energyEvery', 10, 'trackedBarEvery', 0));\n" +">> results = ldem.runSimulation(params, OutputFolder=\"output\", ...\n" +" Formats=[\"mat\" \"ansys\" \"vtk\"]);\n" +">> ldem.post.plotEnergy(results);" +msgstr "" +">> setup_path % agrega src/ al path de MATLAB\n" +">> params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4, ...\n" +" fractureEnergy=0.1, ...\n" +" output=struct('snapshotEvery', 250, 'controlNodesEvery', 10, ...\n" +" 'energyEvery', 10, 'trackedBarEvery', 0));\n" +">> results = ldem.runSimulation(params, OutputFolder=\"output\", ...\n" +" Formats=[\"mat\" \"ansys\" \"vtk\"]);\n" +">> ldem.post.plotEnergy(results);" + +msgid "" +"``ldem.Parameters`` checks every value when it is set and explains what is wrong (for" +" example an unstable time step). The complete, ready-to-run version of this script is" +" ``examples/tension_101/runTension.m``." +msgstr "" +"``ldem.Parameters`` valida cada valor al asignarlo y explica qué está mal (por " +"ejemplo, un paso de tiempo inestable). La versión completa y lista para ejecutar está" +" en ``examples/tension_101/runTension.m``." + +msgid "To use an input file in the format of the original program:" +msgstr "Para usar un archivo de entrada con el formato del programa original:" + +msgid ">> params = ldem.Parameters.fromFile(\"DATA0.DAT\");" +msgstr "" + +msgid "Case files (``.ldem``)" +msgstr "Archivos de caso (``.ldem``)" + +msgid "" +"A *case file* describes the whole model in one readable text file: named keys instead" +" of positions, units next to the numbers, comments, and the test, the random scatter " +"and the output files together. It replaces ``DATA0.DAT``." +msgstr "" +"Un *archivo de caso* describe todo el modelo en un único texto legible: claves con " +"nombre en lugar de posiciones, unidades junto a los números, comentarios, y el " +"ensayo, la dispersión aleatoria y los archivos de salida juntos. Reemplaza al " +"``DATA0.DAT``." + +msgid "" +"format = 1\n" +"title = \"Small tension test\"\n" +"\n" +"[mesh]\n" +"module_size = 3 mm\n" +"modules = [5, 2, 2] # cubic modules along x, y and z\n" +"\n" +"[material]\n" +"young_modulus = 32 GPa\n" +"density = 2000 kg/m3\n" +"\n" +"[time]\n" +"step = auto # 0.9 times the critical step\n" +"duration = 40 us\n" +"\n" +"[scenario]\n" +"type = \"uniaxial_tension\"\n" +"\n" +"[output]\n" +"folder = \"output\"" +msgstr "" +"format = 1\n" +"title = \"Ensayo de tracción pequeño\"\n" +"\n" +"[mesh]\n" +"module_size = 3 mm\n" +"modules = [5, 2, 2] # módulos cúbicos en x, y y z\n" +"\n" +"[material]\n" +"young_modulus = 32 GPa\n" +"density = 2000 kg/m3\n" +"\n" +"[time]\n" +"step = auto # 0.9 veces el paso crítico\n" +"duration = 40 us\n" +"\n" +"[scenario]\n" +"type = \"uniaxial_tension\"\n" +"\n" +"[output]\n" +"folder = \"output\"" + +#, python-format +msgid "" +">> ldem.io.writeTemplate(\"my_test.ldem\", \"clamped_beam\"); % a commented file to " +"edit\n" +">> ldem.check(\"my_test.ldem\") % validate and report, " +"no simulation\n" +">> results = ldem.run(\"my_test.ldem\"); % run it\n" +">> ldem.io.convertLegacyInput(\"DATA0.DAT\", \"case.ldem\"); % convert an old input" +" file" +msgstr "" +">> ldem.io.writeTemplate(\"mi_ensayo.ldem\", \"clamped_beam\"); % archivo comentado " +"para editar\n" +">> ldem.check(\"mi_ensayo.ldem\") % valida e informa, " +"sin simular\n" +">> results = ldem.run(\"mi_ensayo.ldem\"); % lo ejecuta\n" +">> ldem.io.convertLegacyInput(\"DATA0.DAT\", \"caso.ldem\"); % convierte un " +"archivo antiguo" + +msgid "Rules of the format:" +msgstr "Reglas del formato:" + +msgid "" +"Keys are read by **name**; the order of the lines does not matter. Keys that are " +"missing take the default of ``ldem.Parameters``. Only ``scenario.type``, " +"``mesh.modules`` and ``time.duration`` are required." +msgstr "" +"Las claves se leen por **nombre**; el orden de las líneas no importa. Las claves " +"ausentes toman el valor por defecto de ``ldem.Parameters``. Solo son obligatorias " +"``scenario.type``, ``mesh.modules`` y ``time.duration``." + +msgid "" +"A number may carry a **unit**: ``3.87 GPa``, ``0.35 us``, ``1500 kg/m3``, ``2 kN/s``." +" Without a unit the value is in SI. The wrong unit for the key is an error that lists" +" the valid ones." +msgstr "" +"Un número puede llevar **unidad**: ``3.87 GPa``, ``0.35 us``, ``1500 kg/m3``, ``2 " +"kN/s``. Sin unidad el valor está en SI. Una unidad incorrecta para la clave es un " +"error que lista las válidas." + +msgid "" +"``#`` starts a comment, ``[section]`` opens a table, ``[[monitor.node]]`` starts the " +"next element of a repeated table, lists are written ``[5, 5, 50]``." +msgstr "" +"``#`` inicia un comentario, ``[sección]`` abre una tabla, ``[[monitor.node]]`` inicia" +" el siguiente elemento de una tabla repetida y las listas se escriben ``[5, 5, 50]``." + +msgid "" +"``mesh.modules`` counts **modules**: the ``M N L`` of ``DATA0.DAT`` count nodes, one " +"more." +msgstr "" +"``mesh.modules`` cuenta **módulos**: los ``M N L`` del ``DATA0.DAT`` cuentan nodos, " +"uno más." + +msgid "``time.step = auto`` (or no ``step``) takes 0.9 times the critical step." +msgstr "``time.step = auto`` (o sin ``step``) toma 0.9 veces el paso crítico." + +msgid "" +"Every error names the file, the line, the section and the key, and suggests the " +"closest valid name for a mistyped one." +msgstr "" +"Cada error indica el archivo, la línea, la sección y la clave, y sugiere el nombre " +"válido más parecido cuando hay un error de tipeo." + +msgid "" +"Relative paths (the random-field file, the output folder) are relative to the case " +"file." +msgstr "" +"Las rutas relativas (archivo del campo aleatorio, carpeta de salida) son relativas al" +" archivo de caso." + +msgid "A JSON file with the same structure (values with units as strings) is also read." +msgstr "" +"También se lee un archivo JSON con la misma estructura (los valores con unidades, " +"como texto)." + +msgid "Section" +msgstr "Sección" + +msgid "Keys" +msgstr "Claves" + +msgid "(top)" +msgstr "(inicio)" + +msgid "``format`` (1), ``title``, ``authors``" +msgstr "" + +msgid "``[mesh]``" +msgstr "" + +msgid "" +"``module_size``, ``modules``, ``perturbation`` (random displacement of the nodes, " +"fraction of the module), ``seed`` (of the perturbation)" +msgstr "" +"``module_size``, ``modules``, ``perturbation`` (desplazamiento aleatorio de los " +"nodos, fracción del módulo), ``seed`` (de la perturbación)" + +msgid "``[material]``" +msgstr "" + +msgid "" +"``law`` (``bilinear``, the legacy law, or ``linear_elastic``: no damage and no " +"rupture), ``young_modulus``, ``poisson_ratio``, ``density``, ``fracture_energy``, " +"``critical_distance``, ``failure_area_factor``" +msgstr "" +"``law`` (``bilinear``, la ley original, o ``linear_elastic``: sin daño ni rotura), " +"``young_modulus``, ``poisson_ratio``, ``density``, ``fracture_energy``, " +"``critical_distance``, ``failure_area_factor``" + +msgid "``[material.scatter]``" +msgstr "" + +msgid "" +"Scatter of the critical strain of the bars. ``type = \"none\"``; ``\"file\"`` with " +"``file`` (one multiplier per bar); or ``\"generated\"`` with ``cv``, " +"``correlation_length`` (in modules) and ``seed`` (the field is computed in memory)" +msgstr "" +"Dispersión de la deformación crítica de las barras. ``type = \"none\"``; ``\"file\"``" +" con ``file`` (un multiplicador por barra); o ``\"generated\"`` con ``cv``, " +"``correlation_length`` (en módulos) y ``seed`` (el campo se calcula en memoria)" + +msgid "``[time]``" +msgstr "" + +msgid "``step`` (or ``auto``), ``duration``" +msgstr "``step`` (o ``auto``), ``duration``" + +msgid "``[damping]``" +msgstr "" + +msgid "" +"``type`` (``mass_proportional``, the legacy damping, or ``none``), ``initial``, " +"``final``, ``switch_time`` (not allowed with ``none``), ``constitutive``" +msgstr "" +"``type`` (``mass_proportional``, el amortiguamiento original, o ``none``), " +"``initial``, ``final``, ``switch_time`` (no se admiten con ``none``), " +"``constitutive``" + +msgid "``[scenario]``" +msgstr "" + +msgid "" +"``type`` (``uniaxial_tension``, ``four_point_bending``, ``clamped_beam`` or " +"``custom``, see below) and the properties of that scenario in snake_case, for example" +" ``force_rate``, ``ramp_time``, ``load_position`` (``\"midspan\"`` is allowed)" +msgstr "" +"``type`` (``uniaxial_tension``, ``four_point_bending``, ``clamped_beam`` o " +"``custom``, ver más abajo) y las propiedades de ese escenario en snake_case, por " +"ejemplo ``force_rate``, ``ramp_time``, ``load_position`` (se admite ``\"midspan\"``)" + +msgid "``[[monitor.node]]``" +msgstr "" + +msgid "" +"One element per control node: ``id`` (node number) or ``at = [x, y, z]`` (position in" +" modules, the nearest node is used), and ``name``" +msgstr "" +"Un elemento por nodo de control: ``id`` (número de nodo) o ``at = [x, y, z]`` " +"(posición en módulos, se usa el nodo más cercano), y ``name``" + +msgid "``[monitor.bar]``" +msgstr "" + +msgid "``tracked``: bar whose strain history is stored at every step" +msgstr "``tracked``: barra cuya historia de deformación se guarda en cada paso" + +msgid "``[output]``" +msgstr "" + +msgid "``folder``, ``mat``, ``ansys``, ``vtk`` (true or false)" +msgstr "``folder``, ``mat``, ``ansys``, ``vtk`` (true o false)" + +msgid "``[output.snapshots]``, ``[output.control_nodes]``, ``[output.energy]``" +msgstr "" + +msgid "" +"``every``: ``1000 steps`` or a time such as ``0.1 ms`` (converted to steps); ``0`` " +"means never" +msgstr "" +"``every``: ``1000 steps`` o un tiempo como ``0.1 ms`` (se convierte a pasos); ``0`` " +"significa nunca" + +msgid "" +"``ldem.io.readCase`` returns the parameters, the scenario and the output options; " +"``ldem.Parameters.fromFile`` also accepts a case file. The list of keys lives in one " +"table, ``ldem.schema.caseSchema``, which drives the reader, the writer and the " +"template. To add a scenario, add a line to ``ldem.scenarios.registry``. A new " +"constitutive law is a subclass of ``ldem.material.MaterialLaw`` registered in " +"``ldem.material.lawRegistry``; a new damping model is a subclass of " +"``ldem.solver.DampingModel`` registered in ``ldem.solver.dampingRegistry``." +msgstr "" +"``ldem.io.readCase`` devuelve los parámetros, el escenario y las opciones de salida; " +"``ldem.Parameters.fromFile`` también acepta un archivo de caso. La lista de claves " +"está en una sola tabla, ``ldem.schema.caseSchema``, que gobierna el lector, el " +"escritor y la plantilla. Para agregar un escenario, se agrega una línea a " +"``ldem.scenarios.registry``. Una ley constitutiva nueva es una subclase de " +"``ldem.material.MaterialLaw`` registrada en ``ldem.material.lawRegistry``; un modelo " +"de amortiguamiento nuevo, una subclase de ``ldem.solver.DampingModel`` registrada en " +"``ldem.solver.dampingRegistry``." + +msgid "Your own test: supports and loads" +msgstr "Su propio ensayo: apoyos y cargas" + +msgid "" +"With ``type = \"custom\"`` the test is described in the case file by ``[[support]]`` " +"and ``[[load]]`` blocks, without writing a class. This is the uniaxial test (``testId" +" = 101``) as blocks:" +msgstr "" +"Con ``type = \"custom\"`` el ensayo se describe en el archivo de caso con bloques " +"``[[support]]`` y ``[[load]]``, sin escribir una clase. Este es el ensayo uniaxial " +"(``testId = 101``) como bloques:" + +msgid "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"left end\"\n" +"x = 0.5 # the layer of centre nodes at x = 0.5 modules\n" +"fix = [\"x\"] # directions that cannot move\n" +"\n" +"[[load]]\n" +"name = \"right end\"\n" +"x = \"max - 0.5\"\n" +"direction = \"x\"\n" +"type = \"displacement\" # or \"force\"\n" +"time_function = \"linear\"\n" +"rate = -4 mm/s\n" +"reaction = true # its force is the reaction of the test" +msgstr "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"left end\"\n" +"x = 0.5 # la capa de nodos centrales en x = 0.5 módulos\n" +"fix = [\"x\"] # direcciones que no se pueden mover\n" +"\n" +"[[load]]\n" +"name = \"right end\"\n" +"x = \"max - 0.5\"\n" +"direction = \"x\"\n" +"type = \"displacement\" # o \"force\"\n" +"time_function = \"linear\"\n" +"rate = -4 mm/s\n" +"reaction = true # su fuerza es la reacción del ensayo" + +msgid "" +"**Nodes** are chosen with ``nodes`` (``all``, ``grid`` for the corners of the modules" +" or ``centre`` for their centres), ``ids`` (node numbers) and ``x``, ``y``, ``z``. A " +"position is in modules (centre nodes lie at half-integers, grid nodes at integers), a" +" range ``[lo, hi]``, or a text with the references ``min``, ``max`` and ``mid`` and " +"an offset, such as ``\"max - 0.5\"``. A node must satisfy every condition. The " +"positions refer to the regular lattice, so they do not change when " +"``mesh.perturbation`` moves the nodes." +msgstr "" +"Los **nodos** se eligen con ``nodes`` (``all``, ``grid`` para las esquinas de los " +"módulos o ``centre`` para sus centros), ``ids`` (números de nodo) y ``x``, ``y``, " +"``z``. Una posición está en módulos (los nodos centrales están en semienteros, los de" +" esquina en enteros), un rango ``[lo, hi]``, o un texto con las referencias ``min``, " +"``max`` y ``mid`` y un desplazamiento, como ``\"max - 0.5\"``. Un nodo debe cumplir " +"todas las condiciones. Las posiciones se refieren a la malla regular, así que no " +"cambian cuando ``mesh.perturbation`` mueve los nodos." + +msgid "" +"**Supports** hold the directions listed in ``fix``. **Loads** act on one " +"``direction`` as a ``force`` (newtons on each selected node) or as a prescribed " +"``displacement`` (metres from the initial position, and the solver holds that " +"direction). The value follows ``time_function``: ``constant`` (``value``), ``linear``" +" (``rate``), ``ramp`` (``rate`` until the time ``until``, then constant) or ``table``" +" (``times`` and ``values`` in SI units, linear between points and constant outside)." +msgstr "" +"Los **apoyos** fijan las direcciones de ``fix``. Las **cargas** actúan en una " +"``direction`` como ``force`` (newtons en cada nodo elegido) o como ``displacement`` " +"impuesto (metros desde la posición inicial; el solver fija esa dirección). El valor " +"sigue ``time_function``: ``constant`` (``value``), ``linear`` (``rate``), ``ramp`` " +"(``rate`` hasta el tiempo ``until`` y luego constante) o ``table`` (``times`` y " +"``values`` en unidades SI, lineal entre puntos y constante fuera)." + +msgid "" +"A block with ``reaction = true`` adds its force to the reaction of the test (the sum " +"of the bar forces on its held directions); with none, the reaction is NaN. A block " +"that selects no node is an error that names it. The three built-in tests written this" +" way give exactly the same results as their classes." +msgstr "" +"Un bloque con ``reaction = true`` suma su fuerza a la reacción del ensayo (la suma de" +" las fuerzas de barra en sus direcciones fijas); si ninguno la pide, la reacción es " +"NaN. Un bloque que no elige ningún nodo es un error que lo nombra. Los tres ensayos " +"incorporados escritos así dan exactamente los mismos resultados que sus clases." + +msgid "Reuse a case: extends" +msgstr "Reutilizar un caso: extends" + +msgid "A case file can start from another one and change only what differs:" +msgstr "Un archivo de caso puede partir de otro y cambiar solo lo que difiere:" + +msgid "" +"extends = \"base.ldem\" # or a list: [\"base.ldem\", \"material.ldem\"]\n" +"\n" +"[material]\n" +"fracture_energy = 1 N/m # only what changes" +msgstr "" +"extends = \"base.ldem\" # o una lista: [\"base.ldem\", " +"\"material.ldem\"]\n" +"\n" +"[material]\n" +"fracture_energy = 1 N/m # solo lo que cambia" + +msgid "" +"The keys of the file replace the inherited ones. A repeated table (``[[support]]``, " +"``[[load]]``, ``[[monitor.node]]``, ``[[sweep]]``) replaces the whole inherited list." +" When the ``type`` of the scenario, of ``[material.scatter]`` or of ``[damping]`` " +"changes, the keys of the old type that are not set again are dropped. With a list, " +"later files win. Relative paths (the random-field file, the output folder) are " +"relative to the file that contains them, and an error names the file and line where " +"the problem is written. ``results.info.case.parents`` keeps the hash of every " +"inherited file." +msgstr "" +"Las claves del archivo reemplazan a las heredadas. Una tabla repetida " +"(``[[support]]``, ``[[load]]``, ``[[monitor.node]]``, ``[[sweep]]``) reemplaza toda " +"la lista heredada. Cuando cambia el ``type`` del escenario, de ``[material.scatter]``" +" o de ``[damping]``, se descartan las claves del tipo anterior que no se vuelven a " +"definir. Con una lista, los últimos archivos ganan. Las rutas relativas (archivo del " +"campo aleatorio, carpeta de salida) son relativas al archivo que las contiene, y un " +"error nombra el archivo y la línea donde está escrito el problema. " +"``results.info.case.parents`` guarda el hash de cada archivo heredado." + +msgid "Parameter sweeps" +msgstr "Barridos de parámetros" + +msgid "" +"To study how the result depends on a value, list the values in ``[[sweep]]`` blocks " +"and run ``ldem.sweep``:" +msgstr "" +"Para estudiar cómo depende el resultado de un valor, se listan los valores en bloques" +" ``[[sweep]]`` y se ejecuta ``ldem.sweep``:" + +msgid "" +"[[sweep]]\n" +"key = \"material.fracture_energy\"\n" +"values = [\"0.1 N/m\", \"0.5 N/m\", \"1 N/m\"]\n" +"\n" +"[[sweep]]\n" +"key = \"time.duration\"\n" +"values = [\"20 us\", \"40 us\"]" +msgstr "" + +#, python-brace-format, python-format +msgid "" +">> summary = ldem.sweep(\"case.ldem\"); % 3 x 2 = 6 runs, one folder " +"each\n" +">> ldem.sweep(\"case.ldem\", DryRun=true); % only validate and list the " +"runs\n" +">> ldem.sweep(\"case.ldem\", Vary={\"scenario.force_rate\", [\"1 kN/s\" \"2 " +"kN/s\"]});\n" +">> results = ldem.run(\"case.ldem\", Overrides=struct(\"path\", " +"\"material.fracture_energy\", \"value\", \"2 N/m\"));" +msgstr "" +">> summary = ldem.sweep(\"case.ldem\"); % 3 x 2 = 6 corridas, una " +"carpeta cada una\n" +">> ldem.sweep(\"case.ldem\", DryRun=true); % solo valida y lista las " +"corridas\n" +">> ldem.sweep(\"case.ldem\", Vary={\"scenario.force_rate\", [\"1 kN/s\" \"2 " +"kN/s\"]});\n" +">> results = ldem.run(\"case.ldem\", Overrides=struct(\"path\", " +"\"material.fracture_energy\", \"value\", \"2 N/m\"));" + +msgid "" +"Several blocks give every combination; ``sweep_mode = \"zip\"`` (a key at the top of " +"the file) takes them one by one. Any key with a single value can be varied, and the " +"keys of the scenario as ``scenario.``. Values are numbers or texts with units. " +"Every run is validated before the first one starts. The runs go to ``run_001``, " +"``run_002``, ... (each with its resolved ``case.ldem``) and the table " +"``sweep_summary.csv`` lists them, with the number of damaged and broken bars; a run " +"that fails is recorded and the sweep goes on." +msgstr "" +"Varios bloques dan todas las combinaciones; ``sweep_mode = \"zip\"`` (una clave al " +"principio del archivo) los toma uno a uno. Se puede variar cualquier clave de un solo" +" valor, y las del escenario como ``scenario.``. Los valores son números o " +"textos con unidades. Cada corrida se valida antes de empezar la primera. Las corridas" +" van a ``run_001``, ``run_002``, ... (cada una con su ``case.ldem`` resuelto) y la " +"tabla ``sweep_summary.csv`` las lista, con el número de barras dañadas y rotas; una " +"corrida que falla queda registrada y el barrido continúa." + +msgid "Reference of every key" +msgstr "Referencia de todas las claves" + +msgid "" +"The tables below are generated from ``ldem.schema.caseSchema``, the same table that " +"the reader uses, so they always agree with it." +msgstr "" +"Las tablas siguientes se generan desde ``ldem.schema.caseSchema``, la misma tabla que" +" usa el lector, así que siempre coinciden con él. Las descripciones están en inglés." + +msgid "``(top level)``" +msgstr "``(nivel superior)``" + +msgid "Key" +msgstr "Clave" + +msgid "Value" +msgstr "Valor" + +msgid "Default" +msgstr "Por defecto" + +msgid "Legacy" +msgstr "Original" + +msgid "Description" +msgstr "Descripción" + +msgid "``format``" +msgstr "" + +msgid "integer" +msgstr "entero" + +msgid "1" +msgstr "" + +msgid "(none)" +msgstr "(ninguno)" + +msgid "Version of the case-file format (currently 1)." +msgstr "Versión del formato del archivo de caso (actualmente 1)." + +msgid "``title``" +msgstr "" + +msgid "text" +msgstr "texto" + +msgid "Free text title of the case." +msgstr "Título del caso, en texto libre." + +msgid "``authors``" +msgstr "" + +msgid "list of texts" +msgstr "lista de textos" + +msgid "Names of the authors." +msgstr "Nombres de los autores." + +msgid "``extends``" +msgstr "" + +msgid "Case file(s) to inherit from; the keys of this file replace the inherited ones." +msgstr "" +"Archivo(s) de caso del que se hereda; las claves de este archivo reemplazan a las " +"heredadas." + +msgid "``sweep_mode``" +msgstr "" + +msgid "product, zip" +msgstr "" + +msgid "\"product\"" +msgstr "" + +msgid "How several [[sweep]] blocks combine: all combinations (product) or one by one (zip)." +msgstr "" +"Cómo se combinan varios bloques [[sweep]]: todas las combinaciones (product) o uno a " +"uno (zip)." + +msgid "``module_size``" +msgstr "" + +msgid "number + unit (m, cm, mm, um, km)" +msgstr "número + unidad (m, cm, mm, um, km)" + +msgid "3 mm" +msgstr "" + +msgid "LCO" +msgstr "" + +msgid "Edge length of each cubic module." +msgstr "Longitud de la arista de cada módulo cúbico." + +msgid "``modules``" +msgstr "" + +msgid "list of integers" +msgstr "lista de enteros" + +msgid "required" +msgstr "obligatorio" + +msgid "M N L" +msgstr "" + +msgid "Cubic modules along x, y and z (M N L of the legacy file count nodes: one more)." +msgstr "Módulos cúbicos en x, y y z (los M N L del archivo original cuentan nodos: uno más)." + +msgid "``perturbation``" +msgstr "" + +msgid "number" +msgstr "número" + +msgid "0" +msgstr "" + +msgid "Random node displacement as a fraction of the module size; 0 = regular lattice." +msgstr "" +"Desplazamiento aleatorio de los nodos como fracción del tamaño del módulo; 0 = malla " +"regular." + +msgid "``seed``" +msgstr "" + +msgid "123" +msgstr "" + +msgid "SEED" +msgstr "" + +msgid "Seed of the mesh perturbation (the random field has its own seed)." +msgstr "Semilla de la perturbación de la malla (el campo aleatorio tiene su propia semilla)." + +msgid "``law``" +msgstr "" + +msgid "bilinear, linear\\_elastic" +msgstr "" + +msgid "\"bilinear\"" +msgstr "" + +msgid "Constitutive law of the bars (see ldem.material.lawRegistry)." +msgstr "Ley constitutiva de las barras (ver ldem.material.lawRegistry)." + +msgid "``young_modulus``" +msgstr "" + +msgid "number + unit (Pa, kPa, MPa, GPa)" +msgstr "número + unidad (Pa, kPa, MPa, GPa)" + +msgid "32 GPa" +msgstr "" + +msgid "YNG" +msgstr "" + +msgid "Young's modulus." +msgstr "Módulo de Young." + +msgid "``poisson_ratio``" +msgstr "" + +msgid "0.25" +msgstr "" + +msgid "PSN" +msgstr "" + +msgid "Poisson's ratio, from 0 up to less than 0.5." +msgstr "Coeficiente de Poisson, de 0 hasta menos de 0.5." + +msgid "``density``" +msgstr "" + +msgid "number + unit (kg/m3, g/cm3)" +msgstr "número + unidad (kg/m3, g/cm3)" + +msgid "2000 kg/m3" +msgstr "" + +msgid "ROH" +msgstr "" + +msgid "Mass density." +msgstr "Densidad de masa." + +msgid "``fracture_energy``" +msgstr "" + +msgid "number + unit (N/m, kN/m)" +msgstr "número + unidad (N/m, kN/m)" + +msgid "50 N/m" +msgstr "" + +msgid "GFR" +msgstr "" + +msgid "Specific fracture energy." +msgstr "Energía específica de fractura." + +msgid "``critical_distance``" +msgstr "" + +msgid "28 mm" +msgstr "" + +msgid "DEQ" +msgstr "" + +msgid "Equivalent (critical) distance." +msgstr "Distancia equivalente (crítica)." + +msgid "``failure_area_factor``" +msgstr "" + +msgid "0.1385" +msgstr "" + +msgid "CAF" +msgstr "" + +msgid "Fraction of the module face that fails per bar." +msgstr "Fracción de la cara del módulo que falla por barra." + +msgid "``type``" +msgstr "" + +msgid "none, file, generated" +msgstr "" + +msgid "\"none\"" +msgstr "" + +msgid "Scatter of the critical strain: none, file (one multiplier per bar) or generated." +msgstr "" +"Dispersión de la deformación crítica: none, file (un multiplicador por barra) o " +"generated." + +msgid "``file``" +msgstr "" + +msgid "file path" +msgstr "ruta de archivo" + +msgid "Text file with one multiplier per bar, relative to this file." +msgstr "Archivo de texto con un multiplicador por barra, relativo a este archivo." + +msgid "``cv``" +msgstr "" + +msgid "Coefficient of variation of the generated field (1e-4 to 3)." +msgstr "Coeficiente de variación del campo generado (1e-4 a 3)." + +msgid "``correlation_length``" +msgstr "" + +msgid "list of numbers" +msgstr "lista de números" + +msgid "[3]" +msgstr "" + +msgid "Correlation length of the generated field in modules: one value or [x, y, z]." +msgstr "Longitud de correlación del campo generado en módulos: un valor o [x, y, z]." + +msgid "515" +msgstr "" + +msgid "Seed of the generated field." +msgstr "Semilla del campo generado." + +msgid "``step``" +msgstr "" + +msgid "time, or auto" +msgstr "tiempo, o auto" + +msgid "\"auto\"" +msgstr "" + +msgid "DT" +msgstr "" + +msgid "Integration time step, or auto (0.9 times the critical step)." +msgstr "Paso de tiempo de integración, o auto (0.9 veces el paso crítico)." + +msgid "``duration``" +msgstr "" + +msgid "number + unit (s, ms, us, ns)" +msgstr "número + unidad (s, ms, us, ns)" + +msgid "TTOT" +msgstr "" + +msgid "Total simulated time." +msgstr "Tiempo total simulado." + +msgid "mass\\_proportional, none" +msgstr "" + +msgid "\"mass\\_proportional\"" +msgstr "" + +msgid "Damping model of the nodes (see ldem.solver.dampingRegistry)." +msgstr "Modelo de amortiguamiento de los nodos (ver ldem.solver.dampingRegistry)." + +msgid "``initial``" +msgstr "" + +msgid "number + unit (1/s, 1/ms)" +msgstr "número + unidad (1/s, 1/ms)" + +msgid "25000 1/s" +msgstr "" + +msgid "DF1" +msgstr "" + +msgid "Mass-proportional damping before switch\\_time." +msgstr "Amortiguamiento proporcional a la masa antes de switch\\_time." + +msgid "``final``" +msgstr "" + +msgid "DF2" +msgstr "" + +msgid "Mass-proportional damping after switch\\_time." +msgstr "Amortiguamiento proporcional a la masa después de switch\\_time." + +msgid "``switch_time``" +msgstr "" + +msgid "15 ms" +msgstr "" + +msgid "TDAF" +msgstr "" + +msgid "Time at which the damping changes from initial to final." +msgstr "Tiempo en que el amortiguamiento pasa de initial a final." + +msgid "``constitutive``" +msgstr "" + +msgid "0 s" +msgstr "" + +msgid "CON" +msgstr "" + +msgid "Stiffness-proportional damping inside the bar law." +msgstr "Amortiguamiento proporcional a la rigidez dentro de la ley de las barras." + +msgid "TEST" +msgstr "" + +msgid "Test case (see ldem.scenarios.registry); its other keys follow." +msgstr "Ensayo (ver ldem.scenarios.registry); sus otras claves siguen." + +msgid "``[[support]]``" +msgstr "" + +msgid "``name``" +msgstr "" + +msgid "Label of the support." +msgstr "Etiqueta del apoyo." + +msgid "``nodes``" +msgstr "" + +msgid "all, centre, grid" +msgstr "" + +msgid "\"all\"" +msgstr "" + +msgid "Kind of nodes: all, grid (module corners) or centre (module centres)." +msgstr "Tipo de nodos: all, grid (esquinas de los módulos) o centre (centros de los módulos)." + +msgid "``ids``" +msgstr "" + +msgid "Node numbers to select." +msgstr "Números de nodo a elegir." + +msgid "``x``" +msgstr "" + +msgid "modules: number, text or [lo, hi]" +msgstr "módulos: número, texto o [lo, hi]" + +msgid "Positions along x in modules: 0.5, \"max - 0.5\" or a range [lo, hi]." +msgstr "Posiciones en x, en módulos: 0.5, \"max - 0.5\" o un rango [lo, hi]." + +msgid "``y``" +msgstr "" + +msgid "Positions along y in modules (see x)." +msgstr "Posiciones en y, en módulos (ver x)." + +msgid "``z``" +msgstr "" + +msgid "Positions along z in modules (see x)." +msgstr "Posiciones en z, en módulos (ver x)." + +msgid "``fix``" +msgstr "" + +msgid "Directions held at their initial position: [\"x\", \"y\", \"z\"]." +msgstr "Direcciones que se mantienen en su posición inicial: [\"x\", \"y\", \"z\"]." + +msgid "``reaction``" +msgstr "" + +msgid "true or false" +msgstr "true o false" + +msgid "false" +msgstr "" + +msgid "Include the force on the held directions in the reaction of the test." +msgstr "Incluye la fuerza en las direcciones fijas en la reacción del ensayo." + +msgid "``[[load]]``" +msgstr "" + +msgid "Label of the load." +msgstr "Etiqueta de la carga." + +msgid "``direction``" +msgstr "" + +msgid "x, y, z" +msgstr "" + +msgid "Direction of the load." +msgstr "Dirección de la carga." + +msgid "force, displacement" +msgstr "" + +msgid "force (N on each selected node) or displacement (m from the initial position)." +msgstr "force (N en cada nodo elegido) o displacement (m desde la posición inicial)." + +msgid "``time_function``" +msgstr "" + +msgid "constant, linear, ramp, table" +msgstr "" + +msgid "How the value changes with time." +msgstr "Cómo cambia el valor con el tiempo." + +msgid "``value``" +msgstr "" + +msgid "N, N/s, m or m/s, by type" +msgstr "N, N/s, m o m/s, según el tipo" + +msgid "constant: the value (N or m)." +msgstr "constant: el valor (N o m)." + +msgid "``rate``" +msgstr "" + +msgid "linear and ramp: change per second (N/s or m/s)." +msgstr "linear y ramp: cambio por segundo (N/s o m/s)." + +msgid "``until``" +msgstr "" + +msgid "ramp: time at which it stops growing." +msgstr "ramp: tiempo en que deja de crecer." + +msgid "``times``" +msgstr "" + +msgid "table: increasing times in seconds." +msgstr "table: tiempos crecientes en segundos." + +msgid "``values``" +msgstr "" + +msgid "table: one value per time (N or m)." +msgstr "table: un valor por tiempo (N o m)." + +msgid "Include the force on the loaded direction in the reaction of the test." +msgstr "Incluye la fuerza en la dirección cargada en la reacción del ensayo." + +msgid "``[[sweep]]``" +msgstr "" + +msgid "``key``" +msgstr "" + +msgid "Key to vary, for example \"material.fracture\\_energy\" (see ldem.sweep)." +msgstr "Clave a variar, por ejemplo \"material.fracture\\_energy\" (ver ldem.sweep)." + +msgid "Values to try: numbers, or texts with units such as [\"0.1 N/m\", \"0.5 N/m\"]." +msgstr "Valores a probar: números, o textos con unidades como [\"0.1 N/m\", \"0.5 N/m\"]." + +msgid "``id``" +msgstr "" + +msgid "NCON" +msgstr "" + +msgid "Number of a node whose motion is recorded." +msgstr "Número de un nodo cuyo movimiento se registra." + +msgid "``at``" +msgstr "" + +msgid "Position [x, y, z] in modules; the nearest node is recorded." +msgstr "Posición [x, y, z] en módulos; se registra el nodo más cercano." + +msgid "Label of the node." +msgstr "Etiqueta del nodo." + +msgid "``tracked``" +msgstr "" + +msgid "off" +msgstr "desactivado" + +msgid "OU9" +msgstr "" + +msgid "Number of the bar whose strain history is stored at every step." +msgstr "Número de la barra cuya historia de deformación se guarda en cada paso." + +msgid "``folder``" +msgstr "" + +msgid "no files" +msgstr "sin archivos" + +msgid "Output folder, relative to the case file." +msgstr "Carpeta de salida, relativa al archivo de caso." + +msgid "``mat``" +msgstr "" + +msgid "true" +msgstr "" + +msgid "Write results.mat." +msgstr "Escribe results.mat." + +msgid "``ansys``" +msgstr "" + +msgid "Write ANSYS macro files (needs snapshots.every > 0)." +msgstr "Escribe archivos macro de ANSYS (requiere snapshots.every > 0)." + +msgid "``vtk``" +msgstr "" + +msgid "Write VTK files for ParaView (needs snapshots.every > 0)." +msgstr "Escribe archivos VTK para ParaView (requiere snapshots.every > 0)." + +msgid "``[output.snapshots]``" +msgstr "" + +msgid "``every``" +msgstr "" + +msgid "steps or time (0 = never)" +msgstr "pasos o tiempo (0 = nunca)" + +msgid "OU3" +msgstr "" + +msgid "Steps or time between full-field snapshots; 0 = never." +msgstr "Pasos o tiempo entre instantáneas del campo completo; 0 = nunca." + +msgid "``[output.control_nodes]``" +msgstr "" + +msgid "OU6" +msgstr "" + +msgid "Steps or time between records of the control nodes and reactions; 0 = never." +msgstr "Pasos o tiempo entre registros de los nodos de control y reacciones; 0 = nunca." + +msgid "``[output.energy]``" +msgstr "" + +msgid "OU8" +msgstr "" + +msgid "Steps or time between records of the energies; 0 = never." +msgstr "Pasos o tiempo entre registros de las energías; 0 = nunca." + +msgid "Tests available" +msgstr "Ensayos disponibles" + +msgid "``testId = 101``" +msgstr "" + +msgid "" +"Uniaxial load: the centre nodes of the last column of modules move along :math:`x` " +"with a prescribed velocity." +msgstr "" +"Carga uniaxial: los nodos centrales de la última columna de módulos se mueven en " +":math:`x` con velocidad impuesta." + +msgid "``testId = 102``" +msgstr "" + +msgid "" +"Beam with two supports and two load points. The positions are parameters of " +"``ldem.scenarios.FourPointBending`` (``supportPosition``, ``loadPosition``, in " +"modules from each end); the defaults need a beam longer than about 70 modules. See " +"``examples/beam_102``." +msgstr "" +"Viga con dos apoyos y dos puntos de carga. Las posiciones son parámetros de " +"``ldem.scenarios.FourPointBending`` (``supportPosition``, ``loadPosition``, en " +"módulos desde cada extremo); los valores por defecto requieren una viga de más de " +"unos 70 módulos. Ver ``examples/beam_102``." + +msgid "``testId = 103``" +msgstr "" + +msgid "" +"Beam clamped at both ends, loaded at mid-span with a force that grows linearly and " +"then stays constant (``ldem.scenarios.ClampedBeam``). It is the only test loaded with" +" a force instead of a displacement. See ``examples/example1_clamped_beam``." +msgstr "" +"Viga empotrada en los dos extremos, cargada a media luz con una fuerza que crece " +"linealmente y luego se mantiene constante (``ldem.scenarios.ClampedBeam``). Es el " +"único ensayo cargado con una fuerza en lugar de un desplazamiento. Ver " +"``examples/example1_clamped_beam``." + +msgid "" +"To add a new test, create a subclass of ``ldem.scenarios.Scenario`` (see " +":doc:`model`)." +msgstr "" +"Para agregar un ensayo nuevo se crea una subclase de ``ldem.scenarios.Scenario`` (ver" +" :doc:`model`)." + +msgid "Mesh perturbation" +msgstr "Perturbación de la malla" + +msgid "" +"The parameter ``meshPerturbation`` randomly displaces the interior nodes. Its value " +"is the standard deviation as a fraction of the module length: ``0`` (the default) " +"keeps the lattice regular and any positive value activates the perturbation with that" +" value. The random numbers follow ``seed``." +msgstr "" +"El parámetro ``meshPerturbation`` desplaza al azar los nodos interiores. Su valor es " +"la desviación estándar como fracción de la longitud del módulo: ``0`` (el valor por " +"defecto) deja el reticulado regular y cualquier valor positivo activa la perturbación" +" con ese valor. Los números aleatorios siguen a ``seed``." + +msgid ">> params = ldem.Parameters(testId=101, nModules=[6 3 3], meshPerturbation=0.02);" +msgstr "" + +msgid "What you get: the ``results`` struct" +msgstr "Qué se obtiene: la estructura ``results``" + +msgid "Field" +msgstr "Campo" + +msgid "Content" +msgstr "Contenido" + +msgid "``info``" +msgstr "" + +msgid "ldem version, date, MATLAB release, run time [s]." +msgstr "Versión de ldem, fecha, versión de MATLAB, tiempo de cálculo [s]." + +msgid "``params``" +msgstr "" + +msgid "The parameters used, as a plain struct (derived values included)." +msgstr "Los parámetros usados, como estructura simple (con valores derivados)." + +msgid "``model``" +msgstr "" + +msgid "" +"Counts and mass of the model: modules, nodes, bars by type, fixed degrees of freedom," +" total mass and volume." +msgstr "" +"Cantidades y masa del modelo: módulos, nodos, barras por tipo, grados de libertad " +"fijos, masa total y volumen." + +msgid "``material``" +msgstr "" + +msgid "" +"Material data (E, Gf, ...), lattice coefficients, critical length and the statistics " +"of the critical strain (mean, coefficient of variation, minimum and maximum)." +msgstr "" +"Datos del material (E, Gf, ...), coeficientes del reticulado, longitud crítica y " +"estadísticas de la deformación crítica (media, coeficiente de variación, mínimo y " +"máximo)." + +msgid "``mesh``" +msgstr "" + +msgid "Initial node positions, supports (``fixed``), masses, bars, bar lengths and bar types." +msgstr "Posiciones iniciales, apoyos (``fixed``), masas, barras, longitudes y tipos de barra." + +msgid "``barProps``" +msgstr "" + +msgid "Stiffness, critical strain and rupture strain of every bar." +msgstr "Rigidez, deformación crítica y deformación de rotura de cada barra." + +msgid "``controlNodes``" +msgstr "" + +msgid "Time and displacement, velocity and acceleration of the control nodes." +msgstr "Tiempo y desplazamiento, velocidad y aceleración de los nodos de control." + +msgid "``reactions``" +msgstr "" + +msgid "" +"Time and reaction force ``[Rx Ry Rz]`` of the test: vertical force at the load points" +" (test 102), force on the clamped ends (test 103); ``NaN`` where the test defines " +"none." +msgstr "" +"Tiempo y fuerza de reacción ``[Rx Ry Rz]`` del ensayo: fuerza vertical en los puntos " +"de carga (ensayo 102), fuerza en los extremos empotrados (ensayo 103); ``NaN`` donde " +"el ensayo no la define." + +msgid "``energy``" +msgstr "" + +msgid "" +"Time, kinetic, elastic, damage and damping energies [J], their sum (``internal``), " +"the energy of the broken bars (``brokenBars``), the external work, the ``balance`` " +"(external minus internal) and the damage rate." +msgstr "" +"Tiempo, energías cinética, elástica, de daño y de amortiguamiento [J], su suma " +"(``internal``), la energía de las barras rotas (``brokenBars``), el trabajo externo, " +"el balance (``balance``, externo menos interno) y la tasa de daño." + +msgid "``trackedBar``" +msgstr "" + +msgid "Strain, force and damage energy of one bar at every step (optional)." +msgstr "Deformación, fuerza y energía de daño de una barra en cada paso (opcional)." + +msgid "``snapshots``" +msgstr "" + +msgid "" +"Step, time, number of intact/damaged/broken bars, and compact copies of the " +"displacements, the damage state and the nodal kinetic energy at the snapshot steps." +msgstr "" +"Paso, tiempo, número de barras intactas/dañadas/rotas y copias compactas de los " +"desplazamientos, del estado de daño y de la energía cinética de cada nodo." + +msgid "" +"Final displacement, velocity, force and damage state, and the kinetic energy of every" +" node." +msgstr "" +"Desplazamiento, velocidad, fuerza y estado de daño finales, y la energía cinética de " +"cada nodo." + +msgid "" +"The energy ``balance`` is a check of the simulation: it should be a small fraction " +"(below 1 %) of the final external work. The total kinetic energy is " +"``energy.kinetic``; the kinetic energy of each node is in ``final.kineticEnergy``." +msgstr "" +"El ``balance`` de energía es una comprobación de la simulación: debe ser una fracción" +" pequeña (menos del 1 %) del trabajo externo final. La energía cinética total es " +"``energy.kinetic``; la de cada nodo está en ``final.kineticEnergy``." + +msgid "``results.mat`` contains this struct and loads without the package:" +msgstr "``results.mat`` contiene esta estructura y se carga sin el paquete:" + +msgid "" +">> data = load(\"output/results.mat\");\n" +">> results = data.results;" +msgstr "" + +msgid "Output files" +msgstr "Archivos de salida" + +msgid "``results.mat``" +msgstr "" + +msgid "The ``results`` struct (format v7.3, readable from Python with ``h5py``)." +msgstr "La estructura ``results`` (formato v7.3, legible desde Python con ``h5py``)." + +msgid "``snapshot_0000.mac``, ``snapshot_0001.mac``, ..." +msgstr "" + +msgid "" +"ANSYS macro files with the deformed lattice. Bars are element types 1 (intact), 2 " +"(damaged) and 5 (broken). The held degrees of freedom are listed as " +"``D,node,direction`` and the displacement imposed on the loaded nodes, measured from " +"their initial position, as ``D,node,direction,value``. In test 103 the applied forces" +" are listed as ``F,node,direction,value``." +msgstr "" +"Macros de ANSYS con el reticulado deformado. Las barras son elementos de tipo 1 " +"(intactas), 2 (dañadas) y 5 (rotas). Los grados de libertad fijos se listan como " +"``D,nodo,dirección`` y el desplazamiento impuesto a los nodos cargados, medido desde " +"su posición inicial, como ``D,nodo,dirección,valor``. En el ensayo 103 las fuerzas " +"aplicadas se listan como ``F,nodo,dirección,valor``." + +msgid "``snapshot_0000.vtu``, ... and ``snapshots.pvd``" +msgstr "``snapshot_0000.vtu``, ... y ``snapshots.pvd``" + +msgid "" +"VTK files. Open ``snapshots.pvd`` in `ParaView `_; colour " +"by ``damageState`` (cell data) to see the cracks and use the time slider to follow " +"them. Displacement and velocity are point data." +msgstr "" +"Archivos VTK. Abrir ``snapshots.pvd`` en `ParaView `_; " +"colorear por ``damageState`` (datos de celda) para ver las fisuras y usar el control " +"de tiempo para seguirlas. Desplazamiento y velocidad son datos de nodo." + +msgid "" +"ANSYS and VTK files are written at time zero and every " +"``params.output.snapshotEvery`` steps." +msgstr "" +"Los archivos ANSYS y VTK se escriben en el tiempo cero y cada " +"``params.output.snapshotEvery`` pasos." + +msgid "Run the tests" +msgstr "Ejecutar los tests" + +#, python-format +msgid "" +">> addpath tests\n" +">> run_tests % fast tests\n" +">> run_tests(IncludeSlow=true) % also the slow tests" +msgstr "" +">> addpath tests\n" +">> run_tests % tests rápidos\n" +">> run_tests(IncludeSlow=true) % también los tests lentos" + diff --git a/docs/locale/it/LC_MESSAGES/api/index.po b/docs/locale/it/LC_MESSAGES/api/index.po new file mode 100644 index 0000000..13b2d13 --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/api/index.po @@ -0,0 +1,54 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "API reference" +msgstr "Riferimento dell'API" + +msgid "Generated automatically from the comments of the ``.m`` files." +msgstr "Generato automaticamente dai commenti dei ``.m``." + +msgid "" +"The ``ldem`` package (``src/+ldem``) is the refactored code. It replaces the original" +" routines, which are kept in the git history (tag ``legacy-reference``); the problems" +" found in them are listed in ``docs/known-issues/KNOWN_ISSUES.md``." +msgstr "" +"Il pacchetto ``ldem`` (``src/+ldem``) è il codice rifattorizzato. Sostituisce le " +"routine originali, conservate nella cronologia di git (tag ``legacy-reference``); i " +"problemi trovati in esse sono elencati in ``docs/known-issues/KNOWN_ISSUES.md``." + +msgid "Running a simulation" +msgstr "Eseguire una simulazione" + +msgid "Input and output" +msgstr "Ingresso e uscita" + +msgid "Mesh" +msgstr "Mesh" + +msgid "Material" +msgstr "Materiale" + +msgid "Scenarios" +msgstr "Scenari di prova" + +msgid "Case-file schema" +msgstr "Schema dei file di caso" + +msgid "Solver" +msgstr "" + +msgid "Post-processing" +msgstr "Post-elaborazione" + diff --git a/docs/locale/it/LC_MESSAGES/authors.po b/docs/locale/it/LC_MESSAGES/authors.po new file mode 100644 index 0000000..fc1e657 --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/authors.po @@ -0,0 +1,59 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Authors" +msgstr "Autori" + +msgid "" +"This list is generated automatically from the commits of the git history (people with" +" the same name or e-mail are merged through ``.mailmap``) and from the authors of " +"``CITATION.cff``. Authors without commits in this repository appear with ``-``. The " +"same list is in ``AUTHORS.md``." +msgstr "" +"Questo elenco è generato automaticamente dai commit della cronologia di git (le " +"persone con lo stesso nome o e-mail sono unificate tramite ``.mailmap``) e dagli " +"autori di ``CITATION.cff``. Gli autori senza commit in questo repository compaiono " +"con ``-``. Lo stesso elenco è in ``AUTHORS.md``." + +msgid "Name" +msgstr "Nome" + +msgid "Commits" +msgstr "" + +msgid "Boris Rojo Tanzi" +msgstr "" + +msgid "26" +msgstr "" + +msgid "Rodrigo Cavasotto Oscar Montanha" +msgstr "" + +msgid "7" +msgstr "" + +msgid "Ignacio Iturrioz" +msgstr "" + +msgid "To update it after new commits, build the documentation or run:" +msgstr "Per aggiornarlo dopo nuovi commit, costruire la documentazione oppure eseguire:" + +msgid "python docs/tools/generate_authors.py" +msgstr "" + +msgid "If a person appears twice, add a line to ``.mailmap``." +msgstr "Se una persona compare due volte, aggiungere una riga a ``.mailmap``." + diff --git a/docs/locale/it/LC_MESSAGES/contributing.po b/docs/locale/it/LC_MESSAGES/contributing.po new file mode 100644 index 0000000..e146b26 --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/contributing.po @@ -0,0 +1,42 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Contributing" +msgstr "Contribuire" + +msgid "" +"The API documentation is generated from the ``.m`` comments. The docstring must be " +"the comment block placed **immediately after** the ``function`` line (before any " +"``global`` declaration). Source comments are written in English." +msgstr "" +"La documentazione dell'API è generata dai commenti dei ``.m``. Il docstring deve " +"essere il blocco di commenti posto **subito dopo** la riga ``function`` (prima di " +"qualsiasi ``global``). I commenti del codice sono scritti in inglese." + +#, python-format +msgid "" +"function ini = CALOAD()\n" +"% CALOAD One-line summary.\n" +"% Longer description.\n" +"global ..." +msgstr "" +"function ini = CALOAD()\n" +"% CALOAD Riepilogo in una riga.\n" +"% Descrizione più lunga.\n" +"global ..." + +msgid "See ``CONTRIBUTING.md`` in the repository root." +msgstr "Vedi ``CONTRIBUTING.md`` nella radice del repository." + diff --git a/docs/locale/it/LC_MESSAGES/docs.po b/docs/locale/it/LC_MESSAGES/docs.po new file mode 100644 index 0000000..3b564bf --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/docs.po @@ -0,0 +1,183 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Building this documentation" +msgstr "Costruire questa documentazione" + +msgid "" +"The documentation is written in English, which is the only set of source pages, and " +"translated into Spanish, Portuguese and Italian with gettext catalogs (``.po`` files " +"in ``docs/locale/``). Each language is built as its own site and the sidebar has a " +"language selector. A text that is not translated yet is shown in English. The API " +"reference is generated from the comments of the ``.m`` files and is in English only." +msgstr "" +"La documentazione è scritta in inglese, che è l'unico insieme di pagine sorgente, e " +"tradotta in spagnolo, portoghese e italiano con cataloghi gettext (file ``.po`` in " +"``docs/locale/``). Ogni lingua viene costruita come un sito a sé e la barra laterale " +"ha un selettore di lingua. Un testo non ancora tradotto viene mostrato in inglese. Il" +" riferimento dell'API è generato dai commenti dei file ``.m`` ed è solo in inglese." + +msgid "Requirements" +msgstr "Requisiti" + +msgid "Python 3.9 or newer." +msgstr "Python 3.9 o successivo." + +msgid "" +"``git`` (the list of authors is generated from the commit history; with a shallow " +"clone use ``git fetch --unshallow`` first)." +msgstr "" +"``git`` (l'elenco degli autori è generato dalla cronologia dei commit; con un clone " +"superficiale eseguire prima ``git fetch --unshallow``)." + +msgid "No MATLAB is needed; the API is read from the source text." +msgstr "MATLAB non è necessario; l'API viene letta dal testo dei sorgenti." + +msgid "pip install -r docs/requirements.txt" +msgstr "" + +msgid "Build" +msgstr "Costruzione" + +msgid "From the repository root, with any of these:" +msgstr "Dalla radice del repository, con una qualsiasi di queste opzioni:" + +msgid "python docs/tools/build_docs.py" +msgstr "" + +msgid "cd docs && make html" +msgstr "" + +msgid ">> buildtool docs" +msgstr "" + +msgid "" +"This builds the four languages into ``docs/build/html/en``, ``es``, ``pt`` and " +"``it``; ``docs/build/html/index.html`` sends the reader to the English site. Open it " +"in a browser. To build only some languages use for example ``python " +"docs/tools/build_docs.py --languages en es``. Warnings are errors: the documentation " +"must build without any. ``buildtool clean`` deletes the result." +msgstr "" +"Questo costruisce le quattro lingue in ``docs/build/html/en``, ``es``, ``pt`` e " +"``it``; ``docs/build/html/index.html`` porta il lettore al sito in inglese. Aprirlo " +"in un browser. Per costruire solo alcune lingue si usi, per esempio, ``python " +"docs/tools/build_docs.py --languages en es``. Gli avvisi sono errori: la " +"documentazione deve essere costruita senza alcuno. ``buildtool clean`` cancella il " +"risultato." + +msgid "Where things are" +msgstr "Dove si trova ogni cosa" + +msgid "``docs/source/``" +msgstr "" + +msgid "The pages, in English." +msgstr "Le pagine, in inglese." + +msgid "``docs/locale/es/``, ``pt/``, ``it/``" +msgstr "" + +msgid "" +"Translations: one ``.po`` file per page in ``LC_MESSAGES/``, with each English text " +"and its translation." +msgstr "" +"Traduzioni: un file ``.po`` per pagina in ``LC_MESSAGES/``, con ogni testo inglese e " +"la sua traduzione." + +msgid "``docs/source/api/``" +msgstr "" + +msgid "API reference, generated from the ``.m`` comments." +msgstr "Riferimento dell'API, generato dai commenti dei ``.m``." + +msgid "``docs/tools/build_docs.py``" +msgstr "" + +msgid "Builds every language and the page that sends the reader to the English site." +msgstr "Costruisce ogni lingua e la pagina che porta il lettore al sito in inglese." + +msgid "``docs/tools/update_translations.py``" +msgstr "" + +msgid "" +"Updates the ``.po`` files after the English text changes, and reports what is left to" +" translate." +msgstr "" +"Aggiorna i file ``.po`` quando cambia il testo inglese e riferisce cosa resta da " +"tradurre." + +msgid "``docs/tools/generate_authors.py``" +msgstr "" + +msgid "Writes the authors page and ``AUTHORS.md`` (run by the build)." +msgstr "Scrive la pagina degli autori e ``AUTHORS.md`` (eseguito dalla costruzione)." + +msgid "``docs/source/case-keys.inc``" +msgstr "" + +msgid "" +"Reference of the case-file keys, generated from the schema. After changing " +"``ldem.schema.caseSchema`` regenerate it from MATLAB with " +"``ldem.schema.writeKeyReference(\"docs/source/case-keys.inc\")``; a test fails if it " +"is out of date." +msgstr "" +"Riferimento delle chiavi del file di caso, generato dallo schema. Dopo aver cambiato " +"``ldem.schema.caseSchema`` si rigenera da MATLAB con " +"``ldem.schema.writeKeyReference(\"docs/source/case-keys.inc\")``; un test fallisce se" +" è obsoleto." + +msgid "Write or change a page" +msgstr "Scrivere o modificare una pagina" + +msgid "" +"Edit the English page in ``docs/source/``. A new page also goes in the list of " +"``index.rst``." +msgstr "" +"Modificare la pagina inglese in ``docs/source/``. Una pagina nuova va anche " +"nell'elenco di ``index.rst``." + +msgid "" +"Run ``python docs/tools/update_translations.py``. It extracts the texts and updates " +"the ``.po`` files: new texts appear untranslated and changed texts are marked as " +"fuzzy, both shown in English until they are translated." +msgstr "" +"Eseguire ``python docs/tools/update_translations.py``. Estrae i testi e aggiorna i " +"file ``.po``: i testi nuovi compaiono non tradotti e i testi modificati sono marcati " +"come fuzzy; entrambi sono mostrati in inglese finché non vengono tradotti." + +msgid "" +"Translate the new entries in ``docs/locale//LC_MESSAGES/.po`` (with " +"any text editor or a tool such as Poedit) and remove the fuzzy marks you have " +"reviewed. ``python docs/tools/update_translations.py --status`` shows how much is " +"left in each language." +msgstr "" +"Tradurre le voci nuove in ``docs/locale//LC_MESSAGES/.po`` (con un " +"qualsiasi editor di testo o uno strumento come Poedit) e togliere i contrassegni " +"fuzzy che sono stati rivisti. ``python docs/tools/update_translations.py --status`` " +"mostra quanto resta in ogni lingua." + +msgid "Build with ``python docs/tools/build_docs.py`` and fix any warning." +msgstr "Costruire con ``python docs/tools/build_docs.py`` e correggere ogni avviso." + +msgid "Publishing" +msgstr "Pubblicazione" + +msgid "" +"The workflow ``.github/workflows/docs.yml`` builds the documentation on every pull " +"request and publishes the four languages to GitHub Pages when ``main`` changes." +msgstr "" +"Il workflow ``.github/workflows/docs.yml`` costruisce la documentazione a ogni pull " +"request e pubblica le quattro lingue su GitHub Pages quando cambia ``main``." + diff --git a/docs/locale/it/LC_MESSAGES/examples.po b/docs/locale/it/LC_MESSAGES/examples.po new file mode 100644 index 0000000..661788b --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/examples.po @@ -0,0 +1,587 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Examples" +msgstr "Esempi" + +msgid "" +"The folder ``examples/`` has three models that run from start to finish, each with " +"its inputs and a script that runs it and plots the results. The numbers in this page " +"come from running them with the current code." +msgstr "" +"La cartella ``examples/`` contiene tre modelli che girano dall'inizio alla fine, " +"ciascuno con i propri dati di ingresso e uno script che lo esegue e traccia i " +"risultati. I numeri di questa pagina provengono dalla loro esecuzione con il codice " +"attuale." + +msgid "Folder" +msgstr "Cartella" + +msgid "What it shows" +msgstr "Cosa mostra" + +msgid "Size" +msgstr "Dimensione" + +msgid "Time" +msgstr "Tempo" + +msgid "``example1_clamped_beam/``" +msgstr "" + +msgid "A beam clamped at both ends and loaded with a force at mid-span" +msgstr "Una trave incastrata a entrambe le estremità e caricata con una forza in mezzeria" + +msgid "3,086 nodes" +msgstr "3,086 nodi" + +msgid "about 35 s" +msgstr "circa 35 s" + +msgid "``tension_101/``" +msgstr "" + +msgid "A small prism under a uniaxial load, with damage and every output format" +msgstr "Un piccolo prisma sotto carico uniassiale, con danno e tutti i formati di uscita" + +msgid "74 nodes" +msgstr "74 nodi" + +msgid "about 6 s" +msgstr "circa 6 s" + +msgid "``beam_102/``" +msgstr "" + +msgid "The four-point bending beam of the paper (a demo of its first 50 steps)" +msgstr "" +"La trave a flessione su quattro punti dell'articolo (una dimostrazione dei suoi primi" +" 50 passi)" + +msgid "166,961 nodes" +msgstr "166,961 nodi" + +msgid "about 30 s for 50 steps" +msgstr "circa 30 s per 50 passi" + +msgid "" +"Start with ``tension_101`` to learn the interface and with ``example1_clamped_beam`` " +"to see a model loaded with a force, described by a case file and checked against the " +"original code." +msgstr "" +"Iniziare con ``tension_101`` per imparare l'interfaccia e con " +"``example1_clamped_beam`` per vedere un modello caricato con una forza, descritto da " +"un file di caso e verificato rispetto al codice originale." + +msgid "Running an example" +msgstr "Eseguire un esempio" + +msgid "From MATLAB, from any folder:" +msgstr "Da MATLAB, da qualsiasi cartella:" + +#, python-format +msgid "" +">> run('examples/example1_clamped_beam/runClampedBeam.m') % script: run and" +" plot\n" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % from the case " +"file" +msgstr "" +">> run('examples/example1_clamped_beam/runClampedBeam.m') % script: esegue " +"e traccia\n" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % dal file di caso" + +msgid "" +"The two beam examples also have a ``case.ldem``: the same model in the readable case-" +"file format (see :doc:`usage`), generated from the ``DATA0.DAT`` of the original " +"program and giving the same parameters. ``ldem.check`` shows what a case file would " +"simulate without running it." +msgstr "" +"I due esempi di trave hanno anche un ``case.ldem``: lo stesso modello nel formato " +"leggibile del file di caso (vedi :doc:`usage`), generato dal ``DATA0.DAT`` del " +"programma originale e che dà gli stessi parametri. ``ldem.check`` mostra cosa " +"simulerebbe un file di caso senza eseguirlo." + +msgid "" +"The scripts write their files to a folder ``output`` next to the script (ignored by " +"git), or to ``outputFolder`` if that variable already exists:" +msgstr "" +"Gli script scrivono i loro file in una cartella ``output`` accanto allo script " +"(ignorata da git), o in ``outputFolder`` se quella variabile esiste già:" + +msgid "" +"``results.mat``: one struct, ``results``, with everything that was recorded. Load it " +"with ``data = load('results.mat'); results = data.results;``." +msgstr "" +"``results.mat``: una struttura, ``results``, con tutto ciò che è stato registrato. Si" +" carica con ``data = load('results.mat'); results = data.results;``." + +msgid "``snapshot_0000.mac``, ...: ANSYS macro files of the deformed lattice." +msgstr "``snapshot_0000.mac``, ...: file macro di ANSYS del reticolo deformato." + +msgid "" +"``snapshot_0000.vtu``, ... and ``snapshots.pvd``: open ``snapshots.pvd`` in `ParaView" +" `_ to see the damage evolve in time." +msgstr "" +"``snapshot_0000.vtu``, ... e ``snapshots.pvd``: aprire ``snapshots.pvd`` in `ParaView" +" `_ per vedere il danno evolvere nel tempo." + +msgid "Example 1: beam clamped at both ends" +msgstr "Esempio 1: trave incastrata a entrambe le estremità" + +msgid "" +"A small beam of 5 x 5 x 50 modules of 1 mm, clamped at both ends and loaded at mid-" +"span with a force that grows during 0.35 ms and then stays constant. It is the model " +"of Rodrigo (branch ``dev_rodrigo``) and the first test loaded with a force instead of" +" a displacement (``ldem.scenarios.ClampedBeam``, test 103)." +msgstr "" +"Una piccola trave di 5 x 5 x 50 moduli da 1 mm, incastrata a entrambe le estremità e " +"caricata in mezzeria con una forza che cresce per 0.35 ms e poi resta costante. È il " +"modello di Rodrigo (ramo ``dev_rodrigo``) e la prima prova caricata con una forza " +"invece che con uno spostamento (``ldem.scenarios.ClampedBeam``, prova 103)." + +msgid "The model" +msgstr "Il modello" + +msgid "Part" +msgstr "Parte" + +msgid "Value" +msgstr "Valore" + +msgid "Geometry" +msgstr "Geometria" + +msgid "" +"5 x 5 x 50 modules of 1 mm (a prism of 5 x 5 x 50 mm, axis along z), with 3,086 " +"nodes, 18,085 bars and a mass of 1.875 g" +msgstr "" +"5 x 5 x 50 moduli da 1 mm (un prisma di 5 x 5 x 50 mm, asse lungo z), con 3,086 nodi," +" 18,085 barre e una massa di 1.875 g" + +msgid "Supports" +msgstr "Appoggi" + +msgid "" +"The centre nodes of the first and of the last layer of modules (z = 0.5 and z = 49.5 " +"modules) are clamped: x, y and z held" +msgstr "" +"I nodi centrali del primo e dell'ultimo strato di moduli (z = 0.5 e z = 49.5 moduli) " +"sono incastrati: x, y e z bloccati" + +msgid "Load" +msgstr "Carico" + +msgid "" +"The 5 centre nodes of the line at mid-span (z = 24.5 modules, y = 0.5 modules) carry " +"a force in +y of ``1000 N/s * min(t, 0.35 ms)`` each: 0.35 N per node, 1.75 N in " +"total" +msgstr "" +"I 5 nodi centrali della linea in mezzeria (z = 24.5 moduli, y = 0.5 moduli) portano " +"ciascuno una forza in +y di ``1000 N/s * min(t, 0.35 ms)``: 0.35 N per nodo, 1.75 N " +"in totale" + +msgid "Material" +msgstr "Materiale" + +msgid "" +"E = 3.87 GPa, Poisson's ratio 0.25, density 1500 kg/m\\ :sup:`3`, fracture energy 0.5" +" N/m, critical distance 4.5 mm; mass-proportional damping of 2500 1/s" +msgstr "" +"E = 3.87 GPa, coefficiente di Poisson 0.25, densità 1500 kg/m\\ :sup:`3`, energia di " +"frattura 0.5 N/m, distanza critica 4.5 mm; smorzamento proporzionale alla massa di " +"2500 1/s" + +msgid "Scatter" +msgstr "Dispersione" + +msgid "" +"One multiplier of the critical strain per bar, read from a file (shared with " +"``beam_102``)" +msgstr "" +"Un moltiplicatore della deformazione critica per barra, letto da un file (condiviso " +"con ``beam_102``)" + +#, python-format +msgid "2.8 ms in 8000 steps of 0.35 us (65 % of the critical step)" +msgstr "2.8 ms in 8000 passi da 0.35 us (65 % del passo critico)" + +msgid "Recorded" +msgstr "Registrato" + +msgid "" +"Control nodes 2441 (a loaded node) and 884 (a grid node at mid-span); tracked bar " +"14398" +msgstr "" +"Nodi di controllo 2441 (un nodo caricato) e 884 (un nodo d'angolo in mezzeria); barra" +" seguita 14398" + +msgid "" +"The original input file listed five control nodes, but nodes 6870 and 14398 do not " +"exist in this 3,086-node mesh, so the input keeps 2441 and 884. The tracked bar is " +"14398, as in the original." +msgstr "" +"Il file di ingresso originale elencava cinque nodi di controllo, ma i nodi 6870 e " +"14398 non esistono in questa mesh di 3,086 nodi, quindi l'ingresso mantiene 2441 e " +"884. La barra seguita è la 14398, come nell'originale." + +msgid "Files" +msgstr "File" + +msgid "File" +msgstr "File" + +msgid "Purpose" +msgstr "Scopo" + +msgid "``case.ldem``" +msgstr "" + +msgid "The model as a case file: run it with ``ldem.run``" +msgstr "Il modello come file di caso: si esegue con ``ldem.run``" + +msgid "``runClampedBeam.m``" +msgstr "" + +msgid "" +"Reads ``DATA0.DAT``, runs the simulation and plots the force on the clamped ends, the" +" vertical displacement of the control nodes and the energies" +msgstr "" +"Legge ``DATA0.DAT``, esegue la simulazione e traccia la forza alle estremità " +"incastrate, lo spostamento verticale dei nodi di controllo e le energie" + +msgid "``DATA0.DAT``" +msgstr "" + +msgid "The parameters in the format of the original program (``TEST 103``)" +msgstr "I parametri nel formato del programma originale (``TEST 103``)" + +msgid "" +"The scenario and the load are the lines of the ``[scenario]`` section of " +"``case.ldem``:" +msgstr "Lo scenario e il carico sono le righe della sezione ``[scenario]`` di ``case.ldem``:" + +msgid "" +"[scenario]\n" +"type = \"clamped_beam\"\n" +"force_rate = 1000 N/s\n" +"ramp_time = 0.35 ms\n" +"load_position = \"midspan\"\n" +"load_height = 0.5 modules" +msgstr "" + +msgid "" +"The same test can be written without a scenario class, with supports and loads. It " +"gives the same results as ``ldem.scenarios.ClampedBeam`` (the tests check it):" +msgstr "" +"La stessa prova si può scrivere senza una classe di scenario, con appoggi e carichi. " +"Dà gli stessi risultati di ``ldem.scenarios.ClampedBeam`` (i test lo verificano):" + +msgid "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"first end\"\n" +"z = 0.5\n" +"fix = [\"x\", \"y\", \"z\"]\n" +"reaction = true\n" +"\n" +"[[support]]\n" +"name = \"last end\"\n" +"z = \"max - 0.5\"\n" +"fix = [\"x\", \"y\", \"z\"]\n" +"reaction = true\n" +"\n" +"[[load]]\n" +"name = \"line at mid-span\"\n" +"y = 0.5\n" +"z = \"mid - 0.5\"\n" +"direction = \"y\"\n" +"type = \"force\"\n" +"time_function = \"ramp\"\n" +"rate = 1000 N/s\n" +"until = 0.35 ms" +msgstr "" + +msgid "Reading the results" +msgstr "Leggere i risultati" + +#, python-format +msgid "" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem', " +"OutputFolder=tempname);\n" +">> y0 = results.mesh.nodes0(results.params.controlNodes, 2).';\n" +">> dy = results.controlNodes.displacement(:, :, 2) - y0; % vertical displacement " +"[m]\n" +">> results.reactions.force(end, :) % force on the clamped " +"ends [N]\n" +">> ldem.post.plotReaction(results);\n" +">> ldem.post.plotEnergy(results);" +msgstr "" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem', " +"OutputFolder=tempname);\n" +">> y0 = results.mesh.nodes0(results.params.controlNodes, 2).';\n" +">> dy = results.controlNodes.displacement(:, :, 2) - y0; % spostamento verticale " +"[m]\n" +">> results.reactions.force(end, :) % forza alle estremità " +"incastrate [N]\n" +">> ldem.post.plotReaction(results);\n" +">> ldem.post.plotEnergy(results);" + +msgid "What you should see" +msgstr "Cosa si dovrebbe vedere" + +msgid "" +"Force carried by the clamped ends. It rises with the load, overshoots to 1.94 N and " +"settles at the total applied force." +msgstr "" +"Forza sopportata dalle estremità incastrate. Cresce con il carico, supera fino a 1.94" +" N e si stabilizza sulla forza totale applicata." + +msgid "" +"Vertical displacement of the two control nodes: a peak of 6.7 um at 0.46 ms and about" +" 6.3 um at the end." +msgstr "" +"Spostamento verticale dei due nodi di controllo: un picco di 6.7 um a 0.46 ms e circa" +" 6.3 um alla fine." + +msgid "Energies. The external work equals the sum of the internal energies." +msgstr "Energie. Il lavoro esterno è uguale alla somma delle energie interne." + +msgid "" +"The reaction settles at 1.75 N, the 1.75 N applied in total: the beam is in " +"equilibrium at the end. The overshoot (1.94 N) and the oscillation are the dynamic " +"response, which the damping removes." +msgstr "" +"La reazione si stabilizza a 1.75 N, gli 1.75 N applicati in totale: la trave è in " +"equilibrio alla fine. Il superamento (1.94 N) e l'oscillazione sono la risposta " +"dinamica, che lo smorzamento elimina." + +msgid "" +"With these values the beam stays elastic: at the end 18,085 bars are intact and none " +"is damaged or broken." +msgstr "" +"Con questi valori la trave resta elastica: alla fine 18,085 barre sono intatte e " +"nessuna è danneggiata o rotta." + +msgid "" +"The energy balance closes: the external work of 5.76 uJ is the elastic energy (5.48 " +"uJ) plus the energy dissipated by damping (0.28 uJ); the kinetic energy is about zero" +" and the balance is below 1e-13 J." +msgstr "" +"Il bilancio energetico si chiude: il lavoro esterno di 5.76 uJ è l'energia elastica " +"(5.48 uJ) più l'energia dissipata dallo smorzamento (0.28 uJ); l'energia cinetica è " +"quasi zero e il bilancio è inferiore a 1e-13 J." + +msgid "Try other values" +msgstr "Provare altri valori" + +msgid "" +"Every key of the case file can be changed, or swept without editing the file (see " +":doc:`usage`):" +msgstr "" +"Ogni chiave del file di caso si può cambiare, o scansionare senza modificare il file " +"(vedi :doc:`usage`):" + +#, python-brace-format +msgid "" +">> summary = ldem.sweep('examples/example1_clamped_beam/case.ldem', ...\n" +" Vary = {'scenario.force_rate', [\"10 kN/s\" \"30 kN/s\" \"100 kN/s\"]}, " +"Formats = \"mat\");" +msgstr "" + +msgid "" +"With the original value (1 kN/s) no bar is damaged. Ten times more force already " +"breaks the beam; each run takes about 50 s:" +msgstr "" +"Con il valore originale (1 kN/s) nessuna barra si danneggia. Con una forza dieci " +"volte maggiore la trave si rompe già; ogni esecuzione dura circa 50 s:" + +msgid "Force rate" +msgstr "Velocità della forza" + +msgid "Damaged bars (including broken)" +msgstr "Barre danneggiate (comprese le rotte)" + +msgid "Broken bars" +msgstr "Barre rotte" + +msgid "10 kN/s" +msgstr "" + +msgid "5,630" +msgstr "" + +msgid "3,584" +msgstr "" + +msgid "30 kN/s" +msgstr "" + +msgid "6,074" +msgstr "" + +msgid "3,579" +msgstr "" + +msgid "100 kN/s" +msgstr "" + +msgid "4,760" +msgstr "" + +msgid "2,783" +msgstr "" + +msgid "" +"After the failure the loaded nodes keep being pushed by the force and move freely, so" +" the displacements of these runs are not meaningful; the damage counts are. Each run " +"has its own folder (``run_001``, ...) with its results and its resolved " +"``case.ldem``, and the table is also saved as ``sweep_summary.csv``." +msgstr "" +"Dopo la rottura, i nodi caricati continuano a essere spinti dalla forza e si muovono " +"liberamente, quindi gli spostamenti di queste esecuzioni non hanno significato; i " +"conteggi del danno sì. Ogni esecuzione ha la propria cartella (``run_001``, ...) con " +"i suoi risultati e il suo ``case.ldem`` risolto, e la tabella viene salvata anche " +"come ``sweep_summary.csv``." + +msgid "" +"Other changes to try in ``case.ldem``: ``law = \"linear_elastic\"`` (no damage at " +"all), ``type = \"generated\"`` with a ``cv`` in ``[material.scatter]`` to generate " +"the random field in memory instead of reading it, or ``type = \"none\"`` to remove " +"the scatter." +msgstr "" +"Altre modifiche da provare in ``case.ldem``: ``law = \"linear_elastic\"`` (nessun " +"danno), ``type = \"generated\"`` con un ``cv`` in ``[material.scatter]`` per generare" +" il campo casuale in memoria invece di leggerlo, oppure ``type = \"none\"`` per " +"eliminare la dispersione." + +msgid "Example: uniaxial prism" +msgstr "Esempio: prisma uniassiale" + +msgid "" +"``examples/tension_101/runTension.m`` runs a prism of 5 x 2 x 2 modules of 3 mm (74 " +"nodes, 313 bars) under the uniaxial test (test 101): the centre nodes of the last " +"column move along x with a prescribed velocity of 4 mm/s while those of the first " +"column are held. It is the best place to start: it has no input file, the model is " +"described in the script with ``ldem.Parameters``, and it writes every kind of output." +msgstr "" +"``examples/tension_101/runTension.m`` esegue un prisma di 5 x 2 x 2 moduli da 3 mm " +"(74 nodi, 313 barre) sotto la prova uniassiale (prova 101): i nodi centrali " +"dell'ultima colonna si muovono lungo x con una velocità imposta di 4 mm/s mentre " +"quelli della prima colonna sono bloccati. È il posto migliore da cui iniziare: non ha" +" un file di ingresso, il modello è descritto nello script con ``ldem.Parameters`` e " +"scrive ogni tipo di uscita." + +msgid "" +"E = 32 GPa, Poisson's ratio 0.25, density 2000 kg/m\\ :sup:`3`; a low fracture energy" +" of 0.1 N/m on purpose, so that bars soften and break" +msgstr "" +"E = 32 GPa, coefficiente di Poisson 0.25, densità 2000 kg/m\\ :sup:`3`; un'energia di" +" frattura bassa di 0.1 N/m di proposito, perché le barre si ammorbidiscano e si " +"rompano" + +msgid "0.2 ms in 1000 steps of 0.2 us" +msgstr "0.2 ms in 1000 passi da 0.2 us" + +msgid "Output" +msgstr "Uscita" + +msgid "" +"Snapshots (ANSYS and VTK) every 250 steps, control nodes and energies every 10 steps," +" no tracked bar" +msgstr "" +"Istantanee (ANSYS e VTK) ogni 250 passi, nodi di controllo ed energie ogni 10 passi, " +"senza barra seguita" + +#, python-format +msgid "" +"At the end 251 bars are intact, 58 are damaged and 4 are broken. The external work is" +" 24.7 uJ: 22.5 uJ of elastic energy, 2.2 uJ dissipated by damage and 0.03 uJ by " +"damping; the balance is 0.01 % of the external work." +msgstr "" +"Alla fine 251 barre sono intatte, 58 danneggiate e 4 rotte. Il lavoro esterno è di " +"24.7 uJ: 22.5 uJ di energia elastica, 2.2 uJ dissipati dal danno e 0.03 uJ dallo " +"smorzamento; il bilancio è lo 0.01 % del lavoro esterno." + +msgid "Energies of the uniaxial prism." +msgstr "Energie del prisma uniassiale." + +msgid "" +"With the sign convention of the original code a positive ``loadingVelocity`` moves " +"the loaded face toward the fixed one, that is, it compresses the prism; use a " +"negative value to pull it (see ``ldem.scenarios.UniaxialTension``)." +msgstr "" +"Con la convenzione dei segni del codice originale, un ``loadingVelocity`` positivo " +"muove la faccia caricata verso quella fissa, cioè comprime il prisma; usare un valore" +" negativo per tirarlo (vedi ``ldem.scenarios.UniaxialTension``)." + +msgid "Example: four-point bending beam" +msgstr "Esempio: trave a flessione su quattro punti" + +msgid "" +"``examples/beam_102/runBeam.m`` reads the input of the beam of the paper (test 102, " +"``ldem.scenarios.FourPointBending``): 100 x 40 x 20 modules of 3 mm (300 x 120 x 60 " +"mm), 166,961 nodes and 1,126,960 bars. The beam rests on two supports 4.5 modules " +"from its ends and two load points 33.5 modules from its ends push its top face down " +"with a prescribed velocity of 4 mm/s. The material is E = 32 GPa, density 2000 kg/m\\" +" :sup:`3`, fracture energy 50 N/m, critical distance 28 mm, with a random field of " +"the critical strain read from a file." +msgstr "" +"``examples/beam_102/runBeam.m`` legge l'ingresso della trave dell'articolo (prova " +"102, ``ldem.scenarios.FourPointBending``): 100 x 40 x 20 moduli da 3 mm (300 x 120 x " +"60 mm), 166,961 nodi e 1,126,960 barre. La trave poggia su due appoggi a 4.5 moduli " +"dalle sue estremità e due punti di carico a 33.5 moduli dalle sue estremità spingono " +"la faccia superiore verso il basso con una velocità imposta di 4 mm/s. Il materiale " +"ha E = 32 GPa, densità 2000 kg/m\\ :sup:`3`, energia di frattura 50 N/m, distanza " +"critica 28 mm, con un campo casuale della deformazione critica letto da un file." + +msgid "" +"The real simulation has 150,000 steps (0.03 s in steps of 0.2 us) and needs roughly " +"20 hours on a laptop (about 0.5 s per step). The script therefore runs only the first" +" 50 steps: it builds the complete model (about 20 s) and shows that the input is read" +" and the model runs; the plotted reaction is only that of the start of the test. " +"Change ``nStepsDemo`` at the top of the script, or remove the ``totalTime`` override," +" for the full run." +msgstr "" +"La simulazione reale ha 150,000 passi (0.03 s in passi da 0.2 us) e richiede circa 20" +" ore su un portatile (circa 0.5 s per passo). Per questo lo script esegue solo i " +"primi 50 passi: costruisce il modello completo (circa 20 s) e mostra che l'ingresso " +"viene letto e il modello gira; la reazione tracciata è solo quella dell'inizio della " +"prova. Cambiare ``nStepsDemo`` all'inizio dello script, o togliere la sostituzione di" +" ``totalTime``, per l'esecuzione completa." + +msgid "The same parameters as a case file (``ldem.io.readCase``, ``ldem.run``)" +msgstr "Gli stessi parametri come file di caso (``ldem.io.readCase``, ``ldem.run``)" + +msgid "Parameters in the format of the original program (``ldem.Parameters.fromFile``)" +msgstr "Parametri nel formato del programma originale (``ldem.Parameters.fromFile``)" + +msgid "``arquivo_3lc_rnao_cv05``" +msgstr "" + +msgid "" +"Random field applied to the critical strain of each bar (11 MB); it is also used by " +"``example1_clamped_beam``" +msgstr "" +"Campo casuale applicato alla deformazione critica di ogni barra (11 MB); è usato " +"anche da ``example1_clamped_beam``" + +msgid "``runBeam.m``" +msgstr "" + +msgid "Reads the input, runs the first 50 steps and plots the reaction force" +msgstr "Legge l'ingresso, esegue i primi 50 passi e traccia la forza di reazione" + diff --git a/docs/locale/it/LC_MESSAGES/index.po b/docs/locale/it/LC_MESSAGES/index.po new file mode 100644 index 0000000..0180b6a --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/index.po @@ -0,0 +1,34 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "User guide" +msgstr "Guida per l'utente" + +msgid "API" +msgstr "" + +msgid "LDEM-MATLAB" +msgstr "" + +msgid "Lattice Discrete Element Method (LDEM) in MATLAB." +msgstr "Metodo degli Elementi Discreti tipo Lattice (LDEM) in MATLAB." + +msgid "" +"The documentation is written in English and translated into Spanish, Portuguese and " +"Italian. Choose the language in the sidebar of any page." +msgstr "" +"La documentazione è scritta in inglese e tradotta in spagnolo, portoghese e italiano." +" Scegliere la lingua nella barra laterale di qualsiasi pagina." + diff --git a/docs/locale/it/LC_MESSAGES/installation.po b/docs/locale/it/LC_MESSAGES/installation.po new file mode 100644 index 0000000..4379269 --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/installation.po @@ -0,0 +1,70 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Installation" +msgstr "Installazione" + +msgid "" +"Requirements: MATLAB R2022b or newer (developed and tested on R2023b). The package " +"itself uses the ``arguments`` block and name=value syntax; the test suite and " +"``buildtool`` need R2022b. No toolbox is required." +msgstr "" +"Requisiti: MATLAB R2022b o successivo (sviluppato e testato su R2023b). Il pacchetto " +"usa il blocco ``arguments`` e la sintassi nome=valore; la suite di test e " +"``buildtool`` richiedono R2022b. Non serve alcun toolbox." + +msgid "" +"git clone ldem-matlab\n" +"cd ldem-matlab" +msgstr "" +"git clone ldem-matlab\n" +"cd ldem-matlab" + +msgid ">> setup_path" +msgstr "" + +msgid "Check the installation with the fast tests:" +msgstr "Verificare l'installazione con i test rapidi:" + +msgid ">> buildtool test" +msgstr "" + +msgid "Developer tasks (``buildtool`` is run from the repository root):" +msgstr "Attività per sviluppatori (``buildtool`` si esegue dalla radice del repository):" + +#, python-format +msgid "" +">> buildtool % static analysis + fast tests (the default)\n" +">> buildtool check % Code Analyzer only\n" +">> buildtool testAll % all tests, including the slow ones\n" +">> buildtool docs % build this documentation (needs Python)\n" +">> buildtool clean % delete generated files" +msgstr "" +">> buildtool % analisi statica + test rapidi (predefinito)\n" +">> buildtool check % solo l'analizzatore di codice\n" +">> buildtool testAll % tutti i test, compresi quelli lenti\n" +">> buildtool docs % costruire questa documentazione (richiede Python)\n" +">> buildtool clean % eliminare i file generati" + +msgid "" +"``buildtool test`` writes ``test-results/results.xml`` (JUnit) and ``code-" +"coverage/coverage.xml`` (Cobertura)." +msgstr "" +"``buildtool test`` scrive ``test-results/results.xml`` (JUnit) e ``code-" +"coverage/coverage.xml`` (Cobertura)." + +msgid "To build this documentation without MATLAB see :doc:`docs`." +msgstr "Per costruire questa documentazione senza MATLAB vedi :doc:`docs`." + diff --git a/docs/locale/it/LC_MESSAGES/introduction.po b/docs/locale/it/LC_MESSAGES/introduction.po new file mode 100644 index 0000000..40c785e --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/introduction.po @@ -0,0 +1,79 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Introduction" +msgstr "Introduzione" + +msgid "" +"The **Lattice Discrete Element Method (LDEM)** models a continuum as a regular " +"lattice of nodes connected by bars arranged in cubic modules (edges plus diagonals). " +"Nodal masses are lumped, bar constitutive laws include damage/fracture, and the " +"equations of motion are integrated with an explicit central-difference scheme. " +"Energies (external, kinetic, elastic, dissipated) are tracked at every step." +msgstr "" +"Il **Metodo degli Elementi Discreti a Reticolo (LDEM)** modella un continuo come un " +"reticolo regolare di nodi collegati da barre disposte in moduli cubici (spigoli più " +"diagonali). Le masse sono concentrate nei nodi, le leggi costitutive delle barre " +"includono danno/frattura e le equazioni del moto sono integrate con uno schema " +"esplicito alle differenze centrali. Le energie (esterna, cinetica, elastica, " +"dissipata) sono monitorate a ogni passo." + +msgid "Main parts of the ``ldem`` package (see :doc:`api/index`):" +msgstr "Parti principali del pacchetto ``ldem`` (vedi :doc:`api/index`):" + +msgid "" +"``ldem.Parameters`` / ``ldem.io.readCase`` / ``ldem.io.readInputFile`` – validated " +"input data (case files and the legacy ``DATA0.DAT``)." +msgstr "" +"``ldem.Parameters`` / ``ldem.io.readCase`` / ``ldem.io.readInputFile`` – dati di " +"ingresso validati (file di caso e il ``DATA0.DAT`` originale)." + +msgid "``ldem.run`` / ``ldem.sweep`` / ``ldem.check`` – run, sweep and check a case file." +msgstr "" +"``ldem.run`` / ``ldem.sweep`` / ``ldem.check`` – eseguire, scansionare e controllare " +"un file di caso." + +msgid "``ldem.mesh`` – nodes, bars, masses and bar geometry." +msgstr "``ldem.mesh`` – nodi, barre, masse e geometria delle barre." + +msgid "``ldem.material`` – bar stiffness, critical strain and the bilinear damage law." +msgstr "" +"``ldem.material`` – rigidezza delle barre, deformazione critica e legge bilineare di " +"danno." + +msgid "``ldem.scenarios`` – supports, loads and reactions of each test." +msgstr "``ldem.scenarios`` – vincoli, carichi e reazioni di ogni prova." + +msgid "``ldem.solver`` – time integration and energy balance." +msgstr "``ldem.solver`` – integrazione nel tempo e bilancio energetico." + +msgid "" +"``ldem.runSimulation`` – the whole simulation, with ``results.mat``, ANSYS and VTK " +"output." +msgstr "" +"``ldem.runSimulation`` – la simulazione completa, con uscita ``results.mat``, ANSYS e" +" VTK." + +msgid "" +"The routines of the original program (``ini_DEM3``, ``read_dat0``, ``RMEC``, " +"``BOUND``, ``CALOAD``, ``ENERG2``, ...) are kept in the git history under the tag " +"``legacy-reference``; the ``Legacy:`` line of each help text names the routine it " +"replaces." +msgstr "" +"Le routine del programma originale (``ini_DEM3``, ``read_dat0``, ``RMEC``, ``BOUND``," +" ``CALOAD``, ``ENERG2``, ...) sono conservate nella cronologia di git, con il tag " +"``legacy-reference``; la riga ``Legacy:`` di ogni guida indica la routine che " +"sostituisce." + diff --git a/docs/locale/it/LC_MESSAGES/model.po b/docs/locale/it/LC_MESSAGES/model.po new file mode 100644 index 0000000..f1418c8 --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/model.po @@ -0,0 +1,240 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Building a different model" +msgstr "Costruire un modello diverso" + +msgid "" +"A model is defined by three things: the **geometry** of the lattice, the **material**" +" and the **test** (supports and loads). The first two are parameters; the third is a " +"*scenario* class. You can change any of them without touching the solver." +msgstr "" +"Un modello è definito da tre cose: la **geometria** del reticolo, il **materiale** e " +"la **prova** (vincoli e carichi). Le prime due sono parametri; la terza è una classe " +"*scenario*. Ciascuna si può cambiare senza toccare il solver." + +msgid "1. Change the geometry and the material" +msgstr "1. Cambiare la geometria e il materiale" + +msgid "Everything is a property of ``ldem.Parameters``:" +msgstr "Tutto è una proprietà di ``ldem.Parameters``:" + +#, python-format +msgid "" +">> params = ldem.Parameters(testId=101, ...\n" +" moduleLength=0.002, ... % edge of the cubic module [m]\n" +" nModules=[21 6 6], ... % nodes along x, y and z\n" +" youngModulus=30e9, density=2400, poissonRatio=0.2, ...\n" +" fractureEnergy=80, criticalDistance=0.02, ...\n" +" meshPerturbation=0.02); % optional irregular mesh" +msgstr "" +">> params = ldem.Parameters(testId=101, ...\n" +" moduleLength=0.002, ... % spigolo del modulo cubico [m]\n" +" nModules=[21 6 6], ... % nodi in x, y e z\n" +" youngModulus=30e9, density=2400, poissonRatio=0.2, ...\n" +" fractureEnergy=80, criticalDistance=0.02, ...\n" +" meshPerturbation=0.02); % mesh irregolare (opzionale)" + +msgid "" +"``nModules = [M N L]`` is the number of grid nodes along each axis, so the prism has " +"``(M-1)*(N-1)*(L-1)`` modules." +msgstr "" +"``nModules = [M N L]`` è il numero di nodi della griglia lungo ogni asse, quindi il " +"prisma ha ``(M-1)*(N-1)*(L-1)`` moduli." + +msgid "" +"``randomFieldFile`` multiplies the critical strain of each bar by a value read from a" +" text file (a random field of the material strength)." +msgstr "" +"``randomFieldFile`` moltiplica la deformazione critica di ogni barra per un valore " +"letto da un file di testo (campo casuale della resistenza)." + +msgid "" +"``randomFieldCv`` generates that random field in memory instead, with no file: " +"Weibull values with mean 1 and that coefficient of variation on a grid of poles " +"spaced ``randomFieldCorrelationLength`` module lengths apart (default 3), " +"interpolated to each bar; ``randomFieldSeed`` fixes the random numbers. The value of " +"each bar is kept in ``results.barProps.randomField``." +msgstr "" +"``randomFieldCv`` genera invece quel campo casuale in memoria, senza file: valori di " +"Weibull con media 1 e quel coefficiente di variazione su una griglia di poli " +"distanziati ``randomFieldCorrelationLength`` lunghezze di modulo (3 per default), " +"interpolati su ogni barra; ``randomFieldSeed`` fissa i numeri casuali. Il valore di " +"ogni barra resta in ``results.barProps.randomField``." + +msgid "" +"``dt`` must be below ``params.criticalTimeStep``; ``Parameters`` rejects an unstable " +"value and says so." +msgstr "" +"``dt`` deve essere minore di ``params.criticalTimeStep``; ``Parameters`` rifiuta un " +"valore instabile e ne spiega il motivo." + +msgid "" +"The same data can come from a case file (``ldem.io.readCase``, see :doc:`usage`) or " +"from an input file in the format of the original program with " +"``ldem.Parameters.fromFile(\"DATA0.DAT\", ...)``; extra name=value pairs override the" +" file. The mesh can be built and inspected before running anything:" +msgstr "" +"Gli stessi dati possono provenire da un file di caso (``ldem.io.readCase``, vedi " +":doc:`usage`) o da un file di ingresso nel formato del programma originale: " +"``ldem.Parameters.fromFile(\"DATA0.DAT\", ...)``; le coppie nome=valore aggiuntive " +"sostituiscono quelle del file. La mesh può essere costruita e ispezionata prima di " +"eseguire qualsiasi cosa:" + +#, python-format +msgid "" +">> mesh = ldem.mesh.buildMesh(params);\n" +">> fprintf(\"%d nodes, %d bars\\n\", size(mesh.nodes0, 1), size(mesh.bars, 1));" +msgstr "" +">> mesh = ldem.mesh.buildMesh(params);\n" +">> fprintf(\"%d nodi, %d barre\\n\", size(mesh.nodes0, 1), size(mesh.bars, 1));" + +msgid "2. Change the test: write a scenario" +msgstr "2. Cambiare la prova: scrivere uno scenario" + +msgid "" +"A *scenario* says which degrees of freedom are fixed, how the load is applied at " +"every time step and which reaction is reported. The solver never checks the test " +"number, it only asks the scenario. To model a new test, create a subclass of " +"``ldem.scenarios.Scenario`` in ``src/+ldem/+scenarios/``." +msgstr "" +"Uno *scenario* dice quali gradi di libertà sono bloccati, come viene applicato il " +"carico a ogni passo di tempo e quale reazione viene riportata. Il solver non " +"controlla mai il numero della prova: lo chiede allo scenario. Per modellare una prova" +" nuova si crea una sottoclasse di ``ldem.scenarios.Scenario`` in " +"``src/+ldem/+scenarios/``." + +msgid "" +"The example below is a cantilever beam along :math:`z`: the first layer of centre " +"nodes is clamped and a force that grows linearly is applied in :math:`y` at the free " +"end." +msgstr "" +"L'esempio è una trave a mensola lungo :math:`z`: il primo strato di nodi centrali è " +"incastrato e all'estremità libera si applica in :math:`y` una forza che cresce " +"linearmente." + +#, python-format +msgid "" +"classdef Cantilever < ldem.scenarios.Scenario\n" +" properties (Constant)\n" +" testId = 104 % new number, unique\n" +" end\n" +" properties\n" +" forceRate (1,1) double = 500 % [N/s] on each loaded node\n" +" end\n" +" methods\n" +" function fixed = fixedDofs(~, nodes0, params)\n" +" z = nodes0(:, 3);\n" +" atStart = abs(z - 0.5*params.moduleLength) < 0.01*params.moduleLength;\n" +" fixed = false(size(nodes0));\n" +" fixed(atStart, :) = true; % x, y and z held\n" +" end\n" +" function state = applyLoads(obj, state, mesh, params)\n" +" L1 = params.nModules(3) - 1;\n" +" z = mesh.nodes0(:, 3);\n" +" atEnd = abs(z - (L1 - 0.5)*params.moduleLength) < " +"0.01*params.moduleLength;\n" +" state.appliedForce(:) = 0;\n" +" state.appliedForce(atEnd, 2) = obj.forceRate * state.time;\n" +" end\n" +" end\n" +"end" +msgstr "" +"classdef Cantilever < ldem.scenarios.Scenario\n" +" properties (Constant)\n" +" testId = 104 % numero nuovo, univoco\n" +" end\n" +" properties\n" +" forceRate (1,1) double = 500 % [N/s] su ogni nodo caricato\n" +" end\n" +" methods\n" +" function fixed = fixedDofs(~, nodes0, params)\n" +" z = nodes0(:, 3);\n" +" atStart = abs(z - 0.5*params.moduleLength) < 0.01*params.moduleLength;\n" +" fixed = false(size(nodes0));\n" +" fixed(atStart, :) = true; % x, y e z bloccati\n" +" end\n" +" function state = applyLoads(obj, state, mesh, params)\n" +" L1 = params.nModules(3) - 1;\n" +" z = mesh.nodes0(:, 3);\n" +" atEnd = abs(z - (L1 - 0.5)*params.moduleLength) < " +"0.01*params.moduleLength;\n" +" state.appliedForce(:) = 0;\n" +" state.appliedForce(atEnd, 2) = obj.forceRate * state.time;\n" +" end\n" +" end\n" +"end" + +msgid "Rules to follow:" +msgstr "Regole:" + +msgid "" +"``fixedDofs`` returns an ``nNodes``-by-3 logical matrix, true where the node cannot " +"move (``1 = x``, ``2 = y``, ``3 = z``)." +msgstr "" +"``fixedDofs`` restituisce una matrice logica ``nNodes`` per 3, vera dove il nodo non " +"può muoversi (``1 = x``, ``2 = y``, ``3 = z``)." + +msgid "" +"``applyLoads`` runs once per step. A **displacement-controlled** test sets " +"``state.displacement`` of the loaded nodes (see ``UniaxialTension``); a **force-" +"controlled** test sets ``state.appliedForce`` in newtons (see ``ClampedBeam``) and " +"the solver counts its work in the external energy." +msgstr "" +"``applyLoads`` viene eseguito a ogni passo. Una prova **a spostamento controllato** " +"assegna ``state.displacement`` dei nodi caricati (vedi ``UniaxialTension``); una **a " +"forza controllata** assegna ``state.appliedForce`` in newton (vedi ``ClampedBeam``) e" +" il solver ne conta il lavoro nell'energia esterna." + +msgid "Override ``reactions`` if the test reports a reaction force (default: ``NaN``)." +msgstr "" +"Ridefinire ``reactions`` se la prova riporta una forza di reazione (predefinito: " +"``NaN``)." + +msgid "" +"The centre nodes of the modules lie at half-integer multiples of ``moduleLength``; " +"select nodes with a small tolerance, never with ``==``." +msgstr "" +"I nodi centrali dei moduli si trovano a multipli semi-interi di ``moduleLength``; " +"selezionare i nodi con una piccola tolleranza, mai con ``==``." + +msgid "3. Register and run it" +msgstr "3. Registrarlo ed eseguirlo" + +msgid "Either pass the object directly, with no registration:" +msgstr "L'oggetto si può passare direttamente, senza registrare nulla:" + +msgid "" +">> scenario = ldem.scenarios.Cantilever(forceRate=1000);\n" +">> results = ldem.runSimulation(params, Scenario=scenario, ...\n" +" OutputFolder=\"output\", Formats=[\"mat\" \"vtk\"]);" +msgstr "" + +msgid "" +"or add one line to ``ldem.scenarios.registry`` so that ``testId = 104`` finds it and " +"a case file can name it with ``type``. Then add a test in ``tests/unit`` and, if it " +"is a reference case, an example in ``examples/`` (see " +"``examples/example1_clamped_beam``)." +msgstr "" +"oppure aggiungere una riga a ``ldem.scenarios.registry`` in modo che ``testId = 104``" +" lo trovi e un file di caso possa nominarlo con ``type``. Poi si aggiunge un test in " +"``tests/unit`` e, se è un caso di riferimento, un esempio in ``examples/`` (vedi " +"``examples/example1_clamped_beam``)." + +msgid "The result is the same ``results`` struct as for any other test, see :doc:`usage`." +msgstr "" +"Il risultato è la stessa struttura ``results`` di qualsiasi altra prova, vedi " +":doc:`usage`." + diff --git a/docs/locale/it/LC_MESSAGES/sphinx.po b/docs/locale/it/LC_MESSAGES/sphinx.po new file mode 100644 index 0000000..aa0ebc2 --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/sphinx.po @@ -0,0 +1,45 @@ +# User-interface texts of the theme (Furo) in it: buttons, search and page navigation. +# Kept by hand: docs/tools/update_translations.py does not touch this file. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Skip to content" +msgstr "Vai al contenuto" + +msgid "Back to top" +msgstr "Torna su" + +msgid "Next" +msgstr "Successivo" + +msgid "Previous" +msgstr "Precedente" + +msgid "Home" +msgstr "Home" + +msgid "On this page" +msgstr "In questa pagina" + +msgid "Search" +msgstr "Cerca" + +msgid "Index" +msgstr "Indice" + +msgid "Error" +msgstr "Errore" + +msgid "Please activate JavaScript to enable the search functionality." +msgstr "Attivare JavaScript per abilitare la funzione di ricerca." + diff --git a/docs/locale/it/LC_MESSAGES/usage.po b/docs/locale/it/LC_MESSAGES/usage.po new file mode 100644 index 0000000..cd599c5 --- /dev/null +++ b/docs/locale/it/LC_MESSAGES/usage.po @@ -0,0 +1,1346 @@ +# Translation of the LDEM-MATLAB documentation (it). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: it\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Usage" +msgstr "Uso" + +msgid "Run a simulation" +msgstr "Eseguire una simulazione" + +msgid "" +">> setup_path % adds src/ to the MATLAB path\n" +">> params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4, ...\n" +" fractureEnergy=0.1, ...\n" +" output=struct('snapshotEvery', 250, 'controlNodesEvery', 10, ...\n" +" 'energyEvery', 10, 'trackedBarEvery', 0));\n" +">> results = ldem.runSimulation(params, OutputFolder=\"output\", ...\n" +" Formats=[\"mat\" \"ansys\" \"vtk\"]);\n" +">> ldem.post.plotEnergy(results);" +msgstr "" +">> setup_path % aggiunge src/ al path di MATLAB\n" +">> params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4, ...\n" +" fractureEnergy=0.1, ...\n" +" output=struct('snapshotEvery', 250, 'controlNodesEvery', 10, ...\n" +" 'energyEvery', 10, 'trackedBarEvery', 0));\n" +">> results = ldem.runSimulation(params, OutputFolder=\"output\", ...\n" +" Formats=[\"mat\" \"ansys\" \"vtk\"]);\n" +">> ldem.post.plotEnergy(results);" + +msgid "" +"``ldem.Parameters`` checks every value when it is set and explains what is wrong (for" +" example an unstable time step). The complete, ready-to-run version of this script is" +" ``examples/tension_101/runTension.m``." +msgstr "" +"``ldem.Parameters`` valida ogni valore quando viene assegnato e spiega cosa non va " +"(per esempio un passo di tempo instabile). La versione completa e pronta all'uso è in" +" ``examples/tension_101/runTension.m``." + +msgid "To use an input file in the format of the original program:" +msgstr "Per usare un file di ingresso nel formato del programma originale:" + +msgid ">> params = ldem.Parameters.fromFile(\"DATA0.DAT\");" +msgstr "" + +msgid "Case files (``.ldem``)" +msgstr "File di caso (``.ldem``)" + +msgid "" +"A *case file* describes the whole model in one readable text file: named keys instead" +" of positions, units next to the numbers, comments, and the test, the random scatter " +"and the output files together. It replaces ``DATA0.DAT``." +msgstr "" +"Un *file di caso* descrive l'intero modello in un unico testo leggibile: chiavi con " +"nome invece di posizioni, unità accanto ai numeri, commenti, e la prova, la " +"dispersione casuale e i file di uscita insieme. Sostituisce ``DATA0.DAT``." + +msgid "" +"format = 1\n" +"title = \"Small tension test\"\n" +"\n" +"[mesh]\n" +"module_size = 3 mm\n" +"modules = [5, 2, 2] # cubic modules along x, y and z\n" +"\n" +"[material]\n" +"young_modulus = 32 GPa\n" +"density = 2000 kg/m3\n" +"\n" +"[time]\n" +"step = auto # 0.9 times the critical step\n" +"duration = 40 us\n" +"\n" +"[scenario]\n" +"type = \"uniaxial_tension\"\n" +"\n" +"[output]\n" +"folder = \"output\"" +msgstr "" +"format = 1\n" +"title = \"Piccola prova di trazione\"\n" +"\n" +"[mesh]\n" +"module_size = 3 mm\n" +"modules = [5, 2, 2] # moduli cubici lungo x, y e z\n" +"\n" +"[material]\n" +"young_modulus = 32 GPa\n" +"density = 2000 kg/m3\n" +"\n" +"[time]\n" +"step = auto # 0.9 volte il passo critico\n" +"duration = 40 us\n" +"\n" +"[scenario]\n" +"type = \"uniaxial_tension\"\n" +"\n" +"[output]\n" +"folder = \"output\"" + +#, python-format +msgid "" +">> ldem.io.writeTemplate(\"my_test.ldem\", \"clamped_beam\"); % a commented file to " +"edit\n" +">> ldem.check(\"my_test.ldem\") % validate and report, " +"no simulation\n" +">> results = ldem.run(\"my_test.ldem\"); % run it\n" +">> ldem.io.convertLegacyInput(\"DATA0.DAT\", \"case.ldem\"); % convert an old input" +" file" +msgstr "" +">> ldem.io.writeTemplate(\"mia_prova.ldem\", \"clamped_beam\"); % file commentato da" +" modificare\n" +">> ldem.check(\"mia_prova.ldem\") % valida e riferisce, " +"senza simulare\n" +">> results = ldem.run(\"mia_prova.ldem\"); % la esegue\n" +">> ldem.io.convertLegacyInput(\"DATA0.DAT\", \"caso.ldem\"); % converte un " +"vecchio file" + +msgid "Rules of the format:" +msgstr "Regole del formato:" + +msgid "" +"Keys are read by **name**; the order of the lines does not matter. Keys that are " +"missing take the default of ``ldem.Parameters``. Only ``scenario.type``, " +"``mesh.modules`` and ``time.duration`` are required." +msgstr "" +"Le chiavi si leggono per **nome**; l'ordine delle righe non conta. Le chiavi assenti " +"prendono il valore predefinito di ``ldem.Parameters``. Sono obbligatorie solo " +"``scenario.type``, ``mesh.modules`` e ``time.duration``." + +msgid "" +"A number may carry a **unit**: ``3.87 GPa``, ``0.35 us``, ``1500 kg/m3``, ``2 kN/s``." +" Without a unit the value is in SI. The wrong unit for the key is an error that lists" +" the valid ones." +msgstr "" +"Un numero può avere un'**unità**: ``3.87 GPa``, ``0.35 us``, ``1500 kg/m3``, ``2 " +"kN/s``. Senza unità il valore è in SI. Un'unità sbagliata per la chiave è un errore " +"che elenca quelle valide." + +msgid "" +"``#`` starts a comment, ``[section]`` opens a table, ``[[monitor.node]]`` starts the " +"next element of a repeated table, lists are written ``[5, 5, 50]``." +msgstr "" +"``#`` inizia un commento, ``[sezione]`` apre una tabella, ``[[monitor.node]]`` inizia" +" l'elemento successivo di una tabella ripetuta e le liste si scrivono ``[5, 5, 50]``." + +msgid "" +"``mesh.modules`` counts **modules**: the ``M N L`` of ``DATA0.DAT`` count nodes, one " +"more." +msgstr "" +"``mesh.modules`` conta **moduli**: gli ``M N L`` di ``DATA0.DAT`` contano nodi, uno " +"in più." + +msgid "``time.step = auto`` (or no ``step``) takes 0.9 times the critical step." +msgstr "``time.step = auto`` (o senza ``step``) prende 0.9 volte il passo critico." + +msgid "" +"Every error names the file, the line, the section and the key, and suggests the " +"closest valid name for a mistyped one." +msgstr "" +"Ogni errore indica il file, la riga, la sezione e la chiave, e suggerisce il nome " +"valido più vicino se c'è un errore di battitura." + +msgid "" +"Relative paths (the random-field file, the output folder) are relative to the case " +"file." +msgstr "" +"I percorsi relativi (file del campo casuale, cartella di uscita) sono relativi al " +"file di caso." + +msgid "A JSON file with the same structure (values with units as strings) is also read." +msgstr "Si legge anche un file JSON con la stessa struttura (i valori con unità come testo)." + +msgid "Section" +msgstr "Sezione" + +msgid "Keys" +msgstr "Chiavi" + +msgid "(top)" +msgstr "(inizio)" + +msgid "``format`` (1), ``title``, ``authors``" +msgstr "" + +msgid "``[mesh]``" +msgstr "" + +msgid "" +"``module_size``, ``modules``, ``perturbation`` (random displacement of the nodes, " +"fraction of the module), ``seed`` (of the perturbation)" +msgstr "" +"``module_size``, ``modules``, ``perturbation`` (spostamento casuale dei nodi, " +"frazione del modulo), ``seed`` (della perturbazione)" + +msgid "``[material]``" +msgstr "" + +msgid "" +"``law`` (``bilinear``, the legacy law, or ``linear_elastic``: no damage and no " +"rupture), ``young_modulus``, ``poisson_ratio``, ``density``, ``fracture_energy``, " +"``critical_distance``, ``failure_area_factor``" +msgstr "" +"``law`` (``bilinear``, la legge originale, o ``linear_elastic``: senza danno né " +"rottura), ``young_modulus``, ``poisson_ratio``, ``density``, ``fracture_energy``, " +"``critical_distance``, ``failure_area_factor``" + +msgid "``[material.scatter]``" +msgstr "" + +msgid "" +"Scatter of the critical strain of the bars. ``type = \"none\"``; ``\"file\"`` with " +"``file`` (one multiplier per bar); or ``\"generated\"`` with ``cv``, " +"``correlation_length`` (in modules) and ``seed`` (the field is computed in memory)" +msgstr "" +"Dispersione della deformazione critica delle barre. ``type = \"none\"``; ``\"file\"``" +" con ``file`` (un moltiplicatore per barra); oppure ``\"generated\"`` con ``cv``, " +"``correlation_length`` (in moduli) e ``seed`` (il campo è calcolato in memoria)" + +msgid "``[time]``" +msgstr "" + +msgid "``step`` (or ``auto``), ``duration``" +msgstr "``step`` (o ``auto``), ``duration``" + +msgid "``[damping]``" +msgstr "" + +msgid "" +"``type`` (``mass_proportional``, the legacy damping, or ``none``), ``initial``, " +"``final``, ``switch_time`` (not allowed with ``none``), ``constitutive``" +msgstr "" +"``type`` (``mass_proportional``, lo smorzamento originale, o ``none``), ``initial``, " +"``final``, ``switch_time`` (non ammessi con ``none``), ``constitutive``" + +msgid "``[scenario]``" +msgstr "" + +msgid "" +"``type`` (``uniaxial_tension``, ``four_point_bending``, ``clamped_beam`` or " +"``custom``, see below) and the properties of that scenario in snake_case, for example" +" ``force_rate``, ``ramp_time``, ``load_position`` (``\"midspan\"`` is allowed)" +msgstr "" +"``type`` (``uniaxial_tension``, ``four_point_bending``, ``clamped_beam`` o " +"``custom``, vedi sotto) e le proprietà di quello scenario in snake_case, per esempio " +"``force_rate``, ``ramp_time``, ``load_position`` (è ammesso ``\"midspan\"``)" + +msgid "``[[monitor.node]]``" +msgstr "" + +msgid "" +"One element per control node: ``id`` (node number) or ``at = [x, y, z]`` (position in" +" modules, the nearest node is used), and ``name``" +msgstr "" +"Un elemento per nodo di controllo: ``id`` (numero del nodo) oppure ``at = [x, y, z]``" +" (posizione in moduli, si usa il nodo più vicino), e ``name``" + +msgid "``[monitor.bar]``" +msgstr "" + +msgid "``tracked``: bar whose strain history is stored at every step" +msgstr "``tracked``: barra la cui storia di deformazione è salvata a ogni passo" + +msgid "``[output]``" +msgstr "" + +msgid "``folder``, ``mat``, ``ansys``, ``vtk`` (true or false)" +msgstr "``folder``, ``mat``, ``ansys``, ``vtk`` (true o false)" + +msgid "``[output.snapshots]``, ``[output.control_nodes]``, ``[output.energy]``" +msgstr "" + +msgid "" +"``every``: ``1000 steps`` or a time such as ``0.1 ms`` (converted to steps); ``0`` " +"means never" +msgstr "" +"``every``: ``1000 steps`` o un tempo come ``0.1 ms`` (convertito in passi); ``0`` " +"significa mai" + +msgid "" +"``ldem.io.readCase`` returns the parameters, the scenario and the output options; " +"``ldem.Parameters.fromFile`` also accepts a case file. The list of keys lives in one " +"table, ``ldem.schema.caseSchema``, which drives the reader, the writer and the " +"template. To add a scenario, add a line to ``ldem.scenarios.registry``. A new " +"constitutive law is a subclass of ``ldem.material.MaterialLaw`` registered in " +"``ldem.material.lawRegistry``; a new damping model is a subclass of " +"``ldem.solver.DampingModel`` registered in ``ldem.solver.dampingRegistry``." +msgstr "" +"``ldem.io.readCase`` restituisce i parametri, lo scenario e le opzioni di uscita; " +"``ldem.Parameters.fromFile`` accetta anche un file di caso. L'elenco delle chiavi è " +"in un'unica tabella, ``ldem.schema.caseSchema``, che governa il lettore, lo scrittore" +" e il modello. Per aggiungere uno scenario si aggiunge una riga a " +"``ldem.scenarios.registry``. Una nuova legge costitutiva è una sottoclasse di " +"``ldem.material.MaterialLaw`` registrata in ``ldem.material.lawRegistry``; un nuovo " +"modello di smorzamento, una sottoclasse di ``ldem.solver.DampingModel`` registrata in" +" ``ldem.solver.dampingRegistry``." + +msgid "Your own test: supports and loads" +msgstr "La propria prova: appoggi e carichi" + +msgid "" +"With ``type = \"custom\"`` the test is described in the case file by ``[[support]]`` " +"and ``[[load]]`` blocks, without writing a class. This is the uniaxial test (``testId" +" = 101``) as blocks:" +msgstr "" +"Con ``type = \"custom\"`` la prova si descrive nel file di caso con blocchi " +"``[[support]]`` e ``[[load]]``, senza scrivere una classe. Questa è la prova " +"uniassiale (``testId = 101``) come blocchi:" + +msgid "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"left end\"\n" +"x = 0.5 # the layer of centre nodes at x = 0.5 modules\n" +"fix = [\"x\"] # directions that cannot move\n" +"\n" +"[[load]]\n" +"name = \"right end\"\n" +"x = \"max - 0.5\"\n" +"direction = \"x\"\n" +"type = \"displacement\" # or \"force\"\n" +"time_function = \"linear\"\n" +"rate = -4 mm/s\n" +"reaction = true # its force is the reaction of the test" +msgstr "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"left end\"\n" +"x = 0.5 # lo strato di nodi centrali a x = 0.5 moduli\n" +"fix = [\"x\"] # direzioni che non si possono muovere\n" +"\n" +"[[load]]\n" +"name = \"right end\"\n" +"x = \"max - 0.5\"\n" +"direction = \"x\"\n" +"type = \"displacement\" # oppure \"force\"\n" +"time_function = \"linear\"\n" +"rate = -4 mm/s\n" +"reaction = true # la sua forza è la reazione della prova" + +msgid "" +"**Nodes** are chosen with ``nodes`` (``all``, ``grid`` for the corners of the modules" +" or ``centre`` for their centres), ``ids`` (node numbers) and ``x``, ``y``, ``z``. A " +"position is in modules (centre nodes lie at half-integers, grid nodes at integers), a" +" range ``[lo, hi]``, or a text with the references ``min``, ``max`` and ``mid`` and " +"an offset, such as ``\"max - 0.5\"``. A node must satisfy every condition. The " +"positions refer to the regular lattice, so they do not change when " +"``mesh.perturbation`` moves the nodes." +msgstr "" +"I **nodi** si scelgono con ``nodes`` (``all``, ``grid`` per gli angoli dei moduli o " +"``centre`` per i loro centri), ``ids`` (numeri di nodo) e ``x``, ``y``, ``z``. Una " +"posizione è in moduli (i nodi centrali sono a semi-interi, quelli d'angolo a interi)," +" un intervallo ``[lo, hi]``, o un testo con i riferimenti ``min``, ``max`` e ``mid`` " +"e uno scostamento, come ``\"max - 0.5\"``. Un nodo deve soddisfare tutte le " +"condizioni. Le posizioni si riferiscono al reticolo regolare, quindi non cambiano " +"quando ``mesh.perturbation`` sposta i nodi." + +msgid "" +"**Supports** hold the directions listed in ``fix``. **Loads** act on one " +"``direction`` as a ``force`` (newtons on each selected node) or as a prescribed " +"``displacement`` (metres from the initial position, and the solver holds that " +"direction). The value follows ``time_function``: ``constant`` (``value``), ``linear``" +" (``rate``), ``ramp`` (``rate`` until the time ``until``, then constant) or ``table``" +" (``times`` and ``values`` in SI units, linear between points and constant outside)." +msgstr "" +"Gli **appoggi** bloccano le direzioni di ``fix``. I **carichi** agiscono su una " +"``direction`` come ``force`` (newton su ogni nodo scelto) o come ``displacement`` " +"imposto (metri dalla posizione iniziale; il solver blocca quella direzione). Il " +"valore segue ``time_function``: ``constant`` (``value``), ``linear`` (``rate``), " +"``ramp`` (``rate`` fino al tempo ``until``, poi costante) o ``table`` (``times`` e " +"``values`` in unità SI, lineare tra i punti e costante fuori)." + +msgid "" +"A block with ``reaction = true`` adds its force to the reaction of the test (the sum " +"of the bar forces on its held directions); with none, the reaction is NaN. A block " +"that selects no node is an error that names it. The three built-in tests written this" +" way give exactly the same results as their classes." +msgstr "" +"Un blocco con ``reaction = true`` aggiunge la sua forza alla reazione della prova (la" +" somma delle forze di barra nelle sue direzioni bloccate); se nessuno la richiede, la" +" reazione è NaN. Un blocco che non sceglie alcun nodo è un errore che lo nomina. Le " +"tre prove incorporate scritte così danno esattamente gli stessi risultati delle loro " +"classi." + +msgid "Reuse a case: extends" +msgstr "Riutilizzare un caso: extends" + +msgid "A case file can start from another one and change only what differs:" +msgstr "Un file di caso può partire da un altro e cambiare solo ciò che differisce:" + +msgid "" +"extends = \"base.ldem\" # or a list: [\"base.ldem\", \"material.ldem\"]\n" +"\n" +"[material]\n" +"fracture_energy = 1 N/m # only what changes" +msgstr "" +"extends = \"base.ldem\" # oppure un elenco: [\"base.ldem\", " +"\"material.ldem\"]\n" +"\n" +"[material]\n" +"fracture_energy = 1 N/m # solo ciò che cambia" + +msgid "" +"The keys of the file replace the inherited ones. A repeated table (``[[support]]``, " +"``[[load]]``, ``[[monitor.node]]``, ``[[sweep]]``) replaces the whole inherited list." +" When the ``type`` of the scenario, of ``[material.scatter]`` or of ``[damping]`` " +"changes, the keys of the old type that are not set again are dropped. With a list, " +"later files win. Relative paths (the random-field file, the output folder) are " +"relative to the file that contains them, and an error names the file and line where " +"the problem is written. ``results.info.case.parents`` keeps the hash of every " +"inherited file." +msgstr "" +"Le chiavi del file sostituiscono quelle ereditate. Una tabella ripetuta " +"(``[[support]]``, ``[[load]]``, ``[[monitor.node]]``, ``[[sweep]]``) sostituisce " +"l'intero elenco ereditato. Quando cambia il ``type`` dello scenario, di " +"``[material.scatter]`` o di ``[damping]``, le chiavi del tipo precedente non " +"ridefinite vengono scartate. Con un elenco, i file successivi prevalgono. I percorsi " +"relativi (file del campo casuale, cartella di uscita) sono relativi al file che li " +"contiene, e un errore indica il file e la riga in cui il problema è scritto. " +"``results.info.case.parents`` conserva l'hash di ogni file ereditato." + +msgid "Parameter sweeps" +msgstr "Scansioni di parametri" + +msgid "" +"To study how the result depends on a value, list the values in ``[[sweep]]`` blocks " +"and run ``ldem.sweep``:" +msgstr "" +"Per studiare come il risultato dipende da un valore, si elencano i valori in blocchi " +"``[[sweep]]`` e si esegue ``ldem.sweep``:" + +msgid "" +"[[sweep]]\n" +"key = \"material.fracture_energy\"\n" +"values = [\"0.1 N/m\", \"0.5 N/m\", \"1 N/m\"]\n" +"\n" +"[[sweep]]\n" +"key = \"time.duration\"\n" +"values = [\"20 us\", \"40 us\"]" +msgstr "" + +#, python-brace-format, python-format +msgid "" +">> summary = ldem.sweep(\"case.ldem\"); % 3 x 2 = 6 runs, one folder " +"each\n" +">> ldem.sweep(\"case.ldem\", DryRun=true); % only validate and list the " +"runs\n" +">> ldem.sweep(\"case.ldem\", Vary={\"scenario.force_rate\", [\"1 kN/s\" \"2 " +"kN/s\"]});\n" +">> results = ldem.run(\"case.ldem\", Overrides=struct(\"path\", " +"\"material.fracture_energy\", \"value\", \"2 N/m\"));" +msgstr "" +">> summary = ldem.sweep(\"case.ldem\"); % 3 x 2 = 6 esecuzioni, una " +"cartella ciascuna\n" +">> ldem.sweep(\"case.ldem\", DryRun=true); % valida ed elenca soltanto " +"le esecuzioni\n" +">> ldem.sweep(\"case.ldem\", Vary={\"scenario.force_rate\", [\"1 kN/s\" \"2 " +"kN/s\"]});\n" +">> results = ldem.run(\"case.ldem\", Overrides=struct(\"path\", " +"\"material.fracture_energy\", \"value\", \"2 N/m\"));" + +msgid "" +"Several blocks give every combination; ``sweep_mode = \"zip\"`` (a key at the top of " +"the file) takes them one by one. Any key with a single value can be varied, and the " +"keys of the scenario as ``scenario.``. Values are numbers or texts with units. " +"Every run is validated before the first one starts. The runs go to ``run_001``, " +"``run_002``, ... (each with its resolved ``case.ldem``) and the table " +"``sweep_summary.csv`` lists them, with the number of damaged and broken bars; a run " +"that fails is recorded and the sweep goes on." +msgstr "" +"Più blocchi danno tutte le combinazioni; ``sweep_mode = \"zip\"`` (una chiave " +"all'inizio del file) li prende uno a uno. Si può variare qualsiasi chiave a valore " +"singolo, e quelle dello scenario come ``scenario.``. I valori sono numeri o " +"testi con unità. Ogni esecuzione viene validata prima di iniziare la prima. Le " +"esecuzioni vanno in ``run_001``, ``run_002``, ... (ciascuna con il proprio " +"``case.ldem`` risolto) e la tabella ``sweep_summary.csv`` le elenca, con il numero di" +" barre danneggiate e rotte; un'esecuzione che fallisce viene registrata e la " +"scansione prosegue." + +msgid "Reference of every key" +msgstr "Riferimento di tutte le chiavi" + +msgid "" +"The tables below are generated from ``ldem.schema.caseSchema``, the same table that " +"the reader uses, so they always agree with it." +msgstr "" +"Le tabelle seguenti sono generate da ``ldem.schema.caseSchema``, la stessa tabella " +"usata dal lettore, quindi concordano sempre con esso. Le descrizioni sono in inglese." + +msgid "``(top level)``" +msgstr "``(livello superiore)``" + +msgid "Key" +msgstr "Chiave" + +msgid "Value" +msgstr "Valore" + +msgid "Default" +msgstr "Predefinito" + +msgid "Legacy" +msgstr "Originale" + +msgid "Description" +msgstr "Descrizione" + +msgid "``format``" +msgstr "" + +msgid "integer" +msgstr "intero" + +msgid "1" +msgstr "" + +msgid "(none)" +msgstr "(nessuno)" + +msgid "Version of the case-file format (currently 1)." +msgstr "Versione del formato del file di caso (attualmente 1)." + +msgid "``title``" +msgstr "" + +msgid "text" +msgstr "testo" + +msgid "Free text title of the case." +msgstr "Titolo del caso, in testo libero." + +msgid "``authors``" +msgstr "" + +msgid "list of texts" +msgstr "elenco di testi" + +msgid "Names of the authors." +msgstr "Nomi degli autori." + +msgid "``extends``" +msgstr "" + +msgid "Case file(s) to inherit from; the keys of this file replace the inherited ones." +msgstr "" +"File di caso da cui si eredita; le chiavi di questo file sostituiscono quelle " +"ereditate." + +msgid "``sweep_mode``" +msgstr "" + +msgid "product, zip" +msgstr "" + +msgid "\"product\"" +msgstr "" + +msgid "How several [[sweep]] blocks combine: all combinations (product) or one by one (zip)." +msgstr "" +"Come si combinano più blocchi [[sweep]]: tutte le combinazioni (product) o uno a uno " +"(zip)." + +msgid "``module_size``" +msgstr "" + +msgid "number + unit (m, cm, mm, um, km)" +msgstr "numero + unità (m, cm, mm, um, km)" + +msgid "3 mm" +msgstr "" + +msgid "LCO" +msgstr "" + +msgid "Edge length of each cubic module." +msgstr "Lunghezza dello spigolo di ogni modulo cubico." + +msgid "``modules``" +msgstr "" + +msgid "list of integers" +msgstr "elenco di interi" + +msgid "required" +msgstr "obbligatorio" + +msgid "M N L" +msgstr "" + +msgid "Cubic modules along x, y and z (M N L of the legacy file count nodes: one more)." +msgstr "Moduli cubici lungo x, y e z (gli M N L del file originale contano nodi: uno in più)." + +msgid "``perturbation``" +msgstr "" + +msgid "number" +msgstr "numero" + +msgid "0" +msgstr "" + +msgid "Random node displacement as a fraction of the module size; 0 = regular lattice." +msgstr "" +"Spostamento casuale dei nodi come frazione della dimensione del modulo; 0 = reticolo " +"regolare." + +msgid "``seed``" +msgstr "" + +msgid "123" +msgstr "" + +msgid "SEED" +msgstr "" + +msgid "Seed of the mesh perturbation (the random field has its own seed)." +msgstr "Seme della perturbazione della mesh (il campo casuale ha il proprio seme)." + +msgid "``law``" +msgstr "" + +msgid "bilinear, linear\\_elastic" +msgstr "" + +msgid "\"bilinear\"" +msgstr "" + +msgid "Constitutive law of the bars (see ldem.material.lawRegistry)." +msgstr "Legge costitutiva delle barre (vedi ldem.material.lawRegistry)." + +msgid "``young_modulus``" +msgstr "" + +msgid "number + unit (Pa, kPa, MPa, GPa)" +msgstr "numero + unità (Pa, kPa, MPa, GPa)" + +msgid "32 GPa" +msgstr "" + +msgid "YNG" +msgstr "" + +msgid "Young's modulus." +msgstr "Modulo di Young." + +msgid "``poisson_ratio``" +msgstr "" + +msgid "0.25" +msgstr "" + +msgid "PSN" +msgstr "" + +msgid "Poisson's ratio, from 0 up to less than 0.5." +msgstr "Coefficiente di Poisson, da 0 fino a meno di 0.5." + +msgid "``density``" +msgstr "" + +msgid "number + unit (kg/m3, g/cm3)" +msgstr "numero + unità (kg/m3, g/cm3)" + +msgid "2000 kg/m3" +msgstr "" + +msgid "ROH" +msgstr "" + +msgid "Mass density." +msgstr "Densità di massa." + +msgid "``fracture_energy``" +msgstr "" + +msgid "number + unit (N/m, kN/m)" +msgstr "numero + unità (N/m, kN/m)" + +msgid "50 N/m" +msgstr "" + +msgid "GFR" +msgstr "" + +msgid "Specific fracture energy." +msgstr "Energia di frattura specifica." + +msgid "``critical_distance``" +msgstr "" + +msgid "28 mm" +msgstr "" + +msgid "DEQ" +msgstr "" + +msgid "Equivalent (critical) distance." +msgstr "Distanza equivalente (critica)." + +msgid "``failure_area_factor``" +msgstr "" + +msgid "0.1385" +msgstr "" + +msgid "CAF" +msgstr "" + +msgid "Fraction of the module face that fails per bar." +msgstr "Frazione della faccia del modulo che si rompe per ogni barra." + +msgid "``type``" +msgstr "" + +msgid "none, file, generated" +msgstr "" + +msgid "\"none\"" +msgstr "" + +msgid "Scatter of the critical strain: none, file (one multiplier per bar) or generated." +msgstr "" +"Dispersione della deformazione critica: none, file (un moltiplicatore per barra) o " +"generated." + +msgid "``file``" +msgstr "" + +msgid "file path" +msgstr "percorso del file" + +msgid "Text file with one multiplier per bar, relative to this file." +msgstr "File di testo con un moltiplicatore per barra, relativo a questo file." + +msgid "``cv``" +msgstr "" + +msgid "Coefficient of variation of the generated field (1e-4 to 3)." +msgstr "Coefficiente di variazione del campo generato (da 1e-4 a 3)." + +msgid "``correlation_length``" +msgstr "" + +msgid "list of numbers" +msgstr "elenco di numeri" + +msgid "[3]" +msgstr "" + +msgid "Correlation length of the generated field in modules: one value or [x, y, z]." +msgstr "Lunghezza di correlazione del campo generato in moduli: un valore o [x, y, z]." + +msgid "515" +msgstr "" + +msgid "Seed of the generated field." +msgstr "Seme del campo generato." + +msgid "``step``" +msgstr "" + +msgid "time, or auto" +msgstr "tempo, oppure auto" + +msgid "\"auto\"" +msgstr "" + +msgid "DT" +msgstr "" + +msgid "Integration time step, or auto (0.9 times the critical step)." +msgstr "Passo di integrazione nel tempo, oppure auto (0.9 volte il passo critico)." + +msgid "``duration``" +msgstr "" + +msgid "number + unit (s, ms, us, ns)" +msgstr "numero + unità (s, ms, us, ns)" + +msgid "TTOT" +msgstr "" + +msgid "Total simulated time." +msgstr "Tempo totale simulato." + +msgid "mass\\_proportional, none" +msgstr "" + +msgid "\"mass\\_proportional\"" +msgstr "" + +msgid "Damping model of the nodes (see ldem.solver.dampingRegistry)." +msgstr "Modello di smorzamento dei nodi (vedi ldem.solver.dampingRegistry)." + +msgid "``initial``" +msgstr "" + +msgid "number + unit (1/s, 1/ms)" +msgstr "numero + unità (1/s, 1/ms)" + +msgid "25000 1/s" +msgstr "" + +msgid "DF1" +msgstr "" + +msgid "Mass-proportional damping before switch\\_time." +msgstr "Smorzamento proporzionale alla massa prima di switch\\_time." + +msgid "``final``" +msgstr "" + +msgid "DF2" +msgstr "" + +msgid "Mass-proportional damping after switch\\_time." +msgstr "Smorzamento proporzionale alla massa dopo switch\\_time." + +msgid "``switch_time``" +msgstr "" + +msgid "15 ms" +msgstr "" + +msgid "TDAF" +msgstr "" + +msgid "Time at which the damping changes from initial to final." +msgstr "Tempo in cui lo smorzamento passa da initial a final." + +msgid "``constitutive``" +msgstr "" + +msgid "0 s" +msgstr "" + +msgid "CON" +msgstr "" + +msgid "Stiffness-proportional damping inside the bar law." +msgstr "Smorzamento proporzionale alla rigidezza all'interno della legge delle barre." + +msgid "TEST" +msgstr "" + +msgid "Test case (see ldem.scenarios.registry); its other keys follow." +msgstr "Prova (vedi ldem.scenarios.registry); le sue altre chiavi seguono." + +msgid "``[[support]]``" +msgstr "" + +msgid "``name``" +msgstr "" + +msgid "Label of the support." +msgstr "Etichetta dell'appoggio." + +msgid "``nodes``" +msgstr "" + +msgid "all, centre, grid" +msgstr "" + +msgid "\"all\"" +msgstr "" + +msgid "Kind of nodes: all, grid (module corners) or centre (module centres)." +msgstr "Tipo di nodi: all, grid (angoli dei moduli) o centre (centri dei moduli)." + +msgid "``ids``" +msgstr "" + +msgid "Node numbers to select." +msgstr "Numeri di nodo da scegliere." + +msgid "``x``" +msgstr "" + +msgid "modules: number, text or [lo, hi]" +msgstr "moduli: numero, testo o [lo, hi]" + +msgid "Positions along x in modules: 0.5, \"max - 0.5\" or a range [lo, hi]." +msgstr "Posizioni lungo x, in moduli: 0.5, \"max - 0.5\" o un intervallo [lo, hi]." + +msgid "``y``" +msgstr "" + +msgid "Positions along y in modules (see x)." +msgstr "Posizioni lungo y, in moduli (vedi x)." + +msgid "``z``" +msgstr "" + +msgid "Positions along z in modules (see x)." +msgstr "Posizioni lungo z, in moduli (vedi x)." + +msgid "``fix``" +msgstr "" + +msgid "Directions held at their initial position: [\"x\", \"y\", \"z\"]." +msgstr "Direzioni mantenute nella posizione iniziale: [\"x\", \"y\", \"z\"]." + +msgid "``reaction``" +msgstr "" + +msgid "true or false" +msgstr "true o false" + +msgid "false" +msgstr "" + +msgid "Include the force on the held directions in the reaction of the test." +msgstr "Include la forza nelle direzioni bloccate nella reazione della prova." + +msgid "``[[load]]``" +msgstr "" + +msgid "Label of the load." +msgstr "Etichetta del carico." + +msgid "``direction``" +msgstr "" + +msgid "x, y, z" +msgstr "" + +msgid "Direction of the load." +msgstr "Direzione del carico." + +msgid "force, displacement" +msgstr "" + +msgid "force (N on each selected node) or displacement (m from the initial position)." +msgstr "force (N su ogni nodo scelto) o displacement (m dalla posizione iniziale)." + +msgid "``time_function``" +msgstr "" + +msgid "constant, linear, ramp, table" +msgstr "" + +msgid "How the value changes with time." +msgstr "Come cambia il valore nel tempo." + +msgid "``value``" +msgstr "" + +msgid "N, N/s, m or m/s, by type" +msgstr "N, N/s, m o m/s, secondo il tipo" + +msgid "constant: the value (N or m)." +msgstr "constant: il valore (N o m)." + +msgid "``rate``" +msgstr "" + +msgid "linear and ramp: change per second (N/s or m/s)." +msgstr "linear e ramp: variazione al secondo (N/s o m/s)." + +msgid "``until``" +msgstr "" + +msgid "ramp: time at which it stops growing." +msgstr "ramp: tempo in cui smette di crescere." + +msgid "``times``" +msgstr "" + +msgid "table: increasing times in seconds." +msgstr "table: tempi crescenti in secondi." + +msgid "``values``" +msgstr "" + +msgid "table: one value per time (N or m)." +msgstr "table: un valore per ogni tempo (N o m)." + +msgid "Include the force on the loaded direction in the reaction of the test." +msgstr "Include la forza nella direzione caricata nella reazione della prova." + +msgid "``[[sweep]]``" +msgstr "" + +msgid "``key``" +msgstr "" + +msgid "Key to vary, for example \"material.fracture\\_energy\" (see ldem.sweep)." +msgstr "Chiave da variare, per esempio \"material.fracture\\_energy\" (vedi ldem.sweep)." + +msgid "Values to try: numbers, or texts with units such as [\"0.1 N/m\", \"0.5 N/m\"]." +msgstr "Valori da provare: numeri, o testi con unità come [\"0.1 N/m\", \"0.5 N/m\"]." + +msgid "``id``" +msgstr "" + +msgid "NCON" +msgstr "" + +msgid "Number of a node whose motion is recorded." +msgstr "Numero di un nodo il cui movimento viene registrato." + +msgid "``at``" +msgstr "" + +msgid "Position [x, y, z] in modules; the nearest node is recorded." +msgstr "Posizione [x, y, z] in moduli; viene registrato il nodo più vicino." + +msgid "Label of the node." +msgstr "Etichetta del nodo." + +msgid "``tracked``" +msgstr "" + +msgid "off" +msgstr "disattivato" + +msgid "OU9" +msgstr "" + +msgid "Number of the bar whose strain history is stored at every step." +msgstr "Numero della barra la cui storia di deformazione è salvata a ogni passo." + +msgid "``folder``" +msgstr "" + +msgid "no files" +msgstr "nessun file" + +msgid "Output folder, relative to the case file." +msgstr "Cartella di uscita, relativa al file di caso." + +msgid "``mat``" +msgstr "" + +msgid "true" +msgstr "" + +msgid "Write results.mat." +msgstr "Scrive results.mat." + +msgid "``ansys``" +msgstr "" + +msgid "Write ANSYS macro files (needs snapshots.every > 0)." +msgstr "Scrive file macro di ANSYS (richiede snapshots.every > 0)." + +msgid "``vtk``" +msgstr "" + +msgid "Write VTK files for ParaView (needs snapshots.every > 0)." +msgstr "Scrive file VTK per ParaView (richiede snapshots.every > 0)." + +msgid "``[output.snapshots]``" +msgstr "" + +msgid "``every``" +msgstr "" + +msgid "steps or time (0 = never)" +msgstr "passi o tempo (0 = mai)" + +msgid "OU3" +msgstr "" + +msgid "Steps or time between full-field snapshots; 0 = never." +msgstr "Passi o tempo tra istantanee del campo completo; 0 = mai." + +msgid "``[output.control_nodes]``" +msgstr "" + +msgid "OU6" +msgstr "" + +msgid "Steps or time between records of the control nodes and reactions; 0 = never." +msgstr "Passi o tempo tra registrazioni dei nodi di controllo e delle reazioni; 0 = mai." + +msgid "``[output.energy]``" +msgstr "" + +msgid "OU8" +msgstr "" + +msgid "Steps or time between records of the energies; 0 = never." +msgstr "Passi o tempo tra registrazioni delle energie; 0 = mai." + +msgid "Tests available" +msgstr "Prove disponibili" + +msgid "``testId = 101``" +msgstr "" + +msgid "" +"Uniaxial load: the centre nodes of the last column of modules move along :math:`x` " +"with a prescribed velocity." +msgstr "" +"Carico uniassiale: i nodi centrali dell'ultima colonna di moduli si muovono in " +":math:`x` con velocità imposta." + +msgid "``testId = 102``" +msgstr "" + +msgid "" +"Beam with two supports and two load points. The positions are parameters of " +"``ldem.scenarios.FourPointBending`` (``supportPosition``, ``loadPosition``, in " +"modules from each end); the defaults need a beam longer than about 70 modules. See " +"``examples/beam_102``." +msgstr "" +"Trave con due appoggi e due punti di carico. Le posizioni sono parametri di " +"``ldem.scenarios.FourPointBending`` (``supportPosition``, ``loadPosition``, in moduli" +" da ciascuna estremità); i valori predefiniti richiedono una trave di oltre 70 moduli" +" circa. Vedi ``examples/beam_102``." + +msgid "``testId = 103``" +msgstr "" + +msgid "" +"Beam clamped at both ends, loaded at mid-span with a force that grows linearly and " +"then stays constant (``ldem.scenarios.ClampedBeam``). It is the only test loaded with" +" a force instead of a displacement. See ``examples/example1_clamped_beam``." +msgstr "" +"Trave incastrata alle due estremità, caricata in mezzeria con una forza che cresce " +"linearmente e poi resta costante (``ldem.scenarios.ClampedBeam``). È l'unica prova " +"caricata con una forza invece che con uno spostamento. Vedi " +"``examples/example1_clamped_beam``." + +msgid "" +"To add a new test, create a subclass of ``ldem.scenarios.Scenario`` (see " +":doc:`model`)." +msgstr "" +"Per aggiungere una prova nuova si crea una sottoclasse di ``ldem.scenarios.Scenario``" +" (vedi :doc:`model`)." + +msgid "Mesh perturbation" +msgstr "Perturbazione della mesh" + +msgid "" +"The parameter ``meshPerturbation`` randomly displaces the interior nodes. Its value " +"is the standard deviation as a fraction of the module length: ``0`` (the default) " +"keeps the lattice regular and any positive value activates the perturbation with that" +" value. The random numbers follow ``seed``." +msgstr "" +"Il parametro ``meshPerturbation`` sposta in modo casuale i nodi interni. Il suo " +"valore è la deviazione standard come frazione della lunghezza del modulo: ``0`` (il " +"predefinito) mantiene il reticolo regolare e qualsiasi valore positivo attiva la " +"perturbazione con quel valore. I numeri casuali seguono ``seed``." + +msgid ">> params = ldem.Parameters(testId=101, nModules=[6 3 3], meshPerturbation=0.02);" +msgstr "" + +msgid "What you get: the ``results`` struct" +msgstr "Cosa si ottiene: la struttura ``results``" + +msgid "Field" +msgstr "Campo" + +msgid "Content" +msgstr "Contenuto" + +msgid "``info``" +msgstr "" + +msgid "ldem version, date, MATLAB release, run time [s]." +msgstr "Versione di ldem, data, versione di MATLAB, tempo di esecuzione [s]." + +msgid "``params``" +msgstr "" + +msgid "The parameters used, as a plain struct (derived values included)." +msgstr "I parametri usati, come struttura semplice (con i valori derivati)." + +msgid "``model``" +msgstr "" + +msgid "" +"Counts and mass of the model: modules, nodes, bars by type, fixed degrees of freedom," +" total mass and volume." +msgstr "" +"Conteggi e massa del modello: moduli, nodi, barre per tipo, gradi di libertà " +"bloccati, massa totale e volume." + +msgid "``material``" +msgstr "" + +msgid "" +"Material data (E, Gf, ...), lattice coefficients, critical length and the statistics " +"of the critical strain (mean, coefficient of variation, minimum and maximum)." +msgstr "" +"Dati del materiale (E, Gf, ...), coefficienti del reticolo, lunghezza critica e " +"statistiche della deformazione critica (media, coefficiente di variazione, minimo e " +"massimo)." + +msgid "``mesh``" +msgstr "" + +msgid "Initial node positions, supports (``fixed``), masses, bars, bar lengths and bar types." +msgstr "" +"Posizioni iniziali dei nodi, vincoli (``fixed``), masse, barre, lunghezze e tipi di " +"barra." + +msgid "``barProps``" +msgstr "" + +msgid "Stiffness, critical strain and rupture strain of every bar." +msgstr "Rigidezza, deformazione critica e deformazione di rottura di ogni barra." + +msgid "``controlNodes``" +msgstr "" + +msgid "Time and displacement, velocity and acceleration of the control nodes." +msgstr "Tempo e spostamento, velocità e accelerazione dei nodi di controllo." + +msgid "``reactions``" +msgstr "" + +msgid "" +"Time and reaction force ``[Rx Ry Rz]`` of the test: vertical force at the load points" +" (test 102), force on the clamped ends (test 103); ``NaN`` where the test defines " +"none." +msgstr "" +"Tempo e forza di reazione ``[Rx Ry Rz]`` della prova: forza verticale nei punti di " +"carico (prova 102), forza alle estremità incastrate (prova 103); ``NaN`` dove la " +"prova non la definisce." + +msgid "``energy``" +msgstr "" + +msgid "" +"Time, kinetic, elastic, damage and damping energies [J], their sum (``internal``), " +"the energy of the broken bars (``brokenBars``), the external work, the ``balance`` " +"(external minus internal) and the damage rate." +msgstr "" +"Tempo, energie cinetica, elastica, di danno e di smorzamento [J], la loro somma " +"(``internal``), l'energia delle barre rotte (``brokenBars``), il lavoro esterno, il " +"bilancio (``balance``, esterno meno interno) e la velocità di danno." + +msgid "``trackedBar``" +msgstr "" + +msgid "Strain, force and damage energy of one bar at every step (optional)." +msgstr "Deformazione, forza ed energia di danno di una barra a ogni passo (opzionale)." + +msgid "``snapshots``" +msgstr "" + +msgid "" +"Step, time, number of intact/damaged/broken bars, and compact copies of the " +"displacements, the damage state and the nodal kinetic energy at the snapshot steps." +msgstr "" +"Passo, tempo, numero di barre intatte/danneggiate/rotte e copie compatte degli " +"spostamenti, dello stato di danno e dell'energia cinetica nodale nei passi salvati." + +msgid "" +"Final displacement, velocity, force and damage state, and the kinetic energy of every" +" node." +msgstr "" +"Spostamento, velocità, forza e stato di danno finali, e l'energia cinetica di ogni " +"nodo." + +msgid "" +"The energy ``balance`` is a check of the simulation: it should be a small fraction " +"(below 1 %) of the final external work. The total kinetic energy is " +"``energy.kinetic``; the kinetic energy of each node is in ``final.kineticEnergy``." +msgstr "" +"Il ``balance`` energetico è un controllo della simulazione: deve essere una piccola " +"frazione (meno dell'1 %) del lavoro esterno finale. L'energia cinetica totale è " +"``energy.kinetic``; quella di ogni nodo è in ``final.kineticEnergy``." + +msgid "``results.mat`` contains this struct and loads without the package:" +msgstr "``results.mat`` contiene questa struttura e si carica senza il pacchetto:" + +msgid "" +">> data = load(\"output/results.mat\");\n" +">> results = data.results;" +msgstr "" + +msgid "Output files" +msgstr "File di uscita" + +msgid "``results.mat``" +msgstr "" + +msgid "The ``results`` struct (format v7.3, readable from Python with ``h5py``)." +msgstr "La struttura ``results`` (formato v7.3, leggibile da Python con ``h5py``)." + +msgid "``snapshot_0000.mac``, ``snapshot_0001.mac``, ..." +msgstr "" + +msgid "" +"ANSYS macro files with the deformed lattice. Bars are element types 1 (intact), 2 " +"(damaged) and 5 (broken). The held degrees of freedom are listed as " +"``D,node,direction`` and the displacement imposed on the loaded nodes, measured from " +"their initial position, as ``D,node,direction,value``. In test 103 the applied forces" +" are listed as ``F,node,direction,value``." +msgstr "" +"Macro ANSYS con il reticolo deformato. Le barre sono elementi di tipo 1 (intatte), 2 " +"(danneggiate) e 5 (rotte). I gradi di libertà bloccati sono elencati come " +"``D,nodo,direzione`` e lo spostamento imposto ai nodi caricati, misurato dalla " +"posizione iniziale, come ``D,nodo,direzione,valore``. Nella prova 103 le forze " +"applicate sono elencate come ``F,nodo,direzione,valore``." + +msgid "``snapshot_0000.vtu``, ... and ``snapshots.pvd``" +msgstr "``snapshot_0000.vtu``, ... e ``snapshots.pvd``" + +msgid "" +"VTK files. Open ``snapshots.pvd`` in `ParaView `_; colour " +"by ``damageState`` (cell data) to see the cracks and use the time slider to follow " +"them. Displacement and velocity are point data." +msgstr "" +"File VTK. Aprire ``snapshots.pvd`` in `ParaView `_; " +"colorare per ``damageState`` (dati di cella) per vedere le fessure e usare il cursore" +" del tempo per seguirle. Spostamento e velocità sono dati di punto." + +msgid "" +"ANSYS and VTK files are written at time zero and every " +"``params.output.snapshotEvery`` steps." +msgstr "" +"I file ANSYS e VTK vengono scritti al tempo zero e ogni " +"``params.output.snapshotEvery`` passi." + +msgid "Run the tests" +msgstr "Eseguire i test" + +#, python-format +msgid "" +">> addpath tests\n" +">> run_tests % fast tests\n" +">> run_tests(IncludeSlow=true) % also the slow tests" +msgstr "" +">> addpath tests\n" +">> run_tests % test rapidi\n" +">> run_tests(IncludeSlow=true) % anche i test lenti" + diff --git a/docs/locale/pt/LC_MESSAGES/api/index.po b/docs/locale/pt/LC_MESSAGES/api/index.po new file mode 100644 index 0000000..9b5c255 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/api/index.po @@ -0,0 +1,54 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "API reference" +msgstr "Referência da API" + +msgid "Generated automatically from the comments of the ``.m`` files." +msgstr "Gerada automaticamente a partir dos comentários dos ``.m``." + +msgid "" +"The ``ldem`` package (``src/+ldem``) is the refactored code. It replaces the original" +" routines, which are kept in the git history (tag ``legacy-reference``); the problems" +" found in them are listed in ``docs/known-issues/KNOWN_ISSUES.md``." +msgstr "" +"O pacote ``ldem`` (``src/+ldem``) é o código refatorado. Substitui as rotinas " +"originais, que são mantidas no histórico do git (tag ``legacy-reference``); os " +"problemas encontrados nelas estão listados em ``docs/known-issues/KNOWN_ISSUES.md``." + +msgid "Running a simulation" +msgstr "Executar uma simulação" + +msgid "Input and output" +msgstr "Entrada e saída" + +msgid "Mesh" +msgstr "Malha" + +msgid "Material" +msgstr "Material" + +msgid "Scenarios" +msgstr "Cenários de ensaio" + +msgid "Case-file schema" +msgstr "Esquema dos arquivos de caso" + +msgid "Solver" +msgstr "" + +msgid "Post-processing" +msgstr "Pós-processamento" + diff --git a/docs/locale/pt/LC_MESSAGES/authors.po b/docs/locale/pt/LC_MESSAGES/authors.po new file mode 100644 index 0000000..fb16b6e --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/authors.po @@ -0,0 +1,59 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Authors" +msgstr "Autores" + +msgid "" +"This list is generated automatically from the commits of the git history (people with" +" the same name or e-mail are merged through ``.mailmap``) and from the authors of " +"``CITATION.cff``. Authors without commits in this repository appear with ``-``. The " +"same list is in ``AUTHORS.md``." +msgstr "" +"Esta lista é gerada automaticamente a partir dos commits do histórico do git (pessoas" +" com o mesmo nome ou e-mail são unificadas com ``.mailmap``) e dos autores de " +"``CITATION.cff``. Autores sem commits neste repositório aparecem com ``-``. A mesma " +"lista está em ``AUTHORS.md``." + +msgid "Name" +msgstr "Nome" + +msgid "Commits" +msgstr "" + +msgid "Boris Rojo Tanzi" +msgstr "" + +msgid "26" +msgstr "" + +msgid "Rodrigo Cavasotto Oscar Montanha" +msgstr "" + +msgid "7" +msgstr "" + +msgid "Ignacio Iturrioz" +msgstr "" + +msgid "To update it after new commits, build the documentation or run:" +msgstr "Para atualizá-la depois de novos commits, construa a documentação ou execute:" + +msgid "python docs/tools/generate_authors.py" +msgstr "" + +msgid "If a person appears twice, add a line to ``.mailmap``." +msgstr "Se uma pessoa aparecer duas vezes, adicione uma linha ao ``.mailmap``." + diff --git a/docs/locale/pt/LC_MESSAGES/contributing.po b/docs/locale/pt/LC_MESSAGES/contributing.po new file mode 100644 index 0000000..eb72049 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/contributing.po @@ -0,0 +1,42 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Contributing" +msgstr "Contribuir" + +msgid "" +"The API documentation is generated from the ``.m`` comments. The docstring must be " +"the comment block placed **immediately after** the ``function`` line (before any " +"``global`` declaration). Source comments are written in English." +msgstr "" +"A documentação da API é gerada a partir dos comentários dos ``.m``. O docstring deve " +"ser o bloco de comentários colocado **imediatamente depois** da linha ``function`` " +"(antes de qualquer ``global``). Os comentários do código são escritos em inglês." + +#, python-format +msgid "" +"function ini = CALOAD()\n" +"% CALOAD One-line summary.\n" +"% Longer description.\n" +"global ..." +msgstr "" +"function ini = CALOAD()\n" +"% CALOAD Resumo em uma linha.\n" +"% Descrição mais longa.\n" +"global ..." + +msgid "See ``CONTRIBUTING.md`` in the repository root." +msgstr "Veja ``CONTRIBUTING.md`` na raiz do repositório." + diff --git a/docs/locale/pt/LC_MESSAGES/docs.po b/docs/locale/pt/LC_MESSAGES/docs.po new file mode 100644 index 0000000..c09eba7 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/docs.po @@ -0,0 +1,183 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Building this documentation" +msgstr "Construir esta documentação" + +msgid "" +"The documentation is written in English, which is the only set of source pages, and " +"translated into Spanish, Portuguese and Italian with gettext catalogs (``.po`` files " +"in ``docs/locale/``). Each language is built as its own site and the sidebar has a " +"language selector. A text that is not translated yet is shown in English. The API " +"reference is generated from the comments of the ``.m`` files and is in English only." +msgstr "" +"A documentação está escrita em inglês, que é o único conjunto de páginas-fonte, e " +"traduzida para espanhol, português e italiano com catálogos gettext (arquivos ``.po``" +" em ``docs/locale/``). Cada idioma é construído como um site próprio e a barra " +"lateral tem um seletor de idioma. Um texto que ainda não foi traduzido é mostrado em " +"inglês. A referência da API é gerada a partir dos comentários dos arquivos ``.m`` e " +"está apenas em inglês." + +msgid "Requirements" +msgstr "Requisitos" + +msgid "Python 3.9 or newer." +msgstr "Python 3.9 ou superior." + +msgid "" +"``git`` (the list of authors is generated from the commit history; with a shallow " +"clone use ``git fetch --unshallow`` first)." +msgstr "" +"``git`` (a lista de autores é gerada a partir do histórico de commits; com um clone " +"superficial execute antes ``git fetch --unshallow``)." + +msgid "No MATLAB is needed; the API is read from the source text." +msgstr "Não é necessário MATLAB; a API é lida do texto das fontes." + +msgid "pip install -r docs/requirements.txt" +msgstr "" + +msgid "Build" +msgstr "Construção" + +msgid "From the repository root, with any of these:" +msgstr "A partir da raiz do repositório, com qualquer uma destas opções:" + +msgid "python docs/tools/build_docs.py" +msgstr "" + +msgid "cd docs && make html" +msgstr "" + +msgid ">> buildtool docs" +msgstr "" + +msgid "" +"This builds the four languages into ``docs/build/html/en``, ``es``, ``pt`` and " +"``it``; ``docs/build/html/index.html`` sends the reader to the English site. Open it " +"in a browser. To build only some languages use for example ``python " +"docs/tools/build_docs.py --languages en es``. Warnings are errors: the documentation " +"must build without any. ``buildtool clean`` deletes the result." +msgstr "" +"Isto constrói os quatro idiomas em ``docs/build/html/en``, ``es``, ``pt`` e ``it``; " +"``docs/build/html/index.html`` leva o leitor ao site em inglês. Abra-o em um " +"navegador. Para construir apenas alguns idiomas use, por exemplo, ``python " +"docs/tools/build_docs.py --languages en es``. Os avisos são erros: a documentação " +"deve ser construída sem nenhum. ``buildtool clean`` apaga o resultado." + +msgid "Where things are" +msgstr "Onde fica cada coisa" + +msgid "``docs/source/``" +msgstr "" + +msgid "The pages, in English." +msgstr "As páginas, em inglês." + +msgid "``docs/locale/es/``, ``pt/``, ``it/``" +msgstr "" + +msgid "" +"Translations: one ``.po`` file per page in ``LC_MESSAGES/``, with each English text " +"and its translation." +msgstr "" +"Traduções: um arquivo ``.po`` por página em ``LC_MESSAGES/``, com cada texto em " +"inglês e a sua tradução." + +msgid "``docs/source/api/``" +msgstr "" + +msgid "API reference, generated from the ``.m`` comments." +msgstr "Referência da API, gerada a partir dos comentários dos ``.m``." + +msgid "``docs/tools/build_docs.py``" +msgstr "" + +msgid "Builds every language and the page that sends the reader to the English site." +msgstr "Constrói cada idioma e a página que leva o leitor ao site em inglês." + +msgid "``docs/tools/update_translations.py``" +msgstr "" + +msgid "" +"Updates the ``.po`` files after the English text changes, and reports what is left to" +" translate." +msgstr "" +"Atualiza os arquivos ``.po`` quando o texto em inglês muda e informa o que falta " +"traduzir." + +msgid "``docs/tools/generate_authors.py``" +msgstr "" + +msgid "Writes the authors page and ``AUTHORS.md`` (run by the build)." +msgstr "Escreve a página de autores e ``AUTHORS.md`` (executado pela construção)." + +msgid "``docs/source/case-keys.inc``" +msgstr "" + +msgid "" +"Reference of the case-file keys, generated from the schema. After changing " +"``ldem.schema.caseSchema`` regenerate it from MATLAB with " +"``ldem.schema.writeKeyReference(\"docs/source/case-keys.inc\")``; a test fails if it " +"is out of date." +msgstr "" +"Referência das chaves do arquivo de caso, gerada a partir do esquema. Depois de mudar" +" ``ldem.schema.caseSchema`` regenera-se a partir do MATLAB com " +"``ldem.schema.writeKeyReference(\"docs/source/case-keys.inc\")``; um teste falha se " +"estiver desatualizada." + +msgid "Write or change a page" +msgstr "Escrever ou alterar uma página" + +msgid "" +"Edit the English page in ``docs/source/``. A new page also goes in the list of " +"``index.rst``." +msgstr "" +"Edite a página em inglês em ``docs/source/``. Uma página nova também entra na lista " +"de ``index.rst``." + +msgid "" +"Run ``python docs/tools/update_translations.py``. It extracts the texts and updates " +"the ``.po`` files: new texts appear untranslated and changed texts are marked as " +"fuzzy, both shown in English until they are translated." +msgstr "" +"Execute ``python docs/tools/update_translations.py``. Ele extrai os textos e atualiza" +" os arquivos ``.po``: os textos novos aparecem sem tradução e os textos alterados são" +" marcados como fuzzy; ambos são mostrados em inglês até serem traduzidos." + +msgid "" +"Translate the new entries in ``docs/locale//LC_MESSAGES/.po`` (with " +"any text editor or a tool such as Poedit) and remove the fuzzy marks you have " +"reviewed. ``python docs/tools/update_translations.py --status`` shows how much is " +"left in each language." +msgstr "" +"Traduza as entradas novas em ``docs/locale//LC_MESSAGES/.po`` (com " +"qualquer editor de texto ou uma ferramenta como o Poedit) e remova as marcas fuzzy " +"que revisou. ``python docs/tools/update_translations.py --status`` mostra quanto " +"falta em cada idioma." + +msgid "Build with ``python docs/tools/build_docs.py`` and fix any warning." +msgstr "Construa com ``python docs/tools/build_docs.py`` e corrija qualquer aviso." + +msgid "Publishing" +msgstr "Publicação" + +msgid "" +"The workflow ``.github/workflows/docs.yml`` builds the documentation on every pull " +"request and publishes the four languages to GitHub Pages when ``main`` changes." +msgstr "" +"O workflow ``.github/workflows/docs.yml`` constrói a documentação a cada pull request" +" e publica os quatro idiomas no GitHub Pages quando ``main`` muda." + diff --git a/docs/locale/pt/LC_MESSAGES/examples.po b/docs/locale/pt/LC_MESSAGES/examples.po new file mode 100644 index 0000000..56a34cb --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/examples.po @@ -0,0 +1,588 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Examples" +msgstr "Exemplos" + +msgid "" +"The folder ``examples/`` has three models that run from start to finish, each with " +"its inputs and a script that runs it and plots the results. The numbers in this page " +"come from running them with the current code." +msgstr "" +"A pasta ``examples/`` tem três modelos que são executados do início ao fim, cada um " +"com seus dados de entrada e um script que o executa e plota os resultados. Os números" +" desta página saem de executá-los com o código atual." + +msgid "Folder" +msgstr "Pasta" + +msgid "What it shows" +msgstr "O que mostra" + +msgid "Size" +msgstr "Tamanho" + +msgid "Time" +msgstr "Tempo" + +msgid "``example1_clamped_beam/``" +msgstr "" + +msgid "A beam clamped at both ends and loaded with a force at mid-span" +msgstr "Uma viga engastada nas duas extremidades e carregada com uma força no meio do vão" + +msgid "3,086 nodes" +msgstr "3,086 nós" + +msgid "about 35 s" +msgstr "cerca de 35 s" + +msgid "``tension_101/``" +msgstr "" + +msgid "A small prism under a uniaxial load, with damage and every output format" +msgstr "Um prisma pequeno sob carga uniaxial, com dano e todos os formatos de saída" + +msgid "74 nodes" +msgstr "74 nós" + +msgid "about 6 s" +msgstr "cerca de 6 s" + +msgid "``beam_102/``" +msgstr "" + +msgid "The four-point bending beam of the paper (a demo of its first 50 steps)" +msgstr "" +"A viga em flexão de quatro pontos do artigo (uma demonstração dos seus primeiros 50 " +"passos)" + +msgid "166,961 nodes" +msgstr "166,961 nós" + +msgid "about 30 s for 50 steps" +msgstr "cerca de 30 s para 50 passos" + +msgid "" +"Start with ``tension_101`` to learn the interface and with ``example1_clamped_beam`` " +"to see a model loaded with a force, described by a case file and checked against the " +"original code." +msgstr "" +"Comece com ``tension_101`` para aprender a interface e com ``example1_clamped_beam`` " +"para ver um modelo carregado com uma força, descrito por um arquivo de caso e " +"verificado contra o código original." + +msgid "Running an example" +msgstr "Executar um exemplo" + +msgid "From MATLAB, from any folder:" +msgstr "No MATLAB, a partir de qualquer pasta:" + +#, python-format +msgid "" +">> run('examples/example1_clamped_beam/runClampedBeam.m') % script: run and" +" plot\n" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % from the case " +"file" +msgstr "" +">> run('examples/example1_clamped_beam/runClampedBeam.m') % script: executa" +" e plota\n" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % a partir do " +"arquivo de caso" + +msgid "" +"The two beam examples also have a ``case.ldem``: the same model in the readable case-" +"file format (see :doc:`usage`), generated from the ``DATA0.DAT`` of the original " +"program and giving the same parameters. ``ldem.check`` shows what a case file would " +"simulate without running it." +msgstr "" +"Os dois exemplos de viga também têm um ``case.ldem``: o mesmo modelo no formato " +"legível de arquivo de caso (ver :doc:`usage`), gerado a partir do ``DATA0.DAT`` do " +"programa original e que dá os mesmos parâmetros. ``ldem.check`` mostra o que um " +"arquivo de caso simularia sem executá-lo." + +msgid "" +"The scripts write their files to a folder ``output`` next to the script (ignored by " +"git), or to ``outputFolder`` if that variable already exists:" +msgstr "" +"Os scripts escrevem seus arquivos em uma pasta ``output`` junto ao script (ignorada " +"pelo git), ou em ``outputFolder`` se essa variável já existir:" + +msgid "" +"``results.mat``: one struct, ``results``, with everything that was recorded. Load it " +"with ``data = load('results.mat'); results = data.results;``." +msgstr "" +"``results.mat``: uma estrutura, ``results``, com tudo o que foi registrado. Carrega-" +"se com ``data = load('results.mat'); results = data.results;``." + +msgid "``snapshot_0000.mac``, ...: ANSYS macro files of the deformed lattice." +msgstr "``snapshot_0000.mac``, ...: arquivos macro do ANSYS da malha deformada." + +msgid "" +"``snapshot_0000.vtu``, ... and ``snapshots.pvd``: open ``snapshots.pvd`` in `ParaView" +" `_ to see the damage evolve in time." +msgstr "" +"``snapshot_0000.vtu``, ... e ``snapshots.pvd``: abra ``snapshots.pvd`` no `ParaView " +"`_ para ver o dano evoluir no tempo." + +msgid "Example 1: beam clamped at both ends" +msgstr "Exemplo 1: viga engastada nas duas extremidades" + +msgid "" +"A small beam of 5 x 5 x 50 modules of 1 mm, clamped at both ends and loaded at mid-" +"span with a force that grows during 0.35 ms and then stays constant. It is the model " +"of Rodrigo (branch ``dev_rodrigo``) and the first test loaded with a force instead of" +" a displacement (``ldem.scenarios.ClampedBeam``, test 103)." +msgstr "" +"Uma viga pequena de 5 x 5 x 50 módulos de 1 mm, engastada nas duas extremidades e " +"carregada no meio do vão com uma força que cresce durante 0.35 ms e depois permanece " +"constante. É o modelo de Rodrigo (ramo ``dev_rodrigo``) e o primeiro ensaio carregado" +" com uma força em vez de um deslocamento (``ldem.scenarios.ClampedBeam``, ensaio " +"103)." + +msgid "The model" +msgstr "O modelo" + +msgid "Part" +msgstr "Parte" + +msgid "Value" +msgstr "Valor" + +msgid "Geometry" +msgstr "Geometria" + +msgid "" +"5 x 5 x 50 modules of 1 mm (a prism of 5 x 5 x 50 mm, axis along z), with 3,086 " +"nodes, 18,085 bars and a mass of 1.875 g" +msgstr "" +"5 x 5 x 50 módulos de 1 mm (um prisma de 5 x 5 x 50 mm, eixo ao longo de z), com " +"3,086 nós, 18,085 barras e uma massa de 1.875 g" + +msgid "Supports" +msgstr "Apoios" + +msgid "" +"The centre nodes of the first and of the last layer of modules (z = 0.5 and z = 49.5 " +"modules) are clamped: x, y and z held" +msgstr "" +"Os nós centrais da primeira e da última camada de módulos (z = 0.5 e z = 49.5 " +"módulos) são engastados: x, y e z fixos" + +msgid "Load" +msgstr "Carga" + +msgid "" +"The 5 centre nodes of the line at mid-span (z = 24.5 modules, y = 0.5 modules) carry " +"a force in +y of ``1000 N/s * min(t, 0.35 ms)`` each: 0.35 N per node, 1.75 N in " +"total" +msgstr "" +"Os 5 nós centrais da linha no meio do vão (z = 24.5 módulos, y = 0.5 módulos) levam " +"cada um uma força em +y de ``1000 N/s * min(t, 0.35 ms)``: 0.35 N por nó, 1.75 N no " +"total" + +msgid "Material" +msgstr "Material" + +msgid "" +"E = 3.87 GPa, Poisson's ratio 0.25, density 1500 kg/m\\ :sup:`3`, fracture energy 0.5" +" N/m, critical distance 4.5 mm; mass-proportional damping of 2500 1/s" +msgstr "" +"E = 3.87 GPa, coeficiente de Poisson 0.25, densidade 1500 kg/m\\ :sup:`3`, energia de" +" fratura 0.5 N/m, distância crítica 4.5 mm; amortecimento proporcional à massa de " +"2500 1/s" + +msgid "Scatter" +msgstr "Dispersão" + +msgid "" +"One multiplier of the critical strain per bar, read from a file (shared with " +"``beam_102``)" +msgstr "" +"Um multiplicador da deformação crítica por barra, lido de um arquivo (compartilhado " +"com ``beam_102``)" + +#, python-format +msgid "2.8 ms in 8000 steps of 0.35 us (65 % of the critical step)" +msgstr "2.8 ms em 8000 passos de 0.35 us (65 % do passo crítico)" + +msgid "Recorded" +msgstr "Registrado" + +msgid "" +"Control nodes 2441 (a loaded node) and 884 (a grid node at mid-span); tracked bar " +"14398" +msgstr "" +"Nós de controle 2441 (um nó carregado) e 884 (um nó de canto no meio do vão); barra " +"acompanhada 14398" + +msgid "" +"The original input file listed five control nodes, but nodes 6870 and 14398 do not " +"exist in this 3,086-node mesh, so the input keeps 2441 and 884. The tracked bar is " +"14398, as in the original." +msgstr "" +"O arquivo de entrada original listava cinco nós de controle, mas os nós 6870 e 14398 " +"não existem nesta malha de 3,086 nós, então a entrada mantém 2441 e 884. A barra " +"acompanhada é a 14398, como no original." + +msgid "Files" +msgstr "Arquivos" + +msgid "File" +msgstr "Arquivo" + +msgid "Purpose" +msgstr "Propósito" + +msgid "``case.ldem``" +msgstr "" + +msgid "The model as a case file: run it with ``ldem.run``" +msgstr "O modelo como arquivo de caso: é executado com ``ldem.run``" + +msgid "``runClampedBeam.m``" +msgstr "" + +msgid "" +"Reads ``DATA0.DAT``, runs the simulation and plots the force on the clamped ends, the" +" vertical displacement of the control nodes and the energies" +msgstr "" +"Lê o ``DATA0.DAT``, executa a simulação e plota a força nas extremidades engastadas, " +"o deslocamento vertical dos nós de controle e as energias" + +msgid "``DATA0.DAT``" +msgstr "" + +msgid "The parameters in the format of the original program (``TEST 103``)" +msgstr "Os parâmetros no formato do programa original (``TEST 103``)" + +msgid "" +"The scenario and the load are the lines of the ``[scenario]`` section of " +"``case.ldem``:" +msgstr "O cenário e a carga são as linhas da seção ``[scenario]`` de ``case.ldem``:" + +msgid "" +"[scenario]\n" +"type = \"clamped_beam\"\n" +"force_rate = 1000 N/s\n" +"ramp_time = 0.35 ms\n" +"load_position = \"midspan\"\n" +"load_height = 0.5 modules" +msgstr "" + +msgid "" +"The same test can be written without a scenario class, with supports and loads. It " +"gives the same results as ``ldem.scenarios.ClampedBeam`` (the tests check it):" +msgstr "" +"O mesmo ensaio pode ser escrito sem uma classe de cenário, com apoios e cargas. Dá os" +" mesmos resultados que ``ldem.scenarios.ClampedBeam`` (os testes o verificam):" + +msgid "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"first end\"\n" +"z = 0.5\n" +"fix = [\"x\", \"y\", \"z\"]\n" +"reaction = true\n" +"\n" +"[[support]]\n" +"name = \"last end\"\n" +"z = \"max - 0.5\"\n" +"fix = [\"x\", \"y\", \"z\"]\n" +"reaction = true\n" +"\n" +"[[load]]\n" +"name = \"line at mid-span\"\n" +"y = 0.5\n" +"z = \"mid - 0.5\"\n" +"direction = \"y\"\n" +"type = \"force\"\n" +"time_function = \"ramp\"\n" +"rate = 1000 N/s\n" +"until = 0.35 ms" +msgstr "" + +msgid "Reading the results" +msgstr "Ler os resultados" + +#, python-format +msgid "" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem', " +"OutputFolder=tempname);\n" +">> y0 = results.mesh.nodes0(results.params.controlNodes, 2).';\n" +">> dy = results.controlNodes.displacement(:, :, 2) - y0; % vertical displacement " +"[m]\n" +">> results.reactions.force(end, :) % force on the clamped " +"ends [N]\n" +">> ldem.post.plotReaction(results);\n" +">> ldem.post.plotEnergy(results);" +msgstr "" +">> results = ldem.run('examples/example1_clamped_beam/case.ldem', " +"OutputFolder=tempname);\n" +">> y0 = results.mesh.nodes0(results.params.controlNodes, 2).';\n" +">> dy = results.controlNodes.displacement(:, :, 2) - y0; % deslocamento vertical " +"[m]\n" +">> results.reactions.force(end, :) % força nas extremidades" +" engastadas [N]\n" +">> ldem.post.plotReaction(results);\n" +">> ldem.post.plotEnergy(results);" + +msgid "What you should see" +msgstr "O que se deve ver" + +msgid "" +"Force carried by the clamped ends. It rises with the load, overshoots to 1.94 N and " +"settles at the total applied force." +msgstr "" +"Força suportada pelas extremidades engastadas. Cresce com a carga, ultrapassa até " +"1.94 N e se estabiliza na força total aplicada." + +msgid "" +"Vertical displacement of the two control nodes: a peak of 6.7 um at 0.46 ms and about" +" 6.3 um at the end." +msgstr "" +"Deslocamento vertical dos dois nós de controle: um pico de 6.7 um aos 0.46 ms e cerca" +" de 6.3 um no final." + +msgid "Energies. The external work equals the sum of the internal energies." +msgstr "Energias. O trabalho externo é igual à soma das energias internas." + +msgid "" +"The reaction settles at 1.75 N, the 1.75 N applied in total: the beam is in " +"equilibrium at the end. The overshoot (1.94 N) and the oscillation are the dynamic " +"response, which the damping removes." +msgstr "" +"A reação se estabiliza em 1.75 N, os 1.75 N aplicados no total: a viga está em " +"equilíbrio no final. A ultrapassagem (1.94 N) e a oscilação são a resposta dinâmica, " +"que o amortecimento elimina." + +msgid "" +"With these values the beam stays elastic: at the end 18,085 bars are intact and none " +"is damaged or broken." +msgstr "" +"Com estes valores a viga permanece elástica: no final 18,085 barras estão intactas e " +"nenhuma está danificada nem rompida." + +msgid "" +"The energy balance closes: the external work of 5.76 uJ is the elastic energy (5.48 " +"uJ) plus the energy dissipated by damping (0.28 uJ); the kinetic energy is about zero" +" and the balance is below 1e-13 J." +msgstr "" +"O balanço de energia fecha: o trabalho externo de 5.76 uJ é a energia elástica (5.48 " +"uJ) mais a energia dissipada pelo amortecimento (0.28 uJ); a energia cinética é quase" +" zero e o balanço é menor que 1e-13 J." + +msgid "Try other values" +msgstr "Experimentar outros valores" + +msgid "" +"Every key of the case file can be changed, or swept without editing the file (see " +":doc:`usage`):" +msgstr "" +"Cada chave do arquivo de caso pode ser mudada, ou varrida sem editar o arquivo (ver " +":doc:`usage`):" + +#, python-brace-format +msgid "" +">> summary = ldem.sweep('examples/example1_clamped_beam/case.ldem', ...\n" +" Vary = {'scenario.force_rate', [\"10 kN/s\" \"30 kN/s\" \"100 kN/s\"]}, " +"Formats = \"mat\");" +msgstr "" + +msgid "" +"With the original value (1 kN/s) no bar is damaged. Ten times more force already " +"breaks the beam; each run takes about 50 s:" +msgstr "" +"Com o valor original (1 kN/s) nenhuma barra é danificada. Com dez vezes mais força a " +"viga já se rompe; cada execução leva cerca de 50 s:" + +msgid "Force rate" +msgstr "Taxa de força" + +msgid "Damaged bars (including broken)" +msgstr "Barras danificadas (incluídas as rompidas)" + +msgid "Broken bars" +msgstr "Barras rompidas" + +msgid "10 kN/s" +msgstr "" + +msgid "5,630" +msgstr "" + +msgid "3,584" +msgstr "" + +msgid "30 kN/s" +msgstr "" + +msgid "6,074" +msgstr "" + +msgid "3,579" +msgstr "" + +msgid "100 kN/s" +msgstr "" + +msgid "4,760" +msgstr "" + +msgid "2,783" +msgstr "" + +msgid "" +"After the failure the loaded nodes keep being pushed by the force and move freely, so" +" the displacements of these runs are not meaningful; the damage counts are. Each run " +"has its own folder (``run_001``, ...) with its results and its resolved " +"``case.ldem``, and the table is also saved as ``sweep_summary.csv``." +msgstr "" +"Depois da falha, os nós carregados continuam sendo empurrados pela força e se movem " +"livremente, então os deslocamentos dessas execuções não têm significado; as contagens" +" de dano têm. Cada execução tem sua própria pasta (``run_001``, ...) com seus " +"resultados e seu ``case.ldem`` resolvido, e a tabela também é salva como " +"``sweep_summary.csv``." + +msgid "" +"Other changes to try in ``case.ldem``: ``law = \"linear_elastic\"`` (no damage at " +"all), ``type = \"generated\"`` with a ``cv`` in ``[material.scatter]`` to generate " +"the random field in memory instead of reading it, or ``type = \"none\"`` to remove " +"the scatter." +msgstr "" +"Outras mudanças para experimentar em ``case.ldem``: ``law = \"linear_elastic\"`` " +"(nenhum dano), ``type = \"generated\"`` com um ``cv`` em ``[material.scatter]`` para " +"gerar o campo aleatório na memória em vez de lê-lo, ou ``type = \"none\"`` para " +"remover a dispersão." + +msgid "Example: uniaxial prism" +msgstr "Exemplo: prisma uniaxial" + +msgid "" +"``examples/tension_101/runTension.m`` runs a prism of 5 x 2 x 2 modules of 3 mm (74 " +"nodes, 313 bars) under the uniaxial test (test 101): the centre nodes of the last " +"column move along x with a prescribed velocity of 4 mm/s while those of the first " +"column are held. It is the best place to start: it has no input file, the model is " +"described in the script with ``ldem.Parameters``, and it writes every kind of output." +msgstr "" +"``examples/tension_101/runTension.m`` executa um prisma de 5 x 2 x 2 módulos de 3 mm " +"(74 nós, 313 barras) sob o ensaio uniaxial (ensaio 101): os nós centrais da última " +"coluna se movem em x com uma velocidade imposta de 4 mm/s enquanto os da primeira " +"coluna ficam fixos. É o melhor lugar para começar: não tem arquivo de entrada, o " +"modelo é descrito no script com ``ldem.Parameters`` e escreve todos os tipos de " +"saída." + +msgid "" +"E = 32 GPa, Poisson's ratio 0.25, density 2000 kg/m\\ :sup:`3`; a low fracture energy" +" of 0.1 N/m on purpose, so that bars soften and break" +msgstr "" +"E = 32 GPa, coeficiente de Poisson 0.25, densidade 2000 kg/m\\ :sup:`3`; uma energia " +"de fratura baixa de 0.1 N/m de propósito, para que as barras amoleçam e rompam" + +msgid "0.2 ms in 1000 steps of 0.2 us" +msgstr "0.2 ms em 1000 passos de 0.2 us" + +msgid "Output" +msgstr "Saída" + +msgid "" +"Snapshots (ANSYS and VTK) every 250 steps, control nodes and energies every 10 steps," +" no tracked bar" +msgstr "" +"Instantâneos (ANSYS e VTK) a cada 250 passos, nós de controle e energias a cada 10 " +"passos, sem barra acompanhada" + +#, python-format +msgid "" +"At the end 251 bars are intact, 58 are damaged and 4 are broken. The external work is" +" 24.7 uJ: 22.5 uJ of elastic energy, 2.2 uJ dissipated by damage and 0.03 uJ by " +"damping; the balance is 0.01 % of the external work." +msgstr "" +"No final 251 barras estão intactas, 58 danificadas e 4 rompidas. O trabalho externo é" +" de 24.7 uJ: 22.5 uJ de energia elástica, 2.2 uJ dissipados pelo dano e 0.03 uJ pelo " +"amortecimento; o balanço é 0.01 % do trabalho externo." + +msgid "Energies of the uniaxial prism." +msgstr "Energias do prisma uniaxial." + +msgid "" +"With the sign convention of the original code a positive ``loadingVelocity`` moves " +"the loaded face toward the fixed one, that is, it compresses the prism; use a " +"negative value to pull it (see ``ldem.scenarios.UniaxialTension``)." +msgstr "" +"Com a convenção de sinais do código original, um ``loadingVelocity`` positivo move a " +"face carregada em direção à fixa, isto é, comprime o prisma; use um valor negativo " +"para tracioná-lo (ver ``ldem.scenarios.UniaxialTension``)." + +msgid "Example: four-point bending beam" +msgstr "Exemplo: viga em flexão de quatro pontos" + +msgid "" +"``examples/beam_102/runBeam.m`` reads the input of the beam of the paper (test 102, " +"``ldem.scenarios.FourPointBending``): 100 x 40 x 20 modules of 3 mm (300 x 120 x 60 " +"mm), 166,961 nodes and 1,126,960 bars. The beam rests on two supports 4.5 modules " +"from its ends and two load points 33.5 modules from its ends push its top face down " +"with a prescribed velocity of 4 mm/s. The material is E = 32 GPa, density 2000 kg/m\\" +" :sup:`3`, fracture energy 50 N/m, critical distance 28 mm, with a random field of " +"the critical strain read from a file." +msgstr "" +"``examples/beam_102/runBeam.m`` lê a entrada da viga do artigo (ensaio 102, " +"``ldem.scenarios.FourPointBending``): 100 x 40 x 20 módulos de 3 mm (300 x 120 x 60 " +"mm), 166,961 nós e 1,126,960 barras. A viga se apoia em dois apoios a 4.5 módulos das" +" suas extremidades e dois pontos de carga a 33.5 módulos das suas extremidades " +"empurram sua face superior para baixo com uma velocidade imposta de 4 mm/s. O " +"material tem E = 32 GPa, densidade 2000 kg/m\\ :sup:`3`, energia de fratura 50 N/m, " +"distância crítica 28 mm, com um campo aleatório da deformação crítica lido de um " +"arquivo." + +msgid "" +"The real simulation has 150,000 steps (0.03 s in steps of 0.2 us) and needs roughly " +"20 hours on a laptop (about 0.5 s per step). The script therefore runs only the first" +" 50 steps: it builds the complete model (about 20 s) and shows that the input is read" +" and the model runs; the plotted reaction is only that of the start of the test. " +"Change ``nStepsDemo`` at the top of the script, or remove the ``totalTime`` override," +" for the full run." +msgstr "" +"A simulação real tem 150,000 passos (0.03 s em passos de 0.2 us) e precisa de cerca " +"de 20 horas em um laptop (cerca de 0.5 s por passo). Por isso o script executa apenas" +" os primeiros 50 passos: constrói o modelo completo (cerca de 20 s) e mostra que a " +"entrada é lida e o modelo roda; a reação plotada é apenas a do início do ensaio. Mude" +" ``nStepsDemo`` no início do script, ou remova a substituição de ``totalTime``, para " +"a execução completa." + +msgid "The same parameters as a case file (``ldem.io.readCase``, ``ldem.run``)" +msgstr "Os mesmos parâmetros como arquivo de caso (``ldem.io.readCase``, ``ldem.run``)" + +msgid "Parameters in the format of the original program (``ldem.Parameters.fromFile``)" +msgstr "Parâmetros no formato do programa original (``ldem.Parameters.fromFile``)" + +msgid "``arquivo_3lc_rnao_cv05``" +msgstr "" + +msgid "" +"Random field applied to the critical strain of each bar (11 MB); it is also used by " +"``example1_clamped_beam``" +msgstr "" +"Campo aleatório aplicado à deformação crítica de cada barra (11 MB); também é usado " +"por ``example1_clamped_beam``" + +msgid "``runBeam.m``" +msgstr "" + +msgid "Reads the input, runs the first 50 steps and plots the reaction force" +msgstr "Lê a entrada, executa os primeiros 50 passos e plota a força de reação" + diff --git a/docs/locale/pt/LC_MESSAGES/index.po b/docs/locale/pt/LC_MESSAGES/index.po new file mode 100644 index 0000000..b53fad8 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/index.po @@ -0,0 +1,34 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "User guide" +msgstr "Guia do usuário" + +msgid "API" +msgstr "" + +msgid "LDEM-MATLAB" +msgstr "" + +msgid "Lattice Discrete Element Method (LDEM) in MATLAB." +msgstr "Método dos Elementos Discretos tipo Lattice (LDEM) em MATLAB." + +msgid "" +"The documentation is written in English and translated into Spanish, Portuguese and " +"Italian. Choose the language in the sidebar of any page." +msgstr "" +"A documentação está escrita em inglês e traduzida para espanhol, português e " +"italiano. Escolha o idioma na barra lateral de qualquer página." + diff --git a/docs/locale/pt/LC_MESSAGES/installation.po b/docs/locale/pt/LC_MESSAGES/installation.po new file mode 100644 index 0000000..61f8aa8 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/installation.po @@ -0,0 +1,72 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Installation" +msgstr "Instalação" + +msgid "" +"Requirements: MATLAB R2022b or newer (developed and tested on R2023b). The package " +"itself uses the ``arguments`` block and name=value syntax; the test suite and " +"``buildtool`` need R2022b. No toolbox is required." +msgstr "" +"Requisitos: MATLAB R2022b ou superior (desenvolvido e testado na R2023b). O pacote " +"usa o bloco ``arguments`` e a sintaxe nome=valor; a suíte de testes e o ``buildtool``" +" exigem a R2022b. Nenhum toolbox é necessário." + +msgid "" +"git clone ldem-matlab\n" +"cd ldem-matlab" +msgstr "" +"git clone ldem-matlab\n" +"cd ldem-matlab" + +msgid ">> setup_path" +msgstr "" + +msgid "Check the installation with the fast tests:" +msgstr "Verifique a instalação com os testes rápidos:" + +msgid ">> buildtool test" +msgstr "" + +msgid "Developer tasks (``buildtool`` is run from the repository root):" +msgstr "" +"Tarefas para desenvolvedores (``buildtool`` é executado a partir da raiz do " +"repositório):" + +#, python-format +msgid "" +">> buildtool % static analysis + fast tests (the default)\n" +">> buildtool check % Code Analyzer only\n" +">> buildtool testAll % all tests, including the slow ones\n" +">> buildtool docs % build this documentation (needs Python)\n" +">> buildtool clean % delete generated files" +msgstr "" +">> buildtool % análise estática + testes rápidos (padrão)\n" +">> buildtool check % somente o analisador de código\n" +">> buildtool testAll % todos os testes, inclusive os lentos\n" +">> buildtool docs % construir esta documentação (requer Python)\n" +">> buildtool clean % apagar os arquivos gerados" + +msgid "" +"``buildtool test`` writes ``test-results/results.xml`` (JUnit) and ``code-" +"coverage/coverage.xml`` (Cobertura)." +msgstr "" +"``buildtool test`` escreve ``test-results/results.xml`` (JUnit) e ``code-" +"coverage/coverage.xml`` (Cobertura)." + +msgid "To build this documentation without MATLAB see :doc:`docs`." +msgstr "Para construir esta documentação sem MATLAB, veja :doc:`docs`." + diff --git a/docs/locale/pt/LC_MESSAGES/introduction.po b/docs/locale/pt/LC_MESSAGES/introduction.po new file mode 100644 index 0000000..f1f2872 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/introduction.po @@ -0,0 +1,74 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Introduction" +msgstr "Introdução" + +msgid "" +"The **Lattice Discrete Element Method (LDEM)** models a continuum as a regular " +"lattice of nodes connected by bars arranged in cubic modules (edges plus diagonals). " +"Nodal masses are lumped, bar constitutive laws include damage/fracture, and the " +"equations of motion are integrated with an explicit central-difference scheme. " +"Energies (external, kinetic, elastic, dissipated) are tracked at every step." +msgstr "" +"O **Método dos Elementos Discretos tipo Treliça (LDEM)** modela um contínuo como um " +"reticulado regular de nós ligados por barras dispostas em módulos cúbicos (arestas " +"mais diagonais). As massas são concentradas nos nós, as leis constitutivas das barras" +" incluem dano/fratura e as equações de movimento são integradas com um esquema " +"explícito de diferenças centrais. As energias (externa, cinética, elástica, " +"dissipada) são acompanhadas a cada passo." + +msgid "Main parts of the ``ldem`` package (see :doc:`api/index`):" +msgstr "Principais partes do pacote ``ldem`` (ver :doc:`api/index`):" + +msgid "" +"``ldem.Parameters`` / ``ldem.io.readCase`` / ``ldem.io.readInputFile`` – validated " +"input data (case files and the legacy ``DATA0.DAT``)." +msgstr "" +"``ldem.Parameters`` / ``ldem.io.readCase`` / ``ldem.io.readInputFile`` – dados de " +"entrada validados (arquivos de caso e o ``DATA0.DAT`` original)." + +msgid "``ldem.run`` / ``ldem.sweep`` / ``ldem.check`` – run, sweep and check a case file." +msgstr "" +"``ldem.run`` / ``ldem.sweep`` / ``ldem.check`` – executar, varrer e verificar um " +"arquivo de caso." + +msgid "``ldem.mesh`` – nodes, bars, masses and bar geometry." +msgstr "``ldem.mesh`` – nós, barras, massas e geometria das barras." + +msgid "``ldem.material`` – bar stiffness, critical strain and the bilinear damage law." +msgstr "``ldem.material`` – rigidez das barras, deformação crítica e lei bilinear de dano." + +msgid "``ldem.scenarios`` – supports, loads and reactions of each test." +msgstr "``ldem.scenarios`` – apoios, cargas e reações de cada ensaio." + +msgid "``ldem.solver`` – time integration and energy balance." +msgstr "``ldem.solver`` – integração no tempo e balanço de energia." + +msgid "" +"``ldem.runSimulation`` – the whole simulation, with ``results.mat``, ANSYS and VTK " +"output." +msgstr "``ldem.runSimulation`` – a simulação completa, com saída ``results.mat``, ANSYS e VTK." + +msgid "" +"The routines of the original program (``ini_DEM3``, ``read_dat0``, ``RMEC``, " +"``BOUND``, ``CALOAD``, ``ENERG2``, ...) are kept in the git history under the tag " +"``legacy-reference``; the ``Legacy:`` line of each help text names the routine it " +"replaces." +msgstr "" +"As rotinas do programa original (``ini_DEM3``, ``read_dat0``, ``RMEC``, ``BOUND``, " +"``CALOAD``, ``ENERG2``, ...) são mantidas no histórico do git, com a tag ``legacy-" +"reference``; a linha ``Legacy:`` de cada ajuda indica a rotina que ela substitui." + diff --git a/docs/locale/pt/LC_MESSAGES/model.po b/docs/locale/pt/LC_MESSAGES/model.po new file mode 100644 index 0000000..a60e193 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/model.po @@ -0,0 +1,237 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Building a different model" +msgstr "Construir um modelo diferente" + +msgid "" +"A model is defined by three things: the **geometry** of the lattice, the **material**" +" and the **test** (supports and loads). The first two are parameters; the third is a " +"*scenario* class. You can change any of them without touching the solver." +msgstr "" +"Um modelo é definido por três coisas: a **geometria** do reticulado, o **material** e" +" o **ensaio** (apoios e cargas). As duas primeiras são parâmetros; a terceira é uma " +"classe *cenário*. Qualquer uma pode ser alterada sem tocar no solver." + +msgid "1. Change the geometry and the material" +msgstr "1. Alterar a geometria e o material" + +msgid "Everything is a property of ``ldem.Parameters``:" +msgstr "Tudo é uma propriedade de ``ldem.Parameters``:" + +#, python-format +msgid "" +">> params = ldem.Parameters(testId=101, ...\n" +" moduleLength=0.002, ... % edge of the cubic module [m]\n" +" nModules=[21 6 6], ... % nodes along x, y and z\n" +" youngModulus=30e9, density=2400, poissonRatio=0.2, ...\n" +" fractureEnergy=80, criticalDistance=0.02, ...\n" +" meshPerturbation=0.02); % optional irregular mesh" +msgstr "" +">> params = ldem.Parameters(testId=101, ...\n" +" moduleLength=0.002, ... % aresta do módulo cúbico [m]\n" +" nModules=[21 6 6], ... % nós em x, y e z\n" +" youngModulus=30e9, density=2400, poissonRatio=0.2, ...\n" +" fractureEnergy=80, criticalDistance=0.02, ...\n" +" meshPerturbation=0.02); % malha irregular (opcional)" + +msgid "" +"``nModules = [M N L]`` is the number of grid nodes along each axis, so the prism has " +"``(M-1)*(N-1)*(L-1)`` modules." +msgstr "" +"``nModules = [M N L]`` é o número de nós da grade em cada eixo, de modo que o prisma " +"tem ``(M-1)*(N-1)*(L-1)`` módulos." + +msgid "" +"``randomFieldFile`` multiplies the critical strain of each bar by a value read from a" +" text file (a random field of the material strength)." +msgstr "" +"``randomFieldFile`` multiplica a deformação crítica de cada barra por um valor lido " +"de um arquivo de texto (campo aleatório da resistência)." + +msgid "" +"``randomFieldCv`` generates that random field in memory instead, with no file: " +"Weibull values with mean 1 and that coefficient of variation on a grid of poles " +"spaced ``randomFieldCorrelationLength`` module lengths apart (default 3), " +"interpolated to each bar; ``randomFieldSeed`` fixes the random numbers. The value of " +"each bar is kept in ``results.barProps.randomField``." +msgstr "" +"``randomFieldCv`` gera esse campo aleatório na memória, sem arquivo: valores Weibull " +"com média 1 e esse coeficiente de variação numa grade de polos espaçados " +"``randomFieldCorrelationLength`` comprimentos de módulo (3 por padrão), interpolados " +"para cada barra; ``randomFieldSeed`` fixa os números aleatórios. O valor de cada " +"barra fica em ``results.barProps.randomField``." + +msgid "" +"``dt`` must be below ``params.criticalTimeStep``; ``Parameters`` rejects an unstable " +"value and says so." +msgstr "" +"``dt`` deve ser menor que ``params.criticalTimeStep``; ``Parameters`` rejeita um " +"valor instável e explica o motivo." + +msgid "" +"The same data can come from a case file (``ldem.io.readCase``, see :doc:`usage`) or " +"from an input file in the format of the original program with " +"``ldem.Parameters.fromFile(\"DATA0.DAT\", ...)``; extra name=value pairs override the" +" file. The mesh can be built and inspected before running anything:" +msgstr "" +"Os mesmos dados podem vir de um arquivo de caso (``ldem.io.readCase``, ver " +":doc:`usage`) ou de um arquivo de entrada no formato do programa original: " +"``ldem.Parameters.fromFile(\"DATA0.DAT\", ...)``; os pares nome=valor adicionais " +"substituem os do arquivo. A malha pode ser construída e inspecionada antes de " +"executar qualquer coisa:" + +#, python-format +msgid "" +">> mesh = ldem.mesh.buildMesh(params);\n" +">> fprintf(\"%d nodes, %d bars\\n\", size(mesh.nodes0, 1), size(mesh.bars, 1));" +msgstr "" +">> mesh = ldem.mesh.buildMesh(params);\n" +">> fprintf(\"%d nós, %d barras\\n\", size(mesh.nodes0, 1), size(mesh.bars, 1));" + +msgid "2. Change the test: write a scenario" +msgstr "2. Alterar o ensaio: escrever um cenário" + +msgid "" +"A *scenario* says which degrees of freedom are fixed, how the load is applied at " +"every time step and which reaction is reported. The solver never checks the test " +"number, it only asks the scenario. To model a new test, create a subclass of " +"``ldem.scenarios.Scenario`` in ``src/+ldem/+scenarios/``." +msgstr "" +"Um *cenário* diz quais graus de liberdade estão fixos, como a carga é aplicada a cada" +" passo de tempo e qual reação é informada. O solver nunca consulta o número do " +"ensaio; ele pergunta ao cenário. Para modelar um ensaio novo, crie uma subclasse de " +"``ldem.scenarios.Scenario`` em ``src/+ldem/+scenarios/``." + +msgid "" +"The example below is a cantilever beam along :math:`z`: the first layer of centre " +"nodes is clamped and a force that grows linearly is applied in :math:`y` at the free " +"end." +msgstr "" +"O exemplo é uma viga em balanço segundo :math:`z`: a primeira camada de nós centrais " +"é engastada e, na extremidade livre, aplica-se em :math:`y` uma força que cresce " +"linearmente." + +#, python-format +msgid "" +"classdef Cantilever < ldem.scenarios.Scenario\n" +" properties (Constant)\n" +" testId = 104 % new number, unique\n" +" end\n" +" properties\n" +" forceRate (1,1) double = 500 % [N/s] on each loaded node\n" +" end\n" +" methods\n" +" function fixed = fixedDofs(~, nodes0, params)\n" +" z = nodes0(:, 3);\n" +" atStart = abs(z - 0.5*params.moduleLength) < 0.01*params.moduleLength;\n" +" fixed = false(size(nodes0));\n" +" fixed(atStart, :) = true; % x, y and z held\n" +" end\n" +" function state = applyLoads(obj, state, mesh, params)\n" +" L1 = params.nModules(3) - 1;\n" +" z = mesh.nodes0(:, 3);\n" +" atEnd = abs(z - (L1 - 0.5)*params.moduleLength) < " +"0.01*params.moduleLength;\n" +" state.appliedForce(:) = 0;\n" +" state.appliedForce(atEnd, 2) = obj.forceRate * state.time;\n" +" end\n" +" end\n" +"end" +msgstr "" +"classdef Cantilever < ldem.scenarios.Scenario\n" +" properties (Constant)\n" +" testId = 104 % número novo, único\n" +" end\n" +" properties\n" +" forceRate (1,1) double = 500 % [N/s] em cada nó carregado\n" +" end\n" +" methods\n" +" function fixed = fixedDofs(~, nodes0, params)\n" +" z = nodes0(:, 3);\n" +" atStart = abs(z - 0.5*params.moduleLength) < 0.01*params.moduleLength;\n" +" fixed = false(size(nodes0));\n" +" fixed(atStart, :) = true; % x, y e z fixos\n" +" end\n" +" function state = applyLoads(obj, state, mesh, params)\n" +" L1 = params.nModules(3) - 1;\n" +" z = mesh.nodes0(:, 3);\n" +" atEnd = abs(z - (L1 - 0.5)*params.moduleLength) < " +"0.01*params.moduleLength;\n" +" state.appliedForce(:) = 0;\n" +" state.appliedForce(atEnd, 2) = obj.forceRate * state.time;\n" +" end\n" +" end\n" +"end" + +msgid "Rules to follow:" +msgstr "Regras:" + +msgid "" +"``fixedDofs`` returns an ``nNodes``-by-3 logical matrix, true where the node cannot " +"move (``1 = x``, ``2 = y``, ``3 = z``)." +msgstr "" +"``fixedDofs`` devolve uma matriz lógica de ``nNodes`` por 3, verdadeira onde o nó não" +" pode se mover (``1 = x``, ``2 = y``, ``3 = z``)." + +msgid "" +"``applyLoads`` runs once per step. A **displacement-controlled** test sets " +"``state.displacement`` of the loaded nodes (see ``UniaxialTension``); a **force-" +"controlled** test sets ``state.appliedForce`` in newtons (see ``ClampedBeam``) and " +"the solver counts its work in the external energy." +msgstr "" +"``applyLoads`` é executado a cada passo. Um ensaio **controlado por deslocamento** " +"atribui ``state.displacement`` dos nós carregados (ver ``UniaxialTension``); um " +"**controlado por força** atribui ``state.appliedForce`` em newtons (ver " +"``ClampedBeam``) e o solver conta seu trabalho na energia externa." + +msgid "Override ``reactions`` if the test reports a reaction force (default: ``NaN``)." +msgstr "Redefina ``reactions`` se o ensaio informar uma força de reação (padrão: ``NaN``)." + +msgid "" +"The centre nodes of the modules lie at half-integer multiples of ``moduleLength``; " +"select nodes with a small tolerance, never with ``==``." +msgstr "" +"Os nós centrais dos módulos estão em múltiplos semi-inteiros de ``moduleLength``; " +"selecione os nós com uma tolerância pequena, nunca com ``==``." + +msgid "3. Register and run it" +msgstr "3. Registrar e executar" + +msgid "Either pass the object directly, with no registration:" +msgstr "O objeto pode ser passado diretamente, sem registrar nada:" + +msgid "" +">> scenario = ldem.scenarios.Cantilever(forceRate=1000);\n" +">> results = ldem.runSimulation(params, Scenario=scenario, ...\n" +" OutputFolder=\"output\", Formats=[\"mat\" \"vtk\"]);" +msgstr "" + +msgid "" +"or add one line to ``ldem.scenarios.registry`` so that ``testId = 104`` finds it and " +"a case file can name it with ``type``. Then add a test in ``tests/unit`` and, if it " +"is a reference case, an example in ``examples/`` (see " +"``examples/example1_clamped_beam``)." +msgstr "" +"ou adicionar uma linha a ``ldem.scenarios.registry`` para que ``testId = 104`` o " +"encontre e um arquivo de caso possa nomeá-lo com ``type``. Depois, adicione um teste " +"em ``tests/unit`` e, se for um caso de referência, um exemplo em ``examples/`` (ver " +"``examples/example1_clamped_beam``)." + +msgid "The result is the same ``results`` struct as for any other test, see :doc:`usage`." +msgstr "" +"O resultado é a mesma estrutura ``results`` de qualquer outro ensaio, ver " +":doc:`usage`." + diff --git a/docs/locale/pt/LC_MESSAGES/sphinx.po b/docs/locale/pt/LC_MESSAGES/sphinx.po new file mode 100644 index 0000000..5def05e --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/sphinx.po @@ -0,0 +1,45 @@ +# User-interface texts of the theme (Furo) in pt: buttons, search and page navigation. +# Kept by hand: docs/tools/update_translations.py does not touch this file. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Skip to content" +msgstr "Pular para o conteúdo" + +msgid "Back to top" +msgstr "Voltar ao topo" + +msgid "Next" +msgstr "Próximo" + +msgid "Previous" +msgstr "Anterior" + +msgid "Home" +msgstr "Início" + +msgid "On this page" +msgstr "Nesta página" + +msgid "Search" +msgstr "Pesquisar" + +msgid "Index" +msgstr "Índice" + +msgid "Error" +msgstr "Erro" + +msgid "Please activate JavaScript to enable the search functionality." +msgstr "Ative o JavaScript para habilitar a função de pesquisa." + diff --git a/docs/locale/pt/LC_MESSAGES/usage.po b/docs/locale/pt/LC_MESSAGES/usage.po new file mode 100644 index 0000000..79baf20 --- /dev/null +++ b/docs/locale/pt/LC_MESSAGES/usage.po @@ -0,0 +1,1340 @@ +# Translation of the LDEM-MATLAB documentation (pt). +# Generated by docs/tools/update_translations.py: edit only the msgstr entries. +msgid "" +msgstr "" +"Project-Id-Version: LDEM-MATLAB\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language: pt\n" +"Language-Team: \n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=utf-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 2.18.0\n" + +msgid "Usage" +msgstr "Uso" + +msgid "Run a simulation" +msgstr "Executar uma simulação" + +msgid "" +">> setup_path % adds src/ to the MATLAB path\n" +">> params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4, ...\n" +" fractureEnergy=0.1, ...\n" +" output=struct('snapshotEvery', 250, 'controlNodesEvery', 10, ...\n" +" 'energyEvery', 10, 'trackedBarEvery', 0));\n" +">> results = ldem.runSimulation(params, OutputFolder=\"output\", ...\n" +" Formats=[\"mat\" \"ansys\" \"vtk\"]);\n" +">> ldem.post.plotEnergy(results);" +msgstr "" +">> setup_path % adiciona src/ ao path do MATLAB\n" +">> params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4, ...\n" +" fractureEnergy=0.1, ...\n" +" output=struct('snapshotEvery', 250, 'controlNodesEvery', 10, ...\n" +" 'energyEvery', 10, 'trackedBarEvery', 0));\n" +">> results = ldem.runSimulation(params, OutputFolder=\"output\", ...\n" +" Formats=[\"mat\" \"ansys\" \"vtk\"]);\n" +">> ldem.post.plotEnergy(results);" + +msgid "" +"``ldem.Parameters`` checks every value when it is set and explains what is wrong (for" +" example an unstable time step). The complete, ready-to-run version of this script is" +" ``examples/tension_101/runTension.m``." +msgstr "" +"``ldem.Parameters`` valida cada valor ao atribuí-lo e explica o que está errado (por " +"exemplo, um passo de tempo instável). A versão completa e pronta para executar está " +"em ``examples/tension_101/runTension.m``." + +msgid "To use an input file in the format of the original program:" +msgstr "Para usar um arquivo de entrada no formato do programa original:" + +msgid ">> params = ldem.Parameters.fromFile(\"DATA0.DAT\");" +msgstr "" + +msgid "Case files (``.ldem``)" +msgstr "Arquivos de caso (``.ldem``)" + +msgid "" +"A *case file* describes the whole model in one readable text file: named keys instead" +" of positions, units next to the numbers, comments, and the test, the random scatter " +"and the output files together. It replaces ``DATA0.DAT``." +msgstr "" +"Um *arquivo de caso* descreve todo o modelo em um único texto legível: chaves com " +"nome em vez de posições, unidades junto aos números, comentários, e o ensaio, a " +"dispersão aleatória e os arquivos de saída juntos. Ele substitui o ``DATA0.DAT``." + +msgid "" +"format = 1\n" +"title = \"Small tension test\"\n" +"\n" +"[mesh]\n" +"module_size = 3 mm\n" +"modules = [5, 2, 2] # cubic modules along x, y and z\n" +"\n" +"[material]\n" +"young_modulus = 32 GPa\n" +"density = 2000 kg/m3\n" +"\n" +"[time]\n" +"step = auto # 0.9 times the critical step\n" +"duration = 40 us\n" +"\n" +"[scenario]\n" +"type = \"uniaxial_tension\"\n" +"\n" +"[output]\n" +"folder = \"output\"" +msgstr "" +"format = 1\n" +"title = \"Pequeno ensaio de tração\"\n" +"\n" +"[mesh]\n" +"module_size = 3 mm\n" +"modules = [5, 2, 2] # módulos cúbicos em x, y e z\n" +"\n" +"[material]\n" +"young_modulus = 32 GPa\n" +"density = 2000 kg/m3\n" +"\n" +"[time]\n" +"step = auto # 0.9 vezes o passo crítico\n" +"duration = 40 us\n" +"\n" +"[scenario]\n" +"type = \"uniaxial_tension\"\n" +"\n" +"[output]\n" +"folder = \"output\"" + +#, python-format +msgid "" +">> ldem.io.writeTemplate(\"my_test.ldem\", \"clamped_beam\"); % a commented file to " +"edit\n" +">> ldem.check(\"my_test.ldem\") % validate and report, " +"no simulation\n" +">> results = ldem.run(\"my_test.ldem\"); % run it\n" +">> ldem.io.convertLegacyInput(\"DATA0.DAT\", \"case.ldem\"); % convert an old input" +" file" +msgstr "" +">> ldem.io.writeTemplate(\"meu_ensaio.ldem\", \"clamped_beam\"); % arquivo comentado" +" para editar\n" +">> ldem.check(\"meu_ensaio.ldem\") % valida e informa, " +"sem simular\n" +">> results = ldem.run(\"meu_ensaio.ldem\"); % executa\n" +">> ldem.io.convertLegacyInput(\"DATA0.DAT\", \"caso.ldem\"); % converte um " +"arquivo antigo" + +msgid "Rules of the format:" +msgstr "Regras do formato:" + +msgid "" +"Keys are read by **name**; the order of the lines does not matter. Keys that are " +"missing take the default of ``ldem.Parameters``. Only ``scenario.type``, " +"``mesh.modules`` and ``time.duration`` are required." +msgstr "" +"As chaves são lidas por **nome**; a ordem das linhas não importa. As chaves ausentes " +"assumem o valor padrão de ``ldem.Parameters``. Só são obrigatórias ``scenario.type``," +" ``mesh.modules`` e ``time.duration``." + +msgid "" +"A number may carry a **unit**: ``3.87 GPa``, ``0.35 us``, ``1500 kg/m3``, ``2 kN/s``." +" Without a unit the value is in SI. The wrong unit for the key is an error that lists" +" the valid ones." +msgstr "" +"Um número pode ter **unidade**: ``3.87 GPa``, ``0.35 us``, ``1500 kg/m3``, ``2 " +"kN/s``. Sem unidade o valor está em SI. Uma unidade incorreta para a chave é um erro " +"que lista as válidas." + +msgid "" +"``#`` starts a comment, ``[section]`` opens a table, ``[[monitor.node]]`` starts the " +"next element of a repeated table, lists are written ``[5, 5, 50]``." +msgstr "" +"``#`` inicia um comentário, ``[seção]`` abre uma tabela, ``[[monitor.node]]`` inicia " +"o próximo elemento de uma tabela repetida e as listas são escritas ``[5, 5, 50]``." + +msgid "" +"``mesh.modules`` counts **modules**: the ``M N L`` of ``DATA0.DAT`` count nodes, one " +"more." +msgstr "" +"``mesh.modules`` conta **módulos**: os ``M N L`` do ``DATA0.DAT`` contam nós, um a " +"mais." + +msgid "``time.step = auto`` (or no ``step``) takes 0.9 times the critical step." +msgstr "``time.step = auto`` (ou sem ``step``) assume 0.9 vez o passo crítico." + +msgid "" +"Every error names the file, the line, the section and the key, and suggests the " +"closest valid name for a mistyped one." +msgstr "" +"Cada erro indica o arquivo, a linha, a seção e a chave, e sugere o nome válido mais " +"parecido quando há erro de digitação." + +msgid "" +"Relative paths (the random-field file, the output folder) are relative to the case " +"file." +msgstr "" +"Os caminhos relativos (arquivo do campo aleatório, pasta de saída) são relativos ao " +"arquivo de caso." + +msgid "A JSON file with the same structure (values with units as strings) is also read." +msgstr "" +"Também é lido um arquivo JSON com a mesma estrutura (os valores com unidades, como " +"texto)." + +msgid "Section" +msgstr "Seção" + +msgid "Keys" +msgstr "Chaves" + +msgid "(top)" +msgstr "(início)" + +msgid "``format`` (1), ``title``, ``authors``" +msgstr "" + +msgid "``[mesh]``" +msgstr "" + +msgid "" +"``module_size``, ``modules``, ``perturbation`` (random displacement of the nodes, " +"fraction of the module), ``seed`` (of the perturbation)" +msgstr "" +"``module_size``, ``modules``, ``perturbation`` (deslocamento aleatório dos nós, " +"fração do módulo), ``seed`` (da perturbação)" + +msgid "``[material]``" +msgstr "" + +msgid "" +"``law`` (``bilinear``, the legacy law, or ``linear_elastic``: no damage and no " +"rupture), ``young_modulus``, ``poisson_ratio``, ``density``, ``fracture_energy``, " +"``critical_distance``, ``failure_area_factor``" +msgstr "" +"``law`` (``bilinear``, a lei original, ou ``linear_elastic``: sem dano nem ruptura), " +"``young_modulus``, ``poisson_ratio``, ``density``, ``fracture_energy``, " +"``critical_distance``, ``failure_area_factor``" + +msgid "``[material.scatter]``" +msgstr "" + +msgid "" +"Scatter of the critical strain of the bars. ``type = \"none\"``; ``\"file\"`` with " +"``file`` (one multiplier per bar); or ``\"generated\"`` with ``cv``, " +"``correlation_length`` (in modules) and ``seed`` (the field is computed in memory)" +msgstr "" +"Dispersão da deformação crítica das barras. ``type = \"none\"``; ``\"file\"`` com " +"``file`` (um multiplicador por barra); ou ``\"generated\"`` com ``cv``, " +"``correlation_length`` (em módulos) e ``seed`` (o campo é calculado na memória)" + +msgid "``[time]``" +msgstr "" + +msgid "``step`` (or ``auto``), ``duration``" +msgstr "``step`` (ou ``auto``), ``duration``" + +msgid "``[damping]``" +msgstr "" + +msgid "" +"``type`` (``mass_proportional``, the legacy damping, or ``none``), ``initial``, " +"``final``, ``switch_time`` (not allowed with ``none``), ``constitutive``" +msgstr "" +"``type`` (``mass_proportional``, o amortecimento original, ou ``none``), ``initial``," +" ``final``, ``switch_time`` (não aceitos com ``none``), ``constitutive``" + +msgid "``[scenario]``" +msgstr "" + +msgid "" +"``type`` (``uniaxial_tension``, ``four_point_bending``, ``clamped_beam`` or " +"``custom``, see below) and the properties of that scenario in snake_case, for example" +" ``force_rate``, ``ramp_time``, ``load_position`` (``\"midspan\"`` is allowed)" +msgstr "" +"``type`` (``uniaxial_tension``, ``four_point_bending``, ``clamped_beam`` ou " +"``custom``, veja abaixo) e as propriedades desse cenário em snake_case, por exemplo " +"``force_rate``, ``ramp_time``, ``load_position`` (é aceito ``\"midspan\"``)" + +msgid "``[[monitor.node]]``" +msgstr "" + +msgid "" +"One element per control node: ``id`` (node number) or ``at = [x, y, z]`` (position in" +" modules, the nearest node is used), and ``name``" +msgstr "" +"Um elemento por nó de controle: ``id`` (número do nó) ou ``at = [x, y, z]`` (posição " +"em módulos, usa-se o nó mais próximo), e ``name``" + +msgid "``[monitor.bar]``" +msgstr "" + +msgid "``tracked``: bar whose strain history is stored at every step" +msgstr "``tracked``: barra cuja história de deformação é guardada a cada passo" + +msgid "``[output]``" +msgstr "" + +msgid "``folder``, ``mat``, ``ansys``, ``vtk`` (true or false)" +msgstr "``folder``, ``mat``, ``ansys``, ``vtk`` (true ou false)" + +msgid "``[output.snapshots]``, ``[output.control_nodes]``, ``[output.energy]``" +msgstr "" + +msgid "" +"``every``: ``1000 steps`` or a time such as ``0.1 ms`` (converted to steps); ``0`` " +"means never" +msgstr "" +"``every``: ``1000 steps`` ou um tempo como ``0.1 ms`` (convertido em passos); ``0`` " +"significa nunca" + +msgid "" +"``ldem.io.readCase`` returns the parameters, the scenario and the output options; " +"``ldem.Parameters.fromFile`` also accepts a case file. The list of keys lives in one " +"table, ``ldem.schema.caseSchema``, which drives the reader, the writer and the " +"template. To add a scenario, add a line to ``ldem.scenarios.registry``. A new " +"constitutive law is a subclass of ``ldem.material.MaterialLaw`` registered in " +"``ldem.material.lawRegistry``; a new damping model is a subclass of " +"``ldem.solver.DampingModel`` registered in ``ldem.solver.dampingRegistry``." +msgstr "" +"``ldem.io.readCase`` devolve os parâmetros, o cenário e as opções de saída; " +"``ldem.Parameters.fromFile`` também aceita um arquivo de caso. A lista de chaves está" +" em uma única tabela, ``ldem.schema.caseSchema``, que governa o leitor, o escritor e " +"o modelo. Para adicionar um cenário, adiciona-se uma linha a " +"``ldem.scenarios.registry``. Uma nova lei constitutiva é uma subclasse de " +"``ldem.material.MaterialLaw`` registrada em ``ldem.material.lawRegistry``; um novo " +"modelo de amortecimento, uma subclasse de ``ldem.solver.DampingModel`` registrada em " +"``ldem.solver.dampingRegistry``." + +msgid "Your own test: supports and loads" +msgstr "O seu próprio ensaio: apoios e cargas" + +msgid "" +"With ``type = \"custom\"`` the test is described in the case file by ``[[support]]`` " +"and ``[[load]]`` blocks, without writing a class. This is the uniaxial test (``testId" +" = 101``) as blocks:" +msgstr "" +"Com ``type = \"custom\"`` o ensaio é descrito no arquivo de caso com blocos " +"``[[support]]`` e ``[[load]]``, sem escrever uma classe. Este é o ensaio uniaxial " +"(``testId = 101``) como blocos:" + +msgid "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"left end\"\n" +"x = 0.5 # the layer of centre nodes at x = 0.5 modules\n" +"fix = [\"x\"] # directions that cannot move\n" +"\n" +"[[load]]\n" +"name = \"right end\"\n" +"x = \"max - 0.5\"\n" +"direction = \"x\"\n" +"type = \"displacement\" # or \"force\"\n" +"time_function = \"linear\"\n" +"rate = -4 mm/s\n" +"reaction = true # its force is the reaction of the test" +msgstr "" +"[scenario]\n" +"type = \"custom\"\n" +"\n" +"[[support]]\n" +"name = \"left end\"\n" +"x = 0.5 # a camada de nós centrais em x = 0.5 módulos\n" +"fix = [\"x\"] # direções que não podem se mover\n" +"\n" +"[[load]]\n" +"name = \"right end\"\n" +"x = \"max - 0.5\"\n" +"direction = \"x\"\n" +"type = \"displacement\" # ou \"force\"\n" +"time_function = \"linear\"\n" +"rate = -4 mm/s\n" +"reaction = true # a sua força é a reação do ensaio" + +msgid "" +"**Nodes** are chosen with ``nodes`` (``all``, ``grid`` for the corners of the modules" +" or ``centre`` for their centres), ``ids`` (node numbers) and ``x``, ``y``, ``z``. A " +"position is in modules (centre nodes lie at half-integers, grid nodes at integers), a" +" range ``[lo, hi]``, or a text with the references ``min``, ``max`` and ``mid`` and " +"an offset, such as ``\"max - 0.5\"``. A node must satisfy every condition. The " +"positions refer to the regular lattice, so they do not change when " +"``mesh.perturbation`` moves the nodes." +msgstr "" +"Os **nós** são escolhidos com ``nodes`` (``all``, ``grid`` para os cantos dos módulos" +" ou ``centre`` para os seus centros), ``ids`` (números de nó) e ``x``, ``y``, ``z``. " +"Uma posição é em módulos (os nós centrais ficam em semi-inteiros, os de canto em " +"inteiros), um intervalo ``[lo, hi]``, ou um texto com as referências ``min``, ``max``" +" e ``mid`` e um deslocamento, como ``\"max - 0.5\"``. Um nó deve satisfazer todas as " +"condições. As posições referem-se à malha regular, portanto não mudam quando " +"``mesh.perturbation`` move os nós." + +msgid "" +"**Supports** hold the directions listed in ``fix``. **Loads** act on one " +"``direction`` as a ``force`` (newtons on each selected node) or as a prescribed " +"``displacement`` (metres from the initial position, and the solver holds that " +"direction). The value follows ``time_function``: ``constant`` (``value``), ``linear``" +" (``rate``), ``ramp`` (``rate`` until the time ``until``, then constant) or ``table``" +" (``times`` and ``values`` in SI units, linear between points and constant outside)." +msgstr "" +"Os **apoios** fixam as direções de ``fix``. As **cargas** atuam em uma ``direction`` " +"como ``force`` (newtons em cada nó escolhido) ou como ``displacement`` imposto " +"(metros a partir da posição inicial; o solver fixa essa direção). O valor segue " +"``time_function``: ``constant`` (``value``), ``linear`` (``rate``), ``ramp`` " +"(``rate`` até o tempo ``until``, depois constante) ou ``table`` (``times`` e " +"``values`` em unidades SI, linear entre pontos e constante fora)." + +msgid "" +"A block with ``reaction = true`` adds its force to the reaction of the test (the sum " +"of the bar forces on its held directions); with none, the reaction is NaN. A block " +"that selects no node is an error that names it. The three built-in tests written this" +" way give exactly the same results as their classes." +msgstr "" +"Um bloco com ``reaction = true`` soma sua força à reação do ensaio (a soma das forças" +" de barra nas suas direções fixas); se nenhum a pedir, a reação é NaN. Um bloco que " +"não escolhe nenhum nó é um erro que o nomeia. Os três ensaios incorporados escritos " +"assim dão exatamente os mesmos resultados que as suas classes." + +msgid "Reuse a case: extends" +msgstr "Reutilizar um caso: extends" + +msgid "A case file can start from another one and change only what differs:" +msgstr "Um arquivo de caso pode partir de outro e mudar só o que difere:" + +msgid "" +"extends = \"base.ldem\" # or a list: [\"base.ldem\", \"material.ldem\"]\n" +"\n" +"[material]\n" +"fracture_energy = 1 N/m # only what changes" +msgstr "" +"extends = \"base.ldem\" # ou uma lista: [\"base.ldem\", " +"\"material.ldem\"]\n" +"\n" +"[material]\n" +"fracture_energy = 1 N/m # apenas o que muda" + +msgid "" +"The keys of the file replace the inherited ones. A repeated table (``[[support]]``, " +"``[[load]]``, ``[[monitor.node]]``, ``[[sweep]]``) replaces the whole inherited list." +" When the ``type`` of the scenario, of ``[material.scatter]`` or of ``[damping]`` " +"changes, the keys of the old type that are not set again are dropped. With a list, " +"later files win. Relative paths (the random-field file, the output folder) are " +"relative to the file that contains them, and an error names the file and line where " +"the problem is written. ``results.info.case.parents`` keeps the hash of every " +"inherited file." +msgstr "" +"As chaves do arquivo substituem as herdadas. Uma tabela repetida (``[[support]]``, " +"``[[load]]``, ``[[monitor.node]]``, ``[[sweep]]``) substitui toda a lista herdada. " +"Quando muda o ``type`` do cenário, de ``[material.scatter]`` ou de ``[damping]``, as " +"chaves do tipo anterior que não são definidas de novo são descartadas. Com uma lista," +" os últimos arquivos vencem. Os caminhos relativos (arquivo do campo aleatório, pasta" +" de saída) são relativos ao arquivo que os contém, e um erro indica o arquivo e a " +"linha onde o problema está escrito. ``results.info.case.parents`` guarda o hash de " +"cada arquivo herdado." + +msgid "Parameter sweeps" +msgstr "Varreduras de parâmetros" + +msgid "" +"To study how the result depends on a value, list the values in ``[[sweep]]`` blocks " +"and run ``ldem.sweep``:" +msgstr "" +"Para estudar como o resultado depende de um valor, listam-se os valores em blocos " +"``[[sweep]]`` e executa-se ``ldem.sweep``:" + +msgid "" +"[[sweep]]\n" +"key = \"material.fracture_energy\"\n" +"values = [\"0.1 N/m\", \"0.5 N/m\", \"1 N/m\"]\n" +"\n" +"[[sweep]]\n" +"key = \"time.duration\"\n" +"values = [\"20 us\", \"40 us\"]" +msgstr "" + +#, python-brace-format, python-format +msgid "" +">> summary = ldem.sweep(\"case.ldem\"); % 3 x 2 = 6 runs, one folder " +"each\n" +">> ldem.sweep(\"case.ldem\", DryRun=true); % only validate and list the " +"runs\n" +">> ldem.sweep(\"case.ldem\", Vary={\"scenario.force_rate\", [\"1 kN/s\" \"2 " +"kN/s\"]});\n" +">> results = ldem.run(\"case.ldem\", Overrides=struct(\"path\", " +"\"material.fracture_energy\", \"value\", \"2 N/m\"));" +msgstr "" +">> summary = ldem.sweep(\"case.ldem\"); % 3 x 2 = 6 execuções, uma " +"pasta cada\n" +">> ldem.sweep(\"case.ldem\", DryRun=true); % apenas valida e lista as " +"execuções\n" +">> ldem.sweep(\"case.ldem\", Vary={\"scenario.force_rate\", [\"1 kN/s\" \"2 " +"kN/s\"]});\n" +">> results = ldem.run(\"case.ldem\", Overrides=struct(\"path\", " +"\"material.fracture_energy\", \"value\", \"2 N/m\"));" + +msgid "" +"Several blocks give every combination; ``sweep_mode = \"zip\"`` (a key at the top of " +"the file) takes them one by one. Any key with a single value can be varied, and the " +"keys of the scenario as ``scenario.``. Values are numbers or texts with units. " +"Every run is validated before the first one starts. The runs go to ``run_001``, " +"``run_002``, ... (each with its resolved ``case.ldem``) and the table " +"``sweep_summary.csv`` lists them, with the number of damaged and broken bars; a run " +"that fails is recorded and the sweep goes on." +msgstr "" +"Vários blocos dão todas as combinações; ``sweep_mode = \"zip\"`` (uma chave no início" +" do arquivo) toma-os um a um. Pode-se variar qualquer chave de valor único, e as do " +"cenário como ``scenario.``. Os valores são números ou textos com unidades. " +"Cada execução é validada antes de começar a primeira. As execuções vão para " +"``run_001``, ``run_002``, ... (cada uma com o seu ``case.ldem`` resolvido) e a tabela" +" ``sweep_summary.csv`` as lista, com o número de barras danificadas e rompidas; uma " +"execução que falha fica registrada e a varredura continua." + +msgid "Reference of every key" +msgstr "Referência de todas as chaves" + +msgid "" +"The tables below are generated from ``ldem.schema.caseSchema``, the same table that " +"the reader uses, so they always agree with it." +msgstr "" +"As tabelas a seguir são geradas a partir de ``ldem.schema.caseSchema``, a mesma " +"tabela que o leitor usa, portanto sempre coincidem com ele. As descrições estão em " +"inglês." + +msgid "``(top level)``" +msgstr "``(nível superior)``" + +msgid "Key" +msgstr "Chave" + +msgid "Value" +msgstr "Valor" + +msgid "Default" +msgstr "Padrão" + +msgid "Legacy" +msgstr "Original" + +msgid "Description" +msgstr "Descrição" + +msgid "``format``" +msgstr "" + +msgid "integer" +msgstr "inteiro" + +msgid "1" +msgstr "" + +msgid "(none)" +msgstr "(nenhum)" + +msgid "Version of the case-file format (currently 1)." +msgstr "Versão do formato do arquivo de caso (atualmente 1)." + +msgid "``title``" +msgstr "" + +msgid "text" +msgstr "texto" + +msgid "Free text title of the case." +msgstr "Título do caso, em texto livre." + +msgid "``authors``" +msgstr "" + +msgid "list of texts" +msgstr "lista de textos" + +msgid "Names of the authors." +msgstr "Nomes dos autores." + +msgid "``extends``" +msgstr "" + +msgid "Case file(s) to inherit from; the keys of this file replace the inherited ones." +msgstr "Arquivo(s) de caso do qual se herda; as chaves deste arquivo substituem as herdadas." + +msgid "``sweep_mode``" +msgstr "" + +msgid "product, zip" +msgstr "" + +msgid "\"product\"" +msgstr "" + +msgid "How several [[sweep]] blocks combine: all combinations (product) or one by one (zip)." +msgstr "" +"Como vários blocos [[sweep]] se combinam: todas as combinações (product) ou um a um " +"(zip)." + +msgid "``module_size``" +msgstr "" + +msgid "number + unit (m, cm, mm, um, km)" +msgstr "número + unidade (m, cm, mm, um, km)" + +msgid "3 mm" +msgstr "" + +msgid "LCO" +msgstr "" + +msgid "Edge length of each cubic module." +msgstr "Comprimento da aresta de cada módulo cúbico." + +msgid "``modules``" +msgstr "" + +msgid "list of integers" +msgstr "lista de inteiros" + +msgid "required" +msgstr "obrigatório" + +msgid "M N L" +msgstr "" + +msgid "Cubic modules along x, y and z (M N L of the legacy file count nodes: one more)." +msgstr "Módulos cúbicos em x, y e z (os M N L do arquivo original contam nós: um a mais)." + +msgid "``perturbation``" +msgstr "" + +msgid "number" +msgstr "número" + +msgid "0" +msgstr "" + +msgid "Random node displacement as a fraction of the module size; 0 = regular lattice." +msgstr "Deslocamento aleatório dos nós como fração do tamanho do módulo; 0 = malha regular." + +msgid "``seed``" +msgstr "" + +msgid "123" +msgstr "" + +msgid "SEED" +msgstr "" + +msgid "Seed of the mesh perturbation (the random field has its own seed)." +msgstr "Semente da perturbação da malha (o campo aleatório tem a sua própria semente)." + +msgid "``law``" +msgstr "" + +msgid "bilinear, linear\\_elastic" +msgstr "" + +msgid "\"bilinear\"" +msgstr "" + +msgid "Constitutive law of the bars (see ldem.material.lawRegistry)." +msgstr "Lei constitutiva das barras (ver ldem.material.lawRegistry)." + +msgid "``young_modulus``" +msgstr "" + +msgid "number + unit (Pa, kPa, MPa, GPa)" +msgstr "número + unidade (Pa, kPa, MPa, GPa)" + +msgid "32 GPa" +msgstr "" + +msgid "YNG" +msgstr "" + +msgid "Young's modulus." +msgstr "Módulo de Young." + +msgid "``poisson_ratio``" +msgstr "" + +msgid "0.25" +msgstr "" + +msgid "PSN" +msgstr "" + +msgid "Poisson's ratio, from 0 up to less than 0.5." +msgstr "Coeficiente de Poisson, de 0 até menos de 0.5." + +msgid "``density``" +msgstr "" + +msgid "number + unit (kg/m3, g/cm3)" +msgstr "número + unidade (kg/m3, g/cm3)" + +msgid "2000 kg/m3" +msgstr "" + +msgid "ROH" +msgstr "" + +msgid "Mass density." +msgstr "Densidade de massa." + +msgid "``fracture_energy``" +msgstr "" + +msgid "number + unit (N/m, kN/m)" +msgstr "número + unidade (N/m, kN/m)" + +msgid "50 N/m" +msgstr "" + +msgid "GFR" +msgstr "" + +msgid "Specific fracture energy." +msgstr "Energia específica de fratura." + +msgid "``critical_distance``" +msgstr "" + +msgid "28 mm" +msgstr "" + +msgid "DEQ" +msgstr "" + +msgid "Equivalent (critical) distance." +msgstr "Distância equivalente (crítica)." + +msgid "``failure_area_factor``" +msgstr "" + +msgid "0.1385" +msgstr "" + +msgid "CAF" +msgstr "" + +msgid "Fraction of the module face that fails per bar." +msgstr "Fração da face do módulo que falha por barra." + +msgid "``type``" +msgstr "" + +msgid "none, file, generated" +msgstr "" + +msgid "\"none\"" +msgstr "" + +msgid "Scatter of the critical strain: none, file (one multiplier per bar) or generated." +msgstr "Dispersão da deformação crítica: none, file (um multiplicador por barra) ou generated." + +msgid "``file``" +msgstr "" + +msgid "file path" +msgstr "caminho de arquivo" + +msgid "Text file with one multiplier per bar, relative to this file." +msgstr "Arquivo de texto com um multiplicador por barra, relativo a este arquivo." + +msgid "``cv``" +msgstr "" + +msgid "Coefficient of variation of the generated field (1e-4 to 3)." +msgstr "Coeficiente de variação do campo gerado (1e-4 a 3)." + +msgid "``correlation_length``" +msgstr "" + +msgid "list of numbers" +msgstr "lista de números" + +msgid "[3]" +msgstr "" + +msgid "Correlation length of the generated field in modules: one value or [x, y, z]." +msgstr "Comprimento de correlação do campo gerado em módulos: um valor ou [x, y, z]." + +msgid "515" +msgstr "" + +msgid "Seed of the generated field." +msgstr "Semente do campo gerado." + +msgid "``step``" +msgstr "" + +msgid "time, or auto" +msgstr "tempo, ou auto" + +msgid "\"auto\"" +msgstr "" + +msgid "DT" +msgstr "" + +msgid "Integration time step, or auto (0.9 times the critical step)." +msgstr "Passo de tempo de integração, ou auto (0.9 vez o passo crítico)." + +msgid "``duration``" +msgstr "" + +msgid "number + unit (s, ms, us, ns)" +msgstr "número + unidade (s, ms, us, ns)" + +msgid "TTOT" +msgstr "" + +msgid "Total simulated time." +msgstr "Tempo total simulado." + +msgid "mass\\_proportional, none" +msgstr "" + +msgid "\"mass\\_proportional\"" +msgstr "" + +msgid "Damping model of the nodes (see ldem.solver.dampingRegistry)." +msgstr "Modelo de amortecimento dos nós (ver ldem.solver.dampingRegistry)." + +msgid "``initial``" +msgstr "" + +msgid "number + unit (1/s, 1/ms)" +msgstr "número + unidade (1/s, 1/ms)" + +msgid "25000 1/s" +msgstr "" + +msgid "DF1" +msgstr "" + +msgid "Mass-proportional damping before switch\\_time." +msgstr "Amortecimento proporcional à massa antes de switch\\_time." + +msgid "``final``" +msgstr "" + +msgid "DF2" +msgstr "" + +msgid "Mass-proportional damping after switch\\_time." +msgstr "Amortecimento proporcional à massa depois de switch\\_time." + +msgid "``switch_time``" +msgstr "" + +msgid "15 ms" +msgstr "" + +msgid "TDAF" +msgstr "" + +msgid "Time at which the damping changes from initial to final." +msgstr "Tempo em que o amortecimento passa de initial para final." + +msgid "``constitutive``" +msgstr "" + +msgid "0 s" +msgstr "" + +msgid "CON" +msgstr "" + +msgid "Stiffness-proportional damping inside the bar law." +msgstr "Amortecimento proporcional à rigidez dentro da lei das barras." + +msgid "TEST" +msgstr "" + +msgid "Test case (see ldem.scenarios.registry); its other keys follow." +msgstr "Ensaio (ver ldem.scenarios.registry); as suas outras chaves seguem." + +msgid "``[[support]]``" +msgstr "" + +msgid "``name``" +msgstr "" + +msgid "Label of the support." +msgstr "Rótulo do apoio." + +msgid "``nodes``" +msgstr "" + +msgid "all, centre, grid" +msgstr "" + +msgid "\"all\"" +msgstr "" + +msgid "Kind of nodes: all, grid (module corners) or centre (module centres)." +msgstr "Tipo de nós: all, grid (cantos dos módulos) ou centre (centros dos módulos)." + +msgid "``ids``" +msgstr "" + +msgid "Node numbers to select." +msgstr "Números de nó a escolher." + +msgid "``x``" +msgstr "" + +msgid "modules: number, text or [lo, hi]" +msgstr "módulos: número, texto ou [lo, hi]" + +msgid "Positions along x in modules: 0.5, \"max - 0.5\" or a range [lo, hi]." +msgstr "Posições em x, em módulos: 0.5, \"max - 0.5\" ou um intervalo [lo, hi]." + +msgid "``y``" +msgstr "" + +msgid "Positions along y in modules (see x)." +msgstr "Posições em y, em módulos (ver x)." + +msgid "``z``" +msgstr "" + +msgid "Positions along z in modules (see x)." +msgstr "Posições em z, em módulos (ver x)." + +msgid "``fix``" +msgstr "" + +msgid "Directions held at their initial position: [\"x\", \"y\", \"z\"]." +msgstr "Direções mantidas na posição inicial: [\"x\", \"y\", \"z\"]." + +msgid "``reaction``" +msgstr "" + +msgid "true or false" +msgstr "true ou false" + +msgid "false" +msgstr "" + +msgid "Include the force on the held directions in the reaction of the test." +msgstr "Inclui a força nas direções fixas na reação do ensaio." + +msgid "``[[load]]``" +msgstr "" + +msgid "Label of the load." +msgstr "Rótulo da carga." + +msgid "``direction``" +msgstr "" + +msgid "x, y, z" +msgstr "" + +msgid "Direction of the load." +msgstr "Direção da carga." + +msgid "force, displacement" +msgstr "" + +msgid "force (N on each selected node) or displacement (m from the initial position)." +msgstr "force (N em cada nó escolhido) ou displacement (m a partir da posição inicial)." + +msgid "``time_function``" +msgstr "" + +msgid "constant, linear, ramp, table" +msgstr "" + +msgid "How the value changes with time." +msgstr "Como o valor muda com o tempo." + +msgid "``value``" +msgstr "" + +msgid "N, N/s, m or m/s, by type" +msgstr "N, N/s, m ou m/s, conforme o tipo" + +msgid "constant: the value (N or m)." +msgstr "constant: o valor (N ou m)." + +msgid "``rate``" +msgstr "" + +msgid "linear and ramp: change per second (N/s or m/s)." +msgstr "linear e ramp: variação por segundo (N/s ou m/s)." + +msgid "``until``" +msgstr "" + +msgid "ramp: time at which it stops growing." +msgstr "ramp: tempo em que deixa de crescer." + +msgid "``times``" +msgstr "" + +msgid "table: increasing times in seconds." +msgstr "table: tempos crescentes em segundos." + +msgid "``values``" +msgstr "" + +msgid "table: one value per time (N or m)." +msgstr "table: um valor por tempo (N ou m)." + +msgid "Include the force on the loaded direction in the reaction of the test." +msgstr "Inclui a força na direção carregada na reação do ensaio." + +msgid "``[[sweep]]``" +msgstr "" + +msgid "``key``" +msgstr "" + +msgid "Key to vary, for example \"material.fracture\\_energy\" (see ldem.sweep)." +msgstr "Chave a variar, por exemplo \"material.fracture\\_energy\" (ver ldem.sweep)." + +msgid "Values to try: numbers, or texts with units such as [\"0.1 N/m\", \"0.5 N/m\"]." +msgstr "Valores a testar: números, ou textos com unidades como [\"0.1 N/m\", \"0.5 N/m\"]." + +msgid "``id``" +msgstr "" + +msgid "NCON" +msgstr "" + +msgid "Number of a node whose motion is recorded." +msgstr "Número de um nó cujo movimento é registrado." + +msgid "``at``" +msgstr "" + +msgid "Position [x, y, z] in modules; the nearest node is recorded." +msgstr "Posição [x, y, z] em módulos; é registrado o nó mais próximo." + +msgid "Label of the node." +msgstr "Rótulo do nó." + +msgid "``tracked``" +msgstr "" + +msgid "off" +msgstr "desativado" + +msgid "OU9" +msgstr "" + +msgid "Number of the bar whose strain history is stored at every step." +msgstr "Número da barra cuja história de deformação é guardada a cada passo." + +msgid "``folder``" +msgstr "" + +msgid "no files" +msgstr "sem arquivos" + +msgid "Output folder, relative to the case file." +msgstr "Pasta de saída, relativa ao arquivo de caso." + +msgid "``mat``" +msgstr "" + +msgid "true" +msgstr "" + +msgid "Write results.mat." +msgstr "Escreve results.mat." + +msgid "``ansys``" +msgstr "" + +msgid "Write ANSYS macro files (needs snapshots.every > 0)." +msgstr "Escreve arquivos macro do ANSYS (requer snapshots.every > 0)." + +msgid "``vtk``" +msgstr "" + +msgid "Write VTK files for ParaView (needs snapshots.every > 0)." +msgstr "Escreve arquivos VTK para o ParaView (requer snapshots.every > 0)." + +msgid "``[output.snapshots]``" +msgstr "" + +msgid "``every``" +msgstr "" + +msgid "steps or time (0 = never)" +msgstr "passos ou tempo (0 = nunca)" + +msgid "OU3" +msgstr "" + +msgid "Steps or time between full-field snapshots; 0 = never." +msgstr "Passos ou tempo entre instantâneos do campo completo; 0 = nunca." + +msgid "``[output.control_nodes]``" +msgstr "" + +msgid "OU6" +msgstr "" + +msgid "Steps or time between records of the control nodes and reactions; 0 = never." +msgstr "Passos ou tempo entre registros dos nós de controle e reações; 0 = nunca." + +msgid "``[output.energy]``" +msgstr "" + +msgid "OU8" +msgstr "" + +msgid "Steps or time between records of the energies; 0 = never." +msgstr "Passos ou tempo entre registros das energias; 0 = nunca." + +msgid "Tests available" +msgstr "Ensaios disponíveis" + +msgid "``testId = 101``" +msgstr "" + +msgid "" +"Uniaxial load: the centre nodes of the last column of modules move along :math:`x` " +"with a prescribed velocity." +msgstr "" +"Carga uniaxial: os nós centrais da última coluna de módulos se movem em :math:`x` com" +" velocidade imposta." + +msgid "``testId = 102``" +msgstr "" + +msgid "" +"Beam with two supports and two load points. The positions are parameters of " +"``ldem.scenarios.FourPointBending`` (``supportPosition``, ``loadPosition``, in " +"modules from each end); the defaults need a beam longer than about 70 modules. See " +"``examples/beam_102``." +msgstr "" +"Viga com dois apoios e dois pontos de carga. As posições são parâmetros de " +"``ldem.scenarios.FourPointBending`` (``supportPosition``, ``loadPosition``, em " +"módulos a partir de cada extremidade); os valores padrão exigem uma viga com mais de " +"uns 70 módulos. Ver ``examples/beam_102``." + +msgid "``testId = 103``" +msgstr "" + +msgid "" +"Beam clamped at both ends, loaded at mid-span with a force that grows linearly and " +"then stays constant (``ldem.scenarios.ClampedBeam``). It is the only test loaded with" +" a force instead of a displacement. See ``examples/example1_clamped_beam``." +msgstr "" +"Viga engastada nas duas extremidades, carregada no meio do vão com uma força que " +"cresce linearmente e depois se mantém constante (``ldem.scenarios.ClampedBeam``). É o" +" único ensaio carregado com força em vez de deslocamento. Ver " +"``examples/example1_clamped_beam``." + +msgid "" +"To add a new test, create a subclass of ``ldem.scenarios.Scenario`` (see " +":doc:`model`)." +msgstr "" +"Para adicionar um ensaio novo, crie uma subclasse de ``ldem.scenarios.Scenario`` (ver" +" :doc:`model`)." + +msgid "Mesh perturbation" +msgstr "Perturbação da malha" + +msgid "" +"The parameter ``meshPerturbation`` randomly displaces the interior nodes. Its value " +"is the standard deviation as a fraction of the module length: ``0`` (the default) " +"keeps the lattice regular and any positive value activates the perturbation with that" +" value. The random numbers follow ``seed``." +msgstr "" +"O parâmetro ``meshPerturbation`` desloca aleatoriamente os nós interiores. Seu valor " +"é o desvio padrão como fração do comprimento do módulo: ``0`` (o padrão) mantém o " +"reticulado regular e qualquer valor positivo ativa a perturbação com esse valor. Os " +"números aleatórios seguem ``seed``." + +msgid ">> params = ldem.Parameters(testId=101, nModules=[6 3 3], meshPerturbation=0.02);" +msgstr "" + +msgid "What you get: the ``results`` struct" +msgstr "O que se obtém: a estrutura ``results``" + +msgid "Field" +msgstr "Campo" + +msgid "Content" +msgstr "Conteúdo" + +msgid "``info``" +msgstr "" + +msgid "ldem version, date, MATLAB release, run time [s]." +msgstr "Versão do ldem, data, versão do MATLAB, tempo de execução [s]." + +msgid "``params``" +msgstr "" + +msgid "The parameters used, as a plain struct (derived values included)." +msgstr "Os parâmetros usados, como estrutura simples (com valores derivados)." + +msgid "``model``" +msgstr "" + +msgid "" +"Counts and mass of the model: modules, nodes, bars by type, fixed degrees of freedom," +" total mass and volume." +msgstr "" +"Contagens e massa do modelo: módulos, nós, barras por tipo, graus de liberdade fixos," +" massa total e volume." + +msgid "``material``" +msgstr "" + +msgid "" +"Material data (E, Gf, ...), lattice coefficients, critical length and the statistics " +"of the critical strain (mean, coefficient of variation, minimum and maximum)." +msgstr "" +"Dados do material (E, Gf, ...), coeficientes do reticulado, comprimento crítico e " +"estatísticas da deformação crítica (média, coeficiente de variação, mínimo e máximo)." + +msgid "``mesh``" +msgstr "" + +msgid "Initial node positions, supports (``fixed``), masses, bars, bar lengths and bar types." +msgstr "" +"Posições iniciais dos nós, apoios (``fixed``), massas, barras, comprimentos e tipos " +"de barra." + +msgid "``barProps``" +msgstr "" + +msgid "Stiffness, critical strain and rupture strain of every bar." +msgstr "Rigidez, deformação crítica e deformação de ruptura de cada barra." + +msgid "``controlNodes``" +msgstr "" + +msgid "Time and displacement, velocity and acceleration of the control nodes." +msgstr "Tempo e deslocamento, velocidade e aceleração dos nós de controle." + +msgid "``reactions``" +msgstr "" + +msgid "" +"Time and reaction force ``[Rx Ry Rz]`` of the test: vertical force at the load points" +" (test 102), force on the clamped ends (test 103); ``NaN`` where the test defines " +"none." +msgstr "" +"Tempo e força de reação ``[Rx Ry Rz]`` do ensaio: força vertical nos pontos de carga " +"(ensaio 102), força nas extremidades engastadas (ensaio 103); ``NaN`` onde o ensaio " +"não a define." + +msgid "``energy``" +msgstr "" + +msgid "" +"Time, kinetic, elastic, damage and damping energies [J], their sum (``internal``), " +"the energy of the broken bars (``brokenBars``), the external work, the ``balance`` " +"(external minus internal) and the damage rate." +msgstr "" +"Tempo, energias cinética, elástica, de dano e de amortecimento [J], sua soma " +"(``internal``), a energia das barras rompidas (``brokenBars``), o trabalho externo, o" +" balanço (``balance``, externo menos interno) e a taxa de dano." + +msgid "``trackedBar``" +msgstr "" + +msgid "Strain, force and damage energy of one bar at every step (optional)." +msgstr "Deformação, força e energia de dano de uma barra a cada passo (opcional)." + +msgid "``snapshots``" +msgstr "" + +msgid "" +"Step, time, number of intact/damaged/broken bars, and compact copies of the " +"displacements, the damage state and the nodal kinetic energy at the snapshot steps." +msgstr "" +"Passo, tempo, número de barras intactas/danificadas/rompidas e cópias compactas dos " +"deslocamentos, do estado de dano e da energia cinética nodal nos passos salvos." + +msgid "" +"Final displacement, velocity, force and damage state, and the kinetic energy of every" +" node." +msgstr "" +"Deslocamento, velocidade, força e estado de dano finais, e a energia cinética de cada" +" nó." + +msgid "" +"The energy ``balance`` is a check of the simulation: it should be a small fraction " +"(below 1 %) of the final external work. The total kinetic energy is " +"``energy.kinetic``; the kinetic energy of each node is in ``final.kineticEnergy``." +msgstr "" +"O ``balance`` de energia é uma verificação da simulação: deve ser uma fração pequena " +"(menos de 1 %) do trabalho externo final. A energia cinética total é " +"``energy.kinetic``; a de cada nó está em ``final.kineticEnergy``." + +msgid "``results.mat`` contains this struct and loads without the package:" +msgstr "``results.mat`` contém esta estrutura e carrega-se sem o pacote:" + +msgid "" +">> data = load(\"output/results.mat\");\n" +">> results = data.results;" +msgstr "" + +msgid "Output files" +msgstr "Arquivos de saída" + +msgid "``results.mat``" +msgstr "" + +msgid "The ``results`` struct (format v7.3, readable from Python with ``h5py``)." +msgstr "A estrutura ``results`` (formato v7.3, legível em Python com ``h5py``)." + +msgid "``snapshot_0000.mac``, ``snapshot_0001.mac``, ..." +msgstr "" + +msgid "" +"ANSYS macro files with the deformed lattice. Bars are element types 1 (intact), 2 " +"(damaged) and 5 (broken). The held degrees of freedom are listed as " +"``D,node,direction`` and the displacement imposed on the loaded nodes, measured from " +"their initial position, as ``D,node,direction,value``. In test 103 the applied forces" +" are listed as ``F,node,direction,value``." +msgstr "" +"Macros do ANSYS com o reticulado deformado. As barras são elementos do tipo 1 " +"(intactas), 2 (danificadas) e 5 (rompidas). Os graus de liberdade fixos são listados " +"como ``D,nó,direção`` e o deslocamento imposto aos nós carregados, medido a partir da" +" posição inicial, como ``D,nó,direção,valor``. No ensaio 103 as forças aplicadas são " +"listadas como ``F,nó,direção,valor``." + +msgid "``snapshot_0000.vtu``, ... and ``snapshots.pvd``" +msgstr "``snapshot_0000.vtu``, ... e ``snapshots.pvd``" + +msgid "" +"VTK files. Open ``snapshots.pvd`` in `ParaView `_; colour " +"by ``damageState`` (cell data) to see the cracks and use the time slider to follow " +"them. Displacement and velocity are point data." +msgstr "" +"Arquivos VTK. Abra ``snapshots.pvd`` no `ParaView `_; " +"colora por ``damageState`` (dados de célula) para ver as fissuras e use o controle de" +" tempo para acompanhá-las. Deslocamento e velocidade são dados de ponto." + +msgid "" +"ANSYS and VTK files are written at time zero and every " +"``params.output.snapshotEvery`` steps." +msgstr "" +"Os arquivos ANSYS e VTK são escritos no tempo zero e a cada " +"``params.output.snapshotEvery`` passos." + +msgid "Run the tests" +msgstr "Executar os testes" + +#, python-format +msgid "" +">> addpath tests\n" +">> run_tests % fast tests\n" +">> run_tests(IncludeSlow=true) % also the slow tests" +msgstr "" +">> addpath tests\n" +">> run_tests % testes rápidos\n" +">> run_tests(IncludeSlow=true) % também os testes lentos" + diff --git a/docs/source/_static/examples/clamped_beam_displacement.png b/docs/source/_static/examples/clamped_beam_displacement.png new file mode 100644 index 0000000..5517bc9 Binary files /dev/null and b/docs/source/_static/examples/clamped_beam_displacement.png differ diff --git a/docs/source/_static/examples/clamped_beam_energy.png b/docs/source/_static/examples/clamped_beam_energy.png new file mode 100644 index 0000000..7ec3fef Binary files /dev/null and b/docs/source/_static/examples/clamped_beam_energy.png differ diff --git a/docs/source/_static/examples/clamped_beam_reaction.png b/docs/source/_static/examples/clamped_beam_reaction.png new file mode 100644 index 0000000..48bc611 Binary files /dev/null and b/docs/source/_static/examples/clamped_beam_reaction.png differ diff --git a/docs/source/_static/examples/tension_energy.png b/docs/source/_static/examples/tension_energy.png new file mode 100644 index 0000000..20f1d6b Binary files /dev/null and b/docs/source/_static/examples/tension_energy.png differ diff --git a/docs/source/_templates/page.html b/docs/source/_templates/page.html new file mode 100644 index 0000000..38be7e2 --- /dev/null +++ b/docs/source/_templates/page.html @@ -0,0 +1,65 @@ +{#- Furo page with its footer block rewritten without "Made with Sphinx and Furo". + The rest of the page is Furo's (extends "!page.html"). The block below is Furo's own + footer minus that line; the Read the Docs and GitHub icons of Furo are left out because + the documentation is published on GitHub Pages. If Furo changes its footer, compare with + furo/theme/furo/page.html. -#} +{% extends "!page.html" %} +{% block footer %} + +
+
+ {%- if show_copyright %} + + {%- endif %} + {%- if last_updated -%} +
+ {% trans last_updated=last_updated|e -%} + Last updated on {{ last_updated }} + {%- endtrans -%} +
+ {%- endif %} +
+
+ {% if theme_footer_icons -%} +
+ {% for icon_dict in theme_footer_icons -%} + + {{- icon_dict.html -}} + + {% endfor %} +
+ {%- endif %} +
+
+{% endblock footer %} diff --git a/docs/source/_templates/sidebar/languages.html b/docs/source/_templates/sidebar/languages.html new file mode 100644 index 0000000..ae47f86 --- /dev/null +++ b/docs/source/_templates/sidebar/languages.html @@ -0,0 +1,12 @@ +{#- Language selector. Every language is a separate site (docs/build/html//), so the + other languages are reached by a relative link to the same page in the sibling folder. -#} +{%- set depth = pagename.count('/') -%} + diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst index 41235be..5353012 100644 --- a/docs/source/api/index.rst +++ b/docs/source/api/index.rst @@ -1,41 +1,131 @@ -API reference / Referencia de la API -==================================== +API reference +============= -Generated automatically from the comments of the ``.m`` files in -``src/ldem`` (comments are written in Portuguese) / -Generada automáticamente desde los comentarios de los ``.m``. +Generated automatically from the comments of the ``.m`` files. -.. note:: +The ``ldem`` package (``src/+ldem``) is the refactored code. It replaces the +original routines, which are kept in the git history (tag +``legacy-reference``); the problems found in them are listed in +``docs/known-issues/KNOWN_ISSUES.md``. - Only routines that already have a docstring (comment block right below - the ``function`` line) are listed. To add another routine, document it - and append it to this list / Para añadir otra rutina, documentarla y - agregarla a esta lista. +Running a simulation +-------------------- .. mat:module:: ldem -Initialisation / Inicialización -------------------------------- +.. mat:autofunction:: ldem.runSimulation +.. mat:autoclass:: ldem.Parameters + :members: +.. mat:autofunction:: ldem.run +.. mat:autofunction:: ldem.check +.. mat:autofunction:: ldem.sweep +.. mat:autofunction:: ldem.version -.. mat:autofunction:: ldem.ini_DEM3 -.. mat:autofunction:: ldem.read_dat0 -.. mat:autofunction:: ldem.prepvar +Input and output +---------------- -Geometry and connectivity / Geometría y conectividad ----------------------------------------------------- +.. mat:module:: ldem.io -.. mat:autofunction:: ldem.CONECTI -.. mat:autofunction:: ldem.INTCO1 +.. mat:autofunction:: ldem.io.readCase +.. mat:autofunction:: ldem.io.writeCase +.. mat:autofunction:: ldem.io.writeTemplate +.. mat:autofunction:: ldem.io.convertLegacyInput +.. mat:autofunction:: ldem.io.parseCaseText +.. mat:autofunction:: ldem.io.parseCaseJson +.. mat:autofunction:: ldem.io.readInputFile +.. mat:autofunction:: ldem.io.readRandomField +.. mat:autofunction:: ldem.io.saveResults +.. mat:autofunction:: ldem.io.exportAnsys +.. mat:autofunction:: ldem.io.exportVtk +.. mat:autofunction:: ldem.io.writePvd +.. mat:autoclass:: ldem.io.SnapshotWriter + :members: -Mechanics, loads and boundary conditions / Mecánica, cargas y contorno ----------------------------------------------------------------------- +Mesh +---- -.. mat:autofunction:: ldem.RMEC -.. mat:autofunction:: ldem.BOUND -.. mat:autofunction:: ldem.CALOAD +.. mat:module:: ldem.mesh -Results and energy / Resultados y energía ------------------------------------------ +.. mat:autofunction:: ldem.mesh.buildMesh +.. mat:autofunction:: ldem.mesh.buildNodes +.. mat:autofunction:: ldem.mesh.perturbNodes +.. mat:autofunction:: ldem.mesh.buildBars +.. mat:autofunction:: ldem.mesh.computeNodalMasses +.. mat:autofunction:: ldem.mesh.computeBarGeometry +.. mat:autofunction:: ldem.mesh.summarizeModel -.. mat:autofunction:: ldem.CALRES -.. mat:autofunction:: ldem.ENERG2 +Material +-------- + +.. mat:module:: ldem.material + +.. mat:autofunction:: ldem.material.latticeCoefficients +.. mat:autofunction:: ldem.material.computeBarStiffness +.. mat:autofunction:: ldem.material.buildBarProperties +.. mat:autofunction:: ldem.material.generateRandomField +.. mat:autofunction:: ldem.material.bilinearLaw +.. mat:autoclass:: ldem.material.MaterialLaw +.. mat:autoclass:: ldem.material.BilinearBarLaw +.. mat:autoclass:: ldem.material.LinearElasticBarLaw +.. mat:autofunction:: ldem.material.lawRegistry +.. mat:autofunction:: ldem.material.lawFromName +.. mat:autofunction:: ldem.material.summarizeMaterial + +Scenarios +--------- + +.. mat:module:: ldem.scenarios + +.. mat:autoclass:: ldem.scenarios.Scenario +.. mat:autoclass:: ldem.scenarios.UniaxialTension +.. mat:autoclass:: ldem.scenarios.FourPointBending +.. mat:autoclass:: ldem.scenarios.ClampedBeam +.. mat:autofunction:: ldem.scenarios.fromTestId +.. mat:autofunction:: ldem.scenarios.fromName +.. mat:autoclass:: ldem.scenarios.Declarative +.. mat:autofunction:: ldem.scenarios.selectNodes +.. mat:autofunction:: ldem.scenarios.parseCoordinate +.. mat:autofunction:: ldem.scenarios.coordinateText +.. mat:autofunction:: ldem.scenarios.timeFunction +.. mat:autofunction:: ldem.scenarios.registry + +Case-file schema +---------------- + +.. mat:module:: ldem.schema + +.. mat:autofunction:: ldem.schema.caseSchema +.. mat:autofunction:: ldem.schema.parseQuantity +.. mat:autofunction:: ldem.schema.formatQuantity +.. mat:autofunction:: ldem.schema.unitTable +.. mat:autofunction:: ldem.schema.shortestText +.. mat:autofunction:: ldem.schema.suggest +.. mat:autofunction:: ldem.schema.raise +.. mat:autofunction:: ldem.schema.writeKeyReference + +Solver +------ + +.. mat:module:: ldem.solver + +.. mat:autofunction:: ldem.solver.simulate +.. mat:autofunction:: ldem.solver.initialState +.. mat:autoclass:: ldem.solver.DampingModel +.. mat:autoclass:: ldem.solver.MassProportionalDamping +.. mat:autoclass:: ldem.solver.NoDamping +.. mat:autofunction:: ldem.solver.dampingRegistry +.. mat:autofunction:: ldem.solver.dampingFromName +.. mat:autofunction:: ldem.solver.computeBarForces +.. mat:autofunction:: ldem.solver.integrateStep +.. mat:autofunction:: ldem.solver.dampingCoefficient +.. mat:autofunction:: ldem.solver.computeEnergies +.. mat:autofunction:: ldem.solver.nodalKineticEnergy +.. mat:autofunction:: ldem.solver.checkStability + +Post-processing +--------------- + +.. mat:module:: ldem.post + +.. mat:autofunction:: ldem.post.plotEnergy +.. mat:autofunction:: ldem.post.plotReaction diff --git a/docs/source/authors.rst b/docs/source/authors.rst new file mode 100644 index 0000000..90d37be --- /dev/null +++ b/docs/source/authors.rst @@ -0,0 +1,17 @@ +Authors +======= + +This list is generated automatically from the commits of the git history +(people with the same name or e-mail are merged through ``.mailmap``) and +from the authors of ``CITATION.cff``. Authors without commits in this +repository appear with ``-``. The same list is in ``AUTHORS.md``. + +.. include:: _generated/authors.rst + +To update it after new commits, build the documentation or run: + +.. code-block:: bash + + python docs/tools/generate_authors.py + +If a person appears twice, add a line to ``.mailmap``. diff --git a/docs/source/case-keys.inc b/docs/source/case-keys.inc new file mode 100644 index 0000000..31b462a --- /dev/null +++ b/docs/source/case-keys.inc @@ -0,0 +1,519 @@ +.. This file is generated by ldem.schema.writeKeyReference from ldem.schema.caseSchema. +.. Do not edit it by hand: change the schema and generate it again. + +.. rubric:: ``(top level)`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``format`` + - integer + - 1 + - (none) + - Version of the case-file format (currently 1). + * - ``title`` + - text + - (none) + - (none) + - Free text title of the case. + * - ``authors`` + - list of texts + - (none) + - (none) + - Names of the authors. + * - ``extends`` + - list of texts + - (none) + - (none) + - Case file(s) to inherit from; the keys of this file replace the inherited ones. + * - ``sweep_mode`` + - product, zip + - "product" + - (none) + - How several [[sweep]] blocks combine: all combinations (product) or one by one (zip). + +.. rubric:: ``[mesh]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``module_size`` + - number + unit (m, cm, mm, um, km) + - 3 mm + - LCO + - Edge length of each cubic module. + * - ``modules`` + - list of integers + - required + - M N L + - Cubic modules along x, y and z (M N L of the legacy file count nodes: one more). + * - ``perturbation`` + - number + - 0 + - (none) + - Random node displacement as a fraction of the module size; 0 = regular lattice. + * - ``seed`` + - integer + - 123 + - SEED + - Seed of the mesh perturbation (the random field has its own seed). + +.. rubric:: ``[material]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``law`` + - bilinear, linear\_elastic + - "bilinear" + - (none) + - Constitutive law of the bars (see ldem.material.lawRegistry). + * - ``young_modulus`` + - number + unit (Pa, kPa, MPa, GPa) + - 32 GPa + - YNG + - Young's modulus. + * - ``poisson_ratio`` + - number + - 0.25 + - PSN + - Poisson's ratio, from 0 up to less than 0.5. + * - ``density`` + - number + unit (kg/m3, g/cm3) + - 2000 kg/m3 + - ROH + - Mass density. + * - ``fracture_energy`` + - number + unit (N/m, kN/m) + - 50 N/m + - GFR + - Specific fracture energy. + * - ``critical_distance`` + - number + unit (m, cm, mm, um, km) + - 28 mm + - DEQ + - Equivalent (critical) distance. + * - ``failure_area_factor`` + - number + - 0.1385 + - CAF + - Fraction of the module face that fails per bar. + +.. rubric:: ``[material.scatter]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``type`` + - none, file, generated + - "none" + - (none) + - Scatter of the critical strain: none, file (one multiplier per bar) or generated. + * - ``file`` + - file path + - (none) + - (none) + - Text file with one multiplier per bar, relative to this file. + * - ``cv`` + - number + - 0 + - (none) + - Coefficient of variation of the generated field (1e-4 to 3). + * - ``correlation_length`` + - list of numbers + - [3] + - (none) + - Correlation length of the generated field in modules: one value or [x, y, z]. + * - ``seed`` + - integer + - 515 + - (none) + - Seed of the generated field. + +.. rubric:: ``[time]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``step`` + - time, or auto + - "auto" + - DT + - Integration time step, or auto (0.9 times the critical step). + * - ``duration`` + - number + unit (s, ms, us, ns) + - required + - TTOT + - Total simulated time. + +.. rubric:: ``[damping]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``type`` + - mass\_proportional, none + - "mass\_proportional" + - (none) + - Damping model of the nodes (see ldem.solver.dampingRegistry). + * - ``initial`` + - number + unit (1/s, 1/ms) + - 25000 1/s + - DF1 + - Mass-proportional damping before switch\_time. + * - ``final`` + - number + unit (1/s, 1/ms) + - 25000 1/s + - DF2 + - Mass-proportional damping after switch\_time. + * - ``switch_time`` + - number + unit (s, ms, us, ns) + - 15 ms + - TDAF + - Time at which the damping changes from initial to final. + * - ``constitutive`` + - number + unit (s, ms, us, ns) + - 0 s + - CON + - Stiffness-proportional damping inside the bar law. + +.. rubric:: ``[scenario]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``type`` + - + - required + - TEST + - Test case (see ldem.scenarios.registry); its other keys follow. + +.. rubric:: ``[[support]]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``name`` + - text + - (none) + - (none) + - Label of the support. + * - ``nodes`` + - all, centre, grid + - "all" + - (none) + - Kind of nodes: all, grid (module corners) or centre (module centres). + * - ``ids`` + - list of integers + - (none) + - (none) + - Node numbers to select. + * - ``x`` + - modules: number, text or [lo, hi] + - (none) + - (none) + - Positions along x in modules: 0.5, "max - 0.5" or a range [lo, hi]. + * - ``y`` + - modules: number, text or [lo, hi] + - (none) + - (none) + - Positions along y in modules (see x). + * - ``z`` + - modules: number, text or [lo, hi] + - (none) + - (none) + - Positions along z in modules (see x). + * - ``fix`` + - list of texts + - (none) + - (none) + - Directions held at their initial position: ["x", "y", "z"]. + * - ``reaction`` + - true or false + - false + - (none) + - Include the force on the held directions in the reaction of the test. + +.. rubric:: ``[[load]]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``name`` + - text + - (none) + - (none) + - Label of the load. + * - ``nodes`` + - all, centre, grid + - "all" + - (none) + - Kind of nodes: all, grid (module corners) or centre (module centres). + * - ``ids`` + - list of integers + - (none) + - (none) + - Node numbers to select. + * - ``x`` + - modules: number, text or [lo, hi] + - (none) + - (none) + - Positions along x in modules: 0.5, "max - 0.5" or a range [lo, hi]. + * - ``y`` + - modules: number, text or [lo, hi] + - (none) + - (none) + - Positions along y in modules (see x). + * - ``z`` + - modules: number, text or [lo, hi] + - (none) + - (none) + - Positions along z in modules (see x). + * - ``direction`` + - x, y, z + - (none) + - (none) + - Direction of the load. + * - ``type`` + - force, displacement + - (none) + - (none) + - force (N on each selected node) or displacement (m from the initial position). + * - ``time_function`` + - constant, linear, ramp, table + - (none) + - (none) + - How the value changes with time. + * - ``value`` + - N, N/s, m or m/s, by type + - (none) + - (none) + - constant: the value (N or m). + * - ``rate`` + - N, N/s, m or m/s, by type + - (none) + - (none) + - linear and ramp: change per second (N/s or m/s). + * - ``until`` + - number + unit (s, ms, us, ns) + - (none) + - (none) + - ramp: time at which it stops growing. + * - ``times`` + - list of numbers + - (none) + - (none) + - table: increasing times in seconds. + * - ``values`` + - list of numbers + - (none) + - (none) + - table: one value per time (N or m). + * - ``reaction`` + - true or false + - false + - (none) + - Include the force on the loaded direction in the reaction of the test. + +.. rubric:: ``[[sweep]]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``key`` + - text + - (none) + - (none) + - Key to vary, for example "material.fracture\_energy" (see ldem.sweep). + * - ``values`` + - list of numbers + - (none) + - (none) + - Values to try: numbers, or texts with units such as ["0.1 N/m", "0.5 N/m"]. + +.. rubric:: ``[[monitor.node]]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``id`` + - integer + - (none) + - NCON + - Number of a node whose motion is recorded. + * - ``at`` + - list of numbers + - (none) + - (none) + - Position [x, y, z] in modules; the nearest node is recorded. + * - ``name`` + - text + - (none) + - (none) + - Label of the node. + +.. rubric:: ``[monitor.bar]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``tracked`` + - integer + - off + - OU9 + - Number of the bar whose strain history is stored at every step. + +.. rubric:: ``[output]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``folder`` + - text + - no files + - (none) + - Output folder, relative to the case file. + * - ``mat`` + - true or false + - true + - (none) + - Write results.mat. + * - ``ansys`` + - true or false + - false + - (none) + - Write ANSYS macro files (needs snapshots.every > 0). + * - ``vtk`` + - true or false + - false + - (none) + - Write VTK files for ParaView (needs snapshots.every > 0). + +.. rubric:: ``[output.snapshots]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``every`` + - steps or time (0 = never) + - (none) + - OU3 + - Steps or time between full-field snapshots; 0 = never. + +.. rubric:: ``[output.control_nodes]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``every`` + - steps or time (0 = never) + - (none) + - OU6 + - Steps or time between records of the control nodes and reactions; 0 = never. + +.. rubric:: ``[output.energy]`` + +.. list-table:: + :header-rows: 1 + :widths: 18 24 12 8 38 + + * - Key + - Value + - Default + - Legacy + - Description + * - ``every`` + - steps or time (0 = never) + - (none) + - OU8 + - Steps or time between records of the energies; 0 = never. diff --git a/docs/source/conf.py b/docs/source/conf.py index 87be76f..e23a72c 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,5 +1,7 @@ """Sphinx configuration for LDEM-MATLAB.""" import os +import subprocess +import sys project = "LDEM-MATLAB" author = "Boris Rojo Tanzi" @@ -21,8 +23,34 @@ # --- General ---------------------------------------------------------------- source_suffix = {".rst": "restructuredtext", ".md": "markdown"} -exclude_patterns = ["_build"] -language = "en" +exclude_patterns = ["_build", "_generated/*"] +language = "en" # the other languages are built with -D language=es|pt|it (docs/tools/build_docs.py) + +# --- Translations: English source pages, one .po catalog per page and language ---- +locale_dirs = ["../locale/"] # docs/locale//LC_MESSAGES/.po +gettext_compact = False # one catalog per page, easier to review +gettext_additional_targets = ["literal-block"] # the comments of the code examples are translated too +html_context = { + "languages": [("en", "English"), ("es", "Español"), ("pt", "Português"), ("it", "Italiano")], +} + +# --- Authors: generated from the git history on every build ----------------- +_tools = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tools")) +subprocess.run([sys.executable, os.path.join(_tools, "generate_authors.py")], + check=True, stdout=subprocess.DEVNULL) + +templates_path = ["_templates"] +html_sidebars = { + "**": [ + "sidebar/scroll-start.html", + "sidebar/brand.html", + "sidebar/search.html", + "sidebar/languages.html", + "sidebar/navigation.html", + "sidebar/ethical-ads.html", + "sidebar/scroll-end.html", + ] +} html_theme = "furo" html_title = "LDEM-MATLAB" diff --git a/docs/source/en/contributing.rst b/docs/source/contributing.rst similarity index 97% rename from docs/source/en/contributing.rst rename to docs/source/contributing.rst index 7cd1017..8f392c9 100644 --- a/docs/source/en/contributing.rst +++ b/docs/source/contributing.rst @@ -4,7 +4,7 @@ Contributing The API documentation is generated from the ``.m`` comments. The docstring must be the comment block placed **immediately after** the ``function`` line (before any ``global`` declaration). Source comments are written in -Portuguese. +English. .. code-block:: matlab diff --git a/docs/source/docs.rst b/docs/source/docs.rst new file mode 100644 index 0000000..f04e41c --- /dev/null +++ b/docs/source/docs.rst @@ -0,0 +1,88 @@ +Building this documentation +=========================== + +The documentation is written in English, which is the only set of source pages, +and translated into Spanish, Portuguese and Italian with gettext catalogs +(``.po`` files in ``docs/locale/``). Each language is built as its own site and +the sidebar has a language selector. A text that is not translated yet is shown +in English. The API reference is generated from the comments of the ``.m`` +files and is in English only. + +Requirements +------------ + +* Python 3.9 or newer. +* ``git`` (the list of authors is generated from the commit history; with a + shallow clone use ``git fetch --unshallow`` first). +* No MATLAB is needed; the API is read from the source text. + +.. code-block:: bash + + pip install -r docs/requirements.txt + +Build +----- + +From the repository root, with any of these: + +.. code-block:: bash + + python docs/tools/build_docs.py + +.. code-block:: bash + + cd docs && make html + +.. code-block:: matlab + + >> buildtool docs + +This builds the four languages into ``docs/build/html/en``, ``es``, ``pt`` and +``it``; ``docs/build/html/index.html`` sends the reader to the English site. Open +it in a browser. To build only some languages use for example +``python docs/tools/build_docs.py --languages en es``. Warnings are errors: the +documentation must build without any. ``buildtool clean`` deletes the result. + +Where things are +---------------- + +``docs/source/`` + The pages, in English. +``docs/locale/es/``, ``pt/``, ``it/`` + Translations: one ``.po`` file per page in ``LC_MESSAGES/``, with each English + text and its translation. +``docs/source/api/`` + API reference, generated from the ``.m`` comments. +``docs/tools/build_docs.py`` + Builds every language and the page that sends the reader to the English site. +``docs/tools/update_translations.py`` + Updates the ``.po`` files after the English text changes, and reports what is + left to translate. +``docs/tools/generate_authors.py`` + Writes the authors page and ``AUTHORS.md`` (run by the build). +``docs/source/case-keys.inc`` + Reference of the case-file keys, generated from the schema. After changing + ``ldem.schema.caseSchema`` regenerate it from MATLAB with + ``ldem.schema.writeKeyReference("docs/source/case-keys.inc")``; a test fails + if it is out of date. + +Write or change a page +---------------------- + +1. Edit the English page in ``docs/source/``. A new page also goes in the list of + ``index.rst``. +2. Run ``python docs/tools/update_translations.py``. It extracts the texts and + updates the ``.po`` files: new texts appear untranslated and changed texts are + marked as fuzzy, both shown in English until they are translated. +3. Translate the new entries in ``docs/locale//LC_MESSAGES/.po`` + (with any text editor or a tool such as Poedit) and remove the fuzzy marks you + have reviewed. ``python docs/tools/update_translations.py --status`` shows how + much is left in each language. +4. Build with ``python docs/tools/build_docs.py`` and fix any warning. + +Publishing +---------- + +The workflow ``.github/workflows/docs.yml`` builds the documentation on every +pull request and publishes the four languages to GitHub Pages when ``main`` +changes. diff --git a/docs/source/en/index.rst b/docs/source/en/index.rst deleted file mode 100644 index 680fb1d..0000000 --- a/docs/source/en/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -User guide -========== - -.. toctree:: - :maxdepth: 1 - - introduction - installation - usage - contributing diff --git a/docs/source/en/installation.rst b/docs/source/en/installation.rst deleted file mode 100644 index 6bda7ed..0000000 --- a/docs/source/en/installation.rst +++ /dev/null @@ -1,20 +0,0 @@ -Installation -============ - -Requirements: MATLAB R2021b or newer. - -.. code-block:: bash - - git clone ldem-matlab - cd ldem-matlab - -.. code-block:: matlab - - >> setup_path - -To build this documentation: - -.. code-block:: bash - - pip install -r docs/requirements.txt - sphinx-build -b html docs/source docs/build/html diff --git a/docs/source/en/introduction.rst b/docs/source/en/introduction.rst deleted file mode 100644 index c838d75..0000000 --- a/docs/source/en/introduction.rst +++ /dev/null @@ -1,18 +0,0 @@ -Introduction -============ - -The **Lattice Discrete Element Method (LDEM)** models a continuum as a -regular lattice of nodes connected by bars arranged in cubic modules -(edges plus diagonals). Nodal masses are lumped, bar constitutive laws -include damage/fracture, and the equations of motion are integrated with an -explicit central-difference scheme. Energies (external, kinetic, elastic, -dissipated) are tracked at every step. - -Main routines (see :doc:`../api/index`): - -* ``ini_DEM3`` – initialises the global variables. -* ``read_dat0`` – reads the input data file. -* ``CONECTI`` / ``INTCO1`` / ``EXTCO1`` – bar connectivity. -* ``RMEC`` – mechanical properties of the bars. -* ``BOUND`` / ``CALOAD`` – boundary conditions and loads. -* ``ENERG2`` – energy balance. diff --git a/docs/source/en/usage.rst b/docs/source/en/usage.rst deleted file mode 100644 index ccff90b..0000000 --- a/docs/source/en/usage.rst +++ /dev/null @@ -1,18 +0,0 @@ -Usage -===== - -.. code-block:: matlab - - >> setup_path - >> main % default simulation - -Input data files (``DATA0.DAT``, ``SIM01.DAT``) are read by ``read_dat0``. -Results are written to ``LET.*`` and ``*.TXT`` files in the working -directory. - -Run the tests: - -.. code-block:: matlab - - >> addpath tests - >> run_tests diff --git a/docs/source/es/contribuir.rst b/docs/source/es/contribuir.rst deleted file mode 100644 index 9ba339d..0000000 --- a/docs/source/es/contribuir.rst +++ /dev/null @@ -1,16 +0,0 @@ -Contribuir -========== - -La documentación de la API se genera desde los comentarios de los ``.m``. El -docstring debe ser el bloque de comentarios ubicado **inmediatamente después** -de la línea ``function`` (antes de cualquier ``global``). Los comentarios del -código se escriben en portugués. - -.. code-block:: matlab - - function ini = CALOAD() - % CALOAD Resumen en una línea. - % Descripción más larga. - global ... - -Ver ``CONTRIBUTING.md`` en la raíz del repositorio. diff --git a/docs/source/es/index.rst b/docs/source/es/index.rst deleted file mode 100644 index 956333f..0000000 --- a/docs/source/es/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -Guía de usuario -=============== - -.. toctree:: - :maxdepth: 1 - - introduccion - instalacion - uso - contribuir diff --git a/docs/source/es/instalacion.rst b/docs/source/es/instalacion.rst deleted file mode 100644 index a7a6eb1..0000000 --- a/docs/source/es/instalacion.rst +++ /dev/null @@ -1,20 +0,0 @@ -Instalación -=========== - -Requisitos: MATLAB R2021b o superior. - -.. code-block:: bash - - git clone ldem-matlab - cd ldem-matlab - -.. code-block:: matlab - - >> setup_path - -Para construir esta documentación: - -.. code-block:: bash - - pip install -r docs/requirements.txt - sphinx-build -b html docs/source docs/build/html diff --git a/docs/source/es/introduccion.rst b/docs/source/es/introduccion.rst deleted file mode 100644 index f760e78..0000000 --- a/docs/source/es/introduccion.rst +++ /dev/null @@ -1,19 +0,0 @@ -Introducción -============ - -El **Método de Elementos Discretos tipo Reticulado (LDEM)** modela un -continuo como un reticulado regular de nodos conectados por barras -dispuestas en módulos cúbicos (aristas más diagonales). Las masas son -concentradas en los nodos, las leyes constitutivas de las barras incluyen -daño/fractura y las ecuaciones de movimiento se integran con un esquema -explícito de diferencias centrales. Las energías (externa, cinética, -elástica, disipada) se controlan en cada paso. - -Rutinas principales (ver :doc:`../api/index`): - -* ``ini_DEM3`` – inicializa las variables globales. -* ``read_dat0`` – lee el archivo de datos de entrada. -* ``CONECTI`` / ``INTCO1`` / ``EXTCO1`` – conectividad de barras. -* ``RMEC`` – propiedades mecánicas de las barras. -* ``BOUND`` / ``CALOAD`` – condiciones de contorno y cargas. -* ``ENERG2`` – balance de energía. diff --git a/docs/source/es/uso.rst b/docs/source/es/uso.rst deleted file mode 100644 index 5007398..0000000 --- a/docs/source/es/uso.rst +++ /dev/null @@ -1,18 +0,0 @@ -Uso -=== - -.. code-block:: matlab - - >> setup_path - >> main % simulación por defecto - -Los archivos de entrada (``DATA0.DAT``, ``SIM01.DAT``) son leídos por -``read_dat0``. Los resultados se escriben en archivos ``LET.*`` y ``*.TXT`` -en el directorio de trabajo. - -Ejecutar los tests: - -.. code-block:: matlab - - >> addpath tests - >> run_tests diff --git a/docs/source/examples.rst b/docs/source/examples.rst new file mode 100644 index 0000000..fc477e9 --- /dev/null +++ b/docs/source/examples.rst @@ -0,0 +1,311 @@ +Examples +======== + +The folder ``examples/`` has three models that run from start to finish, each +with its inputs and a script that runs it and plots the results. The numbers in +this page come from running them with the current code. + +.. list-table:: + :header-rows: 1 + :widths: 30 40 15 15 + + * - Folder + - What it shows + - Size + - Time + * - ``example1_clamped_beam/`` + - A beam clamped at both ends and loaded with a force at mid-span + - 3,086 nodes + - about 35 s + * - ``tension_101/`` + - A small prism under a uniaxial load, with damage and every output format + - 74 nodes + - about 6 s + * - ``beam_102/`` + - The four-point bending beam of the paper (a demo of its first 50 steps) + - 166,961 nodes + - about 30 s for 50 steps + +Start with ``tension_101`` to learn the interface and with +``example1_clamped_beam`` to see a model loaded with a force, described by a +case file and checked against the original code. + +Running an example +------------------ + +From MATLAB, from any folder: + +.. code-block:: matlab + + >> run('examples/example1_clamped_beam/runClampedBeam.m') % script: run and plot + >> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % from the case file + +The two beam examples also have a ``case.ldem``: the same model in the readable +case-file format (see :doc:`usage`), generated from the ``DATA0.DAT`` of the +original program and giving the same parameters. ``ldem.check`` shows what a +case file would simulate without running it. + +The scripts write their files to a folder ``output`` next to the script (ignored +by git), or to ``outputFolder`` if that variable already exists: + +* ``results.mat``: one struct, ``results``, with everything that was recorded. + Load it with ``data = load('results.mat'); results = data.results;``. +* ``snapshot_0000.mac``, ...: ANSYS macro files of the deformed lattice. +* ``snapshot_0000.vtu``, ... and ``snapshots.pvd``: open ``snapshots.pvd`` in + `ParaView `_ to see the damage evolve in time. + +Example 1: beam clamped at both ends +------------------------------------ + +A small beam of 5 x 5 x 50 modules of 1 mm, clamped at both ends and loaded at +mid-span with a force that grows during 0.35 ms and then stays constant. It is +the model of Rodrigo (branch ``dev_rodrigo``) and the first test loaded with a +force instead of a displacement (``ldem.scenarios.ClampedBeam``, test 103). + +The model +~~~~~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Part + - Value + * - Geometry + - 5 x 5 x 50 modules of 1 mm (a prism of 5 x 5 x 50 mm, axis along z), with + 3,086 nodes, 18,085 bars and a mass of 1.875 g + * - Supports + - The centre nodes of the first and of the last layer of modules (z = 0.5 and + z = 49.5 modules) are clamped: x, y and z held + * - Load + - The 5 centre nodes of the line at mid-span (z = 24.5 modules, y = 0.5 modules) + carry a force in +y of ``1000 N/s * min(t, 0.35 ms)`` each: 0.35 N per node, + 1.75 N in total + * - Material + - E = 3.87 GPa, Poisson's ratio 0.25, density 1500 kg/m\ :sup:`3`, fracture + energy 0.5 N/m, critical distance 4.5 mm; mass-proportional damping of + 2500 1/s + * - Scatter + - One multiplier of the critical strain per bar, read from a file (shared with + ``beam_102``) + * - Time + - 2.8 ms in 8000 steps of 0.35 us (65 % of the critical step) + * - Recorded + - Control nodes 2441 (a loaded node) and 884 (a grid node at mid-span); tracked + bar 14398 + +The original input file listed five control nodes, but nodes 6870 and 14398 do +not exist in this 3,086-node mesh, so the input keeps 2441 and 884. The tracked bar +is 14398, as in the original. + +Files +~~~~~ + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - File + - Purpose + * - ``case.ldem`` + - The model as a case file: run it with ``ldem.run`` + * - ``runClampedBeam.m`` + - Reads ``DATA0.DAT``, runs the simulation and plots the force on the clamped + ends, the vertical displacement of the control nodes and the energies + * - ``DATA0.DAT`` + - The parameters in the format of the original program (``TEST 103``) + +The scenario and the load are the lines of the ``[scenario]`` section of +``case.ldem``: + +.. code-block:: text + + [scenario] + type = "clamped_beam" + force_rate = 1000 N/s + ramp_time = 0.35 ms + load_position = "midspan" + load_height = 0.5 modules + +The same test can be written without a scenario class, with supports and loads. +It gives the same results as ``ldem.scenarios.ClampedBeam`` (the tests check it): + +.. code-block:: text + + [scenario] + type = "custom" + + [[support]] + name = "first end" + z = 0.5 + fix = ["x", "y", "z"] + reaction = true + + [[support]] + name = "last end" + z = "max - 0.5" + fix = ["x", "y", "z"] + reaction = true + + [[load]] + name = "line at mid-span" + y = 0.5 + z = "mid - 0.5" + direction = "y" + type = "force" + time_function = "ramp" + rate = 1000 N/s + until = 0.35 ms + +Reading the results +~~~~~~~~~~~~~~~~~~~ + +.. code-block:: matlab + + >> results = ldem.run('examples/example1_clamped_beam/case.ldem', OutputFolder=tempname); + >> y0 = results.mesh.nodes0(results.params.controlNodes, 2).'; + >> dy = results.controlNodes.displacement(:, :, 2) - y0; % vertical displacement [m] + >> results.reactions.force(end, :) % force on the clamped ends [N] + >> ldem.post.plotReaction(results); + >> ldem.post.plotEnergy(results); + +What you should see +~~~~~~~~~~~~~~~~~~~ + +.. figure:: _static/examples/clamped_beam_reaction.png + :width: 90% + + Force carried by the clamped ends. It rises with the load, overshoots to 1.94 N + and settles at the total applied force. + +.. figure:: _static/examples/clamped_beam_displacement.png + :width: 90% + + Vertical displacement of the two control nodes: a peak of 6.7 um at 0.46 ms and + about 6.3 um at the end. + +.. figure:: _static/examples/clamped_beam_energy.png + :width: 90% + + Energies. The external work equals the sum of the internal energies. + +* The reaction settles at 1.75 N, the 1.75 N applied in total: the beam is in + equilibrium at the end. The overshoot (1.94 N) and the oscillation are the + dynamic response, which the damping removes. +* With these values the beam stays elastic: at the end 18,085 bars are intact and + none is damaged or broken. +* The energy balance closes: the external work of 5.76 uJ is the elastic energy + (5.48 uJ) plus the energy dissipated by damping (0.28 uJ); the kinetic energy is + about zero and the balance is below 1e-13 J. + +Try other values +~~~~~~~~~~~~~~~~ + +Every key of the case file can be changed, or swept without editing the file +(see :doc:`usage`): + +.. code-block:: matlab + + >> summary = ldem.sweep('examples/example1_clamped_beam/case.ldem', ... + Vary = {'scenario.force_rate', ["10 kN/s" "30 kN/s" "100 kN/s"]}, Formats = "mat"); + +With the original value (1 kN/s) no bar is damaged. Ten times more force already +breaks the beam; each run takes about 50 s: + +.. list-table:: + :header-rows: 1 + :widths: 30 40 30 + + * - Force rate + - Damaged bars (including broken) + - Broken bars + * - 10 kN/s + - 5,630 + - 3,584 + * - 30 kN/s + - 6,074 + - 3,579 + * - 100 kN/s + - 4,760 + - 2,783 + +After the failure the loaded nodes keep being pushed by the force and move freely, +so the displacements of these runs are not meaningful; the damage counts are. Each run +has its own folder (``run_001``, ...) with its results and its resolved ``case.ldem``, +and the table is also saved as ``sweep_summary.csv``. + +Other changes to try in ``case.ldem``: ``law = "linear_elastic"`` (no damage at all), +``type = "generated"`` with a ``cv`` in ``[material.scatter]`` to generate the random +field in memory instead of reading it, or ``type = "none"`` to remove the scatter. + +Example: uniaxial prism +----------------------- + +``examples/tension_101/runTension.m`` runs a prism of 5 x 2 x 2 modules of 3 mm +(74 nodes, 313 bars) under the uniaxial test (test 101): the centre nodes of the +last column move along x with a prescribed velocity of 4 mm/s while those of the +first column are held. It is the best place to start: it has no input file, the +model is described in the script with ``ldem.Parameters``, and it writes every kind +of output. + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Part + - Value + * - Material + - E = 32 GPa, Poisson's ratio 0.25, density 2000 kg/m\ :sup:`3`; a low fracture + energy of 0.1 N/m on purpose, so that bars soften and break + * - Time + - 0.2 ms in 1000 steps of 0.2 us + * - Output + - Snapshots (ANSYS and VTK) every 250 steps, control nodes and energies every 10 + steps, no tracked bar + +At the end 251 bars are intact, 58 are damaged and 4 are broken. The external work +is 24.7 uJ: 22.5 uJ of elastic energy, 2.2 uJ dissipated by damage and 0.03 uJ by +damping; the balance is 0.01 % of the external work. + +.. figure:: _static/examples/tension_energy.png + :width: 90% + + Energies of the uniaxial prism. + +With the sign convention of the original code a positive ``loadingVelocity`` moves +the loaded face toward the fixed one, that is, it compresses the prism; use a +negative value to pull it (see ``ldem.scenarios.UniaxialTension``). + +Example: four-point bending beam +-------------------------------- + +``examples/beam_102/runBeam.m`` reads the input of the beam of the paper (test 102, +``ldem.scenarios.FourPointBending``): 100 x 40 x 20 modules of 3 mm (300 x 120 x 60 +mm), 166,961 nodes and 1,126,960 bars. The beam rests on two supports 4.5 modules +from its ends and two load points 33.5 modules from its ends push its top face down +with a prescribed velocity of 4 mm/s. The material is E = 32 GPa, density 2000 +kg/m\ :sup:`3`, fracture energy 50 N/m, critical distance 28 mm, with a random field +of the critical strain read from a file. + +The real simulation has 150,000 steps (0.03 s in steps of 0.2 us) and needs roughly +20 hours on a laptop (about 0.5 s per step). The script therefore runs only the first +50 steps: it builds the complete model (about 20 s) and shows that the input is read +and the model runs; the plotted reaction is only that of the start of the test. Change +``nStepsDemo`` at the top of the script, or remove the ``totalTime`` override, for +the full run. + +.. list-table:: + :header-rows: 1 + :widths: 35 65 + + * - File + - Purpose + * - ``case.ldem`` + - The same parameters as a case file (``ldem.io.readCase``, ``ldem.run``) + * - ``DATA0.DAT`` + - Parameters in the format of the original program (``ldem.Parameters.fromFile``) + * - ``arquivo_3lc_rnao_cv05`` + - Random field applied to the critical strain of each bar (11 MB); it is also used + by ``example1_clamped_beam`` + * - ``runBeam.m`` + - Reads the input, runs the first 50 steps and plots the reaction force diff --git a/docs/source/index.rst b/docs/source/index.rst index d623e1f..b2ccc86 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,20 +1,23 @@ LDEM-MATLAB =========== -Lattice Discrete Element Method (LDEM) in MATLAB / -Método de Elementos Discretos tipo Reticulado en MATLAB. +Lattice Discrete Element Method (LDEM) in MATLAB. -.. toctree:: - :maxdepth: 2 - :caption: English - - en/index +The documentation is written in English and translated into Spanish, Portuguese +and Italian. Choose the language in the sidebar of any page. .. toctree:: :maxdepth: 2 - :caption: Español + :caption: User guide - es/index + introduction + installation + usage + examples + model + contributing + docs + authors .. toctree:: :maxdepth: 2 diff --git a/docs/source/installation.rst b/docs/source/installation.rst new file mode 100644 index 0000000..0128adb --- /dev/null +++ b/docs/source/installation.rst @@ -0,0 +1,36 @@ +Installation +============ + +Requirements: MATLAB R2022b or newer (developed and tested on R2023b). The +package itself uses the ``arguments`` block and name=value syntax; the test +suite and ``buildtool`` need R2022b. No toolbox is required. + +.. code-block:: bash + + git clone ldem-matlab + cd ldem-matlab + +.. code-block:: matlab + + >> setup_path + +Check the installation with the fast tests: + +.. code-block:: matlab + + >> buildtool test + +Developer tasks (``buildtool`` is run from the repository root): + +.. code-block:: matlab + + >> buildtool % static analysis + fast tests (the default) + >> buildtool check % Code Analyzer only + >> buildtool testAll % all tests, including the slow ones + >> buildtool docs % build this documentation (needs Python) + >> buildtool clean % delete generated files + +``buildtool test`` writes ``test-results/results.xml`` (JUnit) and +``code-coverage/coverage.xml`` (Cobertura). + +To build this documentation without MATLAB see :doc:`docs`. diff --git a/docs/source/introduction.rst b/docs/source/introduction.rst new file mode 100644 index 0000000..9d774ee --- /dev/null +++ b/docs/source/introduction.rst @@ -0,0 +1,26 @@ +Introduction +============ + +The **Lattice Discrete Element Method (LDEM)** models a continuum as a +regular lattice of nodes connected by bars arranged in cubic modules +(edges plus diagonals). Nodal masses are lumped, bar constitutive laws +include damage/fracture, and the equations of motion are integrated with an +explicit central-difference scheme. Energies (external, kinetic, elastic, +dissipated) are tracked at every step. + +Main parts of the ``ldem`` package (see :doc:`api/index`): + +* ``ldem.Parameters`` / ``ldem.io.readCase`` / ``ldem.io.readInputFile`` – validated input data + (case files and the legacy ``DATA0.DAT``). +* ``ldem.run`` / ``ldem.sweep`` / ``ldem.check`` – run, sweep and check a case file. +* ``ldem.mesh`` – nodes, bars, masses and bar geometry. +* ``ldem.material`` – bar stiffness, critical strain and the bilinear damage law. +* ``ldem.scenarios`` – supports, loads and reactions of each test. +* ``ldem.solver`` – time integration and energy balance. +* ``ldem.runSimulation`` – the whole simulation, with ``results.mat``, ANSYS and + VTK output. + +The routines of the original program (``ini_DEM3``, ``read_dat0``, ``RMEC``, +``BOUND``, ``CALOAD``, ``ENERG2``, ...) are kept in the git history under the tag +``legacy-reference``; the ``Legacy:`` line of each help text names the routine it +replaces. diff --git a/docs/source/model.rst b/docs/source/model.rst new file mode 100644 index 0000000..4c44964 --- /dev/null +++ b/docs/source/model.rst @@ -0,0 +1,114 @@ +Building a different model +========================== + +A model is defined by three things: the **geometry** of the lattice, the +**material** and the **test** (supports and loads). The first two are +parameters; the third is a *scenario* class. You can change any of them +without touching the solver. + +1. Change the geometry and the material +--------------------------------------- + +Everything is a property of ``ldem.Parameters``: + +.. code-block:: matlab + + >> params = ldem.Parameters(testId=101, ... + moduleLength=0.002, ... % edge of the cubic module [m] + nModules=[21 6 6], ... % nodes along x, y and z + youngModulus=30e9, density=2400, poissonRatio=0.2, ... + fractureEnergy=80, criticalDistance=0.02, ... + meshPerturbation=0.02); % optional irregular mesh + +* ``nModules = [M N L]`` is the number of grid nodes along each axis, so the + prism has ``(M-1)*(N-1)*(L-1)`` modules. +* ``randomFieldFile`` multiplies the critical strain of each bar by a value + read from a text file (a random field of the material strength). +* ``randomFieldCv`` generates that random field in memory instead, with no + file: Weibull values with mean 1 and that coefficient of variation on a grid + of poles spaced ``randomFieldCorrelationLength`` module lengths apart (default + 3), interpolated to each bar; ``randomFieldSeed`` fixes the random numbers. + The value of each bar is kept in ``results.barProps.randomField``. +* ``dt`` must be below ``params.criticalTimeStep``; ``Parameters`` rejects an + unstable value and says so. + +The same data can come from a case file (``ldem.io.readCase``, see +:doc:`usage`) or from an input file in the format of the original +program with ``ldem.Parameters.fromFile("DATA0.DAT", ...)``; extra +name=value pairs override the file. The mesh can be built and inspected +before running anything: + +.. code-block:: matlab + + >> mesh = ldem.mesh.buildMesh(params); + >> fprintf("%d nodes, %d bars\n", size(mesh.nodes0, 1), size(mesh.bars, 1)); + +2. Change the test: write a scenario +------------------------------------ + +A *scenario* says which degrees of freedom are fixed, how the load is +applied at every time step and which reaction is reported. The solver never +checks the test number, it only asks the scenario. To model a new test, +create a subclass of ``ldem.scenarios.Scenario`` in ``src/+ldem/+scenarios/``. + +The example below is a cantilever beam along :math:`z`: the first layer of +centre nodes is clamped and a force that grows linearly is applied in +:math:`y` at the free end. + +.. code-block:: matlab + + classdef Cantilever < ldem.scenarios.Scenario + properties (Constant) + testId = 104 % new number, unique + end + properties + forceRate (1,1) double = 500 % [N/s] on each loaded node + end + methods + function fixed = fixedDofs(~, nodes0, params) + z = nodes0(:, 3); + atStart = abs(z - 0.5*params.moduleLength) < 0.01*params.moduleLength; + fixed = false(size(nodes0)); + fixed(atStart, :) = true; % x, y and z held + end + function state = applyLoads(obj, state, mesh, params) + L1 = params.nModules(3) - 1; + z = mesh.nodes0(:, 3); + atEnd = abs(z - (L1 - 0.5)*params.moduleLength) < 0.01*params.moduleLength; + state.appliedForce(:) = 0; + state.appliedForce(atEnd, 2) = obj.forceRate * state.time; + end + end + end + +Rules to follow: + +* ``fixedDofs`` returns an ``nNodes``-by-3 logical matrix, true where the node + cannot move (``1 = x``, ``2 = y``, ``3 = z``). +* ``applyLoads`` runs once per step. A **displacement-controlled** test sets + ``state.displacement`` of the loaded nodes (see ``UniaxialTension``); a + **force-controlled** test sets ``state.appliedForce`` in newtons (see + ``ClampedBeam``) and the solver counts its work in the external energy. +* Override ``reactions`` if the test reports a reaction force (default: + ``NaN``). +* The centre nodes of the modules lie at half-integer multiples of + ``moduleLength``; select nodes with a small tolerance, never with ``==``. + +3. Register and run it +---------------------- + +Either pass the object directly, with no registration: + +.. code-block:: matlab + + >> scenario = ldem.scenarios.Cantilever(forceRate=1000); + >> results = ldem.runSimulation(params, Scenario=scenario, ... + OutputFolder="output", Formats=["mat" "vtk"]); + +or add one line to ``ldem.scenarios.registry`` so that +``testId = 104`` finds it and a case file can name it with ``type``. Then add a +test in ``tests/unit`` and, if it is a reference case, an example in +``examples/`` (see ``examples/example1_clamped_beam``). + +The result is the same ``results`` struct as for any other test, see +:doc:`usage`. diff --git a/docs/source/usage.rst b/docs/source/usage.rst new file mode 100644 index 0000000..b8e9e01 --- /dev/null +++ b/docs/source/usage.rst @@ -0,0 +1,356 @@ +Usage +===== + +Run a simulation +---------------- + +.. code-block:: matlab + + >> setup_path % adds src/ to the MATLAB path + >> params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4, ... + fractureEnergy=0.1, ... + output=struct('snapshotEvery', 250, 'controlNodesEvery', 10, ... + 'energyEvery', 10, 'trackedBarEvery', 0)); + >> results = ldem.runSimulation(params, OutputFolder="output", ... + Formats=["mat" "ansys" "vtk"]); + >> ldem.post.plotEnergy(results); + +``ldem.Parameters`` checks every value when it is set and explains what is +wrong (for example an unstable time step). The complete, ready-to-run version +of this script is ``examples/tension_101/runTension.m``. + +To use an input file in the format of the original program: + +.. code-block:: matlab + + >> params = ldem.Parameters.fromFile("DATA0.DAT"); + +Case files (``.ldem``) +---------------------- + +A *case file* describes the whole model in one readable text file: named keys +instead of positions, units next to the numbers, comments, and the test, the +random scatter and the output files together. It replaces ``DATA0.DAT``. + +.. code-block:: text + + format = 1 + title = "Small tension test" + + [mesh] + module_size = 3 mm + modules = [5, 2, 2] # cubic modules along x, y and z + + [material] + young_modulus = 32 GPa + density = 2000 kg/m3 + + [time] + step = auto # 0.9 times the critical step + duration = 40 us + + [scenario] + type = "uniaxial_tension" + + [output] + folder = "output" + +.. code-block:: matlab + + >> ldem.io.writeTemplate("my_test.ldem", "clamped_beam"); % a commented file to edit + >> ldem.check("my_test.ldem") % validate and report, no simulation + >> results = ldem.run("my_test.ldem"); % run it + >> ldem.io.convertLegacyInput("DATA0.DAT", "case.ldem"); % convert an old input file + +Rules of the format: + +* Keys are read by **name**; the order of the lines does not matter. Keys that + are missing take the default of ``ldem.Parameters``. Only ``scenario.type``, + ``mesh.modules`` and ``time.duration`` are required. +* A number may carry a **unit**: ``3.87 GPa``, ``0.35 us``, ``1500 kg/m3``, + ``2 kN/s``. Without a unit the value is in SI. The wrong unit for the key is + an error that lists the valid ones. +* ``#`` starts a comment, ``[section]`` opens a table, ``[[monitor.node]]`` + starts the next element of a repeated table, lists are written ``[5, 5, 50]``. +* ``mesh.modules`` counts **modules**: the ``M N L`` of ``DATA0.DAT`` count + nodes, one more. +* ``time.step = auto`` (or no ``step``) takes 0.9 times the critical step. +* Every error names the file, the line, the section and the key, and suggests + the closest valid name for a mistyped one. +* Relative paths (the random-field file, the output folder) are relative to + the case file. +* A JSON file with the same structure (values with units as strings) is also + read. + +.. list-table:: + :header-rows: 1 + :widths: 25 75 + + * - Section + - Keys + * - (top) + - ``format`` (1), ``title``, ``authors`` + * - ``[mesh]`` + - ``module_size``, ``modules``, ``perturbation`` (random displacement of + the nodes, fraction of the module), ``seed`` (of the perturbation) + * - ``[material]`` + - ``law`` (``bilinear``, the legacy law, or ``linear_elastic``: no damage and no + rupture), ``young_modulus``, ``poisson_ratio``, ``density``, + ``fracture_energy``, ``critical_distance``, ``failure_area_factor`` + * - ``[material.scatter]`` + - Scatter of the critical strain of the bars. ``type = "none"``; + ``"file"`` with ``file`` (one multiplier per bar); or ``"generated"`` + with ``cv``, ``correlation_length`` (in modules) and ``seed`` (the + field is computed in memory) + * - ``[time]`` + - ``step`` (or ``auto``), ``duration`` + * - ``[damping]`` + - ``type`` (``mass_proportional``, the legacy damping, or ``none``), + ``initial``, ``final``, ``switch_time`` (not allowed with ``none``), + ``constitutive`` + * - ``[scenario]`` + - ``type`` (``uniaxial_tension``, ``four_point_bending``, + ``clamped_beam`` or ``custom``, see below) and the properties of that scenario in snake_case, + for example ``force_rate``, ``ramp_time``, ``load_position`` (``"midspan"`` + is allowed) + * - ``[[monitor.node]]`` + - One element per control node: ``id`` (node number) or ``at = [x, y, z]`` + (position in modules, the nearest node is used), and ``name`` + * - ``[monitor.bar]`` + - ``tracked``: bar whose strain history is stored at every step + * - ``[output]`` + - ``folder``, ``mat``, ``ansys``, ``vtk`` (true or false) + * - ``[output.snapshots]``, ``[output.control_nodes]``, ``[output.energy]`` + - ``every``: ``1000 steps`` or a time such as ``0.1 ms`` (converted to + steps); ``0`` means never + +``ldem.io.readCase`` returns the parameters, the scenario and the output +options; ``ldem.Parameters.fromFile`` also accepts a case file. The list of +keys lives in one table, ``ldem.schema.caseSchema``, which drives the reader, +the writer and the template. To add a scenario, add a line to +``ldem.scenarios.registry``. A new constitutive law is a subclass of +``ldem.material.MaterialLaw`` registered in ``ldem.material.lawRegistry``; a new +damping model is a subclass of ``ldem.solver.DampingModel`` registered in +``ldem.solver.dampingRegistry``. + +Your own test: supports and loads +--------------------------------- + +With ``type = "custom"`` the test is described in the case file by +``[[support]]`` and ``[[load]]`` blocks, without writing a class. This is the +uniaxial test (``testId = 101``) as blocks: + +.. code-block:: text + + [scenario] + type = "custom" + + [[support]] + name = "left end" + x = 0.5 # the layer of centre nodes at x = 0.5 modules + fix = ["x"] # directions that cannot move + + [[load]] + name = "right end" + x = "max - 0.5" + direction = "x" + type = "displacement" # or "force" + time_function = "linear" + rate = -4 mm/s + reaction = true # its force is the reaction of the test + +**Nodes** are chosen with ``nodes`` (``all``, ``grid`` for the corners of the +modules or ``centre`` for their centres), ``ids`` (node numbers) and ``x``, +``y``, ``z``. A position is in modules (centre nodes lie at half-integers, grid +nodes at integers), a range ``[lo, hi]``, or a text with the references +``min``, ``max`` and ``mid`` and an offset, such as ``"max - 0.5"``. A node must +satisfy every condition. The positions refer to the regular lattice, so they do +not change when ``mesh.perturbation`` moves the nodes. + +**Supports** hold the directions listed in ``fix``. **Loads** act on one +``direction`` as a ``force`` (newtons on each selected node) or as a prescribed +``displacement`` (metres from the initial position, and the solver holds that +direction). The value follows ``time_function``: ``constant`` (``value``), +``linear`` (``rate``), ``ramp`` (``rate`` until the time ``until``, then +constant) or ``table`` (``times`` and ``values`` in SI units, linear between +points and constant outside). + +A block with ``reaction = true`` adds its force to the reaction of the test +(the sum of the bar forces on its held directions); with none, the reaction is +NaN. A block that selects no node is an error that names it. The three built-in +tests written this way give exactly the same results as their classes. + +Reuse a case: extends +--------------------- + +A case file can start from another one and change only what differs: + +.. code-block:: text + + extends = "base.ldem" # or a list: ["base.ldem", "material.ldem"] + + [material] + fracture_energy = 1 N/m # only what changes + +The keys of the file replace the inherited ones. A repeated table (``[[support]]``, +``[[load]]``, ``[[monitor.node]]``, ``[[sweep]]``) replaces the whole inherited +list. When the ``type`` of the scenario, of ``[material.scatter]`` or of +``[damping]`` changes, the keys of the old type that are not set again are +dropped. With a list, later files win. Relative paths (the random-field file, the +output folder) are relative to the file that contains them, and an error names the +file and line where the problem is written. ``results.info.case.parents`` keeps +the hash of every inherited file. + +Parameter sweeps +---------------- + +To study how the result depends on a value, list the values in ``[[sweep]]`` +blocks and run ``ldem.sweep``: + +.. code-block:: text + + [[sweep]] + key = "material.fracture_energy" + values = ["0.1 N/m", "0.5 N/m", "1 N/m"] + + [[sweep]] + key = "time.duration" + values = ["20 us", "40 us"] + +.. code-block:: matlab + + >> summary = ldem.sweep("case.ldem"); % 3 x 2 = 6 runs, one folder each + >> ldem.sweep("case.ldem", DryRun=true); % only validate and list the runs + >> ldem.sweep("case.ldem", Vary={"scenario.force_rate", ["1 kN/s" "2 kN/s"]}); + >> results = ldem.run("case.ldem", Overrides=struct("path", "material.fracture_energy", "value", "2 N/m")); + +Several blocks give every combination; ``sweep_mode = "zip"`` (a key at the top of +the file) takes them one by one. Any key with a single value can be varied, and +the keys of the scenario as ``scenario.``. Values are numbers or texts with +units. Every run is validated before the first one starts. The runs go to +``run_001``, ``run_002``, ... (each with its resolved ``case.ldem``) and the +table ``sweep_summary.csv`` lists them, with the number of damaged and broken +bars; a run that fails is recorded and the sweep goes on. + +Reference of every key +---------------------- + +The tables below are generated from ``ldem.schema.caseSchema``, the same table +that the reader uses, so they always agree with it. + +.. include:: case-keys.inc + +Tests available +--------------- + +``testId = 101`` + Uniaxial load: the centre nodes of the last column of modules move along + :math:`x` with a prescribed velocity. +``testId = 102`` + Beam with two supports and two load points. The positions are parameters of + ``ldem.scenarios.FourPointBending`` (``supportPosition``, ``loadPosition``, + in modules from each end); the defaults need a beam longer than about 70 + modules. See ``examples/beam_102``. +``testId = 103`` + Beam clamped at both ends, loaded at mid-span with a force that grows + linearly and then stays constant (``ldem.scenarios.ClampedBeam``). It is the + only test loaded with a force instead of a displacement. See + ``examples/example1_clamped_beam``. + +To add a new test, create a subclass of ``ldem.scenarios.Scenario`` (see :doc:`model`). + +Mesh perturbation +----------------- + +The parameter ``meshPerturbation`` randomly displaces the interior nodes. Its +value is the standard deviation as a fraction of the module length: ``0`` (the +default) keeps the lattice regular and any positive value activates the +perturbation with that value. The random numbers follow ``seed``. + +.. code-block:: matlab + + >> params = ldem.Parameters(testId=101, nModules=[6 3 3], meshPerturbation=0.02); + +What you get: the ``results`` struct +------------------------------------ + +.. list-table:: + :header-rows: 1 + :widths: 22 78 + + * - Field + - Content + * - ``info`` + - ldem version, date, MATLAB release, run time [s]. + * - ``params`` + - The parameters used, as a plain struct (derived values included). + * - ``model`` + - Counts and mass of the model: modules, nodes, bars by type, fixed degrees + of freedom, total mass and volume. + * - ``material`` + - Material data (E, Gf, ...), lattice coefficients, critical length and the + statistics of the critical strain (mean, coefficient of variation, minimum + and maximum). + * - ``mesh`` + - Initial node positions, supports (``fixed``), masses, bars, bar lengths + and bar types. + * - ``barProps`` + - Stiffness, critical strain and rupture strain of every bar. + * - ``controlNodes`` + - Time and displacement, velocity and acceleration of the control nodes. + * - ``reactions`` + - Time and reaction force ``[Rx Ry Rz]`` of the test: vertical force at the load points + (test 102), force on the clamped ends (test 103); ``NaN`` where the test defines none. + * - ``energy`` + - Time, kinetic, elastic, damage and damping energies [J], their sum + (``internal``), the energy of the broken bars (``brokenBars``), the external work, + the ``balance`` (external minus internal) and the damage rate. + * - ``trackedBar`` + - Strain, force and damage energy of one bar at every step (optional). + * - ``snapshots`` + - Step, time, number of intact/damaged/broken bars, and compact copies of + the displacements, the damage state and the nodal kinetic energy at the + snapshot steps. + * - ``final`` + - Final displacement, velocity, force and damage state, and the kinetic + energy of every node. + +The energy ``balance`` is a check of the simulation: it should be a small +fraction (below 1 %) of the final external work. The total kinetic energy is +``energy.kinetic``; the kinetic energy of each node is in ``final.kineticEnergy``. + +``results.mat`` contains this struct and loads without the package: + +.. code-block:: matlab + + >> data = load("output/results.mat"); + >> results = data.results; + +Output files +------------ + +``results.mat`` + The ``results`` struct (format v7.3, readable from Python with ``h5py``). +``snapshot_0000.mac``, ``snapshot_0001.mac``, ... + ANSYS macro files with the deformed lattice. Bars are element types 1 + (intact), 2 (damaged) and 5 (broken). The held degrees of freedom are + listed as ``D,node,direction`` and the displacement imposed on the loaded + nodes, measured from their initial position, as + ``D,node,direction,value``. In test 103 the applied forces are listed as + ``F,node,direction,value``. +``snapshot_0000.vtu``, ... and ``snapshots.pvd`` + VTK files. Open ``snapshots.pvd`` in `ParaView `_; + colour by ``damageState`` (cell data) to see the cracks and use the time + slider to follow them. Displacement and velocity are point data. + +ANSYS and VTK files are written at time zero and every +``params.output.snapshotEvery`` steps. + +Run the tests +------------- + +.. code-block:: matlab + + >> addpath tests + >> run_tests % fast tests + >> run_tests(IncludeSlow=true) % also the slow tests diff --git a/docs/tools/build_docs.py b/docs/tools/build_docs.py new file mode 100644 index 0000000..63b3cc0 --- /dev/null +++ b/docs/tools/build_docs.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +"""Build the documentation in every language. + +The pages are written in English (``docs/source/``); the other languages are +built from the same pages with the translation catalogs of ``docs/locale/``. +Each language is its own site, in ``docs/build/html//``, and +``docs/build/html/index.html`` sends the reader to the English one. Warnings are +errors (``-W``), so the documentation must build without any. + +Usage: + python docs/tools/build_docs.py all languages + python docs/tools/build_docs.py --languages en es only some + python docs/tools/build_docs.py --output some/folder +""" +import argparse +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SOURCE = ROOT / "docs" / "source" +LANGUAGES = [("en", "English"), ("es", "Español"), ("pt", "Português"), ("it", "Italiano")] + + +def build(language, output): + """Run Sphinx for one language; return True when it built without warnings.""" + print("== Building the documentation in %s" % language, flush=True) + result = subprocess.run( + [sys.executable, "-m", "sphinx", "-W", "--keep-going", "-q", "-b", "html", + "-D", "language=%s" % language, str(SOURCE), str(output / language)], + ) + return result.returncode == 0 + + +def write_redirect(output, languages): + links = " · ".join('%s' % (code, name) + for code, name in LANGUAGES if code in languages) + (output / "index.html").write_text( + '\n\nLDEM-MATLAB\n' + '\n' + '

LDEM-MATLAB documentation: %s

\n' % links, + encoding="utf-8", + ) + + +def main(): + codes = [code for code, _ in LANGUAGES] + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--languages", nargs="+", default=codes, choices=codes) + parser.add_argument("--output", default=str(ROOT / "docs" / "build" / "html")) + args = parser.parse_args() + output = Path(args.output) + output.mkdir(parents=True, exist_ok=True) + + failed = [language for language in args.languages if not build(language, output)] + write_redirect(output, args.languages) + if failed: + print("The documentation did not build without warnings in: %s" % ", ".join(failed)) + return 1 + print("Documentation written to %s (open %s)" % (output, output / "index.html")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/tools/generate_authors.py b/docs/tools/generate_authors.py new file mode 100644 index 0000000..60819ad --- /dev/null +++ b/docs/tools/generate_authors.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python +"""Generate the list of authors from the git history. + +The authors are the people who made commits (``git shortlog``, with the +identities merged through ``.mailmap``) plus the authors listed in +``CITATION.cff`` who have no commit yet (original code, scientific +supervision, ...). Nothing is typed by hand: run this script, or build the +documentation, and the list is up to date. + +Outputs + AUTHORS.md list for the repository root + docs/source/_generated/authors.rst table included by the "Authors" pages + +Usage: python docs/tools/generate_authors.py +""" +import re +import subprocess +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + + +def git_authors(): + """Return [(name, commits)] ordered by number of commits (mailmap applied).""" + try: + out = subprocess.run( + ["git", "shortlog", "-sn", "--all"], + cwd=ROOT, capture_output=True, text=True, check=True, encoding="utf-8", + ).stdout + except (OSError, subprocess.CalledProcessError): + return None + authors = [] + for line in out.splitlines(): + match = re.match(r"\s*(\d+)\s+(.+)", line) + if match and "[bot]" not in match.group(2): + authors.append((match.group(2).strip(), int(match.group(1)))) + return authors + + +def citation_authors(): + """Names listed under ``authors:`` in CITATION.cff.""" + path = ROOT / "CITATION.cff" + if not path.is_file(): + return [] + names, family = [], None + in_authors = False + for line in path.read_text(encoding="utf-8").splitlines(): + if re.match(r"^authors:", line): + in_authors = True + elif in_authors and re.match(r"^\S", line): + in_authors = False + if not in_authors: + continue + m = re.search(r"family-names:\s*(.+)", line) + if m: + family = m.group(1).strip().strip('"') + m = re.search(r"given-names:\s*(.+)", line) + if m and family: + names.append(f"{m.group(1).strip().strip(chr(34))} {family}") + family = None + return names + + +def collect(): + authors = git_authors() + cited = citation_authors() + if authors is None: # no git available: only the citation file + return [(n, None) for n in cited] + known = {n.casefold() for n, _ in authors} + return authors + [(n, 0) for n in cited if n.casefold() not in known] + + +def write(authors): + gen = ROOT / "docs" / "source" / "_generated" + gen.mkdir(parents=True, exist_ok=True) + + def commits(n): + return "" if n is None else str(n) + + rows = "\n".join( + f" * - {name}\n - {commits(n) if n else '-'}" for name, n in authors + ) + (gen / "authors.rst").write_text( + ".. list-table::\n :header-rows: 1\n :widths: 75 25\n\n" + " * - Name\n - Commits\n" + rows + "\n", + encoding="utf-8", + ) + + md = ["# Authors", "", + "Generated from the git history and `CITATION.cff` by " + "`docs/tools/generate_authors.py`. Do not edit by hand.", "", + "| Name | Commits |", "|------|---------|"] + md += [f"| {name} | {commits(n) if n else '-'} |" for name, n in authors] + (ROOT / "AUTHORS.md").write_text("\n".join(md) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + result = collect() + write(result) + for name, n in result: + print(f"{name}: {n}") diff --git a/docs/tools/update_translations.py b/docs/tools/update_translations.py new file mode 100644 index 0000000..46869d5 --- /dev/null +++ b/docs/tools/update_translations.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +"""Update the translation catalogs (.po) after the English pages change. + +The English pages in ``docs/source/`` are the only source text. Their +translations live in ``docs/locale//LC_MESSAGES/.po``, one file +per page, each entry holding an English text (``msgid``) and its translation +(``msgstr``). This script + +1. asks Sphinx to extract the texts of every page (the gettext builder), +2. merges them into the catalog of each language: translations of unchanged + texts are kept, new texts appear untranslated and texts that changed a + little are marked ``fuzzy`` so the translator reviews them, +3. writes the catalogs without source locations, so a change in the English + text produces a small diff. + +A text that is untranslated or fuzzy is shown in English in the translated site. +The API page is generated from the ``.m`` comments and stays in English: only +its own headings and sentences are translated. + +Usage: + python docs/tools/update_translations.py update the catalogs + python docs/tools/update_translations.py --status only report what is left + python docs/tools/update_translations.py --languages es pt +""" +import argparse +import io +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +from babel.messages.catalog import Catalog +from babel.messages.pofile import read_po, write_po + +ROOT = Path(__file__).resolve().parents[2] +SOURCE = ROOT / "docs" / "source" +LOCALE = ROOT / "docs" / "locale" +LANGUAGES = ["es", "pt", "it"] +NAMES = {"es": "Spanish", "pt": "Portuguese", "it": "Italian"} + + +def extract(target): + """Run the gettext builder; return {page: Catalog} for every page.""" + subprocess.run( + [sys.executable, "-m", "sphinx", "-q", "-b", "gettext", + "-D", "gettext_compact=0", "-D", "gettext_location=1", str(SOURCE), str(target)], + check=True, + ) + catalogs = {} + for pot in sorted(Path(target).rglob("*.pot")): + page = pot.relative_to(target).with_suffix("").as_posix() + if page == "sphinx": # texts of the theme and of Sphinx itself + continue + with open(pot, "rb") as handle: + catalogs[page] = read_po(handle) + return catalogs + + +def own_texts_only(page, catalog): + """The API page is mostly generated docstrings: keep only the texts written in its .rst.""" + if page != "api/index": + return catalog + kept = Catalog(project=catalog.project, version=catalog.version, charset="utf-8") + for message in catalog: + if message.id and any(str(loc[0]).replace("\\", "/").endswith("api/index.rst") + for loc in message.locations): + kept.add(message.id, locations=message.locations) + return kept + + +def merge(language, page, template): + """Return the catalog of one page and language, merged with its template.""" + path = LOCALE / language / "LC_MESSAGES" / (page + ".po") + if path.is_file(): + with open(path, "rb") as handle: + catalog = read_po(handle, locale=language) + else: + catalog = Catalog(locale=language, project="LDEM-MATLAB", charset="utf-8") + catalog.update(template, no_fuzzy_matching=False) + for message in catalog: + message.locations = [] + catalog.fuzzy = False # the header of the catalog is not a translation to review + catalog.project = "LDEM-MATLAB" + catalog.version = "" + catalog.msgid_bugs_address = "" + catalog.last_translator = "" + catalog.language_team = "" + catalog.header_comment = ( + "# Translation of the LDEM-MATLAB documentation (%s).\n" + "# Generated by docs/tools/update_translations.py: edit only the msgstr entries." % language + ) + return path, catalog + + +def save(path, catalog): + """Write a catalog without the dates and the version, so an update only changes real text.""" + path.parent.mkdir(parents=True, exist_ok=True) + buffer = io.BytesIO() + write_po(buffer, catalog, width=88, ignore_obsolete=True, include_previous=False) + text = buffer.getvalue().decode("utf-8") + text = re.sub(r'"(POT-Creation-Date|PO-Revision-Date): [^\n]*\\n"\n', "", text) + text = text.replace('"Project-Id-Version: LDEM-MATLAB \\n"', '"Project-Id-Version: LDEM-MATLAB\\n"') + path.write_bytes(text.encode("utf-8")) + + +def count(catalog): + translated = fuzzy = missing = 0 + for message in catalog: + if not message.id: + continue + if not message.string or (isinstance(message.string, (list, tuple)) and not any(message.string)): + missing += 1 + elif message.fuzzy: + fuzzy += 1 + else: + translated += 1 + return translated, fuzzy, missing + + +def status(languages): + print("%-10s %12s %8s %12s" % ("language", "translated", "fuzzy", "untranslated")) + for language in languages: + total = [0, 0, 0] + worst = [] + for path in sorted((LOCALE / language / "LC_MESSAGES").rglob("*.po")): + with open(path, "rb") as handle: + numbers = count(read_po(handle, locale=language)) + total = [a + b for a, b in zip(total, numbers)] + if numbers[1] or numbers[2]: + worst.append((path.relative_to(LOCALE / language / "LC_MESSAGES").as_posix(), numbers)) + print("%-10s %12d %8d %12d" % (NAMES.get(language, language), *total)) + for name, numbers in worst: + print(" %-24s fuzzy %d, untranslated %d" % (name, numbers[1], numbers[2])) + print("\nSome untranslated entries are intentional: code lines, names and tables that read " + "the same in every language are left empty and shown as they are.") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--languages", nargs="+", default=LANGUAGES, choices=LANGUAGES) + parser.add_argument("--status", action="store_true", help="only report what is left to translate") + args = parser.parse_args() + if not args.status: + with tempfile.TemporaryDirectory() as tmp: + catalogs = extract(tmp) + for language in args.languages: + for page, template in catalogs.items(): + path, catalog = merge(language, page, own_texts_only(page, template)) + save(path, catalog) + print("Catalogs updated in", LOCALE) + status(args.languages) + + +if __name__ == "__main__": + main() diff --git a/examples/README.md b/examples/README.md index fff4150..683cbef 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,7 +1,54 @@ # Examples -1. From the repository root: `setup_path` -2. Input data: `src/ldem/DATA0.DAT`, `src/ldem/SIM01.DAT` -3. Run `main` (or `mainDEM`) from `src/ldem`. +Three models that run from start to finish. Each has its inputs and a script that runs +it and plots the results. The full description, with the model, the files and the +results to expect, is in the user guide: *Examples* (`docs/source/examples.rst`). -Outputs (`LET.*`, `*.TXT`) are written to the working directory. +| Folder | What it shows | Size | Time | +|--------|---------------|------|------| +| `example1_clamped_beam/` | Beam clamped at both ends and loaded with a force at mid-span (model by Rodrigo) | 3,086 nodes | about 35 s | +| `tension_101/` | Small prism under a uniaxial load, with damage and every output format | 74 nodes | about 6 s | +| `beam_102/` | The 101x41x21-node four-point bending beam of the paper (demo of the first 50 steps) | 166,961 nodes | about 30 s for 50 steps; about 20 h for the full run | + +Run an example from MATLAB, from any folder: + +```matlab +>> run('examples/example1_clamped_beam/runClampedBeam.m') +>> results = ldem.run('examples/example1_clamped_beam/case.ldem'); % from the case file +``` + +Outputs are written to an `output/` folder next to the script (ignored by git): + +- `results.mat` - one struct, `results`, with everything that was recorded. + Load it with `data = load('results.mat'); results = data.results;`. +- `snapshot_0000.mac`, ... - ANSYS macro files of the deformed lattice. +- `snapshot_0000.vtu`, ... and `snapshots.pvd` - open `snapshots.pvd` in + [ParaView](https://www.paraview.org/) to see the damage evolve in time. + +## Case files + +The two beam examples have a `case.ldem` next to their `DATA0.DAT`: the same model in +the readable case-file format (named keys, units, comments, the scenario and the output +files in one place). It is generated from the `DATA0.DAT` and gives the same parameters. + +```matlab +>> ldem.check('examples/example1_clamped_beam/case.ldem') % what would be simulated +>> results = ldem.run('examples/example1_clamped_beam/case.ldem'); +``` + +## Files + +| Folder | File | Purpose | +|--------|------|---------| +| `example1_clamped_beam/` | `case.ldem` | The model as a case file | +| | `runClampedBeam.m` | Reads `DATA0.DAT`, runs, and plots the force on the clamped ends, the vertical displacement of the control nodes and the energies | +| | `DATA0.DAT` | Parameters in the format of the original program (`TEST 103`) | +| `tension_101/` | `runTension.m` | Describes the model with `ldem.Parameters`, runs it and plots the energies | +| `beam_102/` | `case.ldem` | The model as a case file | +| | `runBeam.m` | Reads the input, runs the first 50 steps and plots the reaction | +| | `DATA0.DAT` | Parameters in the format of the original program (`TEST 102`) | +| | `arquivo_3lc_rnao_cv05` | Random field of the critical strain of each bar (11 MB); `example1_clamped_beam` uses it too | + +With the default values the clamped beam stays elastic (no bar softens). Raise the +force (`force_rate` in `case.ldem`, `forceRate` in the scenario) or lower the fracture +energy to see damage. diff --git a/src/ldem/DATA0.DAT b/examples/beam_102/DATA0.DAT similarity index 100% rename from src/ldem/DATA0.DAT rename to examples/beam_102/DATA0.DAT diff --git a/src/ldem/arquivo_3lc_rnao_cv05 b/examples/beam_102/arquivo_3lc_rnao_cv05 similarity index 100% rename from src/ldem/arquivo_3lc_rnao_cv05 rename to examples/beam_102/arquivo_3lc_rnao_cv05 diff --git a/examples/beam_102/case.ldem b/examples/beam_102/case.ldem new file mode 100644 index 0000000..e2add10 --- /dev/null +++ b/examples/beam_102/case.ldem @@ -0,0 +1,80 @@ +# Case file generated by ldem.io.convertLegacyInput from DATA0.DAT. +# The legacy value OU2 was 9999999 (not used by ldem). If it is the number of the tracked bar, set [monitor.bar] tracked. +# Bending test (TEST 102) on the 101x41x21-module beam of the paper + +format = 1 # Version of the case-file format (currently 1). +title = "Bending test (TEST 102) on the 101x41x21-module beam of the paper" # Free text title of the case. + +[mesh] +module_size = 3 mm # Edge length of each cubic module. Legacy: LCO. +modules = [100, 40, 20] # Cubic modules along x, y and z (M N L of the legacy file count nodes: one more). Legacy: M N L. +perturbation = 0 # Random node displacement as a fraction of the module size; 0 = regular lattice. +seed = 123 # Seed of the mesh perturbation (the random field has its own seed). Legacy: SEED. + +[material] +law = "bilinear" # Constitutive law of the bars. +young_modulus = 32 GPa # Young's modulus. Legacy: YNG. +poisson_ratio = 0.25 # Poisson's ratio, from 0 up to less than 0.5. Legacy: PSN. +density = 2000 kg/m3 # Mass density. Legacy: ROH. +fracture_energy = 50 N/m # Specific fracture energy. Legacy: GFR. +critical_distance = 28 mm # Equivalent (critical) distance. Legacy: DEQ. +failure_area_factor = 0.1385 # Fraction of the module face that fails per bar. Legacy: CAF. + +[material.scatter] +type = "file" # Scatter of the critical strain: none, file (one multiplier per bar) or generated. +file = "arquivo_3lc_rnao_cv05" # Text file with one multiplier per bar, relative to this file. + +[time] +step = 0.2 us # Integration time step, or auto (0.9 times the critical step). Legacy: DT. +duration = 30 ms # Total simulated time. Legacy: TTOT. + +[damping] +type = "mass_proportional" # Damping model. +initial = 25000 1/s # Mass-proportional damping before switch_time. Legacy: DF1. +final = 25000 1/s # Mass-proportional damping after switch_time. Legacy: DF2. +switch_time = 15 ms # Time at which the damping changes from initial to final. Legacy: TDAF. +constitutive = 0 s # Stiffness-proportional damping inside the bar law. Legacy: CON. + +[scenario] +type = "four_point_bending" # Test case (see ldem.scenarios.registry); its other keys follow. Legacy: TEST. +loading_velocity = 0.004 m/s # Property loadingVelocity of ldem.scenarios.FourPointBending. +support_position = 4.5 modules # Property supportPosition of ldem.scenarios.FourPointBending. +load_position = 33.5 modules # Property loadPosition of ldem.scenarios.FourPointBending. + +[[monitor.node]] +name = "node_1" # Label of the node. +id = 1 # (x, y, z) = (0, 0, 0) modules + +[[monitor.node]] +name = "node_2" # Label of the node. +id = 2 # (x, y, z) = (1, 0, 0) modules + +[[monitor.node]] +name = "node_3" # Label of the node. +id = 3 # (x, y, z) = (2, 0, 0) modules + +[[monitor.node]] +name = "node_4" # Label of the node. +id = 4 # (x, y, z) = (3, 0, 0) modules + +[[monitor.node]] +name = "node_5" # Label of the node. +id = 5 # (x, y, z) = (4, 0, 0) modules + +[monitor.bar] +tracked = 7014 # Number of the bar whose strain history is stored at every step. Legacy: OU9. + +[output] +folder = "output" # Output folder, relative to the case file. +mat = true # Write results.mat. +ansys = true # Write ANSYS macro files (needs snapshots.every > 0). +vtk = true # Write VTK files for ParaView (needs snapshots.every > 0). + +[output.snapshots] +every = 10000 steps # Steps or time between full-field snapshots; 0 = never. Legacy: OU3. + +[output.control_nodes] +every = 1 step # Steps or time between records of the control nodes and reactions; 0 = never. Legacy: OU6. + +[output.energy] +every = 1 step # Steps or time between records of the energies; 0 = never. Legacy: OU8. diff --git a/examples/beam_102/runBeam.m b/examples/beam_102/runBeam.m new file mode 100644 index 0000000..b2c9978 --- /dev/null +++ b/examples/beam_102/runBeam.m @@ -0,0 +1,41 @@ +%% Bending test (TEST 102) on the 101x41x21-module beam of the paper +% Reads the input file DATA0.DAT of this folder and runs the beam. +% +% The full beam has about 167,000 nodes and 1.1 million bars. A full run is +% 150,000 steps (see the time estimate below), so this script runs only the first +% "nStepsDemo" steps. Increase it (or remove the totalTime override) for the +% real simulation. Measured on a laptop: about 20 s to build the model and 0.5 s +% per step, so the 150,000 steps of the real run need roughly 20 hours. +% +% Output goes to the folder "output" next to this script, or to +% "outputFolder" if that variable already exists in the workspace. + +here = fileparts(mfilename('fullpath')); +addpath(fullfile(fileparts(fileparts(here)), 'src')); +if ~exist('outputFolder', 'var') + outputFolder = fullfile(here, 'output'); +end +nStepsDemo = 50; + +%% 1. Read the input file +% fromFile reads DATA0.DAT; the name-value pairs add what the file does not +% contain (the random field) or replace a value (the simulated time). +params = ldem.Parameters.fromFile(fullfile(here, 'DATA0.DAT'), ... + randomFieldFile = fullfile(here, 'arquivo_3lc_rnao_cv05'), ... + totalTime = nStepsDemo * 2e-7); +% Store the snapshots at the end only (demo). +params.output.snapshotEvery = nStepsDemo; +params.output.controlNodesEvery = 5; +params.output.energyEvery = 5; + +fprintf('Beam with %d nodes, %d steps.\n', params.nNodes, params.nSteps); + +%% 2. Run +results = ldem.runSimulation(params, ... + OutputFolder = outputFolder, ... + Formats = ["mat" "vtk"], ... + Verbose = true); + +%% 3. Plot +fig = figure('Name', 'Reaction force'); +ldem.post.plotReaction(results, axes(fig)); diff --git a/examples/example1_clamped_beam/DATA0.DAT b/examples/example1_clamped_beam/DATA0.DAT new file mode 100644 index 0000000..97308ed --- /dev/null +++ b/examples/example1_clamped_beam/DATA0.DAT @@ -0,0 +1,28 @@ +103 ' TEST ' +123 ' SEED' +1E-3 ' LCO ' +6 ' M ' +6 ' N ' +51 ' L ' +2500 ' DF1 ' +2500 ' DF2 ' +0.015 ' TDAF ' +0.00E-00 ' CON ' +3.5E-7 ' DT ' +2.8E-3 ' TTOT ' +2 ' INCO ' +2441 ' Ncon1 ' +884 ' Ncon2 ' +14398 ' OU2 ' +1000 ' OU3 ' +0 ' OU4 ' +0 ' OU5 ' +1 ' OU6 ' +1 ' OU7 ' +1 ' OU8 ' +1 ' OU9 ' +2.50E-01 ' PSN ' +1500.0E+0 ' ROH ' +3.87E+9 ' YNG ' +0.5E+00 ' GFR ' +4.5E-3 ' DEQ ' diff --git a/examples/example1_clamped_beam/case.ldem b/examples/example1_clamped_beam/case.ldem new file mode 100644 index 0000000..3f61d3c --- /dev/null +++ b/examples/example1_clamped_beam/case.ldem @@ -0,0 +1,69 @@ +# Case file generated by ldem.io.convertLegacyInput from DATA0.DAT. +# Example 1: beam clamped at both ends, loaded with a force at mid-span + +format = 1 # Version of the case-file format (currently 1). +title = "Example 1: beam clamped at both ends, loaded with a force at mid-span" # Free text title of the case. +authors = ["Rodrigo"] # Names of the authors. + +[mesh] +module_size = 1 mm # Edge length of each cubic module. Legacy: LCO. +modules = [5, 5, 50] # Cubic modules along x, y and z (M N L of the legacy file count nodes: one more). Legacy: M N L. +perturbation = 0 # Random node displacement as a fraction of the module size; 0 = regular lattice. +seed = 123 # Seed of the mesh perturbation (the random field has its own seed). Legacy: SEED. + +[material] +law = "bilinear" # Constitutive law of the bars. +young_modulus = 3.87 GPa # Young's modulus. Legacy: YNG. +poisson_ratio = 0.25 # Poisson's ratio, from 0 up to less than 0.5. Legacy: PSN. +density = 1500 kg/m3 # Mass density. Legacy: ROH. +fracture_energy = 0.5 N/m # Specific fracture energy. Legacy: GFR. +critical_distance = 4.5 mm # Equivalent (critical) distance. Legacy: DEQ. +failure_area_factor = 0.1385 # Fraction of the module face that fails per bar. Legacy: CAF. + +[material.scatter] +type = "file" # Scatter of the critical strain: none, file (one multiplier per bar) or generated. +file = "../beam_102/arquivo_3lc_rnao_cv05" # Text file with one multiplier per bar, relative to this file. + +[time] +step = 0.35 us # Integration time step, or auto (0.9 times the critical step). Legacy: DT. +duration = 2.8 ms # Total simulated time. Legacy: TTOT. + +[damping] +type = "mass_proportional" # Damping model. +initial = 2500 1/s # Mass-proportional damping before switch_time. Legacy: DF1. +final = 2500 1/s # Mass-proportional damping after switch_time. Legacy: DF2. +switch_time = 15 ms # Time at which the damping changes from initial to final. Legacy: TDAF. +constitutive = 0 s # Stiffness-proportional damping inside the bar law. Legacy: CON. + +[scenario] +type = "clamped_beam" # Test case (see ldem.scenarios.registry); its other keys follow. Legacy: TEST. +force_rate = 1000 N/s # Property forceRate of ldem.scenarios.ClampedBeam. +ramp_time = 0.35 ms # Property rampTime of ldem.scenarios.ClampedBeam. +load_position = "midspan" # Property loadPosition of ldem.scenarios.ClampedBeam. +load_height = 0.5 modules # Property loadHeight of ldem.scenarios.ClampedBeam. + +[[monitor.node]] +name = "node_2441" # Label of the node. +id = 2441 # (x, y, z) = (4.5, 0.5, 24.5) modules + +[[monitor.node]] +name = "node_884" # Label of the node. +id = 884 # (x, y, z) = (1, 3, 24) modules + +[monitor.bar] +tracked = 14398 # Number of the bar whose strain history is stored at every step. Legacy: OU9. + +[output] +folder = "output" # Output folder, relative to the case file. +mat = true # Write results.mat. +ansys = true # Write ANSYS macro files (needs snapshots.every > 0). +vtk = true # Write VTK files for ParaView (needs snapshots.every > 0). + +[output.snapshots] +every = 1000 steps # Steps or time between full-field snapshots; 0 = never. Legacy: OU3. + +[output.control_nodes] +every = 1 step # Steps or time between records of the control nodes and reactions; 0 = never. Legacy: OU6. + +[output.energy] +every = 1 step # Steps or time between records of the energies; 0 = never. Legacy: OU8. diff --git a/examples/example1_clamped_beam/runClampedBeam.m b/examples/example1_clamped_beam/runClampedBeam.m new file mode 100644 index 0000000..da688e2 --- /dev/null +++ b/examples/example1_clamped_beam/runClampedBeam.m @@ -0,0 +1,71 @@ +%% Example 1: beam clamped at both ends, loaded with a force at mid-span +% Model by Rodrigo (branch dev_rodrigo). A small beam of 5 x 5 x 50 modules +% of 1 mm is clamped at both ends and loaded at mid-span with a force that +% grows during 0.35 ms and then stays constant. The run simulates 2.8 ms +% (8000 steps). +% +% What it does +% 1. Reads the input file DATA0.DAT of this folder (test 103, see +% ldem.scenarios.ClampedBeam) and adds what the file does not contain. +% 2. Runs the simulation, writing results.mat, ANSYS macro files and a VTK +% series (open snapshots.pvd in ParaView). +% 3. Plots the force carried by the clamped ends, the vertical displacement +% of the control nodes and the energies. +% +% The model has 3086 nodes and 18085 bars. Output goes to the folder +% "output" next to this script, or to "outputFolder" if that variable +% already exists in the workspace. + +here = fileparts(mfilename('fullpath')); +repoRoot = fileparts(fileparts(here)); +addpath(fullfile(repoRoot, 'src')); +if ~exist('outputFolder', 'var') + outputFolder = fullfile(here, 'output'); +end + +%% 1. Parameters +% fromFile reads DATA0.DAT. The random field that varies the critical strain +% of each bar is shared with the beam_102 example; trackedBar selects the bar +% whose strain and force are stored at every step. +params = ldem.Parameters.fromFile(fullfile(here, 'DATA0.DAT'), ... + randomFieldFile = fullfile(repoRoot, 'examples', 'beam_102', 'arquivo_3lc_rnao_cv05'), ... + trackedBar = 14398); + +fprintf('Clamped beam with %d nodes, %d steps.\n', params.nNodes, params.nSteps); + +%% 2. Scenario +% Test 103 is registered for testId = 103, so runSimulation would find it by +% itself. It is created here to show the load: a force of +% forceRate*min(t, rampTime) newtons on each node of the loaded line. Change +% the values to try other loads, for example forceRate=2000. +scenario = ldem.scenarios.ClampedBeam(forceRate=1000, rampTime=0.00035); + +%% 3. Run +results = ldem.runSimulation(params, ... + Scenario = scenario, ... + OutputFolder = outputFolder, ... + Formats = ["mat" "ansys" "vtk"], ... + Verbose = true); + +%% 4. Look at the results +counts = results.snapshots.barCounts(end, :); +fprintf('\nAfter %.3g s: %d intact, %d damaged and %d broken bars.\n', ... + results.final.time, counts(1), counts(2), counts(3)); +fprintf('Files written to %s\n', outputFolder); + +fig = figure('Name', 'Force on the clamped ends'); +ldem.post.plotReaction(results, axes(fig)); + +fig = figure('Name', 'Vertical displacement of the control nodes'); +ax = axes(fig); +% The stored values are positions; subtract the initial ones to get displacements. +y0 = results.mesh.nodes0(params.controlNodes, 2).'; +plot(ax, results.controlNodes.time, ... + 1e3 * (results.controlNodes.displacement(:, :, 2) - y0)); +xlabel(ax, 'Time [s]'); +ylabel(ax, 'Vertical displacement [mm]'); +legend(ax, "node " + string(params.controlNodes), 'Location', 'best'); +grid(ax, 'on'); + +fig = figure('Name', 'Energies'); +ldem.post.plotEnergy(results, axes(fig)); diff --git a/examples/tension_101/runTension.m b/examples/tension_101/runTension.m new file mode 100644 index 0000000..3d623e8 --- /dev/null +++ b/examples/tension_101/runTension.m @@ -0,0 +1,51 @@ +%% Uniaxial test (TEST 101) on a small prism +% This script runs a complete simulation in a few seconds and writes every +% kind of output file. It is the best place to start: copy it and change the +% parameters. +% +% What it does +% 1. Describes the model with ldem.Parameters (a 5x2x2-module prism). +% 2. Runs it with ldem.runSimulation, writing results.mat, ANSYS macro files +% and a VTK series (open snapshots.pvd in ParaView). +% 3. Plots the energies. +% +% Output goes to the folder "output" next to this script, or to +% "outputFolder" if that variable already exists in the workspace. + +here = fileparts(mfilename('fullpath')); +addpath(fullfile(fileparts(fileparts(here)), 'src')); +if ~exist('outputFolder', 'var') + outputFolder = fullfile(here, 'output'); +end + +%% 1. Parameters +% The fracture energy is low on purpose so that bars soften and break within +% the 1000 steps (0.2 ms) of the run. +params = ldem.Parameters( ... + testId = 101, ... % prism loaded along x + nModules = [6 3 3], ... % nodes along x, y, z + moduleLength = 0.003, ... % [m] + dt = 2e-7, ... % [s] + totalTime = 2e-4, ... % [s] -> 1000 steps + fractureEnergy = 0.1, ... % [N/m] + controlNodes = [1 2], ... + output = struct( ... + 'snapshotEvery', 250, ... % ANSYS/VTK file every 250 steps + 'controlNodesEvery', 10, ... % control nodes and reactions + 'energyEvery', 10, ... % energies + 'trackedBarEvery', 0)); % tracked bar off + +%% 2. Run +results = ldem.runSimulation(params, ... + OutputFolder = outputFolder, ... + Formats = ["mat" "ansys" "vtk"], ... + Verbose = true); + +%% 3. Look at the results +counts = results.snapshots.barCounts(end, :); +fprintf('\nAfter %.2g s: %d intact, %d damaged and %d broken bars.\n', ... + results.final.time, counts(1), counts(2), counts(3)); +fprintf('Files written to %s\n', outputFolder); + +fig = figure('Name', 'Energies'); +ldem.post.plotEnergy(results, axes(fig)); diff --git a/setup_path.m b/setup_path.m index 2faa86d..df84397 100644 --- a/setup_path.m +++ b/setup_path.m @@ -1,5 +1,15 @@ function setup_path() -%SETUP_PATH Adiciona src/ldem ao path do MATLAB. +%SETUP_PATH Add the LDEM code to the MATLAB path. +% +% setup_path() adds src/ to the MATLAB path for the current session, so +% the package can be used as ldem.. +% +% Example: +% >> setup_path +% >> params = ldem.Parameters(); +% +% See also addpath. + root = fileparts(mfilename('fullpath')); -addpath(fullfile(root, 'src', 'ldem')); +addpath(fullfile(root, 'src')); end diff --git a/src/+ldem/+io/SnapshotWriter.m b/src/+ldem/+io/SnapshotWriter.m new file mode 100644 index 0000000..c915326 --- /dev/null +++ b/src/+ldem/+io/SnapshotWriter.m @@ -0,0 +1,136 @@ +classdef SnapshotWriter < handle + %SNAPSHOTWRITER Collect snapshots of the state and export them to files. + % + % A snapshot is the full state of the lattice at one instant. The solver + % calls the writer at the steps chosen by params.output.snapshotEvery. + % For every snapshot the writer does the following: + % + % * keeps a compact copy (displacement, damage state and nodal kinetic energy), stored in the results; + % * writes an ANSYS macro file if "ansys" is among the formats; + % * writes a VTK file if "vtk" is among the formats. + % + % When the simulation ends, finish() writes the ParaView collection that + % groups the VTK files in time. + % + % Typical use (done by ldem.runSimulation): + % writer = ldem.io.SnapshotWriter(mesh, "output", ["ansys" "vtk"]); + % ldem.solver.simulate(..., SnapshotFcn=@writer.write); + % snapshots = writer.finish(); + % + % Files are written inside the given folder, named snapshot_0000.vtu, + % snapshot_0001.vtu, ... and snapshot_0000.mac, ... (zero is the state + % at time zero); the collection is called snapshots.pvd. + % + % See also ldem.io.exportAnsys, ldem.io.exportVtk, ldem.io.writePvd, + % ldem.solver.simulate. + + properties (SetAccess = private) + % Folder where the files are written ("" if no files are written). + Folder (1,1) string = "" + % Export formats: any of "ansys" and "vtk". + Formats (1,:) string = string.empty + % Number of snapshots taken so far. + Count (1,1) double = 0 + end + + properties (Access = private) + Mesh (1,1) struct + Steps = zeros(0, 1) + Times = zeros(0, 1) + BarCounts = zeros(0, 3) + Displacements = {} + DamageStates = {} + KineticEnergies = {} + VtkFiles = strings(0, 1) + end + + methods + function obj = SnapshotWriter(mesh, folder, formats) + %SNAPSHOTWRITER Create a writer for a mesh. + % + % writer = ldem.io.SnapshotWriter(mesh, folder, formats) prepares + % the writer. folder may be "" when formats is empty, to only keep + % the in-memory snapshots. + arguments + mesh (1,1) struct + folder (1,1) string = "" + formats (1,:) string {mustBeMember(formats, ["ansys", "vtk"])} = string.empty + end + if ~isempty(formats) && strlength(folder) == 0 + error('ldem:io:noFolder', 'A folder is needed to export %s files.', strjoin(formats, ' and ')); + end + if strlength(folder) > 0 && ~isfolder(folder) + mkdir(folder); + end + obj.Mesh = mesh; + obj.Folder = folder; + obj.Formats = formats; + end + + function write(obj, state) + %WRITE Take one snapshot (callback for ldem.solver.simulate). + arguments + obj (1,1) ldem.io.SnapshotWriter + state (1,1) struct + end + index = obj.Count; + baseName = sprintf('snapshot_%04d', index); + + if any(obj.Formats == "ansys") + counts = ldem.io.exportAnsys(fullfile(obj.Folder, baseName + ".mac"), obj.Mesh, state); + else + counts = ldem.io.SnapshotWriter.countBars(state); + end + if any(obj.Formats == "vtk") + ldem.io.exportVtk(fullfile(obj.Folder, baseName + ".vtu"), obj.Mesh, state); + obj.VtkFiles(end + 1, 1) = baseName + ".vtu"; + end + + damageState = uint8(2 * ones(size(state.history.isUndamaged))); + damageState(state.history.isUnbroken) = 1; + damageState(state.history.isUndamaged) = 0; + + obj.Count = obj.Count + 1; + obj.Steps(end + 1, 1) = state.step; + obj.Times(end + 1, 1) = state.time; + obj.BarCounts(end + 1, :) = [counts.intact, counts.damaged, counts.broken]; + obj.Displacements{end + 1} = single(state.displacement); + obj.DamageStates{end + 1} = damageState; + obj.KineticEnergies{end + 1} = single(ldem.solver.nodalKineticEnergy(state, obj.Mesh)); + end + + function snapshots = finish(obj) + %FINISH Write the ParaView collection and return the snapshots. + % + % snapshots = writer.finish() returns a struct with the fields + % step, time (n-by-1), barCounts (n-by-3: intact, damaged, + % broken), and displacement (n-by-1 cell of nNodes-by-3 single) + % and damageState (n-by-1 cell of nBars-by-1 uint8: 0 intact, + % 1 damaged, 2 broken), and kineticEnergy (n-by-1 cell of + % nNodes-by-1 single: kinetic energy of every node [J]). + arguments + obj (1,1) ldem.io.SnapshotWriter + end + if ~isempty(obj.VtkFiles) + ldem.io.writePvd(fullfile(obj.Folder, "snapshots.pvd"), ... + obj.Times(1:numel(obj.VtkFiles)), obj.VtkFiles); + end + snapshots = struct( ... + 'step', obj.Steps, ... + 'time', obj.Times, ... + 'barCounts', obj.BarCounts, ... + 'displacement', {obj.Displacements(:)}, ... + 'damageState', {obj.DamageStates(:)}, ... + 'kineticEnergy', {obj.KineticEnergies(:)}); + end + end + + methods (Static, Access = private) + function counts = countBars(state) + intact = nnz(state.history.isUndamaged); + broken = nnz(~state.history.isUnbroken); + counts = struct('intact', intact, 'damaged', numel(state.history.isUndamaged) - intact - broken, ... + 'broken', broken); + end + end +end diff --git a/src/+ldem/+io/convertLegacyInput.m b/src/+ldem/+io/convertLegacyInput.m new file mode 100644 index 0000000..618600d --- /dev/null +++ b/src/+ldem/+io/convertLegacyInput.m @@ -0,0 +1,95 @@ +function text = convertLegacyInput(dataPath, casePath, options) +%CONVERTLEGACYINPUT Convert a DATA0.DAT input file into a case file (.ldem). +% +% text = ldem.io.convertLegacyInput(dataPath, casePath) reads the legacy +% input file with ldem.io.readInputFile and writes the equivalent case +% file: named keys, units, comments, M N L converted to modules, the control +% nodes with their coordinates, and the scenario of the TEST number with its +% default values. The case file gives exactly the same ldem.Parameters as +% ldem.Parameters.fromFile(dataPath). +% +% Values that the legacy file does not contain can be given as options. The +% converter never guesses them: in the examples of this repository the value +% OU2 of the DATA0.DAT is the number of the tracked bar, but the legacy code +% does not use it, so it is only copied into a comment. +% +% Inputs: +% dataPath Path of the DATA0.DAT file. +% casePath Path of the .ldem file to create ("" to only return the text). +% +% Name-value options: +% RandomFieldFile File with the random field (enables scatter type "file"). +% TrackedBar Bar whose strain history is stored (see monitor.bar). +% Scenario Scenario object (default: the one of the TEST number). +% Title Title for the case file (default: the DATA0 file name). +% Authors String array of authors. +% OutputFolder Value of output.folder (default "output"). +% +% Output: +% text Content of the case file. +% +% Example: +% ldem.io.convertLegacyInput("examples/beam_102/DATA0.DAT", ... +% "examples/beam_102/case.ldem"); +% +% See also ldem.io.readCase, ldem.io.readInputFile, ldem.io.writeCase. + +arguments + dataPath (1,1) string + casePath (1,1) string + options.RandomFieldFile (1,1) string = "" + options.TrackedBar = [] + options.Scenario = [] + options.Title (1,1) string = "" + options.Authors (1,:) string = string.empty + options.OutputFolder (1,1) string = "output" +end + +overrides = {}; +if strlength(options.RandomFieldFile) > 0 + overrides = [overrides, {'randomFieldFile', options.RandomFieldFile}]; +end +if ~isempty(options.TrackedBar) + overrides = [overrides, {'trackedBar', options.TrackedBar}]; +end +params = ldem.Parameters.fromFile(dataPath, overrides{:}); +if ~isempty(options.TrackedBar) + output = params.output; + output.trackedBarEvery = 1; + params.output = output; +end + +[~, dataName, dataExt] = fileparts(dataPath); +title = options.Title; +if title == "" + title = "Converted from " + string(dataName) + string(dataExt); +end +header = "Case file generated by ldem.io.convertLegacyInput from " + string(dataName) + string(dataExt) + "."; +ou2 = legacyOu2(dataPath); +if ~isnan(ou2) && isempty(options.TrackedBar) + header(end+1) = "The legacy value OU2 was " + ldem.schema.shortestText(ou2) + ... + " (not used by ldem). If it is the number of the tracked bar, set [monitor.bar] tracked."; +end + +text = ldem.io.writeCase(casePath, params, options.Scenario, ... + Title = title, Authors = options.Authors, Header = header, ... + OutputFolder = options.OutputFolder); +end + +function value = legacyOu2(dataPath) +%LEGACYOU2 The OU2 value of a DATA0.DAT file, or NaN if it cannot be read. +try + lines = splitlines(string(fileread(dataPath))); + tokens = strings(0, 1); + for k = 1:numel(lines) + word = strtok(strtrim(lines(k))); + if strlength(word) > 0 + tokens(end+1, 1) = word; %#ok + end + end + nControl = str2double(tokens(13)); + value = str2double(tokens(13 + nControl + 1)); +catch + value = NaN; +end +end diff --git a/src/+ldem/+io/exportAnsys.m b/src/+ldem/+io/exportAnsys.m new file mode 100644 index 0000000..ab23c0d --- /dev/null +++ b/src/+ldem/+io/exportAnsys.m @@ -0,0 +1,162 @@ +function counts = exportAnsys(path, mesh, state) +%EXPORTANSYS Write an ANSYS macro file (.mac) with the current state. +% +% counts = ldem.io.exportAnsys(path, mesh, state) writes a text file that +% ANSYS can read to draw the deformed lattice. It contains the node +% positions, the bars coloured by damage state, and the constraints. +% +% The bars are written as elements of three types: +% +% TYPE 1 intact bars (never softened) +% TYPE 2 damaged bars (softening but not broken) +% TYPE 5 broken bars +% +% The element type numbers are the ones used by the colour commands of the +% file, so the damaged zone is easy to see. +% +% The constraint section lists the degrees of freedom held by the scenario +% (mesh.fixed), with value zero. The applied-loads section then gives, as +% "D,node,direction,value", the displacement imposed on the loaded nodes +% measured from their initial position (nothing is written at time zero). +% For a scenario loaded with forces (test 103) a further section lists the +% applied forces of the state as "F,node,direction,value" (FX, FY, FZ); it is +% omitted when there are none. +% Note that the node coordinates of the file are the current positions, so +% the file shows the state of the simulation; it is not a restart of the +% analysis from the undeformed lattice. Node positions are written in +% single precision, like the legacy code. +% +% Inputs: +% path Path of the file to create. +% mesh Struct from ldem.mesh.buildMesh. +% state Solver state (current displacement and damage state). +% +% Output: +% counts Struct with the number of bars in each state: intact, damaged +% and broken. +% +% Errors: +% ldem:io:cannotOpenFile The file cannot be created. +% +% Differences from the legacy file: the line "ET,IFILE,4" (an invalid +% command caused by a translation slip) is written as "ET,3,4"; the +% constraints are written for every scenario, not only for TEST 102; and +% the hardcoded "applied loads" of TEST 102 ("F,node,Fx,-10" on nodes that +% matched no node of the beam) are replaced by the imposed displacements +% of the loaded nodes. +% +% Example: +% counts = ldem.io.exportAnsys("step100.mac", mesh, state); +% +% Legacy: ANSYS. +% +% See also ldem.io.exportVtk, ldem.io.SnapshotWriter. + +arguments + path (1,1) string + mesh (1,1) struct + state (1,1) struct +end + +fid = fopen(path, 'w'); +if fid == -1 + error('ldem:io:cannotOpenFile', 'Cannot create the ANSYS file "%s".', path); +end +closer = onCleanup(@() fclose(fid)); + +nNodes = size(state.displacement, 1); +nBars = size(mesh.bars, 1); + +fprintf(fid, '!ARQUIVO NO TEMPO = %g\n', state.time); +fprintf(fid, '/PREP7\n'); +fprintf(fid, '/TITLE, TEMPO =%g\n', state.time); +for typeNumber = [1 2 3 4 5 6 8 9 10 11 12] + fprintf(fid, 'ET,%d,4\n', typeNumber); +end +fprintf(fid, 'MP,EX,1,2E10\n'); +fprintf(fid, 'MP,PRXY,1,0.25\n'); +fprintf(fid, 'MP,DENS,1,2500\n'); +fprintf(fid, 'R,1,0.13,0.0014,0.36\n'); +fprintf(fid, '\n'); + +% Node coordinates, in single precision. +fprintf(fid, '!COORDENADAS NODAIS\n'); +coordinates = double(single(state.displacement)); +fprintf(fid, 'N,%d,%g,%g,%g\n', [(1:nNodes); coordinates.']); +fprintf(fid, '\n'); + +% Bars as elements, typed by damage state. +fprintf(fid, '!CONECTIVIDADES DOS ELEMENTOS\n'); +elementType = 5 * ones(nBars, 1); % broken +elementType(state.history.isUnbroken) = 2; % damaged +elementType(state.history.isUndamaged) = 1; % intact +fprintf(fid, 'TYPE,%d\nE,%d,%d,!EL%d\n', [elementType.'; mesh.bars.'; (1:nBars)]); +fprintf(fid, '\n'); + +counts = struct('intact', nnz(elementType == 1), ... + 'damaged', nnz(elementType == 2), ... + 'broken', nnz(elementType == 5)); + +% Colours. +fprintf(fid, '!CORES DOS ELEMENTOS\n'); +colours = {1, 'GCYA'; 2, 'ORAN'; 5, 'RED'; 6, 'GREE'}; +for k = 1:size(colours, 1) + fprintf(fid, 'ESEL,S,TYPE,,%d\n', colours{k, 1}); + fprintf(fid, '/COLOR,ELEM,%s\n', colours{k, 2}); + fprintf(fid, '/PNUM,TYPE,0\n'); + fprintf(fid, '/NUMBER,1\n'); + fprintf(fid, 'ESEL,ALL\n'); +end + +% Constraints. +fprintf(fid, '!CONDIÇÕES DE CONTORNO\n'); +directions = ["UX", "UY", "UZ"]; +for node = find(any(mesh.fixed, 2)).' + for direction = find(mesh.fixed(node, :)) + fprintf(fid, 'D,%d,%s\n', node, directions(direction)); + end +end +fprintf(fid, '\n'); + +% Applied loads: the displacement imposed on the held degrees of freedom of +% the loaded nodes, measured from their initial position. ANSYS keeps the +% last constraint given to a degree of freedom, so these lines replace the +% zero-valued ones of the section above. +fprintf(fid, '!CARGAS APLICADAS (DESLOCAMENTO IMPOSTO DESDE A POSICAO INICIAL)\n'); +imposed = state.displacement - mesh.nodes0; +imposed(~mesh.fixed) = 0; +for node = find(any(imposed ~= 0, 2)).' + for direction = find(imposed(node, :) ~= 0) + fprintf(fid, 'D,%d,%s,%g\n', node, directions(direction), imposed(node, direction)); + end +end +fprintf(fid, '\n'); + +% Applied forces: scenarios loaded with forces (test 103) set state.appliedForce. +% The section is written only when there is a force, so that the files of the +% displacement-controlled tests stay equal to the legacy ones. +forces = zeros(nNodes, 3); +if isfield(state, 'appliedForce') + forces = state.appliedForce; +end +if any(forces(:) ~= 0) + forceLabels = ["FX", "FY", "FZ"]; + fprintf(fid, '!FORCAS APLICADAS\n'); + for node = find(any(forces ~= 0, 2)).' + for direction = find(forces(node, :) ~= 0) + fprintf(fid, 'F,%d,%s,%g\n', node, forceLabels(direction), forces(node, direction)); + end + end + fprintf(fid, '\n'); +end + +fprintf(fid, '/VIEW,1,0,-1,0\n'); +fprintf(fid, 'EPLOT\n'); +fprintf(fid, '\n'); + +fprintf(fid, '!ESTADO DAS BARRAS\n'); +fprintf(fid, '!BARRAS INTACTAS = %d\n', counts.intact); +fprintf(fid, '!BARRAS DANIFICADAS = %d\n', counts.damaged); +fprintf(fid, '!BARRAS ROMPIDAS = %d\n', counts.broken); +fprintf(fid, '\n'); +end diff --git a/src/+ldem/+io/exportVtk.m b/src/+ldem/+io/exportVtk.m new file mode 100644 index 0000000..5fdaa03 --- /dev/null +++ b/src/+ldem/+io/exportVtk.m @@ -0,0 +1,92 @@ +function exportVtk(path, mesh, state) +%EXPORTVTK Write the current state as a VTK unstructured grid (.vtu). +% +% ldem.io.exportVtk(path, mesh, state) writes an XML VTK file that opens in +% ParaView (or any VTK reader). The lattice is drawn as line cells. +% +% Points are the current node positions. Data stored: +% +% Point data displacement (current minus initial position [m]) and +% velocity [m/s], both 3-component vectors. +% Cell data damageState (0 intact, 1 damaged, 2 broken), strain, +% axialForce [N] (tension positive) and barType (1 grid +% edge, 2 centre bar, 3 diagonal). +% +% The file is ASCII so that it can be inspected and diffed. To follow a +% whole simulation, ldem.io.SnapshotWriter writes one file per snapshot +% and a .pvd collection that ParaView opens as a time series. +% +% Inputs: +% path Path of the .vtu file to create. +% mesh Struct from ldem.mesh.buildMesh. +% state Solver state. +% +% Errors: +% ldem:io:cannotOpenFile The file cannot be created. +% +% Example: +% ldem.io.exportVtk("step100.vtu", mesh, state); +% +% See also ldem.io.exportAnsys, ldem.io.SnapshotWriter, ldem.io.writePvd. + +arguments + path (1,1) string + mesh (1,1) struct + state (1,1) struct +end + +fid = fopen(path, 'w'); +if fid == -1 + error('ldem:io:cannotOpenFile', 'Cannot create the VTK file "%s".', path); +end +closer = onCleanup(@() fclose(fid)); + +nNodes = size(state.displacement, 1); +nBars = size(mesh.bars, 1); + +damageState = 2 * ones(nBars, 1); % broken +damageState(state.history.isUnbroken) = 1; % damaged +damageState(state.history.isUndamaged) = 0; % intact + +fprintf(fid, '\n'); +fprintf(fid, '\n'); +fprintf(fid, '\n'); +fprintf(fid, '\n', nNodes, nBars); + +fprintf(fid, '\n'); +writeArray(fid, 'Float64', 'displacement', 3, '%.9g', state.displacement - mesh.nodes0); +writeArray(fid, 'Float64', 'velocity', 3, '%.9g', state.velocity); +fprintf(fid, '\n'); + +fprintf(fid, '\n'); +writeArray(fid, 'Int32', 'damageState', 1, '%d', damageState); +writeArray(fid, 'Float64', 'strain', 1, '%.9g', state.strain); +writeArray(fid, 'Float64', 'axialForce', 1, '%.9g', state.axialForce); +if isfield(mesh, 'barType') + writeArray(fid, 'Int32', 'barType', 1, '%d', mesh.barType); +end +fprintf(fid, '\n'); + +fprintf(fid, '\n'); +writeArray(fid, 'Float64', 'position', 3, '%.9g', state.displacement); +fprintf(fid, '\n'); + +fprintf(fid, '\n'); +writeArray(fid, 'Int32', 'connectivity', 1, '%d', mesh.bars - 1); % VTK counts from 0 +writeArray(fid, 'Int32', 'offsets', 1, '%d', 2 * (1:nBars).'); +writeArray(fid, 'UInt8', 'types', 1, '%d', 3 * ones(nBars, 1)); % 3 = VTK_LINE +fprintf(fid, '\n'); + +fprintf(fid, '\n'); +fprintf(fid, '\n'); +fprintf(fid, '\n'); +end + +function writeArray(fid, type, name, nComponents, format, data) +%WRITEARRAY Write one ASCII ; rows of data are the tuples. +fprintf(fid, '\n', ... + type, name, nComponents); +rowFormat = [strjoin(repmat({format}, 1, nComponents), ' ') '\n']; +fprintf(fid, rowFormat, data.'); +fprintf(fid, '\n'); +end diff --git a/src/+ldem/+io/parseCaseJson.m b/src/+ldem/+io/parseCaseJson.m new file mode 100644 index 0000000..444313e --- /dev/null +++ b/src/+ldem/+io/parseCaseJson.m @@ -0,0 +1,87 @@ +function entries = parseCaseJson(text, source) +%PARSECASEJSON Parse a case file written in JSON into a list of entries. +% +% entries = ldem.io.parseCaseJson(text, source) gives the same list as +% ldem.io.parseCaseText for the same case, so ldem.io.readCase treats both +% formats alike. The JSON has one object per section and the values that +% carry a unit are strings: +% +% {"format": 1, "mesh": {"module_size": "1 mm", "modules": [5, 5, 50]}} +% +% A repeated table such as [[monitor.node]] is an array of objects. JSON has +% no comments; use the .ldem format for files written by hand. +% +% Inputs: +% text Content of the file. +% source Name used in the error messages. +% +% Output: +% entries Struct array, see ldem.io.parseCaseText (line is 0). +% +% Errors: +% ldem:case:syntax The text is not valid JSON or has an unsupported shape. +% +% See also ldem.io.readCase, ldem.io.parseCaseText. + +arguments + text (1,1) string + source (1,1) string = "case" +end + +try + data = jsondecode(text); +catch err + ldem.schema.raise('ldem:case:syntax', source, 'Invalid JSON: %s', err.message); +end +if ~isstruct(data) || ~isscalar(data) + ldem.schema.raise('ldem:case:syntax', source, 'The JSON must be an object at the top level.'); +end + +entries = struct('section', {}, 'index', {}, 'key', {}, 'value', {}, 'line', {}); +entries = addObject(entries, data, "", 0, source); +end + +function entries = addObject(entries, object, section, index, source) +names = string(fieldnames(object)).'; +for name = names + value = object.(name); + childSection = joinSection(section, name); + if isstruct(value) && isscalar(value) + entries = addObject(entries, value, childSection, 0, source); + elseif isstruct(value) || (iscell(value) && ~isempty(value) && all(cellfun(@isstruct, value))) + if iscell(value) + items = value; + else + items = num2cell(value); + end + for k = 1:numel(items) + entries = addObject(entries, items{k}, childSection, k, source); + end + else + entries(end+1) = struct('section', section, 'index', index, 'key', name, ... + 'value', {leafValue(value, section, name, source)}, 'line', 0); %#ok + end +end +end + +function value = leafValue(raw, section, name, source) +if ischar(raw) + value = string(raw); +elseif iscell(raw) && all(cellfun(@ischar, raw)) + value = reshape(string(raw), 1, []); +elseif isnumeric(raw) || islogical(raw) + value = reshape(raw, 1, []); + if isscalar(value) + value = value(1); + end +else + ldem.schema.raise('ldem:case:syntax', source, ... + 'The value of "%s" in section "%s" has an unsupported type.', name, section); +end +end + +function name = joinSection(section, name) +if section ~= "" + name = section + "." + name; +end +end diff --git a/src/+ldem/+io/parseCaseText.m b/src/+ldem/+io/parseCaseText.m new file mode 100644 index 0000000..a18313d --- /dev/null +++ b/src/+ldem/+io/parseCaseText.m @@ -0,0 +1,226 @@ +function entries = parseCaseText(text, source) +%PARSECASETEXT Parse the text of a case file (.ldem) into a list of entries. +% +% entries = ldem.io.parseCaseText(text, source) reads the TOML-like syntax +% of the case files. It only checks the syntax: it does not know which keys +% exist (see ldem.io.readCase for that). +% +% Syntax: +% +% # a comment, from # to the end of the line (not inside quotes) +% title = "Text in double quotes" +% [section] a table; names may be dotted: [a.b] +% key = 3.87 GPa a number with an optional unit +% key = [5, 5, 50] a list of numbers or of quoted strings +% key = true true or false +% [[monitor.node]] starts the next element of a repeated table +% +% A value that is neither quoted, a list nor true/false is a number when it +% is a plain number and otherwise kept as text ("3.87 GPa", "1000 steps", +% "auto"); ldem.io.readCase interprets it according to the key. Lists must +% fit in one line. There are no escape sequences in quoted strings. +% +% Inputs: +% text Content of the file. +% source Name used in the error messages, usually the file name. +% +% Output: +% entries Struct array with the fields +% section Table name ("" before the first table). +% index 0 for [section]; k for the k-th [[section]]. +% key Key name. +% value double, double row, logical, string or string row. +% line Line number in the text. +% +% Errors: +% ldem:case:syntax The text does not follow the syntax above. +% +% Example: +% e = ldem.io.parseCaseText("[time]" + newline + "duration = 2.8 ms"); +% e.value % "2.8 ms" +% +% See also ldem.io.readCase, ldem.io.parseCaseJson. + +arguments + text (1,1) string + source (1,1) string = "case" +end + +utf8Bom = string(char([239 187 191])); % a UTF-8 file read with an 8-bit encoding +if startsWith(text, utf8Bom) + text = extractAfter(text, 3); +elseif startsWith(text, string(char(65279))) + text = extractAfter(text, 1); +end + +lines = splitlines(text); +entries = struct('section', {}, 'index', {}, 'key', {}, 'value', {}, 'line', {}); +section = ""; +index = 0; +tablesSeen = strings(0, 1); +arrayCount = struct(); +keysSeen = strings(0, 1); +namePattern = '^[A-Za-z_]\w*(\.[A-Za-z_]\w*)*$'; + +for n = 1:numel(lines) + where = source + ":" + string(n); + line = strtrim(stripComment(char(lines(n)))); + if isempty(line) + continue + end + + if startsWith(line, "[[") + if ~endsWith(line, "]]") + ldem.schema.raise('ldem:case:syntax', where, 'The header "%s" must end with ]].', line); + end + name = strtrim(string(extractBetween(string(line), 3, strlength(line) - 2))); + checkName(name, namePattern, where); + field = regexprep(char(name), '\W', '_'); + if ~isfield(arrayCount, field) + arrayCount.(field) = 0; + end + arrayCount.(field) = arrayCount.(field) + 1; + section = name; + index = arrayCount.(field); + keysSeen = strings(0, 1); + elseif startsWith(line, "[") + if ~endsWith(line, "]") + ldem.schema.raise('ldem:case:syntax', where, 'The header "%s" must end with ].', line); + end + name = strtrim(string(extractBetween(string(line), 2, strlength(line) - 1))); + checkName(name, namePattern, where); + if any(tablesSeen == name) + ldem.schema.raise('ldem:case:syntax', where, 'The section [%s] appears twice.', name); + end + tablesSeen(end+1, 1) = name; %#ok + section = name; + index = 0; + keysSeen = strings(0, 1); + else + eq = find(line == '=', 1); + if isempty(eq) + ldem.schema.raise('ldem:case:syntax', where, ... + 'Expected "key = value" or a [section] header, found "%s".', line); + end + key = strtrim(string(line(1:eq-1))); + if isempty(regexp(key, '^[A-Za-z_]\w*$', 'once')) + ldem.schema.raise('ldem:case:syntax', where, ... + '"%s" is not a valid key name (letters, digits and _, not starting with a digit).', key); + end + if any(keysSeen == key) + ldem.schema.raise('ldem:case:syntax', where, ... + 'The key "%s" appears twice in the same section.', key); + end + keysSeen(end+1, 1) = key; %#ok + value = parseValue(strtrim(string(line(eq+1:end))), where); + entries(end+1) = struct('section', section, 'index', index, 'key', key, ... + 'value', {value}, 'line', n); %#ok + end +end +end + +function checkName(name, pattern, where) +if isempty(regexp(name, pattern, 'once')) + ldem.schema.raise('ldem:case:syntax', where, ... + '"%s" is not a valid section name (words separated by dots).', name); +end +end + +function text = stripComment(text) +%STRIPCOMMENT Remove a # comment that is not inside double quotes. +inQuote = false; +for k = 1:numel(text) + if text(k) == '"' + inQuote = ~inQuote; + elseif text(k) == '#' && ~inQuote + text = text(1:k-1); + return + end +end +end + +function value = parseValue(text, where) +%PARSEVALUE Interpret the right-hand side of "key = value". +if strlength(text) == 0 + ldem.schema.raise('ldem:case:syntax', where, 'The key has no value.'); +end +chars = char(text); +if chars(1) == '"' + closing = find(chars == '"'); + if numel(closing) < 2 + ldem.schema.raise('ldem:case:syntax', where, 'The quoted text %s is not closed.', text); + end + if closing(2) ~= numel(chars) + ldem.schema.raise('ldem:case:syntax', where, ... + 'Unexpected text after the closing quote: %s.', text); + end + value = string(chars(2:closing(2)-1)); +elseif chars(1) == '[' + if chars(end) ~= ']' + ldem.schema.raise('ldem:case:syntax', where, ... + 'The list %s must close with ] on the same line.', text); + end + value = parseList(chars(2:end-1), where); +elseif text == "true" + value = true; +elseif text == "false" + value = false; +elseif ~isempty(regexp(text, '^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$', 'once')) + value = str2double(text); +else + value = text; +end +end + +function value = parseList(inner, where) +%PARSELIST Items of a one-line list, separated by commas outside quotes. +items = strings(0, 1); +current = ''; +inQuote = false; +for k = 1:numel(inner) + c = inner(k); + if c == '"' + inQuote = ~inQuote; + current(end+1) = c; %#ok + elseif c == ',' && ~inQuote + items(end+1, 1) = strtrim(string(current)); %#ok + current = ''; + else + current(end+1) = c; %#ok + end +end +if inQuote + ldem.schema.raise('ldem:case:syntax', where, 'A quoted text in the list is not closed.'); +end +last = strtrim(string(current)); +if last ~= "" || ~isempty(items) + items(end+1, 1) = last; +end +if ~isempty(items) && items(end) == "" && numel(items) > 1 + items(end) = []; % trailing comma +end + +if isempty(items) || (isscalar(items) && items == "") + value = zeros(1, 0); + return +end + +isText = startsWith(items, '"'); +if any(isText) && ~all(isText) + ldem.schema.raise('ldem:case:syntax', where, 'A list cannot mix numbers and quoted texts.'); +end +if all(isText) + if any(~endsWith(items, '"') | strlength(items) < 2) + ldem.schema.raise('ldem:case:syntax', where, 'A quoted text in the list is not closed.'); + end + value = reshape(extractBetween(items, 2, strlength(items) - 1), 1, []); +else + numbers = str2double(items); + bad = find(isnan(numbers), 1); + if ~isempty(bad) + ldem.schema.raise('ldem:case:syntax', where, ... + '"%s" in the list is not a number.', items(bad)); + end + value = reshape(numbers, 1, []); +end +end diff --git a/src/+ldem/+io/readCase.m b/src/+ldem/+io/readCase.m new file mode 100644 index 0000000..d442cbf --- /dev/null +++ b/src/+ldem/+io/readCase.m @@ -0,0 +1,1067 @@ +function c = readCase(path, options) +%READCASE Read a case file (.ldem or .json) and build the simulation inputs. +% +% c = ldem.io.readCase(path) reads a case file, checks every key against +% ldem.schema.caseSchema, converts the units to SI and returns the objects +% that ldem.runSimulation needs. The format is described in +% docs/source/usage.rst and in the template written by +% ldem.io.writeTemplate. A short example: +% +% format = 1 +% [mesh] +% module_size = 3 mm +% modules = [5, 2, 2] # cubic modules along x, y and z +% [time] +% step = auto +% duration = 40 us +% [scenario] +% type = "uniaxial_tension" +% +% Keys that are missing take the default of ldem.Parameters; the keys +% scenario.type, mesh.modules and time.duration are required. Every error +% names the file, the line, the section and the key. +% +% Relative paths (the random-field file and the output folder) are relative +% to the folder of the case file. +% +% A case file may inherit from others with extends = "base.ldem" (or a list): +% its keys replace the inherited ones, a repeated table ([[support]], [[load]], +% [[monitor.node]], [[sweep]]) replaces the whole inherited list, and when the +% scenario, scatter or damping type changes the keys of the old type are dropped. +% Relative paths are relative to the file that contains them. +% +% Input: +% path Path of a .ldem file or of a .json file with the same structure. +% +% Name-value options: +% Overrides Struct array with the fields path ("section.key") and value that +% replace keys of the file; ldem.sweep uses it to vary a key. +% +% Output: +% c Struct with the fields +% params Validated ldem.Parameters. +% scenario Scenario object with the values of the [scenario] section. +% options Struct with OutputFolder and Formats, for runSimulation. +% info Struct: source, format, title, authors, controlNodeNames, nodeNotes, parents, sweep, sweepMode. +% +% Errors: +% ldem:io:fileNotFound The file does not exist. +% ldem:io:unknownExtension The extension is not .ldem or .json. +% ldem:case:syntax The text is not valid. +% ldem:case:unknownKey A key or section does not exist. +% ldem:case:missingKey A required key is missing. +% ldem:case:badValue A value has the wrong type or unit. +% ldem:case:invalidValue ldem.Parameters rejects a value. +% ldem:case:inconsistentKey A key does not fit the chosen type. +% ldem:params:* The cross-checks of ldem.Parameters/validate. +% +% Example: +% c = ldem.io.readCase("examples/example1_clamped_beam/case.ldem"); +% results = ldem.runSimulation(c.params, Scenario=c.scenario); +% +% See also ldem.run, ldem.check, ldem.io.writeCase, +% ldem.io.convertLegacyInput, ldem.Parameters.fromFile. + +arguments + path (1,1) string + options.Overrides = [] +end + +if ~isfile(path) + error('ldem:io:fileNotFound', 'Case file "%s" does not exist.', path); +end +absPath = absolutePath(path); +[folder, name, ext] = fileparts(absPath); +ctx = struct('source', string(name) + string(ext), 'folder', string(folder)); + +[entries, parents] = loadEntries(absPath, strings(0, 1)); +entries = applyOverrides(entries, options.Overrides, ctx); + +schema = ldem.schema.caseSchema(); +reg = ldem.scenarios.registry(); +defaults = ldem.Parameters(); + +checkKnownKeys(entries, schema, ctx); +checkRequired(entries, schema, ctx); +checkFormat(entries, ctx); + +values = struct(); +origin = struct(); +[values, origin] = readSimpleKeys(values, origin, entries, schema, ctx); +[values, origin] = readModules(values, origin, entries, ctx); +[values, origin] = readEnumKeys(values, origin, entries, schema, ctx); +checkDampingKeys(entries, values, ctx); +checkScatter(entries, schema, ctx); + +% Time step: explicit, or "auto" (also when the key is absent). +[values, origin] = readTimeStep(values, origin, entries, defaults, ctx); + +% Cadence of the outputs, in steps. +output = defaults.output; +for row = schema(string({schema.kind}) == "cadence").' + e = findEntry(entries, sectionOf(row.path), keyOf(row.path)); + if ~isempty(e) + output.(row.prop) = cadenceToSteps(e.value, values.dt, location(e, ctx)); + end +end +eTracked = findEntry(entries, "monitor.bar", "tracked"); +output.trackedBarEvery = double(~isempty(eTracked)); + +% Scenario. +[scenario, testId] = readScenario(entries, reg, ctx); + +% Control nodes. +nodeItems = readNodeItems(entries, ctx); + +% Build the parameters, attributing every error to its line. +p = ldem.Parameters(); +for field = string(fieldnames(values)).' + try + p.(field) = values.(field); + catch err + ldem.schema.raise('ldem:case:invalidValue', origin.(field), '%s', firstLine(err.message)); + end +end +p.testId = testId; + +nodeNotes = strings(0, 1); +if ~isempty(nodeItems) + [ids, nodeNotes] = resolveNodes(nodeItems, p, ctx); + try + p.controlNodes = ids; + catch err + ldem.schema.raise('ldem:case:invalidValue', ctx.source + " [monitor.node]", ... + '%s', firstLine(err.message)); + end + names = [nodeItems.name]; + emptyName = names == ""; + names(emptyName) = "node_" + string(ids(emptyName)); +else + names = "node_" + string(p.controlNodes); +end +p.output = output; + +try + p.validate(); +catch err + error(err.identifier, '%s', char(ctx.source + ": " + string(err.message))); +end + +[sweepBlocks, sweepMode] = readSweep(entries, schema, ctx); + +c = struct(); +c.params = p; +c.scenario = scenario; +c.options = readOutputOptions(entries, output, ctx); +c.info = struct('source', string(absPath), 'format', 1, ... + 'title', stringValue(entries, "", "title", ""), ... + 'authors', stringValue(entries, "", "authors", strings(1, 0)), ... + 'controlNodeNames', names, 'nodeNotes', nodeNotes, ... + 'parents', parents, 'sweep', sweepBlocks, 'sweepMode', sweepMode); +end + +% ------------------------------------------------------------------------ + +function [entries, parents] = loadEntries(absPath, chain) +%LOADENTRIES Entries of a case file with the ones it inherits through "extends". +% Every entry also carries the file it was written in (file) and its folder +% (folder), for the error messages and for relative paths. +[folder, name, ext] = fileparts(absPath); +source = string(name) + string(ext); +text = string(fileread(absPath)); +switch lower(string(ext)) + case ".ldem" + entries = ldem.io.parseCaseText(text, source); + case ".json" + entries = ldem.io.parseCaseJson(text, source); + otherwise + error('ldem:io:unknownExtension', ... + 'Case files must be .ldem or .json, got "%s".', ext); +end +if isempty(entries) + entries = struct('section', {}, 'index', {}, 'key', {}, 'value', {}, 'line', {}, ... + 'file', {}, 'folder', {}); +else + for k = 1:numel(entries) + entries(k).file = source; + entries(k).folder = string(folder); + end +end + +parents = strings(0, 1); +eExtends = findEntry(entries, "", "extends"); +if isempty(eExtends) + return +end +entries(string({entries.section}) == "" & string({entries.key}) == "extends") = []; + +where = source + ":" + string(eExtends.line) + " extends"; +if ~(isstring(eExtends.value) && ~isempty(eExtends.value)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected the path of a case file or a list of them, in quotes.'); +end +chain = [chain; string(absPath)]; +merged = entries([]); +for relative = reshape(eExtends.value, 1, []) + parentPath = relative; + if isempty(regexp(parentPath, '^([A-Za-z]:|[\\/])', 'once')) + parentPath = joinPath(folder, parentPath); + end + if ~isfile(parentPath) + ldem.schema.raise('ldem:io:fileNotFound', where, ... + 'The case file "%s" that this one extends does not exist.', relative); + end + parentPath = absolutePath(parentPath); + if any(lower(chain) == lower(parentPath)) + ldem.schema.raise('ldem:case:extendsLoop', where, ... + 'Case files extend each other in a loop: %s.', strjoin([chain; parentPath], ' -> ')); + end + [parentEntries, grandParents] = loadEntries(parentPath, chain); + merged = mergeEntries(merged, parentEntries); + parents = [parents; grandParents; parentPath]; %#ok +end +entries = mergeEntries(merged, entries); +parents = unique(parents, 'stable'); +end + +function merged = mergeEntries(base, over) +%MERGEENTRIES Entries of "over" replace those of "base" that set the same thing. +% A key replaces the same key; a repeated table ([[support]], [[load]], +% [[monitor.node]], [[sweep]]) replaces the whole list of that table; and when +% the type of the scenario, of the scatter or of the damping model changes, the +% keys of the old type that are not set again are dropped. +if isempty(base) + merged = over; + return +end +baseSections = string({base.section}); +baseKeys = string({base.key}); +baseIndices = [base.index]; +overSections = string({over.section}); +overKeys = string({over.key}); +overIndices = [over.index]; + +drop = false(size(base)); +for k = 1:numel(base) + if baseIndices(k) == 0 + drop(k) = any(overSections == baseSections(k) & overKeys == baseKeys(k) & overIndices == 0); + else + drop(k) = any(overSections == baseSections(k) & overIndices > 0); + end +end +for section = ["scenario" "material.scatter" "damping"] + newType = typeOf(over, section); + oldType = typeOf(base, section); + if newType ~= "" && oldType ~= "" && newType ~= oldType + drop = drop | (baseSections == section & baseKeys ~= "type"); + end +end +merged = [base(~drop), over]; +end + +function word = typeOf(entries, section) +e = findEntry(entries, section, "type"); +if isempty(e) || ~isstring(e.value) || ~isscalar(e.value) + word = ""; +else + word = lower(strtrim(e.value)); +end +end + +function entries = applyOverrides(entries, overrides, ctx) +%APPLYOVERRIDES Set keys from outside the file (a sweep): struct array with path and value. +if isempty(overrides) + return +end +schema = ldem.schema.caseSchema(); +paths = string({schema.path}); +for k = 1:numel(overrides) + target = string(overrides(k).path); + section = sectionOf(target); + key = keyOf(target); + if ~any(paths == target) && section ~= "scenario" + ldem.schema.raise('ldem:sweep:unknownKey', "sweep", ... + 'The key "%s" does not exist.%s', target, ldem.schema.suggest(target, paths)); + end + if any(section == arrayTables()) + ldem.schema.raise('ldem:sweep:unsupportedKey', "sweep", ... + 'The key "%s" belongs to a repeated table and cannot be swept.', target); + end + if ~isempty(entries) + entries(string({entries.section}) == section & string({entries.key}) == key ... + & [entries.index] == 0) = []; + end + entry = struct('section', section, 'index', 0, 'key', key, 'value', {overrides(k).value}, ... + 'line', 0, 'file', "sweep", 'folder', ctx.folder); + if isempty(entries) + entries = entry; + else + entries = [entries, entry]; %#ok + end +end +end + +function tables = arrayTables() +tables = ["monitor.node" "support" "load" "sweep"]; +end + +function [blocks, mode] = readSweep(entries, schema, ctx) +%READSWEEP The [[sweep]] blocks and sweep_mode: what ldem.sweep varies. +blocks = struct('key', {}, 'values', {}); +paths = string({schema.path}); +kinds = string({schema.kind}); +scalarKinds = ["integer" "number" "quantity" "string" "path" "enum" "stepOrAuto" "cadence"]; +sections = string({entries.section}); +indices = [entries.index]; +for k = unique(indices(sections == "sweep")) + block = entries(sections == "sweep" & indices == k); + if k == 0 + ldem.schema.raise('ldem:case:syntax', location(block(1), ctx), ... + 'Write [[sweep]] (double brackets): there can be several.'); + end + eKey = pickKey(block, "key"); + eValues = pickKey(block, "values"); + if isempty(eKey) || isempty(eValues) + ldem.schema.raise('ldem:case:missingKey', location(block(1), ctx), ... + 'A [[sweep]] needs "key" (what to vary) and "values" (a list).'); + end + if ~(isstring(eKey.value) && isscalar(eKey.value)) + ldem.schema.raise('ldem:case:badValue', location(eKey, ctx), ... + 'Expected the name of a key in quotes, such as "material.fracture_energy".'); + end + target = eKey.value; + j = find(paths == target, 1); + isScenarioKey = sectionOf(target) == "scenario" && keyOf(target) ~= "type"; + if isempty(j) && ~isScenarioKey + ldem.schema.raise('ldem:case:badValue', location(eKey, ctx), ... + '"%s" is not a key of the case file.%s', target, ldem.schema.suggest(target, paths)); + end + if ~isScenarioKey && (~any(kinds(j) == scalarKinds) || any(sectionOf(target) == arrayTables())) + ldem.schema.raise('ldem:case:badValue', location(eKey, ctx), ... + '"%s" cannot be swept: only keys with a single value and outside repeated tables.', target); + end + v = eValues.value; + if isempty(v) || ~((isnumeric(v) || isstring(v)) && isvector(v)) + ldem.schema.raise('ldem:case:badValue', location(eValues, ctx), ... + 'Expected a non-empty list of numbers or of quoted texts such as ["0.1 N/m", "0.5 N/m"].'); + end + items = num2cell(reshape(v, 1, [])); + blocks(end+1) = struct('key', target, 'values', {items}); %#ok +end +mode = "product"; +eMode = findEntry(entries, "", "sweep_mode"); +if ~isempty(eMode) + mode = enumWord(eMode, ["product" "zip"], ctx); +end +end + +% ------------------------------------------------------------------------ + +function checkKnownKeys(entries, schema, ctx) +paths = string({schema.path}); +pathSections = sectionsOf(paths); +known = unique(pathSections); +for e = entries + if e.section == "scenario" && e.key ~= "type" + continue % keys of the scenario class, checked in readScenario + end + if any(paths == fullPath(e)) + continue + end + if ~any(known == e.section) + ldem.schema.raise('ldem:case:unknownKey', location(e, ctx), ... + 'The section [%s] does not exist.%s Sections: %s.', e.section, ... + ldem.schema.suggest(e.section, known(known ~= "")), strjoin([known(known ~= ""), "scenario"], ', ')); + end + siblings = keysOf(paths(pathSections == e.section)); + ldem.schema.raise('ldem:case:unknownKey', location(e, ctx), ... + 'The key "%s" does not exist in [%s].%s Valid keys: %s.', e.key, e.section, ... + ldem.schema.suggest(e.key, siblings), strjoin(siblings, ', ')); +end +end + +function checkRequired(entries, schema, ctx) +for row = schema([schema.required]).' + if isempty(findEntry(entries, sectionOf(row.path), keyOf(row.path), true)) + ldem.schema.raise('ldem:case:missingKey', ctx.source, ... + 'Missing the required key "%s" in [%s].', keyOf(row.path), sectionOf(row.path)); + end +end +end + +function checkFormat(entries, ctx) +e = findEntry(entries, "", "format"); +if ~isempty(e) && ~(isnumeric(e.value) && isscalar(e.value) && e.value == 1) + ldem.schema.raise('ldem:case:unsupportedFormat', location(e, ctx), ... + 'This version of ldem reads format = 1.'); +end +end + +function [values, origin] = readSimpleKeys(values, origin, entries, schema, ctx) +simple = ["integer" "number" "quantity" "path" "numberlist"]; +for row = schema.' + if row.prop == "" || ~any(row.kind == simple) + continue + end + e = findEntry(entries, sectionOf(row.path), keyOf(row.path)); + if isempty(e) + continue + end + where = location(e, ctx); + entryCtx = ctx; + entryCtx.folder = e.folder; + values.(row.prop) = convertValue(e.value, row, where, entryCtx); + origin.(row.prop) = where; +end +end + +function value = convertValue(v, row, where, ctx) +switch row.kind + case "integer" + if ~(isnumeric(v) && isscalar(v) && isfinite(v) && v == fix(v)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected an integer, found %s.', describe(v)); + end + value = v; + case "number" + if ~(isnumeric(v) && isscalar(v) && isfinite(v)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a number, found %s.', describe(v)); + end + value = v; + case "quantity" + value = ldem.schema.parseQuantity(v, row.dimension, where); + case "numberlist" + if ~(isnumeric(v) && ~isempty(v) && all(isfinite(v))) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a number or a list of numbers, found %s.', describe(v)); + end + value = reshape(v, 1, []); + case "path" + if ~(isstring(v) && isscalar(v)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a path in quotes, found %s.', describe(v)); + end + if isempty(regexp(v, '^([A-Za-z]:|[\\/])', 'once')) && strlength(v) > 0 + value = joinPath(ctx.folder, v); % ctx.folder is the folder of the entry's file + else + value = v; + end +end +end + +function [values, origin] = readModules(values, origin, entries, ctx) +e = findEntry(entries, "mesh", "modules"); +where = location(e, ctx); +v = e.value; +if ~(isnumeric(v) && numel(v) == 3 && all(v >= 1) && all(v == fix(v))) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected three integers >= 1 (modules along x, y and z), found %s.', describe(v)); +end +values.nModules = reshape(v, 1, 3) + 1; % the legacy M N L count nodes +origin.nModules = where; +end + +function [values, origin] = readEnumKeys(values, origin, entries, schema, ctx) +%READENUMKEYS Enum keys that set a Parameters property (the law, the damping model). +for row = schema(string({schema.kind}) == "enum" & string({schema.prop}) ~= "").' + word = readEnum(entries, schema, row.path, ctx); + if word ~= "" + values.(row.prop) = word; + origin.(row.prop) = location(findEntry(entries, sectionOf(row.path), keyOf(row.path)), ctx); + end +end +end + +function checkDampingKeys(entries, values, ctx) +%CHECKDAMPINGKEYS Keys of [damping] that the chosen model does not use are an error. +reg = ldem.solver.dampingRegistry(); +model = "mass_proportional"; +if isfield(values, 'dampingModel') + model = values.dampingModel; +end +spec = reg([reg.name] == model); +for key = ["initial" "final" "switch_time"] + e = findEntry(entries, "damping", key); + if ~isempty(e) && ~any(spec.keys == key) + ldem.schema.raise('ldem:case:inconsistentKey', location(e, ctx), ... + 'The key "%s" does not apply when type = "%s".', key, model); + end +end +end + +function word = readEnum(entries, schema, path, ctx) +%READENUM Value of an "enum" key, or "" if absent. Throws if not allowed. +e = findEntry(entries, sectionOf(path), keyOf(path)); +if isempty(e) + word = ""; + return +end +row = schema(string({schema.path}) == path); +choices = split(string(row.choices), "|").'; +word = enumWord(e, choices, ctx); +end + +function word = enumWord(e, choices, ctx) +where = location(e, ctx); +if ~(isstring(e.value) && isscalar(e.value)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected one of %s in quotes, found %s.', strjoin(choices, ', '), describe(e.value)); +end +word = lower(strtrim(e.value)); +if ~any(choices == word) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Unknown value "%s".%s Allowed: %s.', e.value, ldem.schema.suggest(word, choices), ... + strjoin(choices, ', ')); +end +end + +function checkScatter(entries, schema, ctx) +keys = ["file" "cv" "correlation_length" "seed"]; +present = false(size(keys)); +for k = 1:numel(keys) + present(k) = ~isempty(findEntry(entries, "material.scatter", keys(k))); +end +kind = readEnum(entries, schema, "material.scatter.type", ctx); +if kind == "" + if any(present) + ldem.schema.raise('ldem:case:missingKey', ctx.source, ... + 'Missing "type" in [material.scatter] (none, file or generated).'); + end + return +end +switch kind + case "none" + allowed = strings(1, 0); + case "file" + allowed = "file"; + case "generated" + allowed = ["cv" "correlation_length" "seed"]; +end +for k = find(present) + if ~any(allowed == keys(k)) + e = findEntry(entries, "material.scatter", keys(k)); + ldem.schema.raise('ldem:case:inconsistentKey', location(e, ctx), ... + 'The key "%s" does not apply when type = "%s".', keys(k), kind); + end +end +if kind == "file" && ~present(1) + ldem.schema.raise('ldem:case:missingKey', ctx.source, ... + 'type = "file" needs the key "file" in [material.scatter].'); +end +if kind == "generated" && ~present(2) + ldem.schema.raise('ldem:case:missingKey', ctx.source, ... + 'type = "generated" needs the key "cv" in [material.scatter].'); +end +end + +function [values, origin] = readTimeStep(values, origin, entries, defaults, ctx) +e = findEntry(entries, "time", "step"); +isAuto = isempty(e) || (isstring(e.value) && isscalar(e.value) && lower(strtrim(e.value)) == "auto"); +if isAuto + L = valueOr(values, 'moduleLength', defaults.moduleLength); + E = valueOr(values, 'youngModulus', defaults.youngModulus); + rho = valueOr(values, 'density', defaults.density); + values.dt = 0.9 * (sqrt(3) / 2 * L) / sqrt(E / rho); + origin.dt = ctx.source + " [time] step"; +else + where = location(e, ctx); + values.dt = ldem.schema.parseQuantity(e.value, "time", where); + origin.dt = where; +end +end + +function steps = cadenceToSteps(v, dt, where) +%CADENCETOSTEPS Number of steps for "every = 1000 steps" or "every = 0.1 ms". +if isnumeric(v) && isscalar(v) + steps = checkSteps(v, where); + return +end +if ~(isstring(v) && isscalar(v)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a number of steps or a time, found %s.', describe(v)); +end +tokens = regexp(strtrim(v), '^(\S+)\s*(\S*)$', 'tokens', 'once'); +if isempty(tokens) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected "1000 steps" or a time such as "0.1 ms", found "%s".', v); +end +unit = lower(string(tokens{2})); +if any(unit == ["" "step" "steps"]) + steps = checkSteps(str2double(tokens{1}), where); + return +end +t = ldem.schema.parseQuantity(v, "time", where); +steps = round(t / dt); +if t > 0 && steps < 1 + ldem.schema.raise('ldem:case:badValue', where, ... + '%s is shorter than the time step (%g s).', v, dt); +end +if abs(t / dt - steps) > 1e-6 * max(1, steps) + warning('ldem:case:cadenceNotMultiple', ... + '%s: %s is not a multiple of the time step (%g s); using %d steps.', where, v, dt, steps); +end +end + +function steps = checkSteps(x, where) +if ~(isfinite(x) && x >= 0 && x == fix(x)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a non-negative whole number of steps, found %g.', x); +end +steps = x; +end + +function [scenario, testId] = readScenario(entries, reg, ctx) +eType = findEntry(entries, "scenario", "type"); +choices = [reg.name]; +name = enumWord(eType, choices, ctx); +k = find(choices == name, 1); +spec = reg(k); + +propNames = string(fieldnames(spec.units)).'; +snake = lower(regexprep(propNames, '([a-z0-9])([A-Z])', '$1_$2')); +args = struct(); +for e = entries + if e.section ~= "scenario" || e.key == "type" + continue + end + j = find(snake == e.key, 1); + where = location(e, ctx); + if isempty(j) + ldem.schema.raise('ldem:case:unknownKey', where, ... + 'The scenario "%s" has no key "%s".%s Valid keys: %s.', name, e.key, ... + ldem.schema.suggest(e.key, snake), strjoin(["type" snake], ', ')); + end + prop = propNames(j); + if isfield(spec.keywords, prop) && isstring(e.value) && isscalar(e.value) ... + && lower(strtrim(e.value)) == spec.keywords.(prop) + args.(prop) = NaN; + else + args.(prop) = ldem.schema.parseQuantity(e.value, spec.units.(prop), where); + end +end +try + argList = namedargs2cell(args); + scenario = feval(spec.className, argList{:}); +catch err + ldem.schema.raise('ldem:case:invalidValue', location(eType, ctx) + " (scenario)", ... + '%s', firstLine(err.message)); +end +if name == "custom" + scenario = readBlocks(entries, ctx); +else + for e = entries + if any(e.section == ["support" "load"]) + ldem.schema.raise('ldem:case:inconsistentKey', location(e, ctx), ... + '[[%s]] blocks only apply when [scenario] type = "custom".', e.section); + end + end +end +testId = spec.testId; +end + +function scenario = readBlocks(entries, ctx) +%READBLOCKS Build the declarative scenario from the [[support]] and [[load]] blocks. +supports = ldem.scenarios.Declarative.emptySupports(); +loads = ldem.scenarios.Declarative.emptyLoads(); +sections = string({entries.section}); +indices = [entries.index]; +for kind = ["support" "load"] + for k = unique(indices(sections == kind)) + block = entries(sections == kind & indices == k); + if k == 0 + ldem.schema.raise('ldem:case:syntax', location(block(1), ctx), ... + 'Write [[%s]] (double brackets): there can be several.', kind); + end + if kind == "support" + supports(end+1) = readSupport(block, ctx); %#ok + else + loads(end+1) = readLoad(block, ctx); %#ok + end + end +end +try + scenario = ldem.scenarios.Declarative(supports = supports, loads = loads); +catch err + ldem.schema.raise('ldem:case:invalidValue', ctx.source + " [scenario]", '%s', firstLine(err.message)); +end +end + +function block = readSupport(entries, ctx) +selector = readSelector(entries, ctx); +eFix = pickKey(entries, "fix"); +if isempty(eFix) + ldem.schema.raise('ldem:case:missingKey', location(entries(1), ctx), ... + 'A [[support]] needs "fix": the directions to hold, for example ["x", "y"].'); +end +try + block = ldem.scenarios.Declarative.makeSupport(selector, reshape(string(eFix.value), 1, []), ... + name = textOf(entries, "name", ctx), reaction = boolOf(entries, "reaction", ctx)); +catch err + ldem.schema.raise('ldem:case:badValue', location(eFix, ctx), '%s', firstLine(err.message)); +end +end + +function block = readLoad(entries, ctx) +selector = readSelector(entries, ctx); +for key = ["direction" "type" "time_function"] + if isempty(pickKey(entries, key)) + ldem.schema.raise('ldem:case:missingKey', location(entries(1), ctx), ... + 'A [[load]] needs "%s".', key); + end +end +direction = enumWord(pickKey(entries, "direction"), ["x" "y" "z"], ctx); +type = enumWord(pickKey(entries, "type"), ["force" "displacement"], ctx); +kind = enumWord(pickKey(entries, "time_function"), ["constant" "linear" "ramp" "table"], ctx); + +if type == "force" + valueDimension = "force"; + rateDimension = "forcerate"; +else + valueDimension = "length"; + rateDimension = "velocity"; +end +needs = struct('constant', "value", 'linear', "rate", 'ramp', ["rate" "until"], ... + 'table', ["times" "values"]); +needed = needs.(kind); +for key = ["value" "rate" "until" "times" "values"] + e = pickKey(entries, key); + if ~isempty(e) && ~any(needed == key) + ldem.schema.raise('ldem:case:inconsistentKey', location(e, ctx), ... + 'The key "%s" does not apply when time_function = "%s".', key, kind); + end + if isempty(e) && any(needed == key) + ldem.schema.raise('ldem:case:missingKey', location(entries(1), ctx), ... + 'time_function = "%s" needs the key "%s".', kind, key); + end +end +args = struct(); +for key = needed + e = pickKey(entries, key); + where = location(e, ctx); + switch key + case "value" + args.value = ldem.schema.parseQuantity(e.value, valueDimension, where); + case "rate" + args.rate = ldem.schema.parseQuantity(e.value, rateDimension, where); + case "until" + args.until = ldem.schema.parseQuantity(e.value, "time", where); + otherwise + if ~(isnumeric(e.value) && ~isempty(e.value)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a list of numbers (SI units), found %s.', describe(e.value)); + end + args.(key) = reshape(e.value, 1, []); + end +end +try + argList = namedargs2cell(args); + fn = ldem.scenarios.Declarative.makeFunction(kind, argList{:}); +catch err + ldem.schema.raise('ldem:case:badValue', location(pickKey(entries, "time_function"), ctx), ... + '%s', firstLine(err.message)); +end +block = ldem.scenarios.Declarative.makeLoad(selector, direction, type, fn, ... + name = textOf(entries, "name", ctx), reaction = boolOf(entries, "reaction", ctx)); +end + +function selector = readSelector(entries, ctx) +args = struct(); +e = pickKey(entries, "nodes"); +if ~isempty(e) + args.nodes = enumWord(e, ["all" "centre" "grid"], ctx); +end +e = pickKey(entries, "ids"); +if ~isempty(e) + if ~(isnumeric(e.value) && ~isempty(e.value) && all(e.value >= 1) && all(e.value == fix(e.value))) + ldem.schema.raise('ldem:case:badValue', location(e, ctx), ... + 'Expected node numbers (integers >= 1), found %s.', describe(e.value)); + end + args.ids = reshape(e.value, 1, []); +end +for axis = ["x" "y" "z"] + e = pickKey(entries, axis); + if ~isempty(e) + ldem.scenarios.parseCoordinate(e.value, location(e, ctx)); % checks the form + args.(axis) = e.value; + end +end +argList = namedargs2cell(args); +selector = ldem.scenarios.Declarative.makeSelector(argList{:}); +end + +function e = pickKey(entries, key) +%PICKKEY The entry of a key inside one block, or []. +k = find(string({entries.key}) == key, 1); +if isempty(k) + e = []; +else + e = entries(k); +end +end + +function text = textOf(entries, key, ctx) +e = pickKey(entries, key); +if isempty(e) + text = ""; +elseif isstring(e.value) && isscalar(e.value) + text = e.value; +else + ldem.schema.raise('ldem:case:badValue', location(e, ctx), ... + 'Expected a text in quotes, found %s.', describe(e.value)); +end +end + +function flag = boolOf(entries, key, ctx) +e = pickKey(entries, key); +if isempty(e) + flag = false; +elseif islogical(e.value) && isscalar(e.value) + flag = e.value; +else + ldem.schema.raise('ldem:case:badValue', location(e, ctx), ... + 'Expected true or false, found %s.', describe(e.value)); +end +end + +function items = readNodeItems(entries, ctx) +%READNODEITEMS The [[monitor.node]] elements, as a struct array. +items = struct('id', {}, 'at', {}, 'name', {}, 'line', {}); +sections = string({entries.section}); +indices = [entries.index]; +for k = unique(indices(sections == "monitor.node")) + pick = entries(sections == "monitor.node" & indices == k); + eId = pick(string({pick.key}) == "id"); + eAt = pick(string({pick.key}) == "at"); + eName = pick(string({pick.key}) == "name"); + where = location(pick(1), ctx); + if isempty(eId) && isempty(eAt) + ldem.schema.raise('ldem:case:missingKey', where, ... + 'A [[monitor.node]] needs either "id" or "at".'); + end + if ~isempty(eId) && ~isempty(eAt) + ldem.schema.raise('ldem:case:inconsistentKey', where, ... + 'A [[monitor.node]] takes either "id" or "at", not both.'); + end + item = struct('id', NaN, 'at', zeros(1, 0), 'name', "", 'line', pick(1).line); + if ~isempty(eId) + v = eId.value; + if ~(isnumeric(v) && isscalar(v) && v == fix(v) && v >= 1) + ldem.schema.raise('ldem:case:badValue', location(eId, ctx), ... + 'Expected a node number (integer >= 1), found %s.', describe(v)); + end + item.id = v; + else + v = eAt.value; + if ~(isnumeric(v) && numel(v) == 3 && all(isfinite(v))) + ldem.schema.raise('ldem:case:badValue', location(eAt, ctx), ... + 'Expected three numbers [x, y, z] in modules, found %s.', describe(v)); + end + item.at = reshape(v, 1, 3); + end + if ~isempty(eName) + item.name = string(eName.value); + end + items(end+1) = item; %#ok +end +end + +function [ids, notes] = resolveNodes(items, p, ctx) +%RESOLVENODES Node numbers of the control nodes; "at" positions use the nearest node. +ids = zeros(1, numel(items)); +notes = strings(0, 1); +nodes = []; +for k = 1:numel(items) + if ~isnan(items(k).id) + ids(k) = items(k).id; + continue + end + if isempty(nodes) + nodes = ldem.mesh.buildNodes(p.nModules, p.moduleLength) / p.moduleLength; + end + [distance, ids(k)] = min(vecnorm(nodes - items(k).at, 2, 2)); + if distance > 1e-6 + notes(end+1, 1) = sprintf('%s:%d: the position [%g, %g, %g] modules is not a node; using node %d at [%g, %g, %g] modules.', ... + ctx.source, items(k).line, items(k).at, ids(k), nodes(ids(k), :)); %#ok + warning('ldem:case:nodeApproximated', '%s', notes(end)); + end +end +end + +function options = readOutputOptions(entries, output, ctx) +eFolder = findEntry(entries, "output", "folder"); +if isempty(eFolder) + folder = ""; +else + folder = eFolder.value; + if ~(isstring(folder) && isscalar(folder)) + ldem.schema.raise('ldem:case:badValue', location(eFolder, ctx), ... + 'Expected a folder name in quotes, found %s.', describe(folder)); + end + if strlength(folder) > 0 && isempty(regexp(folder, '^([A-Za-z]:|[\\/])', 'once')) + folder = joinPath(eFolder.folder, folder); + end +end +formats = strings(1, 0); +for format = ["mat" "ansys" "vtk"] + e = findEntry(entries, "output", format); + if isempty(e) + wanted = format == "mat"; + else + wanted = e.value; + if ~(islogical(wanted) && isscalar(wanted)) + ldem.schema.raise('ldem:case:badValue', location(e, ctx), ... + 'Expected true or false, found %s.', describe(wanted)); + end + end + if wanted + formats(end+1) = format; %#ok + end +end +if any(formats == ["ansys"; "vtk"], 'all') && output.snapshotEvery == 0 + warning('ldem:case:noSnapshots', ... + ['%s: ansys/vtk files are requested but [output.snapshots] every is 0, ' ... + 'so none will be written.'], ctx.source); +end +options = struct('OutputFolder', folder, 'Formats', formats); +end + +% ------------------------------------------------------------------------ + +function e = findEntry(entries, section, key, anyIndex) +%FINDENTRY The entry of a key of a plain table (index 0), or [] if absent. +if nargin < 4 + anyIndex = false; +end +if isempty(entries) + e = []; + return +end +match = string({entries.section}) == section & string({entries.key}) == key; +if ~anyIndex + match = match & [entries.index] == 0; +end +k = find(match, 1); +if isempty(k) + e = []; +else + e = entries(k); +end +end + +function section = sectionOf(path) +path = string(path); +dot = find(char(path) == '.', 1, 'last'); +if isempty(dot) + section = ""; +else + section = extractBefore(path, dot); +end +end + +function sections = sectionsOf(paths) +sections = strings(size(paths)); +for k = 1:numel(paths) + sections(k) = sectionOf(paths(k)); +end +end + +function keys = keysOf(paths) +keys = strings(size(paths)); +for k = 1:numel(paths) + keys(k) = keyOf(paths(k)); +end +end + +function key = keyOf(path) +path = string(path); +dot = find(char(path) == '.', 1, 'last'); +if isempty(dot) + key = path; +else + key = extractAfter(path, dot); +end +end + +function p = fullPath(e) +if e.section == "" + p = e.key; +else + p = e.section + "." + e.key; +end +end + +function w = location(e, ctx) +%LOCATION "file:line [section] key" for the error messages. +w = ctx.source; +if isfield(e, 'file') && e.file ~= "" + w = e.file; +end +if e.line > 0 + w = w + ":" + string(e.line); +end +if e.section ~= "" + w = w + " [" + e.section + "]"; +end +w = w + " " + e.key; +end + +function text = describe(v) +%DESCRIBE Short text of a value for the error messages. +if isstring(v) || ischar(v) + text = '"' + strjoin(string(v), '", "') + '"'; +elseif islogical(v) + text = strjoin(string(v), ", "); +else + text = "[" + strjoin(string(v), ", ") + "]"; +end +end + +function value = valueOr(values, field, fallback) +if isfield(values, field) + value = values.(field); +else + value = fallback; +end +end + +function value = stringValue(entries, section, key, fallback) +e = findEntry(entries, section, key); +if isempty(e) + value = fallback; +else + value = reshape(string(e.value), 1, []); + if isscalar(fallback) || ischar(fallback) + value = value(1); + end +end +end + +function line = firstLine(message) +line = strtok(string(message), newline); +end + +function p = joinPath(folder, relative) +%JOINPATH Folder plus a relative path, with the "." and ".." parts removed. +full = strrep(string(fullfile(folder, relative)), '/', filesep); +parts = split(full, filesep).'; +kept = strings(1, 0); +for part = parts + if part == "." + continue + elseif part == ".." && ~isempty(kept) && kept(end) ~= "" && ~endsWith(kept(end), ":") + kept(end) = []; + else + kept(end+1) = part; %#ok + end +end +p = strjoin(kept, filesep); +end + +function p = absolutePath(path) +if isempty(regexp(path, '^([A-Za-z]:|[\\/])', 'once')) + p = string(fullfile(pwd, path)); +else + p = path; +end +end diff --git a/src/+ldem/+io/readInputFile.m b/src/+ldem/+io/readInputFile.m new file mode 100644 index 0000000..d2cc436 --- /dev/null +++ b/src/+ldem/+io/readInputFile.m @@ -0,0 +1,123 @@ +function values = readInputFile(path) +%READINPUTFILE Read a legacy input file (DATA0.DAT format). +% +% values = ldem.io.readInputFile(path) parses the file and returns a +% struct whose field names are properties of ldem.Parameters. The struct +% can be passed to the constructor with namedargs2cell. +% +% File format. Only the FIRST WORD of each line is read; whatever follows +% (usually a quoted label) is a comment. The values appear in this order: +% +% TEST, SEED, LCO, M, N, L, +% DF1, DF2, TDAF, CON, DT, TTOT, +% INCO, NCON(1) ... NCON(INCO), +% OU2, OU3, OU4, OU5, OU6, OU7, OU8, OU9, +% PSN, ROH, YNG, GFR, DEQ +% +% Output codes OU2..OU9 of the legacy code are mapped to +% Parameters.output as follows: +% +% OU3 -> snapshotEvery OU6 -> controlNodesEvery +% OU8 -> energyEvery OU9 -> trackedBarEvery (0 or 1) +% +% OU2 (echo of the input), OU4, OU5 and OU7 only opened files in the +% legacy driver and have no meaning in the new code; they are ignored. +% +% Input: +% path Path of the input file. +% +% Output: +% values Struct with the fields testId, seed, moduleLength, nModules, +% dampingInitial, dampingFinal, dampingSwitchTime, +% constitutiveDamping, dt, totalTime, controlNodes, output, +% poissonRatio, density, youngModulus, fractureEnergy and +% criticalDistance. +% +% Errors: +% ldem:io:fileNotFound The file does not exist. +% ldem:io:malformedInput The file has missing or non-numeric values. +% +% Example: +% values = ldem.io.readInputFile("examples/beam_102/DATA0.DAT"); +% +% Legacy: READ_DAT0. +% +% See also ldem.Parameters.fromFile. + +arguments + path (1,1) string +end + +if ~isfile(path) + error('ldem:io:fileNotFound', 'Input file "%s" does not exist.', path); +end + +tokens = firstWordOfEachLine(path); +nFixedBefore = 13; % TEST .. INCO +if numel(tokens) < nFixedBefore + error('ldem:io:malformedInput', ... + '"%s" has %d values but at least %d are required.', ... + path, numel(tokens), nFixedBefore); +end + +nControl = str2double(tokens(13)); +if ~isfinite(nControl) || nControl < 1 || nControl ~= fix(nControl) + error('ldem:io:malformedInput', ... + 'Value 13 (INCO, number of control nodes) of "%s" must be a positive integer.', path); +end + +expected = 26 + nControl; +if numel(tokens) < expected + error('ldem:io:malformedInput', ... + ['"%s" has %d values but %d are required for INCO = %d ' ... + '(13 + INCO + 13).'], path, numel(tokens), expected, nControl); +end + +numbers = str2double(tokens(1:expected)); +bad = find(isnan(numbers), 1); +if ~isempty(bad) + error('ldem:io:malformedInput', ... + 'Value %d of "%s" ("%s") is not a number.', bad, path, tokens(bad)); +end + +at = @(k) numbers(k); +afterControl = 13 + nControl; % index of the last control node + +values = struct(); +values.testId = at(1); +values.seed = at(2); +values.moduleLength = at(3); +values.nModules = [at(4) at(5) at(6)]; +values.dampingInitial = at(7); +values.dampingFinal = at(8); +values.dampingSwitchTime = at(9); +values.constitutiveDamping = at(10); +values.dt = at(11); +values.totalTime = at(12); +values.controlNodes = reshape(numbers(14:afterControl), 1, []); + +ou = numbers(afterControl + (1:8)); % OU2 ... OU9 +values.output = struct( ... + 'snapshotEvery', ou(2), ... % OU3 + 'controlNodesEvery', ou(5), ... % OU6 + 'energyEvery', ou(7), ... % OU8 + 'trackedBarEvery', double(ou(8) > 0)); % OU9 + +values.poissonRatio = at(afterControl + 9); +values.density = at(afterControl + 10); +values.youngModulus = at(afterControl + 11); +values.fractureEnergy = at(afterControl + 12); +values.criticalDistance = at(afterControl + 13); +end + +function tokens = firstWordOfEachLine(path) +%FIRSTWORDOFEACHLINE First whitespace-delimited word of every non-empty line. +lines = splitlines(string(fileread(path))); +tokens = strings(0, 1); +for k = 1:numel(lines) + word = strtok(strtrim(lines(k))); + if strlength(word) > 0 + tokens(end+1, 1) = word; %#ok + end +end +end diff --git a/src/+ldem/+io/readRandomField.m b/src/+ldem/+io/readRandomField.m new file mode 100644 index 0000000..4b80bf9 --- /dev/null +++ b/src/+ldem/+io/readRandomField.m @@ -0,0 +1,55 @@ +function field = readRandomField(path, nBars) +%READRANDOMFIELD Read the random field that scatters the critical strain. +% +% field = ldem.io.readRandomField(path, nBars) reads the first nBars +% numbers of a text file with one value per line (or separated by +% blanks). Each value multiplies the critical strain of the bar with the +% same number, so the material is not perfectly homogeneous. +% +% The file may be longer than nBars; the extra values are ignored. +% +% Inputs: +% path Path of the text file. +% nBars Number of bars of the mesh. +% +% Output: +% field nBars-by-1 vector of positive multipliers. +% +% Errors: +% ldem:io:fileNotFound The file does not exist. +% ldem:io:randomFieldTooShort The file has fewer than nBars values. +% ldem:io:randomFieldInvalid A value is not finite and positive. +% +% Example: +% field = ldem.io.readRandomField("examples/beam_102/arquivo_3lc_rnao_cv05", 6221); +% +% Legacy: the loop that reads "arquivo_3lc_rnao_cv05" in the main program. +% +% See also ldem.material.buildBarProperties. + +arguments + path (1,1) string + nBars (1,1) double {mustBeInteger, mustBePositive} +end + +if ~isfile(path) + error('ldem:io:fileNotFound', 'Random field file "%s" does not exist.', path); +end + +fid = fopen(path, 'r'); +if fid == -1 + error('ldem:io:cannotOpenFile', 'Cannot open random field file "%s".', path); +end +closer = onCleanup(@() fclose(fid)); +field = fscanf(fid, '%f', nBars); + +if numel(field) < nBars + error('ldem:io:randomFieldTooShort', ... + '"%s" has %d values but the mesh has %d bars.', path, numel(field), nBars); +end +if any(~isfinite(field) | field <= 0) + error('ldem:io:randomFieldInvalid', ... + '"%s" contains values that are not finite and positive (first one: value %d).', ... + path, find(~isfinite(field) | field <= 0, 1)); +end +end diff --git a/src/+ldem/+io/saveResults.m b/src/+ldem/+io/saveResults.m new file mode 100644 index 0000000..80950dc --- /dev/null +++ b/src/+ldem/+io/saveResults.m @@ -0,0 +1,34 @@ +function saveResults(path, results) +%SAVERESULTS Save the results struct of a simulation to a MAT-file. +% +% ldem.io.saveResults(path, results) stores the struct in a MAT-file that +% is loaded with +% +% data = load(path); +% results = data.results; +% +% The file uses the v7.3 format, which supports variables larger than 2 GB +% and is readable from Python (h5py) and other languages. The results +% contain only plain structs and arrays, so no ldem class is needed to load +% them. +% +% Inputs: +% path Path of the .mat file; its folder is created if needed. +% results Struct returned by ldem.runSimulation. +% +% Example: +% ldem.io.saveResults("output/results.mat", results); +% +% See also ldem.runSimulation. + +arguments + path (1,1) string + results (1,1) struct +end + +folder = fileparts(path); +if strlength(folder) > 0 && ~isfolder(folder) + mkdir(folder); +end +save(path, 'results', '-v7.3'); +end diff --git a/src/+ldem/+io/writeCase.m b/src/+ldem/+io/writeCase.m new file mode 100644 index 0000000..a4245a7 --- /dev/null +++ b/src/+ldem/+io/writeCase.m @@ -0,0 +1,412 @@ +function text = writeCase(path, params, scenario, options) +%WRITECASE Write the case file (.ldem) of a parameter set and a scenario. +% +% text = ldem.io.writeCase(path, params, scenario) writes a complete, +% commented case file that ldem.io.readCase reads back into the same +% parameters and scenario, and returns its text. Every key is written, with +% units, so the file documents the model by itself. Use it to save what was +% run, to build a template, and (through ldem.io.convertLegacyInput) to +% convert a DATA0.DAT. +% +% text = ldem.io.writeCase("", params, scenario) only returns the text. +% +% Inputs: +% path Path of the file to create ("" to only return the text). +% params ldem.Parameters. +% scenario Scenario object (default: the one of params.testId). +% +% Name-value options: +% Title Text of the "title" key. +% Authors String array for the "authors" key. +% Header Extra comment lines at the top (without the #). +% OutputFolder Value of output.folder (default "output"). +% Formats Files to enable in [output]: "mat", "ansys", "vtk" (default all; ansys and vtk are off without snapshots). +% ControlNodeNames One label per control node (default "node_"). +% Comments false to omit the explanatory comments (default true). +% +% Output: +% text The content of the file, a string scalar. +% +% Errors: +% ldem:io:unregisteredScenario The scenario class is not in ldem.scenarios.registry. +% ldem:io:cannotOpenFile The file cannot be created. +% +% Example: +% p = ldem.Parameters(testId=101, nModules=[6 3 3]); +% ldem.io.writeCase("tension.ldem", p, ldem.scenarios.UniaxialTension()); +% +% See also ldem.io.readCase, ldem.io.convertLegacyInput, +% ldem.io.writeTemplate. + +arguments + path (1,1) string + params (1,1) ldem.Parameters + scenario = [] + options.Title (1,1) string = "" + options.Authors (1,:) string = string.empty + options.Header (1,:) string = string.empty + options.OutputFolder (1,1) string = "output" + options.Formats (1,:) string {mustBeMember(options.Formats, ["mat" "ansys" "vtk"])} = ["mat" "ansys" "vtk"] + options.ControlNodeNames (1,:) string = string.empty + options.Comments (1,1) logical = true +end + +if isempty(scenario) + scenario = ldem.scenarios.fromTestId(params.testId); +end +reg = ldem.scenarios.registry(); +k = find([reg.className] == string(class(scenario)), 1); +if isempty(k) + error('ldem:io:unregisteredScenario', ... + 'The scenario class %s is not in ldem.scenarios.registry.', class(scenario)); +end +spec = reg(k); + +schema = ldem.schema.caseSchema(); +paths = string({schema.path}); +withComments = options.Comments; +doc = @(key) docText(schema(paths == key)); + +lines = strings(0, 1); +for h = options.Header + lines(end+1, 1) = "# " + h; %#ok +end +if options.Title ~= "" + lines(end+1, 1) = "# " + options.Title; +end +if ~isempty(lines) + lines(end+1, 1) = ""; +end +rows = {"format", "1", doc("format")}; +if options.Title ~= "" + rows(end+1, :) = {"title", quote(options.Title), doc("title")}; +end +if ~isempty(options.Authors) + rows(end+1, :) = {"authors", "[" + strjoin(quote(options.Authors), ", ") + "]", doc("authors")}; +end +lines = [lines; block(rows, withComments); ""]; + +q = @ldem.schema.formatQuantity; +num = @ldem.schema.shortestText; + +% [mesh] +rows = { + "module_size", q(params.moduleLength, "length"), doc("mesh.module_size") + "modules", listText(params.nModules - 1), doc("mesh.modules") + "perturbation", num(params.meshPerturbation), doc("mesh.perturbation") + "seed", num(params.seed), doc("mesh.seed")}; +lines = [lines; section("mesh", rows, withComments)]; + +% [material] +rows = { + "law", quote(params.constitutiveLaw), doc("material.law") + "young_modulus", q(params.youngModulus, "pressure"), doc("material.young_modulus") + "poisson_ratio", num(params.poissonRatio), doc("material.poisson_ratio") + "density", q(params.density, "density"), doc("material.density") + "fracture_energy", q(params.fractureEnergy, "toughness"), doc("material.fracture_energy") + "critical_distance", q(params.criticalDistance, "length"), doc("material.critical_distance") + "failure_area_factor", num(params.failureAreaFactor), doc("material.failure_area_factor")}; +lines = [lines; section("material", rows, withComments)]; + +% [material.scatter] +if strlength(params.randomFieldFile) > 0 + rows = { + "type", quote("file"), doc("material.scatter.type") + "file", quote(relativeTo(params.randomFieldFile, path)), doc("material.scatter.file")}; +elseif params.randomFieldCv > 0 + rows = { + "type", quote("generated"), doc("material.scatter.type") + "cv", num(params.randomFieldCv), doc("material.scatter.cv") + "correlation_length", listOrScalar(params.randomFieldCorrelationLength), ... + doc("material.scatter.correlation_length") + "seed", num(params.randomFieldSeed), doc("material.scatter.seed")}; +else + rows = {"type", quote("none"), doc("material.scatter.type")}; +end +lines = [lines; section("material.scatter", rows, withComments)]; + +% [time] +rows = { + "step", q(params.dt, "time"), doc("time.step") + "duration", q(params.totalTime, "time"), doc("time.duration")}; +lines = [lines; section("time", rows, withComments)]; + +% [damping] +dampingSpec = ldem.solver.dampingRegistry(); +dampingSpec = dampingSpec([dampingSpec.name] == lower(params.dampingModel)); +rows = {"type", quote(params.dampingModel), doc("damping.type")}; +if any(dampingSpec.keys == "initial") + rows(end+1, :) = {"initial", q(params.dampingInitial, "rate"), doc("damping.initial")}; +end +if any(dampingSpec.keys == "final") + rows(end+1, :) = {"final", q(params.dampingFinal, "rate"), doc("damping.final")}; +end +if any(dampingSpec.keys == "switch_time") + rows(end+1, :) = {"switch_time", q(params.dampingSwitchTime, "time"), doc("damping.switch_time")}; +end +rows(end+1, :) = {"constitutive", q(params.constitutiveDamping, "time"), doc("damping.constitutive")}; +lines = [lines; section("damping", rows, withComments)]; + +% [scenario] +rows = {"type", quote(spec.name), doc("scenario.type")}; +for prop = string(fieldnames(spec.units)).' + key = lower(regexprep(prop, '([a-z0-9])([A-Z])', '$1_$2')); + value = scenario.(prop); + if isnan(value) && isfield(spec.keywords, prop) + valueText = quote(spec.keywords.(prop)); + else + valueText = q(value, spec.units.(prop)); + end + rows(end+1, :) = {key, valueText, "Property " + prop + " of " + string(class(scenario)) + "."}; %#ok +end +lines = [lines; section("scenario", rows, withComments)]; +if isa(scenario, 'ldem.scenarios.Declarative') + for j = 1:numel(scenario.supports) + lines = [lines; supportLines(scenario.supports(j), doc, withComments)]; %#ok + end + for j = 1:numel(scenario.loads) + lines = [lines; loadLines(scenario.loads(j), doc, withComments)]; %#ok + end +end + +% [[monitor.node]] +names = options.ControlNodeNames; +if numel(names) ~= numel(params.controlNodes) + names = "node_" + string(params.controlNodes); +end +nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength) / params.moduleLength; +for j = 1:numel(params.controlNodes) + id = params.controlNodes(j); + where = ""; + if id <= size(nodes, 1) + where = "(x, y, z) = (" + strjoin(string(nodes(id, :)), ", ") + ") modules"; + end + rows = { + "name", quote(names(j)), doc("monitor.node.name") + "id", num(id), where}; + lines = [lines; "[[monitor.node]]"; block(rows, withComments); ""]; %#ok +end + +% [monitor.bar] +if params.output.trackedBarEvery > 0 + rows = {"tracked", num(params.trackedBar), doc("monitor.bar.tracked")}; + lines = [lines; section("monitor.bar", rows, withComments)]; +elseif withComments + lines = [lines; "[monitor.bar]"; ... + "# tracked = " + num(params.trackedBar) + " # uncomment to store the strain history of this bar"; ""]; +end + +% [output] +formats = options.Formats; +if params.output.snapshotEvery == 0 + formats = setdiff(formats, ["ansys" "vtk"], 'stable'); +end +rows = { + "folder", quote(options.OutputFolder), doc("output.folder") + "mat", boolText(any(formats == "mat")), doc("output.mat") + "ansys", boolText(any(formats == "ansys")), doc("output.ansys") + "vtk", boolText(any(formats == "vtk")), doc("output.vtk")}; +lines = [lines; section("output", rows, withComments)]; +lines = [lines; section("output.snapshots", ... + {"every", stepsText(params.output.snapshotEvery), doc("output.snapshots.every")}, withComments)]; +lines = [lines; section("output.control_nodes", ... + {"every", stepsText(params.output.controlNodesEvery), doc("output.control_nodes.every")}, withComments)]; +lines = [lines; section("output.energy", ... + {"every", stepsText(params.output.energyEvery), doc("output.energy.every")}, withComments)]; + +text = strjoin(lines, newline); +text = regexprep(text, '\n+$', '') + newline; + +if strlength(path) > 0 + folder = fileparts(path); + if strlength(folder) > 0 && ~isfolder(folder) + mkdir(folder); + end + fid = fopen(path, 'w', 'n', 'UTF-8'); + if fid == -1 + error('ldem:io:cannotOpenFile', 'Cannot create "%s".', path); + end + fprintf(fid, '%s', text); + fclose(fid); +end +end + +function lines = supportLines(b, doc, withComments) +%SUPPORTLINES The [[support]] block of a declarative scenario. +rows = cell(0, 3); +if b.name ~= "" + rows(end+1, :) = {"name", quote(b.name), doc("support.name")}; +end +rows = [rows; selectorRows(b.selector, "support", doc)]; +rows(end+1, :) = {"fix", directionList(b.fix), doc("support.fix")}; +if b.reaction + rows(end+1, :) = {"reaction", "true", doc("support.reaction")}; +end +lines = ["[[support]]"; block(rows, withComments); ""]; +end + +function lines = loadLines(b, doc, withComments) +%LOADLINES The [[load]] block of a declarative scenario. +q = @ldem.schema.formatQuantity; +if b.type == "force" + valueDimension = "force"; + rateDimension = "forcerate"; +else + valueDimension = "length"; + rateDimension = "velocity"; +end +rows = cell(0, 3); +if b.name ~= "" + rows(end+1, :) = {"name", quote(b.name), doc("load.name")}; +end +rows = [rows; selectorRows(b.selector, "load", doc)]; +axisLetters = 'xyz'; +rows(end+1, :) = {"direction", quote(string(axisLetters(b.direction))), doc("load.direction")}; +rows(end+1, :) = {"type", quote(b.type), doc("load.type")}; +rows(end+1, :) = {"time_function", quote(b.fn.type), doc("load.time_function")}; +switch b.fn.type + case "constant" + rows(end+1, :) = {"value", q(b.fn.value, valueDimension), doc("load.value")}; + case "linear" + rows(end+1, :) = {"rate", q(b.fn.rate, rateDimension), doc("load.rate")}; + case "ramp" + rows(end+1, :) = {"rate", q(b.fn.rate, rateDimension), doc("load.rate")}; + rows(end+1, :) = {"until", q(b.fn.until, "time"), doc("load.until")}; + case "table" + rows(end+1, :) = {"times", listText(b.fn.times), doc("load.times")}; + rows(end+1, :) = {"values", listText(b.fn.values), doc("load.values")}; +end +if b.reaction + rows(end+1, :) = {"reaction", "true", doc("load.reaction")}; +end +lines = ["[[load]]"; block(rows, withComments); ""]; +end + +function rows = selectorRows(selector, kind, doc) +%SELECTORROWS Key/value rows of the selector of a block (only what restricts the nodes). +rows = cell(0, 3); +if selector.nodes ~= "all" + rows(end+1, :) = {"nodes", quote(selector.nodes), doc(kind + ".nodes")}; +end +if ~isempty(selector.ids) + rows(end+1, :) = {"ids", listText(selector.ids), doc(kind + ".ids")}; +end +for axis = ["x" "y" "z"] + if ~isempty(selector.(axis)) + rows(end+1, :) = {axis, ldem.scenarios.coordinateText(selector.(axis)), doc(kind + "." + axis)}; %#ok + end +end +end + +function t = directionList(indices) +axisLetters = 'xyz'; +letters = string(num2cell(axisLetters(indices))); +t = "[" + strjoin('"' + letters + '"', ", ") + "]"; +end + +function note = docText(row) +%DOCTEXT Comment of a key: its description and the legacy variable it replaces. +note = string(row.doc); +if row.legacy ~= "" + note = note + " Legacy: " + string(row.legacy) + "."; +end +end + +function lines = section(name, rows, withComments) +lines = ["[" + name + "]"; block(rows, withComments); ""]; +end + +function lines = block(rows, withComments) +%BLOCK Aligned "key = value # comment" lines. +n = size(rows, 1); +keyWidth = max(strlength(string(rows(:, 1)))); +texts = strings(n, 1); +for r = 1:n + texts(r) = string(sprintf('%-*s', keyWidth, rows{r, 1})) + " = " + string(rows{r, 2}); +end +width = max(strlength(texts)); +lines = texts; +if withComments + for r = 1:n + comment = string(rows{r, 3}); + if comment ~= "" + lines(r) = string(sprintf('%-*s', width, texts(r))) + " # " + comment; + end + end +end +end + +function t = quote(s) +if any(contains(s, '"')) + error('ldem:io:badText', 'Texts written to a case file cannot contain double quotes: %s', s(1)); +end +t = '"' + s + '"'; +end + +function t = listText(v) +parts = strings(size(v)); +for k = 1:numel(v) + parts(k) = ldem.schema.shortestText(v(k)); +end +t = "[" + strjoin(parts, ", ") + "]"; +end + +function t = listOrScalar(v) +if isscalar(v) + t = ldem.schema.shortestText(v); +else + t = listText(v); +end +end + +function t = boolText(flag) +if flag + t = "true"; +else + t = "false"; +end +end + +function t = stepsText(n) +if n == 0 + t = "0"; +elseif n == 1 + t = "1 step"; +else + t = string(n) + " steps"; +end +end + +function t = relativeTo(file, casePath) +%RELATIVETO Path of a file relative to the folder of the case file, with / separators. +file = strrep(string(file), '\', '/'); +folder = strrep(string(fileparts(absoluteOf(casePath))), '\', '/'); +if folder == "" || isempty(regexp(file, '^([A-Za-z]:|/)', 'once')) + t = file; % no case folder to compare with, or already relative + return +end +fileParts = split(file, "/"); +folderParts = split(folder, "/"); +n = 0; +while n < min(numel(fileParts) - 1, numel(folderParts)) && ... + strcmpi(fileParts(n + 1), folderParts(n + 1)) + n = n + 1; +end +if n == 0 + t = file; % another drive + return +end +up = repmat("..", 1, numel(folderParts) - n); +t = strjoin([up, fileParts(n + 1:end).'], "/"); +end + +function p = absoluteOf(path) +path = string(path); +if path == "" + p = ""; +elseif isempty(regexp(path, '^([A-Za-z]:|[\\/])', 'once')) + p = string(fullfile(pwd, path)); +else + p = path; +end +end diff --git a/src/+ldem/+io/writePvd.m b/src/+ldem/+io/writePvd.m new file mode 100644 index 0000000..fb68299 --- /dev/null +++ b/src/+ldem/+io/writePvd.m @@ -0,0 +1,49 @@ +function writePvd(path, times, files) +%WRITEPVD Write a ParaView collection (.pvd) that groups VTK files in time. +% +% ldem.io.writePvd(path, times, files) creates a small XML file that lists +% the given .vtu files with their simulation times. Opening it in ParaView +% loads the whole series and enables the time slider. +% +% File names are stored relative to the .pvd file, so the folder can be +% moved or zipped. +% +% Inputs: +% path Path of the .pvd file to create. +% times Simulation times [s], one per file. +% files File names of the .vtu files (same folder as the .pvd). +% +% Errors: +% ldem:io:cannotOpenFile The file cannot be created. +% +% Example: +% ldem.io.writePvd("series.pvd", [0 1e-4], ["a.vtu" "b.vtu"]); +% +% See also ldem.io.exportVtk, ldem.io.SnapshotWriter. + +arguments + path (1,1) string + times (:,1) double + files (:,1) string +end + +if numel(times) ~= numel(files) + error('ldem:io:sizeMismatch', ... + 'times (%d) and files (%d) must have the same length.', numel(times), numel(files)); +end + +fid = fopen(path, 'w'); +if fid == -1 + error('ldem:io:cannotOpenFile', 'Cannot create the PVD file "%s".', path); +end +closer = onCleanup(@() fclose(fid)); + +fprintf(fid, '\n'); +fprintf(fid, '\n'); +fprintf(fid, '\n'); +for k = 1:numel(files) + fprintf(fid, '\n', times(k), files(k)); +end +fprintf(fid, '\n'); +fprintf(fid, '\n'); +end diff --git a/src/+ldem/+io/writeTemplate.m b/src/+ldem/+io/writeTemplate.m new file mode 100644 index 0000000..cf11e05 --- /dev/null +++ b/src/+ldem/+io/writeTemplate.m @@ -0,0 +1,51 @@ +function text = writeTemplate(path, scenarioName) +%WRITETEMPLATE Write a commented case file to start a new model from. +% +% text = ldem.io.writeTemplate(path) writes a complete case file with the +% default values of ldem.Parameters for the "uniaxial_tension" scenario, +% with one comment per key (taken from ldem.schema.caseSchema), ready to +% edit. +% +% text = ldem.io.writeTemplate(path, scenarioName) uses another scenario: +% "uniaxial_tension", "four_point_bending", "clamped_beam" or "custom". The +% keys of the [scenario] section are those of that scenario; "custom" writes +% example [[support]] and [[load]] blocks to edit. +% +% Inputs: +% path Path of the file to create ("" to only return the text). +% scenarioName Name in ldem.scenarios.registry (default "uniaxial_tension"). +% +% Output: +% text Content of the file. +% +% Example: +% ldem.io.writeTemplate("my_test.ldem", "clamped_beam"); +% +% See also ldem.io.writeCase, ldem.io.readCase, ldem.scenarios.fromName. + +arguments + path (1,1) string + scenarioName (1,1) string = "uniaxial_tension" +end + +if lower(scenarioName) == "custom" + scenario = sampleCustomScenario(); +else + scenario = ldem.scenarios.fromName(scenarioName); +end +params = ldem.Parameters(testId = scenario.testId); +text = ldem.io.writeCase(path, params, scenario, ... + Title = "New case (template for " + scenarioName + ")", ... + Header = "Edit the values; every key has a comment. Units go after the number."); +end + +function scenario = sampleCustomScenario() +%SAMPLECUSTOMSCENARIO Example blocks for the template: a prism pulled along x. +left =ldem.scenarios.Declarative.makeSelector(x = 0.5); +right = ldem.scenarios.Declarative.makeSelector(x = "max - 0.5"); +pull = ldem.scenarios.Declarative.makeFunction("linear", rate = -4e-3); +scenario = ldem.scenarios.Declarative( ... + supports = ldem.scenarios.Declarative.makeSupport(left, "x", name = "left end"), ... + loads = ldem.scenarios.Declarative.makeLoad(right, "x", "displacement", pull, ... + name = "right end", reaction = true)); +end diff --git a/src/+ldem/+material/BilinearBarLaw.m b/src/+ldem/+material/BilinearBarLaw.m new file mode 100644 index 0000000..f13ffc3 --- /dev/null +++ b/src/+ldem/+material/BilinearBarLaw.m @@ -0,0 +1,71 @@ +classdef BilinearBarLaw < ldem.material.MaterialLaw + %BILINEARBARLAW Linear elastic in compression, bilinear with softening in tension. + % + % The law of the legacy code: every bar is linear elastic with stiffness + % E1 up to the critical strain EP, then softens linearly down to zero + % force at the rupture strain ER = KR*EP, after which it is broken and + % carries no load. Unloading follows the secant stiffness. The details + % and the history fields are in ldem.material.bilinearLaw (the function + % this class calls); the case-file name is "bilinear". + % + % See also ldem.material.MaterialLaw, ldem.material.bilinearLaw. + + properties (Constant) + name = "bilinear" + end + + methods + function [force, history] = evaluate(~, strain, strainRate, barProps, history, params) + %EVALUATE See ldem.material.bilinearLaw. + [force, history] = ldem.material.bilinearLaw( ... + strain, strainRate, barProps, history, params.constitutiveDamping); + end + + function energy = energies(~, strain, barProps, history, barLength) + %ENERGIES Elastic, damage and broken-bar energy of the bilinear bars. + % + % For a damaged bar with critical strain EP, largest strain EM and + % stiffnesses E1 (compression) and E2 (tension) the energy + % dissipated is L/2 times E1*EP^2 - E2*EM^2 + (E1*EP + E2*EM)*(EM - EP); + % for a broken bar the fracture energy is L/2 * E1*EP^2*KR. + E1 = barProps.stiffness; + E2 = history.tensionStiffness; + stiffness = E1; + stiffness(strain >= 0.0) = E2(strain >= 0.0); + elastic = sum(stiffness .* (strain .* strain .* barLength ./ 2)); + + EP = barProps.criticalStrain; + EM = history.maxStrain; + damaged = ~history.isUndamaged; + area = E1 .* EP .* EP - E2 .* EM .* EM + (E1 .* EP + E2 .* EM) .* (EM - EP); + damage = sum(barLength(damaged) .* area(damaged) ./ 2); + + broken = damaged & ~history.isUnbroken; + brokenBars = sum(E1(broken) .* EP(broken) .* EP(broken) .* barProps.ruptureRatio(broken) ... + .* barLength(broken) ./ 2); + + energy = struct('elastic', elastic, 'damage', damage, 'brokenBars', brokenBars); + end + + function value = barDamageEnergy(~, bar, barProps, history, barLength) + %BARDAMAGEENERGY Energy dissipated by damage in one bar (zero if undamaged). + if history.isUndamaged(bar) + value = 0.0; + return + end + E1 = barProps.stiffness(bar); + E2 = history.tensionStiffness(bar); + EP = barProps.criticalStrain(bar); + EM = history.maxStrain(bar); + area = E1 * EP * EP - E2 * EM * EM + (E1 * EP + E2 * EM) * (EM - EP); + value = barLength(bar) * area / 2; + end + + function stiffness = viscousStiffness(~, strain, barProps, history) + %VISCOUSSTIFFNESS Compression stiffness for compressed bars, tension stiffness otherwise. + isCompressed = strain < 0.0; + stiffness = history.tensionStiffness; + stiffness(isCompressed) = barProps.stiffness(isCompressed); + end + end +end diff --git a/src/+ldem/+material/LinearElasticBarLaw.m b/src/+ldem/+material/LinearElasticBarLaw.m new file mode 100644 index 0000000..574a80c --- /dev/null +++ b/src/+ldem/+material/LinearElasticBarLaw.m @@ -0,0 +1,44 @@ +classdef LinearElasticBarLaw < ldem.material.MaterialLaw + %LINEARELASTICLAW Linear elastic bars that never damage or break. + % + % The force of a bar is E1*strain in tension and in compression, plus the + % viscous term E1*constitutiveDamping*strainRate. There is no softening + % and no rupture, so the damage energy is zero and every bar stays intact. + % It is useful to verify a model against elastic solutions (waves, + % vibration, static deflection) and to separate geometry and loading + % problems from damage. The case-file name is "linear_elastic". + % + % The fracture parameters (fractureEnergy, criticalDistance, + % failureAreaFactor) and the random scatter are still read and computed + % by ldem.material.buildBarProperties, but this law does not use them. + % + % See also ldem.material.MaterialLaw, ldem.material.BilinearBarLaw. + + properties (Constant) + name = "linear_elastic" + end + + methods + function [force, history] = evaluate(~, strain, strainRate, barProps, history, params) + %EVALUATE E1*(strain + constitutiveDamping*strainRate), history unchanged. + force = barProps.stiffness .* strain ... + + barProps.stiffness .* params.constitutiveDamping .* strainRate; + end + + function energy = energies(~, strain, barProps, ~, barLength) + %ENERGIES Sum of E1*strain^2*L/2; no damage and no broken bars. + elastic = sum(barProps.stiffness .* (strain .* strain .* barLength ./ 2)); + energy = struct('elastic', elastic, 'damage', 0, 'brokenBars', 0); + end + + function value = barDamageEnergy(~, ~, ~, ~, ~) + %BARDAMAGEENERGY Always zero. + value = 0.0; + end + + function stiffness = viscousStiffness(~, ~, barProps, ~) + %VISCOUSSTIFFNESS E1 for every bar. + stiffness = barProps.stiffness; + end + end +end diff --git a/src/+ldem/+material/MaterialLaw.m b/src/+ldem/+material/MaterialLaw.m new file mode 100644 index 0000000..afa1fe4 --- /dev/null +++ b/src/+ldem/+material/MaterialLaw.m @@ -0,0 +1,76 @@ +classdef (Abstract) MaterialLaw + %MATERIALLAW Base class of the constitutive laws of the bars. + % + % A law says how the axial force of a bar depends on its strain, its + % strain rate and its history, and how much energy that state stores or + % dissipates. The solver never names a law: it asks the object chosen by + % params.constitutiveLaw (the key "law" of the [material] section of a + % case file). + % + % To add a law: + % 1. Create a subclass in this folder and set the constant property + % name (snake_case, the word used in the case file). + % 2. Implement evaluate, energies, barDamageEnergy and viscousStiffness. + % 3. Add a line to ldem.material.lawRegistry. + % + % What every law can rely on and must respect: + % + % * barProps is the struct of ldem.material.buildBarProperties (stiffness, + % criticalStrain, ruptureStrain, ruptureRatio, ...); history starts as + % its second output. + % * history must always keep the logical fields isUndamaged and + % isUnbroken: the bar counts, the ANSYS and VTK files and the snapshots + % read them. The other fields are private to the law. + % * evaluate is called once per step, with all the bars at once + % (vectors of nBars-by-1), and returns the history after the step. + % + % See also ldem.material.BilinearBarLaw, ldem.material.LinearElasticBarLaw, + % ldem.material.lawRegistry, ldem.material.lawFromName. + + properties (Abstract, Constant) + % Name used in the case file ("bilinear"). + name + end + + methods (Abstract) + % EVALUATE Axial force of every bar and the history after the step. + % + % [force, history] = law.evaluate(strain, strainRate, barProps, history, params) + % + % Inputs: + % strain nBars-by-1 strain (L - L0)/L0, tension positive. + % strainRate nBars-by-1 strain rate [1/s]. + % barProps Struct from ldem.material.buildBarProperties. + % history Struct with the state of every bar before the step. + % params ldem.Parameters (params.constitutiveDamping is the + % viscous coefficient of the law, in s). + % + % Outputs: + % force nBars-by-1 axial force [N], tension positive. + % history The history after the step. + [force, history] = evaluate(obj, strain, strainRate, barProps, history, params) + + % ENERGIES Energies of all the bars, as scalars [J]. + % + % energy = law.energies(strain, barProps, history, barLength) returns a + % struct with the fields + % elastic Strain energy stored in the bars. + % damage Energy dissipated by softening in the damaged bars. + % brokenBars Total fracture energy of the bars that have broken. + energy = energies(obj, strain, barProps, history, barLength) + + % BARDAMAGEENERGY Energy dissipated by damage in one bar [J]. + % + % value = law.barDamageEnergy(bar, barProps, history, barLength) + % for the bar with that number (zero if it is undamaged). + value = barDamageEnergy(obj, bar, barProps, history, barLength) + + % VISCOUSSTIFFNESS Stiffness of every bar in the viscous term [N]. + % + % stiffness = law.viscousStiffness(strain, barProps, history) is the + % stiffness E that multiplies the strain rate in the force of the law, + % E*constitutiveDamping*strainRate; the solver uses it to account for + % the energy dissipated by that term. + stiffness = viscousStiffness(obj, strain, barProps, history) + end +end diff --git a/src/+ldem/+material/bilinearLaw.m b/src/+ldem/+material/bilinearLaw.m new file mode 100644 index 0000000..35fed6f --- /dev/null +++ b/src/+ldem/+material/bilinearLaw.m @@ -0,0 +1,107 @@ +function [force, history] = bilinearLaw(strain, strainRate, barProps, history, constitutiveDamping) +%BILINEARLAW Axial force of the bars: elastic, softening and rupture. +% +% [force, history] = ldem.material.bilinearLaw(strain, strainRate, ... +% barProps, history, constitutiveDamping) evaluates the constitutive law +% of all bars at once and updates their damage state. +% +% The force follows one of four branches, chosen per bar: +% +% 1. Rupture strain >= ER: force is zero, the bar is broken for +% good (tension stiffness becomes zero). +% 2. Softening strain >= EM (a new largest strain, above EP): the +% force decreases linearly with strain, reaching zero +% at ER. The tension stiffness becomes the secant +% stiffness F/strain and EM is updated. +% 3. Tension 0 <= strain < EM: linear with the current tension +% stiffness E2. This is the elastic response of an +% undamaged bar and the unloading/reloading of a damaged +% one (damage is irreversible). +% 4. Compression strain < 0: linear with stiffness E1, damage has no +% effect (contact). +% +% A viscous term stiffness*constitutiveDamping*strainRate is added in +% branches 2, 3 and 4. +% +% Inputs: +% strain nBars-by-1 axial strains (tension positive). +% strainRate nBars-by-1 strain rates [1/s]. +% barProps Struct from ldem.material.buildBarProperties. +% history Damage state of the previous call or the initial one. +% constitutiveDamping Damping coefficient [s] (params.constitutiveDamping). +% +% Outputs: +% force nBars-by-1 axial forces [N], tension positive. +% history Updated damage state. +% +% Example: +% [barProps, history] = ldem.material.buildBarProperties(mesh, params); +% damping = params.constitutiveDamping; +% [force, history] = ldem.material.bilinearLaw(strain, rate, barProps, history, damping); +% +% Legacy: the constitutive branches inside CABAR (and CONSTIT). +% +% See also ldem.material.buildBarProperties. + +arguments + strain (:,1) double + strainRate (:,1) double + barProps (1,1) struct + history (1,1) struct + constitutiveDamping (1,1) double {mustBeNonnegative} +end + +nBars = numel(strain); +if numel(strainRate) ~= nBars || numel(barProps.stiffness) ~= nBars + error('ldem:material:sizeMismatch', ... + 'strain (%d), strainRate (%d) and the bar properties (%d) must have one entry per bar.', ... + nBars, numel(strainRate), numel(barProps.stiffness)); +end + +E1 = barProps.stiffness; +EP = barProps.criticalStrain; +KR = barProps.ruptureRatio; +ER = KR .* EP; + +E2 = history.tensionStiffness; +EM = history.maxStrain; +isUndamaged = history.isUndamaged; +isUnbroken = history.isUnbroken; + +% Select the branch of every bar. The branches are mutually exclusive. +broken = strain >= ER; +softening = ~broken & (strain >= EM); +tension = ~broken & ~softening & (strain >= 0.0); +compression = ~broken & ~softening & ~tension; + +force = zeros(nBars, 1); + +% 1. Rupture. +E2(broken) = 0.0; +EM(broken) = ER(broken); +isUndamaged(broken & isUnbroken) = false; +isUnbroken(broken) = false; +% force stays 0. + +% 2. Softening. +s = softening; +aux = (strain(s) - EP(s)) ./ (KR(s) - 1.0); +aux = E1(s) .* (EP(s) - aux); +E2(s) = aux ./ strain(s); +EM(s) = strain(s); +force(s) = aux + E2(s) .* constitutiveDamping .* strainRate(s); +isUndamaged(s) = false; + +% 3. Tension (elastic or unloading). +t = tension; +force(t) = E2(t) .* strain(t) + E2(t) .* constitutiveDamping .* strainRate(t); + +% 4. Compression. +c = compression; +force(c) = E1(c) .* strain(c) + E1(c) .* constitutiveDamping .* strainRate(c); + +history.tensionStiffness = E2; +history.maxStrain = EM; +history.isUndamaged = isUndamaged; +history.isUnbroken = isUnbroken; +end diff --git a/src/+ldem/+material/buildBarProperties.m b/src/+ldem/+material/buildBarProperties.m new file mode 100644 index 0000000..8db1690 --- /dev/null +++ b/src/+ldem/+material/buildBarProperties.m @@ -0,0 +1,130 @@ +function [barProps, history] = buildBarProperties(mesh, params, options) +%BUILDBARPROPERTIES Material properties and initial damage state of every bar. +% +% [barProps, history] = ldem.material.buildBarProperties(mesh, params) +% computes everything the constitutive law of the bars needs. +% +% Every bar behaves as follows (see ldem.material.bilinearLaw): linear +% elastic with stiffness E1 up to the critical strain EP, then linear +% softening down to zero force at the rupture strain ER = KR*EP. The +% fracture energy is what fixes EP and KR: +% +% EP0 = sqrt(Gf / (E * deq)) critical strain +% Lcr = 2 * deq * CAF / alpha critical length +% KR = Lcr / L rupture strain / critical strain +% +% with the material data of ldem.Parameters, the failure-area factor CAF +% and the lattice coefficient alpha. EP is EP0 times a random field, which +% is read from params.randomFieldFile when it is set, or generated in +% memory (ldem.material.generateRandomField) when params.randomFieldCv is +% positive. +% +% Inputs: +% mesh Struct from ldem.mesh.buildMesh. +% params ldem.Parameters. +% +% Name-value options: +% RandomField nBars-by-1 vector of multipliers of the critical strain. +% Overrides params.randomFieldFile and params.randomFieldCv. +% Default: read the file if there is one, else generate the +% field if randomFieldCv > 0, otherwise all ones. +% +% Outputs: +% barProps Struct of properties that stay constant during the simulation. +% history Struct with the initial damage state of every bar. +% +% Fields of barProps (nBars-by-1 unless stated otherwise): +% +% stiffness E1, axial stiffness [N] +% criticalStrain EP, strain at which damage starts +% ruptureRatio KR, ratio between rupture and critical strain +% ruptureStrain ER = KR*EP, strain at which the bar breaks +% criticalStrainMean scalar, mean of EP +% criticalStrainCv scalar, coefficient of variation of EP +% randomField multiplier of EP0 of each bar (all ones without field) +% randomFieldInfo struct: source ("none", "file", "generated" or "given"), fieldMean, fieldCv and, for a generated field, those of ldem.material.generateRandomField +% +% Fields of history (nBars-by-1), updated by ldem.material.bilinearLaw: +% +% tensionStiffness E2, secant stiffness in tension (starts at E1) +% maxStrain EM, largest strain reached (starts at EP) +% isUndamaged DM, false once the bar has started to soften +% isUnbroken FS, false once the bar has broken +% +% Errors: +% ldem:material:criticalLengthTooShort KR is below 1.01 for some bar; +% the softening branch needs KR > 1. Increase params.criticalDistance +% or reduce params.moduleLength. +% +% Example: +% params = ldem.Parameters(); +% mesh = ldem.mesh.buildMesh(params); +% [barProps, history] = ldem.material.buildBarProperties(mesh, params); +% +% Legacy: NAYFES0, RMEC, the random-field loop of the main program, CALCOEV. +% +% See also ldem.material.bilinearLaw, ldem.material.computeBarStiffness, +% ldem.io.readRandomField, ldem.material.generateRandomField. + +arguments + mesh (1,1) struct + params (1,1) ldem.Parameters + options.RandomField (:,1) double = [] +end + +nBars = numel(mesh.barLength); +[~, alpha] = ldem.material.latticeCoefficients(params.poissonRatio); + +stiffness = ldem.material.computeBarStiffness(mesh, params); + +baseCriticalStrain = sqrt(params.fractureEnergy ./ (params.youngModulus .* params.criticalDistance)); +criticalLength = params.criticalDistance * 2.0 * params.failureAreaFactor / alpha; +ruptureRatio = criticalLength ./ mesh.barLength; + +if any(ruptureRatio < 1.01) + error('ldem:material:criticalLengthTooShort', ... + ['The critical length (%g m) is too short compared with the bar length ' ... + '(%g m): rupture ratio KR = %g < 1.01. Increase criticalDistance or ' ... + 'reduce moduleLength.'], criticalLength, max(mesh.barLength), min(ruptureRatio)); +end + +% Random scatter of the critical strain. +if ~isempty(options.RandomField) + field = options.RandomField; + fieldInfo = struct('source', "given"); +elseif strlength(params.randomFieldFile) > 0 + field = ldem.io.readRandomField(params.randomFieldFile, nBars); + fieldInfo = struct('source', "file", 'file', params.randomFieldFile); +elseif params.randomFieldCv > 0 + [field, fieldInfo] = ldem.material.generateRandomField(mesh.barCentres, ... + params.randomFieldCv, ... + params.randomFieldCorrelationLength * params.moduleLength, ... + params.randomFieldSeed); +else + field = ones(nBars, 1); + fieldInfo = struct('source', "none"); +end +if numel(field) ~= nBars + error('ldem:material:randomFieldSize', ... + 'The random field has %d values but the mesh has %d bars.', numel(field), nBars); +end +fieldInfo.fieldMean = mean(field); +fieldInfo.fieldCv = std(field) / mean(field); +criticalStrain = field .* baseCriticalStrain; + +barProps = struct(); +barProps.stiffness = stiffness; +barProps.criticalStrain = criticalStrain; +barProps.ruptureRatio = ruptureRatio; +barProps.ruptureStrain = ruptureRatio .* criticalStrain; +barProps.criticalStrainMean = mean(criticalStrain); +barProps.criticalStrainCv = std(criticalStrain) / mean(criticalStrain); +barProps.randomField = field; +barProps.randomFieldInfo = fieldInfo; + +history = struct(); +history.tensionStiffness = stiffness; +history.maxStrain = criticalStrain; +history.isUndamaged = true(nBars, 1); +history.isUnbroken = true(nBars, 1); +end diff --git a/src/+ldem/+material/computeBarStiffness.m b/src/+ldem/+material/computeBarStiffness.m new file mode 100644 index 0000000..70f8bf2 --- /dev/null +++ b/src/+ldem/+material/computeBarStiffness.m @@ -0,0 +1,56 @@ +function stiffness = computeBarStiffness(mesh, params) +%COMPUTEBARSTIFFNESS Axial stiffness of every bar of the lattice. +% +% stiffness = ldem.material.computeBarStiffness(mesh, params) returns the +% stiffness E1 [N] of each bar, defined so that the axial force is +% force = stiffness * strain. +% +% The reference value of an edge bar is EA = alpha*E*L^2 (L = bar +% length, see ldem.material.latticeCoefficients). It is modified by the +% type of bar (ldem.mesh.buildBars): +% +% * Grid edges inside the prism: EA. +% * Grid edges on a face of the prism: EA/2 (they are shared by fewer +% modules); on an edge of the prism: EA/4. +% * Centre-to-centre bars: EA. +% * Diagonals: EA * 2*delta*(4/3)/sqrt(3). +% +% Inputs: +% mesh Struct from ldem.mesh.buildMesh. +% params ldem.Parameters (uses youngModulus and poissonRatio). +% +% mesh must contain barLength, barType and barBoundaryFaces. +% +% Output: +% stiffness nBars-by-1 vector [N]. +% +% Example: +% params = ldem.Parameters(); +% mesh = ldem.mesh.buildMesh(params); +% E1 = ldem.material.computeBarStiffness(mesh, params); +% +% Legacy: NAYFES0 (ENR, EDG) and RMEC, RMECEX, RMECIN, RMECDI, DEFEP (E1). +% +% See also ldem.material.latticeCoefficients, ldem.material.buildBarProperties. + +arguments + mesh (1,1) struct + params (1,1) ldem.Parameters +end + +[delta, alpha] = ldem.material.latticeCoefficients(params.poissonRatio); + +edgeStiffness = (params.youngModulus .* (mesh.barLength .^ 2)) .* alpha; +diagonalFactor = (2.0 * delta * (4.0 / 3.0)) / sqrt(3.0); +diagonalStiffness = edgeStiffness * diagonalFactor; + +% Reduction of the grid edges that lie on the surface of the prism: +% 0 faces -> 1, 1 face -> 1/2, 2 faces (an edge of the prism) -> 1/4. +reduction = ones(size(edgeStiffness)); +reduction(mesh.barBoundaryFaces == 1) = 0.50; +reduction(mesh.barBoundaryFaces >= 2) = 0.25; + +stiffness = edgeStiffness .* reduction; % grid edges +stiffness(mesh.barType == 2) = edgeStiffness(mesh.barType == 2); % centre-to-centre +stiffness(mesh.barType == 3) = diagonalStiffness(mesh.barType == 3); % diagonals +end diff --git a/src/+ldem/+material/generateRandomField.m b/src/+ldem/+material/generateRandomField.m new file mode 100644 index 0000000..e9279e0 --- /dev/null +++ b/src/+ldem/+material/generateRandomField.m @@ -0,0 +1,141 @@ +function [field, info] = generateRandomField(barCentres, cv, correlationLength, seed) +%GENERATERANDOMFIELD Spatially correlated Weibull field of critical-strain multipliers. +% +% [field, info] = ldem.material.generateRandomField(barCentres, cv, +% correlationLength, seed) returns one positive multiplier per bar, so +% that bars close to each other get similar values. It replaces the +% external script Aleat_novo4.m and its text file: the field is computed +% in memory, in a fraction of a second, and ldem.runSimulation keeps it in +% the results. +% +% Method (the one of Aleat_novo4.m): +% +% 1. A regular grid of "poles" with spacing correlationLength covers the bar centres, with one extra pole on each side. +% 2. Each pole gets an independent Weibull value with mean 1 and coefficient of variation cv. The shape k solves Gamma(1+2/k)/Gamma(1+1/k)^2 = 1 + cv^2 and the scale is 1/Gamma(1+1/k). +% 3. The value of a bar is the trilinear interpolation of the 8 poles of the grid cell that contains its centre. +% +% The interpolation averages neighbouring poles, so the coefficient of +% variation of the bars (info.fieldCv) is somewhat smaller than cv; the +% larger the correlation length compared with the bars, the closer the +% values of neighbouring bars. +% +% Inputs: +% barCentres nBars-by-3 bar midpoints [m] (mesh.barCentres). +% cv Coefficient of variation of the pole values, > 0. +% correlationLength Pole spacing [m], a scalar or [lx ly lz]. +% seed Seed of the random numbers (non-negative integer). +% +% Outputs: +% field nBars-by-1 vector of positive multipliers. +% info Struct describing the field (fields listed below). +% +% Fields of info: +% +% source "generated" +% cv cv requested +% correlationLength 1-by-3 pole spacing [m] +% seed seed used +% weibullShape shape k of the pole distribution +% weibullScale scale of the pole distribution +% nPoles 1-by-3 number of poles along x, y, z +% fieldMean mean of field +% fieldCv coefficient of variation of field +% +% The random numbers come from a private stream (Mersenne Twister seeded +% with seed), so the global random state is not touched and the same seed +% always gives the same field. No toolbox is needed. +% +% Differences with Aleat_novo4.m, see docs/known-issues/KNOWN_ISSUES.md: +% the legacy script used the scale Gamma(1+1/k) (mean Gamma(1+1/k)^2, +% below 1) and had two typos in the interpolation formula. Its rotation of +% the pole grid (angles that were always zero) is not implemented. +% +% Example: +% params = ldem.Parameters(nModules=[6 3 3]); +% mesh = ldem.mesh.buildMesh(params); +% field = ldem.material.generateRandomField(mesh.barCentres, 0.05, 3 * params.moduleLength, 515); +% +% Legacy: Aleat_novo4.m (outside the main program; it wrote the file read +% by ldem.io.readRandomField). +% +% See also ldem.material.buildBarProperties, ldem.io.readRandomField. + +arguments + barCentres (:,3) double {mustBeFinite} + cv (1,1) double {mustBePositive, mustBeFinite} + correlationLength (1,:) double {mustBePositive, mustBeFinite} + seed (1,1) double {mustBeInteger, mustBeNonnegative} +end + +if isscalar(correlationLength) + correlationLength = repmat(correlationLength, 1, 3); +elseif numel(correlationLength) ~= 3 + error('ldem:material:badCorrelationLength', ... + 'correlationLength must be a scalar or have 3 values [lx ly lz], got %d values.', ... + numel(correlationLength)); +end + +[shape, scale] = weibullForUnitMean(cv); + +% Pole grid: one cell beyond the bars on each side, as in Aleat_novo4.m. +nBars = size(barCentres, 1); +first = floor(min(barCentres, [], 1) ./ correlationLength) - 1; +last = ceil(max(barCentres, [], 1) ./ correlationLength) + 1; +nPoles = last - first + 1; + +% Weibull values by inverse transform: scale * (-log(U))^(1/shape). +stream = RandStream('mt19937ar', 'Seed', seed); +uniform = rand(stream, nPoles); +poles = scale * (-log(uniform)) .^ (1 / shape); + +% Cell containing each bar centre and local coordinates t in [0, 1]. +position = barCentres ./ correlationLength - first; % in pole spacings +corner = floor(position); +corner = min(max(corner, 0), nPoles - 2); % bars on the last pole +t = position - corner; +ix = corner(:, 1) + 1; iy = corner(:, 2) + 1; iz = corner(:, 3) + 1; +tx = t(:, 1); ty = t(:, 2); tz = t(:, 3); + +pole = @(dx, dy, dz) poles(sub2ind(nPoles, ix + dx, iy + dy, iz + dz)); +field = zeros(nBars, 1); +for dx = 0:1 + wx = (1 - dx) * (1 - tx) + dx * tx; + for dy = 0:1 + wy = (1 - dy) * (1 - ty) + dy * ty; + for dz = 0:1 + wz = (1 - dz) * (1 - tz) + dz * tz; + field = field + wx .* wy .* wz .* pole(dx, dy, dz); + end + end +end + +info = struct( ... + 'source', "generated", ... + 'cv', cv, ... + 'correlationLength', correlationLength, ... + 'seed', seed, ... + 'weibullShape', shape, ... + 'weibullScale', scale, ... + 'nPoles', nPoles, ... + 'fieldMean', mean(field), ... + 'fieldCv', std(field) / mean(field)); +end + +function [shape, scale] = weibullForUnitMean(cv) +%WEIBULLFORUNITMEAN Weibull shape and scale with mean 1 and the given CV. +% The squared CV of a Weibull distribution is +% Gamma(1+2/k)/Gamma(1+1/k)^2 - 1, which decreases with k. +target = log1p(cv^2); +excess = @(k) gammaln(1 + 2 ./ k) - 2 * gammaln(1 + 1 ./ k) - target; +bounds = [0.02 1e5]; +if excess(bounds(2)) > 0 + error('ldem:material:randomFieldCvTooSmall', ... + 'cv = %g is too small for a Weibull field; use at least 1e-4.', cv); +end +if excess(bounds(1)) < 0 + error('ldem:material:randomFieldCvTooLarge', ... + 'cv = %g is too large for a Weibull field.', cv); +end +shape = fzero(excess, bounds); +scale = 1 / gamma(1 + 1 / shape); +end diff --git a/src/+ldem/+material/latticeCoefficients.m b/src/+ldem/+material/latticeCoefficients.m new file mode 100644 index 0000000..27a8730 --- /dev/null +++ b/src/+ldem/+material/latticeCoefficients.m @@ -0,0 +1,40 @@ +function [delta, alpha] = latticeCoefficients(poissonRatio) +%LATTICECOEFFICIENTS Coefficients that make the lattice equivalent to a continuum. +% +% [delta, alpha] = ldem.material.latticeCoefficients(poissonRatio) +% returns the two coefficients of the Nayfeh-Hefzy equivalence between the +% cubic lattice (edges plus diagonals) and an isotropic elastic continuum +% with the given Poisson's ratio: +% +% delta = 9*nu / (4 - 8*nu) +% alpha = (9 + 8*delta) / (18 + 24*delta) +% +% alpha scales the stiffness of the edge bars, EA = alpha*E*L^2, and delta +% scales the diagonals relative to the edges. +% +% Input: +% poissonRatio Poisson's ratio, 0 <= nu < 0.5. +% +% Outputs: +% delta, alpha Dimensionless coefficients. +% +% Example: +% [delta, alpha] = ldem.material.latticeCoefficients(0.25); +% % delta = 1.125, alpha = 0.4 +% +% Legacy: first lines of NAYFES0. +% +% See also ldem.material.computeBarStiffness. + +arguments + poissonRatio (1,1) double {mustBeNonnegative, mustBeFinite} +end + +if poissonRatio >= 0.5 + error('ldem:params:badPoissonRatio', ... + 'poissonRatio must be smaller than 0.5, got %g.', poissonRatio); +end + +delta = 9.0 * poissonRatio / (4.0 - 8.0 * poissonRatio); +alpha = (9.0 + 8.0 * delta) / (18.0 + 24.0 * delta); +end diff --git a/src/+ldem/+material/lawFromName.m b/src/+ldem/+material/lawFromName.m new file mode 100644 index 0000000..ab5aa3a --- /dev/null +++ b/src/+ldem/+material/lawFromName.m @@ -0,0 +1,30 @@ +function law = lawFromName(name) +%LAWFROMNAME Create the constitutive-law object with a name used in the case files. +% +% law = ldem.material.lawFromName(name) returns an instance of the class +% registered under name in ldem.material.lawRegistry. +% +% Input: +% name Law name, for example "bilinear" (case is ignored). +% +% Output: +% law Object of a subclass of ldem.material.MaterialLaw. +% +% Errors: +% ldem:material:unknownLaw No law has that name. +% +% See also ldem.material.lawRegistry, ldem.material.MaterialLaw. + +arguments + name (1,1) string +end + +reg = ldem.material.lawRegistry(); +k = find([reg.name] == lower(name), 1); +if isempty(k) + error('ldem:material:unknownLaw', ... + 'There is no constitutive law named "%s".%s Available: %s.', name, ... + ldem.schema.suggest(name, [reg.name]), strjoin([reg.name], ', ')); +end +law = feval(reg(k).className); +end diff --git a/src/+ldem/+material/lawRegistry.m b/src/+ldem/+material/lawRegistry.m new file mode 100644 index 0000000..1ed734e --- /dev/null +++ b/src/+ldem/+material/lawRegistry.m @@ -0,0 +1,31 @@ +function reg = lawRegistry() +%LAWREGISTRY List of the available constitutive laws. +% +% reg = ldem.material.lawRegistry() returns one element per law class. It is +% the only place to edit to register a new law: ldem.material.lawFromName, +% the validation of ldem.Parameters and the case-file reader all read it. +% +% Fields of every element: +% +% name Word used in the case file, "law = ..." (snake_case). +% className Class, a subclass of ldem.material.MaterialLaw. +% description One line for the messages and the documentation. +% +% Output: +% reg Struct array. +% +% Example: +% [ldem.material.lawRegistry().name] % "bilinear" "linear_elastic" +% +% See also ldem.material.MaterialLaw, ldem.material.lawFromName. + +reg = struct('name', {}, 'className', {}, 'description', {}); +reg(end+1) = makeEntry("bilinear", "ldem.material.BilinearBarLaw", ... + "Linear elastic, softening in tension down to rupture (legacy law)"); +reg(end+1) = makeEntry("linear_elastic", "ldem.material.LinearElasticBarLaw", ... + "Linear elastic, no damage and no rupture"); +end + +function entry = makeEntry(name, className, description) +entry = struct('name', name, 'className', className, 'description', description); +end diff --git a/src/+ldem/+material/summarizeMaterial.m b/src/+ldem/+material/summarizeMaterial.m new file mode 100644 index 0000000..592fd9c --- /dev/null +++ b/src/+ldem/+material/summarizeMaterial.m @@ -0,0 +1,76 @@ +function summary = summarizeMaterial(barProps, params) +%SUMMARIZEMATERIAL Material data and derived quantities, for the results file. +% +% summary = ldem.material.summarizeMaterial(barProps, params) collects the +% material parameters, the lattice coefficients and the statistics of the +% critical strain in one struct, so that a results file documents the +% material that was simulated. +% +% Fields of summary: +% +% youngModulus E [Pa] +% poissonRatio nu +% density rho [kg/m^3] +% waveSpeed sqrt(E/rho) [m/s] +% fractureEnergy Gf [N/m] +% criticalDistance equivalent distance deq [m] +% failureAreaFactor CAF +% delta lattice coefficient delta +% alpha lattice coefficient alpha +% normalStiffness alpha*E*L^2 of a bar with the length of a module [N] +% diagonalStiffness normalStiffness times the diagonal factor [N] +% criticalLength Lcr = 2*deq*CAF/alpha [m] +% ruptureRatioNormal Lcr divided by the module length (KR of a normal bar) +% baseCriticalStrain sqrt(Gf/(E*deq)), before the random field +% criticalStrainMean mean of the critical strain EP of all bars +% criticalStrainCv coefficient of variation of EP +% criticalStrainMin smallest EP +% criticalStrainMax largest EP +% randomField where the random field came from and its statistics (barProps.randomFieldInfo); the value of each bar is barProps.randomField +% +% Input: +% barProps Struct from ldem.material.buildBarProperties. +% params ldem.Parameters. +% +% Output: +% summary Struct with the fields above. +% +% Example: +% material = ldem.material.summarizeMaterial(barProps, params); +% +% Legacy: the material block of WRICON (EPMAX and EPMIN were never updated +% there and COEV was never stored, see docs/known-issues/KNOWN_ISSUES.md). +% +% See also ldem.material.buildBarProperties, ldem.mesh.summarizeModel. + +arguments + barProps (1,1) struct + params (1,1) ldem.Parameters +end + +[delta, alpha] = ldem.material.latticeCoefficients(params.poissonRatio); +normalStiffness = alpha * params.youngModulus * params.moduleLength^2; +diagonalFactor = (2.0 * delta * (4.0 / 3.0)) / sqrt(3.0); +criticalLength = params.criticalDistance * 2.0 * params.failureAreaFactor / alpha; + +summary = struct(); +summary.youngModulus = params.youngModulus; +summary.poissonRatio = params.poissonRatio; +summary.density = params.density; +summary.waveSpeed = params.waveSpeed; +summary.fractureEnergy = params.fractureEnergy; +summary.criticalDistance = params.criticalDistance; +summary.failureAreaFactor = params.failureAreaFactor; +summary.delta = delta; +summary.alpha = alpha; +summary.normalStiffness = normalStiffness; +summary.diagonalStiffness = normalStiffness * diagonalFactor; +summary.criticalLength = criticalLength; +summary.ruptureRatioNormal = criticalLength / params.moduleLength; +summary.baseCriticalStrain = sqrt(params.fractureEnergy / (params.youngModulus * params.criticalDistance)); +summary.criticalStrainMean = barProps.criticalStrainMean; +summary.criticalStrainCv = barProps.criticalStrainCv; +summary.criticalStrainMin = min(barProps.criticalStrain); +summary.criticalStrainMax = max(barProps.criticalStrain); +summary.randomField = barProps.randomFieldInfo; +end diff --git a/src/+ldem/+mesh/buildBars.m b/src/+ldem/+mesh/buildBars.m new file mode 100644 index 0000000..61cd7c2 --- /dev/null +++ b/src/+ldem/+mesh/buildBars.m @@ -0,0 +1,92 @@ +function [bars, barType, boundaryFaces] = buildBars(nModules) +%BUILDBARS Connectivity and classification of the bars of the lattice. +% +% bars = ldem.mesh.buildBars(nModules) returns, for every bar, the numbers +% of its two end nodes. Node numbering is the one of ldem.mesh.buildNodes. +% +% [bars, barType, boundaryFaces] = ldem.mesh.buildBars(nModules) also +% classifies each bar, which the material model needs to assign +% stiffness. +% +% Each cubic module has 12 edges, shared with its neighbours, plus 8 +% diagonals that join the centre node to the 8 corners. The bars are +% listed in this order: +% +% 1. Grid edges parallel to x, then to y, then to z. +% 2. Centre-to-centre bars parallel to x, then to y, then to z. +% 3. Diagonals: 8 consecutive bars per module (centre -> each corner), +% modules in node order. +% +% Input: +% nModules [M N L], integers >= 2. +% +% Outputs: +% bars nBars-by-2 matrix of node numbers [startNode endNode]. +% barType nBars-by-1 codes: 1 grid edge, 2 centre bar, 3 diagonal. +% boundaryFaces nBars-by-1 faces of the prism a grid edge lies on (0, 1, 2). +% +% boundaryFaces is 0 for a grid edge inside the prism, 1 for one on a face +% and 2 for one on an edge of the prism. It is 0 for the other bar types. +% +% Example: +% bars = ldem.mesh.buildBars([2 2 2]); +% size(bars, 1) % 12 edges + 8 diagonals = 20 bars +% +% Legacy: CONECTI, EXTCO1, INTCO1, DIACO1 (connectivity) and the +% TYPES counter of RMECEX (classification). +% +% See also ldem.mesh.buildNodes, ldem.mesh.computeBarGeometry, +% ldem.material.buildBarProperties. + +arguments + nModules (1,3) double {mustBeInteger, mustBeGreaterThanOrEqual(nModules, 2)} +end + +M = nModules(1); N = nModules(2); L = nModules(3); +M1 = M - 1; N1 = N - 1; L1 = L - 1; +nGrid = M * N * L; + +% Grid-edge bars: node (i,j,k) joined to its neighbour along one axis. A bar +% along x lies on the surface of the prism when its j or k index is on a +% boundary, and so on for the other axes. +gridNode = @(i, j, k) (k - 1) * M * N + (j - 1) * M + i; +[edgesX, facesX] = edgeBars(gridNode, M1, N, L, 1, [M N L], [false true true]); +[edgesY, facesY] = edgeBars(gridNode, M, N1, L, M, [M N L], [true false true]); +[edgesZ, facesZ] = edgeBars(gridNode, M, N, L1, M * N, [M N L], [true true false]); + +% Centre-to-centre bars: centre (i,j,k) joined to its neighbour. +centreNode = @(i, j, k) nGrid + (k - 1) * M1 * N1 + (j - 1) * M1 + i; +[centresX, ~] = edgeBars(centreNode, M - 2, N1, L1, 1, [M N L], [false false false]); +[centresY, ~] = edgeBars(centreNode, M1, N - 2, L1, M1, [M N L], [false false false]); +[centresZ, ~] = edgeBars(centreNode, M1, N1, L - 2, M1 * N1, [M N L], [false false false]); + +% Diagonals: centre of every module to its 8 corners. +[i, j, k] = ndgrid(1:M1, 1:N1, 1:L1); +corner0 = gridNode(i(:), j(:), k(:)); % lowest corner of each module +centre = centreNode(i(:), j(:), k(:)); +offsets = [0, 1, M, M + 1, M * N, M * N + 1, M * N + M, M * N + M + 1]; +corners = (corner0 + offsets).'; % 8-by-nModulesTotal +starts = repmat(centre.', 8, 1); +diagonals = [starts(:), corners(:)]; + +bars = [edgesX; edgesY; edgesZ; centresX; centresY; centresZ; diagonals]; + +nGridEdges = size(edgesX, 1) + size(edgesY, 1) + size(edgesZ, 1); +nCentreBars = size(centresX, 1) + size(centresY, 1) + size(centresZ, 1); +barType = [ones(nGridEdges, 1); 2 * ones(nCentreBars, 1); 3 * ones(size(diagonals, 1), 1)]; +boundaryFaces = [facesX; facesY; facesZ; zeros(nCentreBars + size(diagonals, 1), 1)]; +end + +function [bars, boundaryFaces] = edgeBars(nodeNumber, nx, ny, nz, stride, nModules, countAxes) +%EDGEBARS Bars [n, n+stride] for every node n of an nx-by-ny-by-nz block. +% +% boundaryFaces counts, over the axes flagged in countAxes, how many of the +% indices i, j, k lie on the first or last node of the prism. +[i, j, k] = ndgrid(1:nx, 1:ny, 1:nz); +first = nodeNumber(i(:), j(:), k(:)); +bars = [first, first + stride]; + +index = [i(:), j(:), k(:)]; +onBoundary = index == 1 | index == nModules; % implicit expansion over columns +boundaryFaces = sum(onBoundary(:, countAxes), 2); +end diff --git a/src/+ldem/+mesh/buildMesh.m b/src/+ldem/+mesh/buildMesh.m new file mode 100644 index 0000000..f47ef06 --- /dev/null +++ b/src/+ldem/+mesh/buildMesh.m @@ -0,0 +1,60 @@ +function mesh = buildMesh(params, scenario) +%BUILDMESH Assemble the complete lattice model from the parameters. +% +% mesh = ldem.mesh.buildMesh(params) builds nodes, supports, masses, bars +% and bar geometry, using the scenario that matches params.testId. +% +% mesh = ldem.mesh.buildMesh(params, scenario) uses the given scenario +% object (a subclass of ldem.scenarios.Scenario). +% +% Inputs: +% params ldem.Parameters. +% scenario (optional) ldem.scenarios.Scenario. +% +% Output: +% mesh Struct with the fields +% nodes0 nNodes-by-3 initial coordinates [m] +% nGridNodes number of grid nodes (they come first, then the centres) +% fixed nNodes-by-3 logical, true where the motion is fixed +% mass nNodes-by-1 lumped masses [kg] +% bars nBars-by-2 end-node numbers +% barType nBars-by-1 codes: 1 grid edge, 2 centre-to-centre, 3 diagonal +% barBoundaryFaces nBars-by-1 prism faces a grid edge lies on (0, 1 or 2) +% barLength nBars-by-1 initial lengths [m] +% barCentres nBars-by-3 midpoints [m] +% scenarioData (only if the scenario has any) data prepared by scenario.prepare +% +% Example: +% params = ldem.Parameters(testId=101, nModules=[6 3 3]); +% mesh = ldem.mesh.buildMesh(params); +% fprintf("%d nodes, %d bars\n", size(mesh.nodes0, 1), size(mesh.bars, 1)); +% +% Legacy: the assembly stage of the main program (COORD, IMPERF, BOUND, +% NODMASS, CONECTI, CALAUX). +% +% See also ldem.mesh.buildNodes, ldem.mesh.buildBars, ldem.Parameters. + +arguments + params (1,1) ldem.Parameters + scenario (1,1) ldem.scenarios.Scenario = ldem.scenarios.fromTestId(params.testId) +end + +nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); +if params.meshPerturbation > 0 + nodes = ldem.mesh.perturbNodes(nodes, params.nModules, params.moduleLength, ... + params.seed, params.meshPerturbation); +end + +mesh = struct(); +mesh.nodes0 = nodes; +mesh.nGridNodes = prod(params.nModules); +mesh.fixed = scenario.fixedDofs(nodes, params); +scenarioData = scenario.prepare(nodes, mesh.fixed, params); +if ~isempty(fieldnames(scenarioData)) + mesh.scenarioData = scenarioData; +end +mesh.mass = ldem.mesh.computeNodalMasses(params.nModules, ... + params.moduleLength, params.density); +[mesh.bars, mesh.barType, mesh.barBoundaryFaces] = ldem.mesh.buildBars(params.nModules); +[mesh.barLength, mesh.barCentres] = ldem.mesh.computeBarGeometry(nodes, mesh.bars); +end diff --git a/src/+ldem/+mesh/buildNodes.m b/src/+ldem/+mesh/buildNodes.m new file mode 100644 index 0000000..6cb0545 --- /dev/null +++ b/src/+ldem/+mesh/buildNodes.m @@ -0,0 +1,45 @@ +function nodes = buildNodes(nModules, moduleLength) +%BUILDNODES Coordinates of the nodes of the regular lattice. +% +% nodes = ldem.mesh.buildNodes(nModules, moduleLength) returns the +% initial coordinates of all nodes of a prism of (M-1)*(N-1)*(L-1) cubic +% modules, where nModules = [M N L] is the number of nodes along x, y, z. +% +% The lattice has two kinds of nodes, numbered in this order: +% 1. Grid nodes, M*N*L of them, at the corners of the modules. Node +% number = (k-1)*M*N + (j-1)*M + i, so x varies fastest. +% 2. Centre nodes, (M-1)*(N-1)*(L-1) of them, one in the middle of each +% module. Numbered after the grid nodes, also with x fastest. +% +% Inputs: +% nModules [M N L], integers >= 2. +% moduleLength Edge length of a module [m]. +% +% Output: +% nodes nNodes-by-3 matrix [x y z] in metres. +% +% Example: +% nodes = ldem.mesh.buildNodes([3 3 3], 0.01); +% size(nodes) % 27 + 8 = 35 nodes +% +% Legacy: COORD, COORDSUB. +% +% See also ldem.mesh.buildBars, ldem.mesh.buildMesh. + +arguments + nModules (1,3) double {mustBeInteger, mustBeGreaterThanOrEqual(nModules, 2)} + moduleLength (1,1) double {mustBePositive, mustBeFinite} +end + +M = nModules(1); N = nModules(2); L = nModules(3); + +% Grid nodes: coordinates are (index - 1) * moduleLength. +[i, j, k] = ndgrid(1:M, 1:N, 1:L); +gridNodes = [i(:) - 1, j(:) - 1, k(:) - 1] * moduleLength; + +% Centre nodes: halfway between grid nodes, (index - 0.5) * moduleLength. +[i, j, k] = ndgrid(1:M-1, 1:N-1, 1:L-1); +centreNodes = [i(:) - 0.5, j(:) - 0.5, k(:) - 0.5] * moduleLength; + +nodes = [gridNodes; centreNodes]; +end diff --git a/src/+ldem/+mesh/computeBarGeometry.m b/src/+ldem/+mesh/computeBarGeometry.m new file mode 100644 index 0000000..013875d --- /dev/null +++ b/src/+ldem/+mesh/computeBarGeometry.m @@ -0,0 +1,51 @@ +function [barLength, barCentres] = computeBarGeometry(nodes, bars) +%COMPUTEBARGEOMETRY Length and midpoint of every bar. +% +% [barLength, barCentres] = ldem.mesh.computeBarGeometry(nodes, bars) +% returns the initial length [m] and the coordinates of the midpoint of +% each bar. +% +% Inputs: +% nodes nNodes-by-3 coordinates. +% bars nBars-by-2 node numbers, from ldem.mesh.buildBars. +% +% Outputs: +% barLength nBars-by-1 vector of lengths [m]. +% barCentres nBars-by-3 matrix of midpoints [x y z]. +% +% Errors: +% ldem:mesh:zeroLengthBar A bar has zero length (coincident nodes). +% +% Example: +% nodes = ldem.mesh.buildNodes([2 2 2], 1); +% bars = ldem.mesh.buildBars([2 2 2]); +% [len, mid] = ldem.mesh.computeBarGeometry(nodes, bars); +% +% Legacy: CALAUX. +% +% See also ldem.mesh.buildBars. + +arguments + nodes (:,3) double + bars (:,2) double {mustBeInteger, mustBePositive} +end + +if max(bars, [], 'all') > size(nodes, 1) + error('ldem:mesh:badConnectivity', ... + 'bars refers to node %d but there are only %d nodes.', ... + max(bars, [], 'all'), size(nodes, 1)); +end + +first = nodes(bars(:, 1), :); +second = nodes(bars(:, 2), :); +delta = second - first; + +barLength = sqrt(delta(:, 1).^2 + delta(:, 2).^2 + delta(:, 3).^2); +barCentres = (second + first) / 2.0; + +if any(barLength == 0) + error('ldem:mesh:zeroLengthBar', ... + '%d bar(s) have zero length (first one: bar %d).', ... + nnz(barLength == 0), find(barLength == 0, 1)); +end +end diff --git a/src/+ldem/+mesh/computeNodalMasses.m b/src/+ldem/+mesh/computeNodalMasses.m new file mode 100644 index 0000000..d31831c --- /dev/null +++ b/src/+ldem/+mesh/computeNodalMasses.m @@ -0,0 +1,49 @@ +function mass = computeNodalMasses(nModules, moduleLength, density) +%COMPUTENODALMASSES Lumped mass of every node. +% +% mass = ldem.mesh.computeNodalMasses(nModules, moduleLength, density) +% returns the mass [kg] associated with each node. +% +% Every module has a volume moduleLength^3 and contains one centre node +% and shares its 8 corners. A full-size mass is density*moduleLength^3/2 +% (half of the module volume per node type). Grid nodes on the surface of +% the prism have less material around them, so their mass is divided by 2 +% for each face they lie on: 1/2 on a face, 1/4 on an edge, 1/8 at a +% corner of the prism. Centre nodes always have the full mass. +% +% Inputs: +% nModules [M N L], integers >= 2. +% moduleLength Module edge length [m]. +% density Mass density [kg/m^3]. +% +% Output: +% mass nNodes-by-1 vector, in the node order of ldem.mesh.buildNodes. +% +% Example: +% m = ldem.mesh.computeNodalMasses([3 3 3], 0.01, 2000); +% sum(m) % total mass, close to density * volume +% +% Legacy: NODMASS. +% +% See also ldem.mesh.buildNodes. + +arguments + nModules (1,3) double {mustBeInteger, mustBeGreaterThanOrEqual(nModules, 2)} + moduleLength (1,1) double {mustBePositive, mustBeFinite} + density (1,1) double {mustBePositive, mustBeFinite} +end + +M = nModules(1); N = nModules(2); L = nModules(3); +fullMass = moduleLength * moduleLength * moduleLength * density / 2.0; + +% Grid nodes: halve the mass once for each face of the prism they touch. +[i, j, k] = ndgrid(1:M, 1:N, 1:L); +facesTouched = (k == 1 | k == L) + (j == 1 | j == N) + (i == 1 | i == M); +gridMass = fullMass * 2 .^ (-facesTouched(:)); + +% Centre nodes: full mass. +nCentres = prod(nModules - 1); +centreMass = fullMass * ones(nCentres, 1); + +mass = [gridMass; centreMass]; +end diff --git a/src/+ldem/+mesh/perturbNodes.m b/src/+ldem/+mesh/perturbNodes.m new file mode 100644 index 0000000..7aa3f1d --- /dev/null +++ b/src/+ldem/+mesh/perturbNodes.m @@ -0,0 +1,60 @@ +function nodes = perturbNodes(nodes, nModules, moduleLength, seed, cv) +%PERTURBNODES Add a random perturbation to the node coordinates. +% +% nodes = ldem.mesh.perturbNodes(nodes, nModules, moduleLength, seed, cv) +% displaces every node by a normally distributed random vector with +% standard deviation cv*moduleLength in each direction. Nodes close to the +% faces of the prism keep their original position, so the outer shape is +% preserved. +% +% The random numbers are generated with rng(seed) and drawn in the order +% x, y, z, so the result is reproducible. The global random stream is +% changed by this call. +% +% Inputs: +% nodes nNodes-by-3 coordinates, from ldem.mesh.buildNodes. +% nModules [M N L]. +% moduleLength Module edge length [m]. +% seed Seed of the random number generator. +% cv Standard deviation as a fraction of moduleLength. +% +% Output: +% nodes Perturbed coordinates (same size as the input). +% +% Note: the legacy code contains this feature but disables it (it sets +% LABELN=1 and immediately LABELN=0), so the legacy results correspond to +% no perturbation. ldem.Parameters.meshPerturbation is 0 (off) by default +% for the same reason; a positive value switches the perturbation on and is +% used as cv. +% +% Legacy: IMPERF. +% +% See also ldem.mesh.buildNodes. + +arguments + nodes (:,3) double + nModules (1,3) double + moduleLength (1,1) double + seed (1,1) double + cv (1,1) double {mustBeNonnegative} +end + +M1 = nModules(1) - 1; N1 = nModules(2) - 1; L1 = nModules(3) - 1; +nNodes = size(nodes, 1); + +original = nodes; +rng(seed); +perturbed = nodes; +for axis = 1:3 + perturbed(:, axis) = nodes(:, axis) + randn(nNodes, 1) * cv * moduleLength; +end + +% Keep the nodes near the faces of the prism where they were. +x = original(:, 1); y = original(:, 2); z = original(:, 3); +nearFace = (z >= (L1 - 1.01) * moduleLength) | (z <= 1.01 * moduleLength) | ... + (x >= (M1 - 1.01) * moduleLength) | (x <= 1.01 * moduleLength) | ... + (y >= (N1 - 1.01) * moduleLength) | (y <= 1.01 * moduleLength); +perturbed(nearFace, :) = original(nearFace, :); + +nodes = perturbed; +end diff --git a/src/+ldem/+mesh/summarizeModel.m b/src/+ldem/+mesh/summarizeModel.m new file mode 100644 index 0000000..8eb42b6 --- /dev/null +++ b/src/+ldem/+mesh/summarizeModel.m @@ -0,0 +1,61 @@ +function summary = summarizeModel(mesh, params) +%SUMMARIZEMODEL Size and mass of the model, for the results file. +% +% summary = ldem.mesh.summarizeModel(mesh, params) collects the counts that +% describe the lattice, so that a results file documents the model that was +% simulated. +% +% Fields of summary: +% +% testId Test number. +% nModules [Mx My Mz], number of cubic modules along x, y and z. +% moduleLength Edge of a module [m]. +% nNodes Total number of nodes. +% nGridNodes Nodes at the corners of the modules. +% nCentreNodes Nodes at the centre of the modules. +% nBars Total number of bars. +% nGridEdges Bars along the edges of the modules. +% nCentreBars Bars between neighbouring centre nodes. +% nDiagonals Bars from a centre node to a corner. +% nFixedDofs Number of degrees of freedom held by the scenario. +% totalMass Sum of the nodal masses [kg]. +% prismVolume Volume of the prism [m^3]. +% controlNodes Control nodes of the output. +% +% Inputs: +% mesh Struct from ldem.mesh.buildMesh. +% params ldem.Parameters. +% +% Output: +% summary Struct with the fields above. +% +% Example: +% model = ldem.mesh.summarizeModel(mesh, params); +% +% Legacy: the geometry and counting block of WRICON. +% +% See also ldem.mesh.buildMesh, ldem.material.summarizeMaterial. + +arguments + mesh (1,1) struct + params (1,1) ldem.Parameters +end + +modules = params.nModules - 1; + +summary = struct(); +summary.testId = params.testId; +summary.nModules = modules; +summary.moduleLength = params.moduleLength; +summary.nNodes = size(mesh.nodes0, 1); +summary.nGridNodes = mesh.nGridNodes; +summary.nCentreNodes = size(mesh.nodes0, 1) - mesh.nGridNodes; +summary.nBars = size(mesh.bars, 1); +summary.nGridEdges = nnz(mesh.barType == 1); +summary.nCentreBars = nnz(mesh.barType == 2); +summary.nDiagonals = nnz(mesh.barType == 3); +summary.nFixedDofs = nnz(mesh.fixed); +summary.totalMass = sum(mesh.mass); +summary.prismVolume = prod(modules) * params.moduleLength^3; +summary.controlNodes = params.controlNodes; +end diff --git a/src/+ldem/+post/plotEnergy.m b/src/+ldem/+post/plotEnergy.m new file mode 100644 index 0000000..115a322 --- /dev/null +++ b/src/+ldem/+post/plotEnergy.m @@ -0,0 +1,49 @@ +function ax = plotEnergy(results, ax) +%PLOTENERGY Plot the energies of a simulation versus time. +% +% ax = ldem.post.plotEnergy(results) draws the kinetic, elastic, damage and +% damping energies, their sum (internal) and the external work, in the +% current axes (a new figure if there are none). +% +% ax = ldem.post.plotEnergy(results, ax) draws in the given axes. +% +% Inputs: +% results Struct returned by ldem.runSimulation. +% ax (optional) Axes object. +% +% Output: +% ax The axes used. +% +% Errors: +% ldem:post:noData The results contain no energy history (set +% params.output.energyEvery > 0). +% +% Example: +% results = ldem.runSimulation(ldem.Parameters()); +% ldem.post.plotEnergy(results); +% +% See also ldem.post.plotReaction, ldem.runSimulation. + +arguments + results (1,1) struct + ax = [] +end + +e = results.energy; +if isempty(e.time) + error('ldem:post:noData', ... + 'The results contain no energy history. Set params.output.energyEvery to a positive number.'); +end +if isempty(ax) + ax = gca; +end + +plot(ax, e.time, e.kinetic, e.time, e.elastic, e.time, e.damage, e.time, e.damping, ... + e.time, e.internal, 'k--', e.time, e.external, 'r:', 'LineWidth', 1.2); +legend(ax, 'Kinetic', 'Elastic', 'Damage', 'Damping', 'Internal (sum)', 'External work', ... + 'Location', 'best'); +xlabel(ax, 'Time [s]'); +ylabel(ax, 'Energy [J]'); +title(ax, 'Energies'); +grid(ax, 'on'); +end diff --git a/src/+ldem/+post/plotReaction.m b/src/+ldem/+post/plotReaction.m new file mode 100644 index 0000000..6ebce5b --- /dev/null +++ b/src/+ldem/+post/plotReaction.m @@ -0,0 +1,50 @@ +function ax = plotReaction(results, ax) +%PLOTREACTION Plot the reaction force of the test versus time. +% +% ax = ldem.post.plotReaction(results) draws the components of the +% reaction force that are defined for the test of the simulation (for the +% beam test only the vertical one) in the current axes. +% +% ax = ldem.post.plotReaction(results, ax) draws in the given axes. +% +% Inputs: +% results Struct returned by ldem.runSimulation. +% ax (optional) Axes object. +% +% Output: +% ax The axes used. +% +% Errors: +% ldem:post:noData The test defines no reaction, or none was stored +% (set params.output.controlNodesEvery > 0). +% +% Example: +% results = ldem.runSimulation(ldem.Parameters(testId=102, nModules=[70 4 3])); +% ldem.post.plotReaction(results); +% +% See also ldem.post.plotEnergy, ldem.runSimulation. + +arguments + results (1,1) struct + ax = [] +end + +r = results.reactions; +defined = ~all(isnan(r.force), 1) & any(r.force ~= 0, 1); +if isempty(r.time) || ~any(defined) + error('ldem:post:noData', ... + ['The simulation has no reaction force: the test does not define one or ' ... + 'params.output.controlNodesEvery is 0.']); +end +if isempty(ax) + ax = gca; +end + +names = ["Rx", "Ry", "Rz"]; +plot(ax, r.time, r.force(:, defined), 'LineWidth', 1.2); +legend(ax, names(defined), 'Location', 'best'); +xlabel(ax, 'Time [s]'); +ylabel(ax, 'Reaction force [N]'); +title(ax, 'Reaction force'); +grid(ax, 'on'); +end diff --git a/src/+ldem/+scenarios/ClampedBeam.m b/src/+ldem/+scenarios/ClampedBeam.m new file mode 100644 index 0000000..fe998ed --- /dev/null +++ b/src/+ldem/+scenarios/ClampedBeam.m @@ -0,0 +1,133 @@ +classdef ClampedBeam < ldem.scenarios.Scenario + %CLAMPEDBEAM Beam clamped at both ends with a force at mid-span (TEST 103). + % + % The beam axis is z. The centre nodes of the first and of the last layer + % of modules are clamped (x, y and z fixed). A line of centre nodes at + % mid-span, on the face y = 0, is loaded with a force in the +y direction + % that grows linearly with time and stays constant after rampTime: + % + % F(t) = forceRate * min(t, rampTime) [N on each loaded node] + % + % This test loads with a force, not with a displacement: the scenario + % sets state.appliedForce and the solver counts its work in the external + % energy. + % + % The load position is measured in modules from the first clamped end + % and selects the line of centre nodes closest to it (a window of +-0.01 + % modules). The centre nodes lie at half-integer positions, so use values + % such as 24.5. The default, NaN, is half the beam length minus half a + % module, the position used by the original model. + % + % Create it with other values using + % scenario = ldem.scenarios.ClampedBeam(forceRate=2000, rampTime=2e-4); + % + % Origin: the bi-clamped beam model of Rodrigo (branch dev_rodrigo), which + % modified BOUND, CALOAD and ANSYS of the original code under TEST 102. + % + % See also ldem.scenarios.Scenario, ldem.scenarios.FourPointBending. + + properties (Constant) + testId = 103 + end + + properties + % Force growth rate on each loaded node [N/s]. + forceRate (1,1) double {mustBeFinite} = 1000 + + % Time at which the force stops growing and stays constant [s]. + rampTime (1,1) double {mustBePositive, mustBeFinite} = 0.00035 + + % Position of the load along the beam, from the first clamped end + % [modules]. NaN means mid-span, (L-1)/2 - 0.5. + loadPosition (1,1) double = NaN + + % Height of the loaded line above the face y = 0 [modules]. + loadHeight (1,1) double {mustBeNonnegative, mustBeFinite} = 0.5 + end + + methods + function obj = ClampedBeam(props) + %CLAMPEDBEAM Create the scenario, optionally with other values. + arguments + props.?ldem.scenarios.ClampedBeam + end + names = fieldnames(props); + for k = 1:numel(names) + obj.(names{k}) = props.(names{k}); + end + end + + function fixed = fixedDofs(obj, nodes0, params) + %FIXEDDOFS The two clamped end layers (x, y and z of their centre nodes). + arguments + obj (1,1) ldem.scenarios.ClampedBeam %#ok + nodes0 (:,3) double + params (1,1) ldem.Parameters + end + LCO = params.moduleLength; + L1 = params.nModules(3) - 1; + z = nodes0(:, 3); + tol = 0.01; + atStart = (z > (0.5 - tol) * LCO) & (z < (0.5 + tol) * LCO); + atEnd = (z > (L1 - 0.5 - tol) * LCO) & (z < (L1 - 0.5 + tol) * LCO); + fixed = false(size(nodes0)); + fixed(atStart | atEnd, :) = true; + end + + function loaded = loadedNodes(obj, nodes0, params) + %LOADEDNODES Logical vector of the nodes that carry the force. + % + % The centre nodes of the line at loadPosition along the beam + % and loadHeight above the face y = 0. Throws + % ldem:scenarios:noNodesSelected when there is none. + arguments + obj (1,1) ldem.scenarios.ClampedBeam + nodes0 (:,3) double + params (1,1) ldem.Parameters + end + LCO = params.moduleLength; + L1 = params.nModules(3) - 1; + position = obj.loadPosition; + if isnan(position) + position = L1 / 2 - 0.5; + end + tol = 0.01; + loaded = (nodes0(:, 3) > (position - tol) * LCO) & (nodes0(:, 3) < (position + tol) * LCO) & ... + (nodes0(:, 2) > (obj.loadHeight - tol) * LCO) & (nodes0(:, 2) < (obj.loadHeight + tol) * LCO); + if ~any(loaded) + error('ldem:scenarios:noNodesSelected', ... + ['The load line of the clamped beam matches no node. The beam has %d ' ... + 'modules along z; loadPosition = %g and loadHeight = %g (modules) must ' ... + 'fall on a line of centre nodes, e.g. 24.5 or 0.5, and lie inside the beam.'], ... + L1, position, obj.loadHeight); + end + end + + function state = applyLoads(obj, state, mesh, params) + %APPLYLOADS Set the force of the current time on the loaded nodes. + arguments + obj (1,1) ldem.scenarios.ClampedBeam + state (1,1) struct + mesh (1,1) struct + params (1,1) ldem.Parameters + end + loaded = obj.loadedNodes(mesh.nodes0, params); + state.appliedForce(:) = 0; + state.appliedForce(loaded, 2) = obj.forceRate * min(state.time, obj.rampTime); + end + + function reaction = reactions(obj, state, mesh, params) + %REACTIONS Force that the beam exerts on the clamped ends, [Rx Ry Rz]. + % + % The sum of the bar forces on the clamped degrees of freedom. At + % rest it equals the total applied force. + arguments + obj (1,1) ldem.scenarios.ClampedBeam %#ok + state (1,1) struct + mesh (1,1) struct + params (1,1) ldem.Parameters %#ok + end + reaction = sum(state.force .* mesh.fixed, 1); + end + end +end diff --git a/src/+ldem/+scenarios/Declarative.m b/src/+ldem/+scenarios/Declarative.m new file mode 100644 index 0000000..9d2126b --- /dev/null +++ b/src/+ldem/+scenarios/Declarative.m @@ -0,0 +1,339 @@ +classdef Declarative < ldem.scenarios.Scenario + %DECLARATIVE A test defined by supports and loads instead of by a class (type "custom"). + % + % The built-in scenarios (ldem.scenarios.UniaxialTension, ...) are fixed + % tests. This one is assembled from blocks, which is what the + % [[support]] and [[load]] sections of a case file read, so a new test is + % written as text, without programming: + % + % support Holds some degrees of freedom of the selected nodes at their + % initial position (a clamp, a roller, a symmetry plane). + % load Acts on one direction of the selected nodes, either as a force + % (N) or as a prescribed displacement (m, measured from the + % initial position). The value is a function of time: + % constant, linear, ramp or table (ldem.scenarios.timeFunction). + % + % Nodes are selected by kind ("all", "grid", "centre"), by number, and by + % coordinate ranges in modules, with the references min, max and mid + % (ldem.scenarios.selectNodes). A degree of freedom with a prescribed + % displacement is held by the solver, like the loaded nodes of the other + % tests. A block can ask to be part of the reaction: the reaction of the + % test is then, for each direction, the sum of the bar forces on the + % degrees of freedom of the blocks that asked for it; without any, the + % reaction is NaN. + % + % Build the blocks with the static methods makeSelector, makeSupport, + % makeLoad and makeFunction. For example, a beam clamped at z = 0.5 and + % pushed by a force that grows for 0.35 ms: + % + % import ldem.scenarios.Declarative + % end1 = Declarative.makeSelector(z = 0.5); + % mid = Declarative.makeSelector(y = 0.5, z = "mid - 0.5"); + % ramp = Declarative.makeFunction("ramp", rate = 1000, until = 3.5e-4); + % support = Declarative.makeSupport(end1, "xyz", reaction = true); + % load = Declarative.makeLoad(mid, "y", "force", ramp); + % scenario = Declarative(supports = support, loads = load); + % + % Selections use the regular lattice, so they do not change when the mesh + % is perturbed. A block that selects no node is an error + % (ldem:scenarios:noNodesSelected). + % + % See also ldem.scenarios.Scenario, ldem.scenarios.selectNodes, + % ldem.scenarios.timeFunction, ldem.scenarios.registry. + + properties (Constant) + testId = 900 + end + + properties + % Struct row of the supports, from makeSupport (fields name, selector, fix, reaction). + supports (1,:) struct = ldem.scenarios.Declarative.emptySupports() + + % Struct row of the loads, from makeLoad (fields name, selector, direction, type, fn, reaction). + loads (1,:) struct = ldem.scenarios.Declarative.emptyLoads() + end + + methods + function obj = Declarative(props) + %DECLARATIVE Create the scenario from lists of supports and loads. + arguments + props.?ldem.scenarios.Declarative + end + names = fieldnames(props); + for k = 1:numel(names) + obj.(names{k}) = props.(names{k}); + end + obj.check(); + end + + function check(obj) + %CHECK Verify the structure of the supports and loads. + % + % Throws ldem:scenarios:badDefinition when a block is malformed. + supportFields = ["name" "selector" "fix" "reaction"]; + loadFields = ["name" "selector" "direction" "type" "fn" "reaction"]; + if ~isempty(obj.supports) && ~isequal(sort(string(fieldnames(obj.supports)).'), sort(supportFields)) + error('ldem:scenarios:badDefinition', ... + 'supports must be built with Declarative.makeSupport (fields %s).', strjoin(supportFields, ', ')); + end + if ~isempty(obj.loads) && ~isequal(sort(string(fieldnames(obj.loads)).'), sort(loadFields)) + error('ldem:scenarios:badDefinition', ... + 'loads must be built with Declarative.makeLoad (fields %s).', strjoin(loadFields, ', ')); + end + end + + function fixed = fixedDofs(obj, nodes0, params) + %FIXEDDOFS Degrees of freedom held by the supports and by the displacement loads. + arguments + obj (1,1) ldem.scenarios.Declarative + nodes0 (:,3) double + params (1,1) ldem.Parameters + end + lattice = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + fixed = false(size(nodes0)); + for k = 1:numel(obj.supports) + block = obj.supports(k); + mask = obj.select(block, "support", k, params, lattice); + fixed(mask, block.fix) = true; + end + for k = 1:numel(obj.loads) + block = obj.loads(k); + if block.type == "displacement" + mask = obj.select(block, "load", k, params, lattice); + fixed(mask, block.direction) = true; + end + end + end + + function data = prepare(obj, nodes0, ~, params) + %PREPARE Nodes of every load and of the reaction, found once. + % + % Returns a struct with loadNodes (cell, the node numbers of each + % load), reactionNodes (1-by-3 cell, the nodes whose force is + % summed in each direction) and hasReaction. + lattice = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + loadNodes = cell(1, numel(obj.loads)); + marked = false(size(nodes0)); + for k = 1:numel(obj.supports) + block = obj.supports(k); + if block.reaction + mask = obj.select(block, "support", k, params, lattice); + marked(mask, block.fix) = true; + end + end + for k = 1:numel(obj.loads) + block = obj.loads(k); + mask = obj.select(block, "load", k, params, lattice); + loadNodes{k} = find(mask); + if block.reaction + marked(mask, block.direction) = true; + end + end + data = struct('loadNodes', {loadNodes}, ... + 'reactionNodes', {{find(marked(:, 1)), find(marked(:, 2)), find(marked(:, 3))}}, ... + 'hasReaction', any(marked, 'all')); + end + + function state = applyLoads(obj, state, mesh, params) + %APPLYLOADS Set the forces and the prescribed displacements of the current time. + arguments + obj (1,1) ldem.scenarios.Declarative + state (1,1) struct + mesh (1,1) struct + params (1,1) ldem.Parameters + end + if isempty(obj.loads) + return + end + data = obj.dataOf(mesh, params); + hasForce = false; + for k = 1:numel(obj.loads) + hasForce = hasForce || obj.loads(k).type == "force"; + end + if hasForce + state.appliedForce(:) = 0; + end + for k = 1:numel(obj.loads) + block = obj.loads(k); + nodes = data.loadNodes{k}; + value = ldem.scenarios.timeFunction(block.fn, state.time); + if block.type == "force" + state.appliedForce(nodes, block.direction) = state.appliedForce(nodes, block.direction) + value; + else + state.displacement(nodes, block.direction) = mesh.nodes0(nodes, block.direction) + value; + end + end + end + + function reaction = reactions(obj, state, mesh, params) + %REACTIONS Sum of the bar forces on the degrees of freedom marked with reaction = true. + arguments + obj (1,1) ldem.scenarios.Declarative + state (1,1) struct + mesh (1,1) struct + params (1,1) ldem.Parameters + end + data = obj.dataOf(mesh, params); + if ~data.hasReaction + reaction = NaN(1, 3); + return + end + reaction = zeros(1, 3); + for direction = 1:3 + reaction(direction) = sum(state.force(data.reactionNodes{direction}, direction)); + end + end + end + + methods (Access = private) + function mask = select(~, block, kind, index, params, lattice) + %SELECT Selected nodes of a block; an empty selection is an error. + mask = ldem.scenarios.selectNodes(block.selector, params, lattice); + if ~any(mask) + label = "[[" + kind + "]] number " + string(index); + if block.name ~= "" + label = label + " (""" + block.name + """)"; + end + message = sprintf(['The %s matches no node. The prism has %d x %d x %d modules; ' ... + 'positions are in modules (centre nodes lie at half-integer positions ' ... + 'such as 0.5, grid nodes at integers), and "min", "max" and "mid" refer ' ... + 'to the ends and the middle of the prism.'], label, params.nModules - 1); + error('ldem:scenarios:noNodesSelected', '%s', message); + end + end + + function data = dataOf(obj, mesh, params) + if isfield(mesh, 'scenarioData') && isfield(mesh.scenarioData, 'loadNodes') + data = mesh.scenarioData; + else + data = obj.prepare(mesh.nodes0, mesh.fixed, params); + end + end + end + + methods (Static) + function selector = makeSelector(options) + %MAKESELECTOR Selector of nodes for a support or a load. + % + % selector = Declarative.makeSelector(Name=Value) with + % + % nodes "all" (default), "grid" or "centre". + % ids Node numbers. + % x, y, z Coordinate or range in modules, see + % ldem.scenarios.parseCoordinate: 0.5, "max - 0.5", + % [0 5]. + arguments + options.nodes (1,1) string {mustBeMember(options.nodes, ["all" "grid" "centre"])} = "all" + options.ids (1,:) double {mustBeInteger, mustBePositive} = zeros(1, 0) + options.x = [] + options.y = [] + options.z = [] + end + selector = struct('nodes', options.nodes, 'ids', options.ids, ... + 'x', coordinate(options.x), 'y', coordinate(options.y), 'z', coordinate(options.z)); + end + + function block = makeSupport(selector, fix, options) + %MAKESUPPORT Support block: the directions in fix are held. + % + % support = Declarative.makeSupport(selector, fix, Name=Value). fix + % is the directions to hold, as text ("xyz", "x", "xz") or a + % string array (["x" "z"]). Options: name (label) and reaction + % (true to include the block in the reaction of the test). + arguments + selector (1,1) struct + fix (1,:) string + options.name (1,1) string = "" + options.reaction (1,1) logical = false + end + block = struct('name', options.name, 'selector', selector, ... + 'fix', directions(fix), 'reaction', options.reaction); + end + + function block = makeLoad(selector, direction, type, fn, options) + %MAKELOAD Load block: a force or a displacement along one direction. + % + % load = Declarative.makeLoad(selector, direction, type, fn, Name=Value) + % with direction "x", "y" or "z", type "force" or "displacement", + % fn from Declarative.makeFunction. Options: name and reaction. + arguments + selector (1,1) struct + direction (1,1) string {mustBeMember(direction, ["x" "y" "z"])} + type (1,1) string {mustBeMember(type, ["force" "displacement"])} + fn (1,1) struct + options.name (1,1) string = "" + options.reaction (1,1) logical = false + end + block = struct('name', options.name, 'selector', selector, ... + 'direction', directions(direction), 'type', type, 'fn', fn, ... + 'reaction', options.reaction); + end + + function fn = makeFunction(type, options) + %MAKEFUNCTION Time function of a load, see ldem.scenarios.timeFunction. + % + % fn = Declarative.makeFunction("constant", value=...) + % fn = Declarative.makeFunction("linear", rate=...) + % fn = Declarative.makeFunction("ramp", rate=..., until=...) + % fn = Declarative.makeFunction("table", times=[...], values=[...]) + % + % All in SI units (N or m, N/s or m/s, s). + arguments + type (1,1) string {mustBeMember(type, ["constant" "linear" "ramp" "table"])} + options.value (1,1) double {mustBeFinite} = 0 + options.rate (1,1) double {mustBeFinite} = 0 + options.until (1,1) double {mustBePositive} = Inf + options.times (1,:) double {mustBeFinite} = zeros(1, 0) + options.values (1,:) double {mustBeFinite} = zeros(1, 0) + end + if type == "ramp" && ~isfinite(options.until) + error('ldem:scenarios:badDefinition', 'A ramp needs the time "until" at which it stops growing.'); + end + if type == "table" + if numel(options.times) < 2 || numel(options.times) ~= numel(options.values) ... + || any(diff(options.times) <= 0) + error('ldem:scenarios:badDefinition', ... + ['A table needs at least two strictly increasing times and one value per ' ... + 'time (got %d times and %d values).'], numel(options.times), numel(options.values)); + end + end + fn = struct('type', type, 'value', options.value, 'rate', options.rate, ... + 'until', options.until, 'times', options.times, 'values', options.values); + end + + function s = emptySupports() + %EMPTYSUPPORTS Zero supports. + s = repmat(struct('name', "", 'selector', [], 'fix', [], 'reaction', false), 1, 0); + end + + function s = emptyLoads() + %EMPTYLOADS Zero loads. + s = repmat(struct('name', "", 'selector', [], 'direction', [], 'type', "", 'fn', [], 'reaction', false), 1, 0); + end + end +end + +function range = coordinate(value) +if isempty(value) + range = []; +else + range = ldem.scenarios.parseCoordinate(value); +end +end + +function indices = directions(text) +%DIRECTIONS Direction letters ("xz" or ["x" "z"]) as column indices 1..3. +letters = char(join(text, "")); +indices = zeros(1, 0); +for c = lower(letters) + k = find('xyz' == c, 1); + if isempty(k) + error('ldem:scenarios:badDefinition', 'Directions are x, y and z, got "%s".', c); + end + indices(end+1) = k; %#ok +end +indices = unique(indices); +if isempty(indices) + error('ldem:scenarios:badDefinition', 'At least one direction (x, y or z) is needed.'); +end +end diff --git a/src/+ldem/+scenarios/FourPointBending.m b/src/+ldem/+scenarios/FourPointBending.m new file mode 100644 index 0000000..1a58f2b --- /dev/null +++ b/src/+ldem/+scenarios/FourPointBending.m @@ -0,0 +1,145 @@ +classdef FourPointBending < ldem.scenarios.Scenario + %FOURPOINTBENDING Beam with two supports and two load points (TEST 102). + % + % The beam is supported near both ends on the bottom face. Two load + % points on the top face are moved down with a constant velocity. + % + % Positions are measured in modules along the beam axis, from the nearest + % end of the beam, and select the line of centre nodes closest to that + % position (windows of +-0.01 modules). Because the centre nodes lie at + % half-integer positions, use values such as 4.5 or 33.5. The defaults are + % the values of the legacy code, which only fit a beam longer than about + % 70 modules. If a position does not match any node, fixedDofs throws + % ldem:scenarios:noNodesSelected. + % + % Create it with other values using + % scenario = ldem.scenarios.FourPointBending( ... + % supportPosition=2.5, loadPosition=10.5, loadingVelocity=1e-3); + % + % Legacy: the "TEST == 102" branches of BOUND, CALOAD and CALRES. The + % legacy CALOAD only moved the right load point (a wrong condition left the + % other one acting as a support); this was corrected in the original code and here + % (docs/known-issues/KNOWN_ISSUES.md, item 15). + % + % See also ldem.scenarios.Scenario. + + properties (Constant) + testId = 102 + end + + properties + % Downward velocity of the loaded nodes [m/s]. Legacy: VF2 = 400e-5. + loadingVelocity (1,1) double {mustBeFinite} = 400e-5 + + % Distance from each end of the beam to the support [modules]. + supportPosition (1,1) double {mustBePositive, mustBeFinite} = 4.5 + + % Distance from each end of the beam to the load point [modules]. + loadPosition (1,1) double {mustBePositive, mustBeFinite} = 33.5 + end + + methods + function obj = FourPointBending(props) + %FOURPOINTBENDING Create the scenario, optionally with other values. + arguments + props.?ldem.scenarios.FourPointBending + end + names = fieldnames(props); + for k = 1:numel(names) + obj.(names{k}) = props.(names{k}); + end + end + + function fixed = fixedDofs(obj, nodes0, params) + %FIXEDDOFS Supports and load points of the beam. + % + % Fixes x and y at the left support, y at the right support and + % y at the two load points on the top face (the y-motion of the + % load points is then imposed by applyLoads). + arguments + obj (1,1) ldem.scenarios.FourPointBending + nodes0 (:,3) double + params (1,1) ldem.Parameters + end + s = obj.selectNodes(nodes0, params); + fixed = false(size(nodes0)); + fixed(s.leftSupport, 1) = true; + fixed(s.leftSupport | s.rightSupport | s.loadLeft | s.loadRight, 2) = true; + end + + function loaded = loadedNodes(obj, nodes0, params) + %LOADEDNODES Logical vector of the nodes that are moved down. + % + % The centre nodes of the two load lines on the top face. + arguments + obj (1,1) ldem.scenarios.FourPointBending + nodes0 (:,3) double + params (1,1) ldem.Parameters + end + s = obj.selectNodes(nodes0, params); + loaded = s.loadLeft | s.loadRight; + end + + function state = applyLoads(obj, state, mesh, params) + %APPLYLOADS Move the loaded nodes to y0 - loadingVelocity*time. + arguments + obj (1,1) ldem.scenarios.FourPointBending + state (1,1) struct + mesh (1,1) struct + params (1,1) ldem.Parameters + end + loaded = obj.loadedNodes(mesh.nodes0, params); + state.displacement(loaded, 2) = mesh.nodes0(loaded, 2) - obj.loadingVelocity * state.time; + end + + function reaction = reactions(obj, state, mesh, params) + %REACTIONS Vertical force carried by the nodes held in y at the top. + % + % Returns [0 Ry 0] where Ry is the sum of the y-component of the + % bar forces on the nodes held in y whose initial height is + % (N-1.51) modules or more, that is, the load points. + arguments + obj (1,1) ldem.scenarios.FourPointBending %#ok + state (1,1) struct + mesh (1,1) struct + params (1,1) ldem.Parameters + end + N1 = params.nModules(2) - 1; + atTop = mesh.fixed(:, 2) & (mesh.nodes0(:, 2) >= params.moduleLength * (N1 - 0.51)); + reaction = [0, sum(state.force(atTop, 2)), 0]; + end + end + + methods (Access = private) + function s = selectNodes(obj, nodes0, params) + %SELECTNODES Masks of the support and load nodes; errors if one is empty. + LCO = params.moduleLength; + M1 = params.nModules(1) - 1; + N1 = params.nModules(2) - 1; + x = nodes0(:, 1); + y = nodes0(:, 2); + tol = 0.01; + + atBottom = (y > (0.5 - tol) * LCO) & (y < (0.5 + tol) * LCO); + atTop = (y > (N1 - 0.5 - tol) * LCO) & (y < (N1 - 0.5 + tol) * LCO); + nearLeft = @(position) (x > (position - tol) * LCO) & (x < (position + tol) * LCO); + nearRight = @(position) (x > (M1 - position - tol) * LCO) & (x < (M1 - position + tol) * LCO); + + s.leftSupport = atBottom & nearLeft(obj.supportPosition); + s.rightSupport = atBottom & nearRight(obj.supportPosition); + s.loadLeft = atTop & nearLeft(obj.loadPosition); + s.loadRight = atTop & nearRight(obj.loadPosition); + + for name = fieldnames(s).' + if ~any(s.(name{1})) + error('ldem:scenarios:noNodesSelected', ... + ['The %s of the beam test matches no node. The beam has %d modules ' ... + 'along x; supportPosition = %g and loadPosition = %g (modules from ' ... + 'each end) must fall on a line of centre nodes, e.g. 4.5 or 33.5, ' ... + 'and lie inside the beam.'], ... + name{1}, M1, obj.supportPosition, obj.loadPosition); + end + end + end + end +end diff --git a/src/+ldem/+scenarios/Scenario.m b/src/+ldem/+scenarios/Scenario.m new file mode 100644 index 0000000..1fea1dc --- /dev/null +++ b/src/+ldem/+scenarios/Scenario.m @@ -0,0 +1,79 @@ +classdef (Abstract) Scenario + %SCENARIO Base class of the test cases (supports, loads and reactions). + % + % A scenario defines everything that is specific to one kind of test: + % which degrees of freedom are fixed, how the load is applied at every + % time step and which reaction force is reported. The solver never + % checks the test number; it asks the scenario. + % + % To add a new test, create a subclass in this folder: + % 1. Set the constant property testId to a new number. + % 2. Implement fixedDofs and applyLoads. + % 3. Optionally override reactions. + % 4. Register the class in ldem.scenarios.registry (one line with its + % name for the case files, its test number and the units of the + % properties that a case file may set). + % + % See also ldem.scenarios.UniaxialTension, + % ldem.scenarios.FourPointBending, ldem.scenarios.ClampedBeam, + % ldem.scenarios.fromTestId. + + properties (Abstract, Constant) + % Number that identifies the scenario in the input file (TEST). + testId + end + + methods (Abstract) + % FIXEDDOFS Degrees of freedom held at their initial position. + % + % fixed = scenario.fixedDofs(nodes0, params) returns an + % nNodes-by-3 logical matrix; fixed(n, d) is true when node n is + % not allowed to move in direction d (1 = x, 2 = y, 3 = z). + % + % Inputs: + % nodes0 nNodes-by-3 initial coordinates [m]. + % params ldem.Parameters. + fixed = fixedDofs(obj, nodes0, params) + + % APPLYLOADS Impose the loading of the current time step. + % + % state = scenario.applyLoads(state, mesh, params) modifies the + % current displacements (state.displacement) of the loaded nodes + % for the time state.time. It is called once per step, before the + % bar forces are computed. + % + % A scenario that loads with forces instead of displacements sets + % state.appliedForce (nNodes-by-3, in N) here; the solver adds it + % to the bar forces and counts its work in the external energy. + % Displacement-controlled scenarios leave it untouched (zeros). + % + % Inputs: + % state Solver state, see ldem.solver.initialState. + % mesh Struct from ldem.mesh.buildMesh. + % params ldem.Parameters. + state = applyLoads(obj, state, mesh, params) + end + + methods + function data = prepare(obj, nodes0, fixed, params) %#ok + %PREPARE Data that depends only on the mesh, computed once. + % + % data = scenario.prepare(nodes0, fixed, params) is called once by + % ldem.mesh.buildMesh; a non-empty struct is stored in + % mesh.scenarioData so that applyLoads and reactions do not have to + % find the loaded nodes again at every step. The default is an empty + % struct (nothing to prepare). + data = struct(); + end + + function reaction = reactions(obj, state, mesh, params) %#ok + %REACTIONS Reaction force of the test as [Rx Ry Rz] [N]. + % + % reaction = scenario.reactions(state, mesh, params) returns the + % force that the test reports for the current step. The + % default is NaN(1,3), meaning "not defined for this test"; + % subclasses override it. + reaction = NaN(1, 3); + end + end +end diff --git a/src/+ldem/+scenarios/UniaxialTension.m b/src/+ldem/+scenarios/UniaxialTension.m new file mode 100644 index 0000000..a076850 --- /dev/null +++ b/src/+ldem/+scenarios/UniaxialTension.m @@ -0,0 +1,94 @@ +classdef UniaxialTension < ldem.scenarios.Scenario + %UNIAXIALTENSION Prism loaded by a prescribed axial displacement (TEST 101). + % + % The centre nodes of the last column of the prism are moved along x + % with a constant velocity, while the centre nodes of the first column + % are held in x. The loaded nodes are also held in x, so the prescribed + % displacement is exact and the energy balance of the simulation closes + % (the work done on them is the external work). + % + % Sign convention (as in the legacy code): the loaded nodes move to + % x0 - loadingVelocity*time, so a positive loadingVelocity pushes them + % toward the fixed end and COMPRESSES the prism. Use a negative value + % to pull it. The comment of the legacy code says "tension". + % + % Create it with a different velocity using + % scenario = ldem.scenarios.UniaxialTension(loadingVelocity=1e-3); + % + % Legacy: the "TEST == 101" branches of BOUND and CALOAD. The legacy + % BOUND wrote the right-end condition with a misplaced parenthesis, so it + % selected no node and the loaded nodes were not held; this was corrected + % in the original code and here (docs/known-issues/KNOWN_ISSUES.md, items 3 and 19). + % + % See also ldem.scenarios.Scenario. + + properties (Constant) + testId = 101 + end + + properties + % Velocity of the loaded nodes along -x [m/s]. Legacy: VF2 = 400e-5. + loadingVelocity (1,1) double {mustBeFinite} = 400e-5 + end + + methods + function obj = UniaxialTension(props) + %UNIAXIALTENSION Create the scenario, optionally with a new velocity. + arguments + props.?ldem.scenarios.UniaxialTension + end + names = fieldnames(props); + for k = 1:numel(names) + obj.(names{k}) = props.(names{k}); + end + end + + function fixed = fixedDofs(obj, nodes0, params) + %FIXEDDOFS Fix the x-motion of the centre nodes of both end faces. + % + % The first column of centre nodes is the support and the last + % column is the loaded one (its x-motion is imposed by applyLoads). + arguments + obj (1,1) ldem.scenarios.UniaxialTension %#ok + nodes0 (:,3) double + params (1,1) ldem.Parameters + end + LCO = params.moduleLength; + M1 = params.nModules(1) - 1; + x = nodes0(:, 1); + + leftEnd = (x < (0.51 * LCO)) & (x > (0.49 * LCO)); + rightEnd = (x > ((M1 - 0.51) * LCO)) & (x < ((M1 - 0.49) * LCO)); + + fixed = false(size(nodes0)); + fixed(leftEnd | rightEnd, 1) = true; + end + + function loaded = loadedNodes(obj, nodes0, params) + %LOADEDNODES Logical vector of the nodes with prescribed motion. + % + % They are the centre nodes of the last column of modules. + arguments + obj (1,1) ldem.scenarios.UniaxialTension %#ok + nodes0 (:,3) double + params (1,1) ldem.Parameters + end + LCO = params.moduleLength; + M1 = params.nModules(1) - 1; + x = nodes0(:, 1); + loaded = (x < (M1 - 0.49) * LCO) & (x > (M1 - 0.51) * LCO); + end + + function state = applyLoads(obj, state, mesh, params) + %APPLYLOADS Move the loaded nodes to x0 - loadingVelocity*time. + arguments + obj (1,1) ldem.scenarios.UniaxialTension + state (1,1) struct + mesh (1,1) struct + params (1,1) ldem.Parameters + end + loaded = obj.loadedNodes(mesh.nodes0, params); + state.displacement(loaded, 1) = mesh.nodes0(loaded, 1) - obj.loadingVelocity * state.time; + end + end +end diff --git a/src/+ldem/+scenarios/coordinateText.m b/src/+ldem/+scenarios/coordinateText.m new file mode 100644 index 0000000..32cf36b --- /dev/null +++ b/src/+ldem/+scenarios/coordinateText.m @@ -0,0 +1,55 @@ +function text = coordinateText(range) +%COORDINATETEXT Write a coordinate range as it appears in a case file. +% +% text = ldem.scenarios.coordinateText(range) is the inverse of +% ldem.scenarios.parseCoordinate: 0.5, "max - 0.5", [0, 5] or +% ["min + 0.5", "max - 0.5"]. The text can be written after "x = ". +% +% Input: +% range Struct with lo and hi, from ldem.scenarios.parseCoordinate. +% +% Output: +% text String scalar. +% +% Example: +% r = ldem.scenarios.parseCoordinate("mid - 0.5"); +% ldem.scenarios.coordinateText(r) % "mid - 0.5" (with quotes) +% +% See also ldem.scenarios.parseCoordinate. + +arguments + range (1,1) struct +end + +if isequal(range.lo, range.hi) + text = scalarText(range.lo); + return +end +if range.lo.base == "" && range.hi.base == "" + text = "[" + ldem.schema.shortestText(range.lo.offset) + ", " ... + + ldem.schema.shortestText(range.hi.offset) + "]"; +else + text = "[" + quoted(range.lo) + ", " + quoted(range.hi) + "]"; +end +end + +function text = scalarText(spec) +if spec.base == "" + text = ldem.schema.shortestText(spec.offset); +else + text = quoted(spec); +end +end + +function text = quoted(spec) +if spec.base == "" + body = ldem.schema.shortestText(spec.offset); +elseif spec.offset == 0 + body = spec.base; +elseif spec.offset > 0 + body = spec.base + " + " + ldem.schema.shortestText(spec.offset); +else + body = spec.base + " - " + ldem.schema.shortestText(-spec.offset); +end +text = '"' + body + '"'; +end diff --git a/src/+ldem/+scenarios/fromName.m b/src/+ldem/+scenarios/fromName.m new file mode 100644 index 0000000..005b13f --- /dev/null +++ b/src/+ldem/+scenarios/fromName.m @@ -0,0 +1,32 @@ +function scenario = fromName(name) +%FROMNAME Create the scenario object with a name used in the case files. +% +% scenario = ldem.scenarios.fromName(name) returns an instance, with its +% default values, of the scenario registered under name in +% ldem.scenarios.registry: "uniaxial_tension", "four_point_bending" or +% "clamped_beam". +% +% Input: +% name Scenario name (case is ignored). +% +% Output: +% scenario Object of a subclass of ldem.scenarios.Scenario. +% +% Errors: +% ldem:scenarios:unknownName No scenario has that name. +% +% See also ldem.scenarios.registry, ldem.scenarios.fromTestId. + +arguments + name (1,1) string +end + +reg = ldem.scenarios.registry(); +k = find([reg.name] == lower(name), 1); +if isempty(k) + error('ldem:scenarios:unknownName', ... + 'There is no scenario named "%s".%s Available: %s.', name, ... + ldem.schema.suggest(name, [reg.name]), strjoin([reg.name], ', ')); +end +scenario = feval(reg(k).className); +end diff --git a/src/+ldem/+scenarios/fromTestId.m b/src/+ldem/+scenarios/fromTestId.m new file mode 100644 index 0000000..9737bad --- /dev/null +++ b/src/+ldem/+scenarios/fromTestId.m @@ -0,0 +1,36 @@ +function scenario = fromTestId(testId) +%FROMTESTID Create the scenario object for a test number. +% +% scenario = ldem.scenarios.fromTestId(testId) returns an instance of the +% scenario class registered for testId: +% +% 101 ldem.scenarios.UniaxialTension +% 102 ldem.scenarios.FourPointBending +% 103 ldem.scenarios.ClampedBeam +% +% To register a new scenario, add a line to ldem.scenarios.registry. +% +% Input: +% testId Test number (Parameters.testId). +% +% Output: +% scenario Object of a subclass of ldem.scenarios.Scenario. +% +% Errors: +% ldem:scenarios:unknownTest No scenario has that number. +% +% See also ldem.scenarios.Scenario, ldem.scenarios.registry. + +arguments + testId (1,1) double +end + +reg = ldem.scenarios.registry(); +k = find([reg.testId] == testId, 1); +if isempty(k) + error('ldem:scenarios:unknownTest', ... + 'There is no scenario for testId = %g. Available: %s.', ... + testId, strjoin(string([reg.testId]), ', ')); +end +scenario = feval(reg(k).className); +end diff --git a/src/+ldem/+scenarios/parseCoordinate.m b/src/+ldem/+scenarios/parseCoordinate.m new file mode 100644 index 0000000..97e1bcb --- /dev/null +++ b/src/+ldem/+scenarios/parseCoordinate.m @@ -0,0 +1,84 @@ +function range = parseCoordinate(value, where) +%PARSECOORDINATE Read a coordinate or a range of coordinates, in modules. +% +% range = ldem.scenarios.parseCoordinate(value) converts what a case file +% gives for the key x, y or z of a [[support]] or [[load]] block into the +% range of positions it selects. The value is +% +% * a number, in modules: 0.5 (a plane of nodes); +% * a text with a number: "0.5" or "0.5 modules"; +% * a text with a reference to the prism, "min", "max" or "mid", and an +% optional offset: "max - 0.5", "mid", "min + 1" (min is 0, max is the +% length of the prism along that axis in modules, mid is half of it); +% * a pair of any of the above, [lo, hi], for the nodes in between (all +% numbers, or all texts). +% +% Inputs: +% value Number, text, or a 2-element numeric or string array. +% where Optional location text for the error messages. +% +% Output: +% range Struct with the fields lo and hi (equal for a single value). Each +% is a struct with base ("", "min", "max" or "mid") and offset +% (modules). +% +% Errors: +% ldem:case:badValue The value is not one of the forms above. +% +% Example: +% r = ldem.scenarios.parseCoordinate("max - 0.5"); +% r.lo.base % "max" +% r.lo.offset % -0.5 +% +% See also ldem.scenarios.coordinateText, ldem.scenarios.selectNodes. + +arguments + value + where (1,1) string = "" +end + +if numel(value) == 1 + range = struct('lo', parseOne(value, where), 'hi', parseOne(value, where)); +elseif numel(value) == 2 && (isnumeric(value) || isstring(value)) + range = struct('lo', parseOne(value(1), where), 'hi', parseOne(value(2), where)); +else + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a coordinate or a pair [lo, hi] in modules.'); +end +end + +function spec = parseOne(value, where) +if isnumeric(value) && isscalar(value) && isfinite(value) + spec = struct('base', "", 'offset', double(value)); + return +end +if ~(isstring(value) && isscalar(value)) + ldem.schema.raise('ldem:case:badValue', where, ... + 'Expected a number or a text such as "max - 0.5" (modules).'); +end +text = regexprep(lower(strtrim(value)), '\s*modules?$', ''); +number = '[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?'; +reference = regexp(text, '^(min|max|mid)(.*)$', 'tokens', 'once'); +if ~isempty(reference) + base = string(reference{1}); + rest = strtrim(string(reference{2})); + offset = 0; + if rest ~= "" + parts = regexp(rest, ['^([+-])\s*(' number ')$'], 'tokens', 'once'); + if isempty(parts) + ldem.schema.raise('ldem:case:badValue', where, ... + '"%s" is not a coordinate; use "min", "max" or "mid" with an optional offset ("max - 0.5").', value); + end + offset = str2double(parts{2}); + if parts{1} == "-" + offset = -offset; + end + end + spec = struct('base', base, 'offset', offset); +elseif ~isempty(regexp(text, ['^' number '$'], 'once')) + spec = struct('base', "", 'offset', str2double(text)); +else + ldem.schema.raise('ldem:case:badValue', where, ... + '"%s" is not a coordinate; use a number or "min", "max" or "mid" with an optional offset ("max - 0.5").', value); +end +end diff --git a/src/+ldem/+scenarios/registry.m b/src/+ldem/+scenarios/registry.m new file mode 100644 index 0000000..353a375 --- /dev/null +++ b/src/+ldem/+scenarios/registry.m @@ -0,0 +1,47 @@ +function reg = registry() +%REGISTRY List of the available scenarios (test cases). +% +% reg = ldem.scenarios.registry() returns one element per scenario class. +% It is the only place that has to be edited to register a new scenario: +% ldem.scenarios.fromTestId, ldem.scenarios.fromName and the case-file +% reader (the [scenario] section) all read it. +% +% Fields of every element: +% +% name Name used in the case file, "type = ..." (snake_case). +% className Name of the class, a subclass of ldem.scenarios.Scenario. +% testId Value of the constant property testId of the class. +% units Struct mapping each property a case file may set to its dimension (key in the file: snake_case, forceRate is force_rate). +% keywords Struct mapping a property to a word that stands for NaN in the file (ClampedBeam.loadPosition: "midspan"). +% +% Output: +% reg Struct array. +% +% Example: +% reg = ldem.scenarios.registry(); +% [reg.name] % "uniaxial_tension" "four_point_bending" ... +% +% See also ldem.scenarios.Scenario, ldem.scenarios.fromTestId, +% ldem.scenarios.fromName. + +reg = struct('name', {}, 'className', {}, 'testId', {}, 'units', {}, 'keywords', {}); + +reg(end+1) = makeEntry("uniaxial_tension", "ldem.scenarios.UniaxialTension", 101, ... + struct('loadingVelocity', "velocity"), struct()); + +reg(end+1) = makeEntry("four_point_bending", "ldem.scenarios.FourPointBending", 102, ... + struct('loadingVelocity', "velocity", 'supportPosition', "modules", ... + 'loadPosition', "modules"), struct()); + +reg(end+1) = makeEntry("custom", "ldem.scenarios.Declarative", 900, struct(), struct()); + +reg(end+1) = makeEntry("clamped_beam", "ldem.scenarios.ClampedBeam", 103, ... + struct('forceRate', "forcerate", 'rampTime', "time", ... + 'loadPosition', "modules", 'loadHeight', "modules"), ... + struct('loadPosition', "midspan")); +end + +function entry = makeEntry(name, className, testId, units, keywords) +entry = struct('name', name, 'className', className, 'testId', testId, ... + 'units', units, 'keywords', keywords); +end diff --git a/src/+ldem/+scenarios/selectNodes.m b/src/+ldem/+scenarios/selectNodes.m new file mode 100644 index 0000000..5d37af0 --- /dev/null +++ b/src/+ldem/+scenarios/selectNodes.m @@ -0,0 +1,84 @@ +function mask = selectNodes(selector, params, nodes) +%SELECTNODES Nodes picked by the selector of a [[support]] or [[load]] block. +% +% mask = ldem.scenarios.selectNodes(selector, params) returns an nNodes-by-1 +% logical vector. The selector is a struct with the fields nodes, ids, x, y +% and z: +% +% nodes "all", "grid" (corners of the modules) or "centre" (middle of each module). +% ids Row of node numbers; empty for no restriction. +% x A range from ldem.scenarios.parseCoordinate, or [] for no restriction (same for y and z). +% +% Positions are in modules, within 0.01 modules. +% +% A node is selected when it passes every restriction. The positions are +% those of the regular lattice, even when the mesh is perturbed, so a +% selection does not depend on the random displacement of the nodes. In the +% lattice the grid nodes are at integer positions and the centre nodes at +% half-integer ones, for example the first layer of centre nodes along z is +% z = 0.5. +% +% Inputs: +% selector Struct as above. +% params ldem.Parameters (nModules and moduleLength). +% nodes Optional nNodes-by-3 coordinates of the regular lattice [m] (default: ldem.mesh.buildNodes). +% +% Output: +% mask nNodes-by-1 logical. +% +% Example: +% sel = ldem.scenarios.Declarative.makeSelector(nodes="centre", x=0.5); +% mask = ldem.scenarios.selectNodes(sel, ldem.Parameters()); +% +% See also ldem.scenarios.Declarative, ldem.scenarios.parseCoordinate. + +arguments + selector (1,1) struct + params (1,1) ldem.Parameters + nodes = [] +end + +if isempty(nodes) + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); +end +nNodes = size(nodes, 1); +nGrid = prod(params.nModules); + +mask = true(nNodes, 1); +switch selector.nodes + case "grid" + mask(nGrid+1:end) = false; + case "centre" + mask(1:nGrid) = false; +end +if ~isempty(selector.ids) + mask = mask & ismember((1:nNodes).', selector.ids); +end + +extent = params.nModules - 1; % length of the prism in modules +tolerance = 0.01; +axisNames = ["x" "y" "z"]; +for k = 1:3 + range = selector.(axisNames(k)); + if isempty(range) + continue + end + lo = resolve(range.lo, extent(k)); + hi = resolve(range.hi, extent(k)); + position = nodes(:, k) / params.moduleLength; + mask = mask & position >= lo - tolerance & position <= hi + tolerance; +end +end + +function value = resolve(spec, extent) +switch spec.base + case "min" + value = spec.offset; + case "max" + value = extent + spec.offset; + case "mid" + value = extent / 2 + spec.offset; + otherwise + value = spec.offset; +end +end diff --git a/src/+ldem/+scenarios/timeFunction.m b/src/+ldem/+scenarios/timeFunction.m new file mode 100644 index 0000000..e4323f3 --- /dev/null +++ b/src/+ldem/+scenarios/timeFunction.m @@ -0,0 +1,50 @@ +function value = timeFunction(fn, t) +%TIMEFUNCTION Value of a load at time t. +% +% value = ldem.scenarios.timeFunction(fn, t) evaluates the time function of +% a [[load]] block. fn is a struct whose field type selects the function: +% +% constant value +% linear rate*t +% ramp rate*min(t, until): grows at rate until the time "until", then stays constant +% table piecewise-linear interpolation of values at times; the end values are kept outside +% +% The result is in newtons for a force load and in metres (the movement from +% the initial position) for a displacement load. +% +% Inputs: +% fn Struct with the fields type, value, rate, until, times and values. +% t Time [s]. +% +% Output: +% value Scalar. +% +% Errors: +% ldem:scenarios:badTimeFunction The type is not one of the above. +% +% Example: +% fn = ldem.scenarios.Declarative.makeFunction("ramp", rate=1000, until=3.5e-4); +% ldem.scenarios.timeFunction(fn, 1e-3) % 0.35 N +% +% See also ldem.scenarios.Declarative. + +arguments + fn (1,1) struct + t (1,1) double +end + +switch fn.type + case "constant" + value = fn.value; + case "linear" + value = fn.rate * t; + case "ramp" + value = fn.rate * min(t, fn.until); + case "table" + clamped = min(max(t, fn.times(1)), fn.times(end)); + value = interp1(fn.times, fn.values, clamped, 'linear'); + otherwise + error('ldem:scenarios:badTimeFunction', ... + 'Unknown time function "%s"; use constant, linear, ramp or table.', fn.type); +end +end diff --git a/src/+ldem/+schema/caseSchema.m b/src/+ldem/+schema/caseSchema.m new file mode 100644 index 0000000..c4cc3a5 --- /dev/null +++ b/src/+ldem/+schema/caseSchema.m @@ -0,0 +1,182 @@ +function schema = caseSchema() +%CASESCHEMA Table of the keys of a case file (.ldem), the single source of truth. +% +% schema = ldem.schema.caseSchema() returns one row per key. The reader +% (ldem.io.readCase), the writer (ldem.io.writeCase) and the template are +% all driven by this table, so adding a key to the file format means adding +% a row here and, when it maps to an ldem.Parameters property, nothing else. +% +% Fields of every row: +% +% path Section and key, for example "material.young_modulus". +% kind How the value is read: integer, number, quantity (number with a unit), string, stringlist, path, intlist, numberlist, bool, enum, stepOrAuto or cadence. +% dimension Dimension of a "quantity", see ldem.schema.unitTable. +% prop Name of the ldem.Parameters property it sets ("" if the key needs special handling). +% required True if the file must contain the key. +% legacy Variable of the legacy DATA0.DAT file it replaces. +% doc One-line description, used for the comments of the template. +% choices Allowed words of an "enum", separated by "|". +% +% The keys of the [scenario] section other than "type" belong to the chosen +% scenario class and are described by ldem.scenarios.registry. +% +% Output: +% schema Struct array (one element per key). +% +% Example: +% schema = ldem.schema.caseSchema(); +% schema(strcmp({schema.path}, "mesh.module_size")).legacy % "LCO" +% +% See also ldem.io.readCase, ldem.io.writeCase, ldem.scenarios.registry. + +fields = ["path" "kind" "dimension" "prop" "required" "legacy" "doc" "choices"]; +rows = { + "format", "integer", "number", "", false, "", ... + "Version of the case-file format (currently 1).", "" + "title", "string", "number", "", false, "", ... + "Free text title of the case.", "" + "authors", "stringlist", "number", "", false, "", ... + "Names of the authors.", "" + "extends", "stringlist", "number", "", false, "", ... + "Case file(s) to inherit from; the keys of this file replace the inherited ones.", "" + "sweep_mode", "enum", "number", "", false, "", ... + "How several [[sweep]] blocks combine: all combinations (product) or one by one (zip).", "product|zip" + + "mesh.module_size", "quantity", "length", "moduleLength", false, "LCO", ... + "Edge length of each cubic module.", "" + "mesh.modules", "intlist", "number", "nModules", true, "M N L", ... + "Cubic modules along x, y and z (M N L of the legacy file count nodes: one more).", "" + "mesh.perturbation", "number", "number", "meshPerturbation", false, "", ... + "Random node displacement as a fraction of the module size; 0 = regular lattice.", "" + "mesh.seed", "integer", "number", "seed", false, "SEED", ... + "Seed of the mesh perturbation (the random field has its own seed).", "" + + "material.law", "enum", "number", "constitutiveLaw", false, "", ... + "Constitutive law of the bars (see ldem.material.lawRegistry).", ... + strjoin([ldem.material.lawRegistry().name], "|") + "material.young_modulus", "quantity", "pressure", "youngModulus", false, "YNG", ... + "Young's modulus.", "" + "material.poisson_ratio", "number", "number", "poissonRatio", false, "PSN", ... + "Poisson's ratio, from 0 up to less than 0.5.", "" + "material.density", "quantity", "density", "density", false, "ROH", ... + "Mass density.", "" + "material.fracture_energy", "quantity", "toughness", "fractureEnergy", false, "GFR", ... + "Specific fracture energy.", "" + "material.critical_distance", "quantity", "length", "criticalDistance", false, "DEQ", ... + "Equivalent (critical) distance.", "" + "material.failure_area_factor", "number", "number", "failureAreaFactor", false, "CAF", ... + "Fraction of the module face that fails per bar.", "" + + "material.scatter.type", "enum", "number", "", false, "", ... + "Scatter of the critical strain: none, file (one multiplier per bar) or generated.", ... + "none|file|generated" + "material.scatter.file", "path", "number", "randomFieldFile", false, "", ... + "Text file with one multiplier per bar, relative to this file.", "" + "material.scatter.cv", "number", "number", "randomFieldCv", false, "", ... + "Coefficient of variation of the generated field (1e-4 to 3).", "" + "material.scatter.correlation_length", "numberlist", "number", ... + "randomFieldCorrelationLength", false, "", ... + "Correlation length of the generated field in modules: one value or [x, y, z].", "" + "material.scatter.seed", "integer", "number", "randomFieldSeed", false, "", ... + "Seed of the generated field.", "" + + "time.step", "stepOrAuto", "time", "dt", false, "DT", ... + "Integration time step, or auto (0.9 times the critical step).", "" + "time.duration", "quantity", "time", "totalTime", true, "TTOT", ... + "Total simulated time.", "" + + "damping.type", "enum", "number", "dampingModel", false, "", ... + "Damping model of the nodes (see ldem.solver.dampingRegistry).", ... + strjoin([ldem.solver.dampingRegistry().name], "|") + "damping.initial", "quantity", "rate", "dampingInitial", false, "DF1", ... + "Mass-proportional damping before switch_time.", "" + "damping.final", "quantity", "rate", "dampingFinal", false, "DF2", ... + "Mass-proportional damping after switch_time.", "" + "damping.switch_time", "quantity", "time", "dampingSwitchTime", false, "TDAF", ... + "Time at which the damping changes from initial to final.", "" + "damping.constitutive", "quantity", "time", "constitutiveDamping", false, "CON", ... + "Stiffness-proportional damping inside the bar law.", "" + + "scenario.type", "enum", "number", "", true, "TEST", ... + "Test case (see ldem.scenarios.registry); its other keys follow.", "" + + "support.name", "string", "number", "", false, "", ... + "Label of the support.", "" + "support.nodes", "enum", "number", "", false, "", ... + "Kind of nodes: all, grid (module corners) or centre (module centres).", "all|centre|grid" + "support.ids", "intlist", "number", "", false, "", ... + "Node numbers to select.", "" + "support.x", "coordinate", "number", "", false, "", ... + "Positions along x in modules: 0.5, ""max - 0.5"" or a range [lo, hi].", "" + "support.y", "coordinate", "number", "", false, "", ... + "Positions along y in modules (see x).", "" + "support.z", "coordinate", "number", "", false, "", ... + "Positions along z in modules (see x).", "" + "support.fix", "stringlist", "number", "", false, "", ... + "Directions held at their initial position: [""x"", ""y"", ""z""].", "" + "support.reaction", "bool", "number", "", false, "", ... + "Include the force on the held directions in the reaction of the test.", "" + + "load.name", "string", "number", "", false, "", ... + "Label of the load.", "" + "load.nodes", "enum", "number", "", false, "", ... + "Kind of nodes: all, grid (module corners) or centre (module centres).", "all|centre|grid" + "load.ids", "intlist", "number", "", false, "", ... + "Node numbers to select.", "" + "load.x", "coordinate", "number", "", false, "", ... + "Positions along x in modules: 0.5, ""max - 0.5"" or a range [lo, hi].", "" + "load.y", "coordinate", "number", "", false, "", ... + "Positions along y in modules (see x).", "" + "load.z", "coordinate", "number", "", false, "", ... + "Positions along z in modules (see x).", "" + "load.direction", "enum", "number", "", false, "", ... + "Direction of the load.", "x|y|z" + "load.type", "enum", "number", "", false, "", ... + "force (N on each selected node) or displacement (m from the initial position).", "force|displacement" + "load.time_function", "enum", "number", "", false, "", ... + "How the value changes with time.", "constant|linear|ramp|table" + "load.value", "loadQuantity", "number", "", false, "", ... + "constant: the value (N or m).", "" + "load.rate", "loadQuantity", "number", "", false, "", ... + "linear and ramp: change per second (N/s or m/s).", "" + "load.until", "quantity", "time", "", false, "", ... + "ramp: time at which it stops growing.", "" + "load.times", "numberlist", "number", "", false, "", ... + "table: increasing times in seconds.", "" + "load.values", "numberlist", "number", "", false, "", ... + "table: one value per time (N or m).", "" + "load.reaction", "bool", "number", "", false, "", ... + "Include the force on the loaded direction in the reaction of the test.", "" + + "sweep.key", "string", "number", "", false, "", ... + "Key to vary, for example ""material.fracture_energy"" (see ldem.sweep).", "" + "sweep.values", "numberlist", "number", "", false, "", ... + "Values to try: numbers, or texts with units such as [""0.1 N/m"", ""0.5 N/m""].", "" + + "monitor.node.id", "integer", "number", "", false, "NCON", ... + "Number of a node whose motion is recorded.", "" + "monitor.node.at", "numberlist", "number", "", false, "", ... + "Position [x, y, z] in modules; the nearest node is recorded.", "" + "monitor.node.name", "string", "number", "", false, "", ... + "Label of the node.", "" + "monitor.bar.tracked", "integer", "number", "trackedBar", false, "OU9", ... + "Number of the bar whose strain history is stored at every step.", "" + + "output.folder", "string", "number", "", false, "", ... + "Output folder, relative to the case file.", "" + "output.mat", "bool", "number", "", false, "", ... + "Write results.mat.", "" + "output.ansys", "bool", "number", "", false, "", ... + "Write ANSYS macro files (needs snapshots.every > 0).", "" + "output.vtk", "bool", "number", "", false, "", ... + "Write VTK files for ParaView (needs snapshots.every > 0).", "" + "output.snapshots.every", "cadence", "number", "snapshotEvery", false, "OU3", ... + "Steps or time between full-field snapshots; 0 = never.", "" + "output.control_nodes.every", "cadence", "number", "controlNodesEvery", false, "OU6", ... + "Steps or time between records of the control nodes and reactions; 0 = never.", "" + "output.energy.every", "cadence", "number", "energyEvery", false, "OU8", ... + "Steps or time between records of the energies; 0 = never.", "" + }; + +schema = cell2struct(rows, fields, 2); +end diff --git a/src/+ldem/+schema/formatQuantity.m b/src/+ldem/+schema/formatQuantity.m new file mode 100644 index 0000000..28a7afd --- /dev/null +++ b/src/+ldem/+schema/formatQuantity.m @@ -0,0 +1,64 @@ +function text = formatQuantity(value, dimension) +%FORMATQUANTITY Write an SI value as a readable number with a unit. +% +% text = ldem.schema.formatQuantity(value, dimension) is the inverse of +% ldem.schema.parseQuantity. Lengths, times and pressures use the unit that +% gives a mantissa of at least 0.1 ("3 mm", "0.35 us", "3.87 GPa"); the other +% dimensions are written in their SI unit. The text always converts back to +% exactly the same value: if a unit would lose a digit, a longer mantissa or +% the SI unit is used. +% +% Inputs: +% value Value in SI units, finite. +% dimension Dimension, see ldem.schema.unitTable. +% +% Output: +% text String scalar. +% +% Example: +% ldem.schema.formatQuantity(3.5e-7, "time") % "0.35 us" +% +% See also ldem.schema.parseQuantity. + +arguments + value (1,1) double {mustBeFinite} + dimension (1,1) string +end + +[names, exps] = ldem.schema.unitTable(dimension); +base = find(exps == 0, 1); + +order = base; +if any(dimension == ["length" "time" "pressure"]) && value ~= 0 + ratios = abs(value) ./ 10.^exps; + usable = find(ratios >= 0.1 & exps ~= -2); + if isempty(usable) + [~, preferred] = max(ratios); + else + [~, i] = min(ratios(usable)); + preferred = usable(i); + end + order = unique([preferred, base], 'stable'); +end + +for k = order + mantissa = value / str2double("1e" + string(exps(k))); + for digits = 1:17 + shown = ldem.schema.shortestText(str2double(sprintf('%.*g', digits, mantissa))); + candidate = joinUnit(shown, names(k)); + if ldem.schema.parseQuantity(candidate, dimension) == value + text = candidate; + return + end + end +end +text = joinUnit(string(sprintf('%.17g', value)), names(base)); +end + +function text = joinUnit(number, unit) +if unit == "" + text = number; +else + text = number + " " + unit; +end +end diff --git a/src/+ldem/+schema/parseQuantity.m b/src/+ldem/+schema/parseQuantity.m new file mode 100644 index 0000000..3a05930 --- /dev/null +++ b/src/+ldem/+schema/parseQuantity.m @@ -0,0 +1,88 @@ +function value = parseQuantity(input, dimension, where) +%PARSEQUANTITY Convert a number with a unit, such as "3.87 GPa", to SI. +% +% value = ldem.schema.parseQuantity(input, dimension) returns the value in +% SI units (m, s, kg, Pa, N). The input is either +% +% * a number, taken as already being in SI units, or +% * text made of a number and, optionally, a unit: "3.87 GPa", "0.35 us", +% "1e-3 m", "3.87e9". +% +% The decimal exponent of the unit is appended to the digits of the text +% before converting ("0.35" and "e-6" become 0.35e-6), so the result is the +% double nearest to the decimal value that was written. "0.35 us" is +% exactly 3.5e-7. +% +% Inputs: +% input Number or text. +% dimension Dimension of the quantity, see ldem.schema.unitTable. +% where Optional location text for the error messages. +% +% Output: +% value Value in SI units. +% +% Errors: +% ldem:case:badQuantity The text is not a number with a unit. +% ldem:case:badUnit The unit does not belong to the dimension. +% +% Example: +% E = ldem.schema.parseQuantity("3.87 GPa", "pressure"); % 3.87e9 +% +% See also ldem.schema.formatQuantity, ldem.schema.unitTable. + +arguments + input + dimension (1,1) string + where (1,1) string = "" +end + +[names, exps] = ldem.schema.unitTable(dimension); + +if isnumeric(input) || islogical(input) + if ~isscalar(input) || ~isfinite(double(input)) + ldem.schema.raise('ldem:case:badQuantity', where, ... + 'Expected a single finite number.'); + end + value = double(input); + return +end + +if ~(isstring(input) || ischar(input)) || ~isscalar(string(input)) + ldem.schema.raise('ldem:case:badQuantity', where, ... + 'Expected a number with an optional unit, for example "3 mm".'); +end + +text = strtrim(string(input)); +pattern = '^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*(\S*)$'; +tokens = regexp(text, pattern, 'tokens', 'once'); +if isempty(tokens) + ldem.schema.raise('ldem:case:badQuantity', where, ... + '"%s" is not a number with an optional unit.', text); +end +mantissa = string(tokens{1}); +unit = string(tokens{2}); + +if unit == "" + k = find(exps == 0, 1); +else + k = find(names == unit, 1); + if isempty(k) + if all(names == "") + allowed = "no unit"; + else + allowed = strjoin(names, ", "); + end + ldem.schema.raise('ldem:case:badUnit', where, ... + 'Unit "%s" is not valid here; use %s.', unit, allowed); + end +end + +e = exps(k); +if e == 0 + value = str2double(mantissa); +elseif ~contains(mantissa, ["e" "E"]) + value = str2double(mantissa + "e" + string(e)); +else + value = str2double(mantissa) * 10^e; +end +end diff --git a/src/+ldem/+schema/raise.m b/src/+ldem/+schema/raise.m new file mode 100644 index 0000000..2487c77 --- /dev/null +++ b/src/+ldem/+schema/raise.m @@ -0,0 +1,22 @@ +function raise(id, where, message, varargin) +%RAISE Throw an error that points at a place in a case file. +% +% ldem.schema.raise(id, where, message, args...) formats the message with +% sprintf and throws it with the identifier id. When where is not empty, +% for example "case.ldem:14 [time] step", the message starts with it so the +% user knows which line to edit. +% +% Inputs: +% id Error identifier, for example "ldem:case:unknownKey". +% where Location text, or "" for none. +% message sprintf format. +% args Values for the format. +% +% See also ldem.io.readCase. + +text = sprintf(message, varargin{:}); +if strlength(string(where)) > 0 + text = char(string(where) + ": " + string(text)); +end +error(id, '%s', text); +end diff --git a/src/+ldem/+schema/shortestText.m b/src/+ldem/+schema/shortestText.m new file mode 100644 index 0000000..35b8d05 --- /dev/null +++ b/src/+ldem/+schema/shortestText.m @@ -0,0 +1,32 @@ +function text = shortestText(x) +%SHORTESTTEXT Shortest decimal text that converts back to exactly x. +% +% text = ldem.schema.shortestText(x) returns, for example, "0.1" for 0.1, +% "32" for 32 and "3.5e-07" for 3.5e-7. str2double(text) == x always holds +% for a finite x. +% +% Input: +% x Finite real scalar. +% +% Output: +% text String scalar. +% +% See also ldem.schema.formatQuantity. + +arguments + x (1,1) double +end + +if x == fix(x) && abs(x) < 1e15 + text = string(sprintf('%d', x)); + return +end +for digits = 1:17 + candidate = sprintf('%.*g', digits, x); + if str2double(candidate) == x + text = string(candidate); + return + end +end +text = string(sprintf('%.17g', x)); +end diff --git a/src/+ldem/+schema/suggest.m b/src/+ldem/+schema/suggest.m new file mode 100644 index 0000000..53b7b52 --- /dev/null +++ b/src/+ldem/+schema/suggest.m @@ -0,0 +1,56 @@ +function text = suggest(word, candidates) +%SUGGEST Ask "did you mean ...?" for a mistyped word. +% +% text = ldem.schema.suggest(word, candidates) returns a sentence such as +% " Did you mean 'young_modulus'?" when one of the candidates is close to +% word (small edit distance), and "" otherwise. The sentence starts with a +% space so it can be appended to an error message. +% +% Inputs: +% word The word that was written. +% candidates String array of valid words. +% +% Output: +% text String scalar. +% +% Example: +% ldem.schema.suggest("young_modulos", ["young_modulus" "density"]) +% +% See also ldem.io.readCase. + +arguments + word (1,1) string + candidates (1,:) string +end + +best = ""; +bestDistance = inf; +for candidate = candidates + d = editDistance(char(lower(word)), char(lower(candidate))); + if d < bestDistance + bestDistance = d; + best = candidate; + end +end +limit = max(2, floor(strlength(word) / 3)); +if bestDistance <= limit + text = " Did you mean '" + best + "'?"; +else + text = ""; +end +end + +function d = editDistance(a, b) +%EDITDISTANCE Levenshtein distance between two char vectors. +previous = 0:numel(b); +for i = 1:numel(a) + current = zeros(1, numel(b) + 1); + current(1) = i; + for j = 1:numel(b) + cost = double(a(i) ~= b(j)); + current(j + 1) = min([previous(j + 1) + 1, current(j) + 1, previous(j) + cost]); + end + previous = current; +end +d = previous(end); +end diff --git a/src/+ldem/+schema/unitTable.m b/src/+ldem/+schema/unitTable.m new file mode 100644 index 0000000..73ea955 --- /dev/null +++ b/src/+ldem/+schema/unitTable.m @@ -0,0 +1,78 @@ +function [names, exps] = unitTable(dimension) +%UNITTABLE Units accepted for a physical dimension in the case files. +% +% [names, exps] = ldem.schema.unitTable(dimension) returns the unit names +% and the decimal exponent of each one with respect to the SI unit, so that +% 1 = 10^exps SI units. The SI unit is the one with exponent 0. +% +% Dimensions: +% +% length m, cm, mm, um, km +% time s, ms, us, ns +% pressure Pa, kPa, MPa, GPa +% density kg/m3, g/cm3 +% rate 1/s, 1/ms (damping coefficient) +% toughness N/m, kN/m (fracture energy) +% velocity m/s, mm/s +% forcerate N/s, kN/s +% force N, kN, MN +% modules modules (length in module lengths) +% number no unit +% +% Input: +% dimension One of the names above. +% +% Outputs: +% names 1-by-n string array of unit names ("" for a dimensionless value). +% exps 1-by-n decimal exponents. +% +% Errors: +% ldem:schema:unknownDimension The dimension does not exist. +% +% Example: +% [names, exps] = ldem.schema.unitTable("pressure"); +% +% See also ldem.schema.parseQuantity, ldem.schema.formatQuantity. + +arguments + dimension (1,1) string +end + +switch dimension + case "length" + names = ["m" "cm" "mm" "um" "km"]; + exps = [0 -2 -3 -6 3]; + case "time" + names = ["s" "ms" "us" "ns"]; + exps = [0 -3 -6 -9]; + case "pressure" + names = ["Pa" "kPa" "MPa" "GPa"]; + exps = [0 3 6 9]; + case "density" + names = ["kg/m3" "g/cm3"]; + exps = [0 3]; + case "rate" + names = ["1/s" "1/ms"]; + exps = [0 3]; + case "toughness" + names = ["N/m" "kN/m"]; + exps = [0 3]; + case "velocity" + names = ["m/s" "mm/s"]; + exps = [0 -3]; + case "forcerate" + names = ["N/s" "kN/s"]; + exps = [0 3]; + case "force" + names = ["N" "kN" "MN"]; + exps = [0 3 6]; + case "modules" + names = "modules"; + exps = 0; + case "number" + names = ""; + exps = 0; + otherwise + error('ldem:schema:unknownDimension', 'Unknown dimension "%s".', dimension); +end +end diff --git a/src/+ldem/+schema/writeKeyReference.m b/src/+ldem/+schema/writeKeyReference.m new file mode 100644 index 0000000..50b8d79 --- /dev/null +++ b/src/+ldem/+schema/writeKeyReference.m @@ -0,0 +1,175 @@ +function text = writeKeyReference(path) +%WRITEKEYREFERENCE Write the reference of the case-file keys, generated from the schema. +% +% text = ldem.schema.writeKeyReference(path) builds the tables of keys that the +% user guide includes (docs/source/case-keys.inc): one table per section with +% the key, the kind of value and its units, the default, the variable of the +% legacy DATA0.DAT it replaces and the description. Everything comes from +% ldem.schema.caseSchema and the defaults of ldem.Parameters, so the guide +% cannot disagree with the reader. The text is reStructuredText. +% +% After changing the schema, regenerate the file from the repository root: +% +% ldem.schema.writeKeyReference("docs/source/case-keys.inc"); +% +% A test compares the file with the generated text and fails when they differ. +% +% Input: +% path File to write ("" to only return the text). +% +% Output: +% text The reStructuredText, a string scalar. +% +% See also ldem.schema.caseSchema, ldem.io.writeTemplate. + +arguments + path (1,1) string = "" +end + +schema = ldem.schema.caseSchema(); +defaults = ldem.Parameters(); +arrayTables = ["monitor.node" "support" "load" "sweep"]; + +lines = [ + ".. This file is generated by ldem.schema.writeKeyReference from ldem.schema.caseSchema." + ".. Do not edit it by hand: change the schema and generate it again." + ""]; + +paths = string({schema.path}); +sections = strings(size(paths)); +for k = 1:numel(paths) + dot = find(char(paths(k)) == '.', 1, 'last'); + if isempty(dot) + sections(k) = ""; + else + sections(k) = extractBefore(paths(k), dot); + end +end + +for section = unique(sections, 'stable') + if section == "" + title = "(top level)"; + elseif any(section == arrayTables) + title = "[[" + section + "]]"; + else + title = "[" + section + "]"; + end + lines = [lines; ".. rubric:: ``" + title + "``"; ""; ... + ".. list-table::"; " :header-rows: 1"; " :widths: 18 24 12 8 38"; ""; ... + " * - Key"; " - Value"; " - Default"; " - Legacy"; " - Description"]; %#ok + for k = find(sections == section) + row = schema(k); + key = extractAfter(paths(k), strlength(section) + double(section ~= "")); + legacy = string(row.legacy); + if legacy == "" + legacy = "(none)"; + end + lines = [lines; ... + " * - ``" + key + "``"; ... + " - " + escape(valueText(row)); ... + " - " + escape(defaultText(row, defaults)); ... + " - " + escape(legacy); ... + " - " + escape(string(row.doc))]; %#ok + end + lines = [lines; ""]; %#ok +end + +text = strjoin(lines, newline); +text = regexprep(text, '\n+$', '') + newline; +if strlength(path) > 0 + fid = fopen(path, 'w', 'n', 'UTF-8'); + if fid == -1 + error('ldem:io:cannotOpenFile', 'Cannot create "%s".', path); + end + fprintf(fid, '%s', text); + fclose(fid); +end +end + +function t = valueText(row) +switch string(row.kind) + case "integer" + t = "integer"; + case "number" + t = "number"; + case "quantity" + names = ldem.schema.unitTable(string(row.dimension)); + t = "number + unit (" + strjoin(names, ", ") + ")"; + case "string" + t = "text"; + case "stringlist" + t = "list of texts"; + case "path" + t = "file path"; + case "intlist" + t = "list of integers"; + case "numberlist" + t = "list of numbers"; + case "bool" + t = "true or false"; + case "enum" + t = strjoin(split(string(row.choices), "|").', ", "); + case "stepOrAuto" + t = "time, or auto"; + case "cadence" + t = "steps or time (0 = never)"; + case "coordinate" + t = "modules: number, text or [lo, hi]"; + case "loadQuantity" + t = "N, N/s, m or m/s, by type"; + otherwise + t = string(row.kind); +end +end + +function t = defaultText(row, defaults) +manual = struct( ... + 'material_scatter_type', '"none"', 'support_nodes', '"all"', 'load_nodes', '"all"', ... + 'time_step', '"auto"', 'output_mat', 'true', 'output_ansys', 'false', 'output_vtk', 'false', ... + 'output_folder', 'no files', 'sweep_mode', '"product"', 'support_reaction', 'false', ... + 'load_reaction', 'false', 'monitor_bar_tracked', 'off', 'format', '1'); +name = strrep(string(row.path), ".", "_"); +if row.required + t = "required"; +elseif isfield(manual, name) + t = string(manual.(name)); +elseif string(row.prop) ~= "" && isprop(defaults, row.prop) + if string(row.kind) == "cadence" + value = defaults.output.(row.prop); + else + value = defaults.(row.prop); + end + t = formatDefault(row, value); +else + t = "(none)"; +end +end + +function t = formatDefault(row, value) +switch string(row.kind) + case "quantity" + t = ldem.schema.formatQuantity(value, string(row.dimension)); + case "cadence" + if value == 0 + t = "0"; + else + t = string(value) + " steps"; + end + case {"enum", "string", "path"} + if strlength(string(value)) == 0 + t = "(none)"; + else + t = '"' + string(value) + '"'; + end + case "numberlist" + t = "[" + strjoin(arrayfun(@ldem.schema.shortestText, value), ", ") + "]"; + otherwise + t = ldem.schema.shortestText(double(value)); +end +end + +function t = escape(s) +%ESCAPE Make a text safe inside a reStructuredText table cell. +t = replace(replace(string(s), "\", "\\"), "_", "\_"); +t = replace(replace(t, "*", "\*"), "|", "\|"); +end diff --git a/src/+ldem/+solver/DampingModel.m b/src/+ldem/+solver/DampingModel.m new file mode 100644 index 0000000..6bb9983 --- /dev/null +++ b/src/+ldem/+solver/DampingModel.m @@ -0,0 +1,32 @@ +classdef (Abstract) DampingModel + %DAMPINGMODEL Base class of the damping models of the nodes. + % + % The integrator damps the motion of every node with the term + % c*m*velocity, where c [1/s] may change from step to step. A damping + % model only has to return c for a step. The solver asks the object chosen + % by params.dampingModel (the key "type" of the [damping] section of a case + % file). + % + % To add a model: + % 1. Create a subclass in this folder and set the constant property name + % (snake_case, the word used in the case file). + % 2. Implement coefficient. + % 3. Add a line to ldem.solver.dampingRegistry, with the keys of the + % [damping] section that the model uses. + % + % See also ldem.solver.MassProportionalDamping, ldem.solver.NoDamping, + % ldem.solver.dampingRegistry, ldem.solver.integrateStep. + + properties (Abstract, Constant) + % Name used in the case file ("mass_proportional"). + name + end + + methods (Abstract) + % COEFFICIENT Mass-proportional damping coefficient of a step [1/s]. + % + % c = model.coefficient(step, params), with step = 1, 2, ... and + % params an ldem.Parameters (the model reads the parameters it needs). + c = coefficient(obj, step, params) + end +end diff --git a/src/+ldem/+solver/MassProportionalDamping.m b/src/+ldem/+solver/MassProportionalDamping.m new file mode 100644 index 0000000..436ce30 --- /dev/null +++ b/src/+ldem/+solver/MassProportionalDamping.m @@ -0,0 +1,21 @@ +classdef MassProportionalDamping < ldem.solver.DampingModel + %MASSPROPORTIONALDAMPING Constant coefficient that switches once (legacy damping). + % + % The coefficient is params.dampingInitial before the switch step and + % params.dampingFinal from then on, see ldem.solver.dampingCoefficient. The + % case-file name is "mass_proportional", with the keys initial, final and + % switch_time. + % + % See also ldem.solver.DampingModel, ldem.solver.dampingCoefficient. + + properties (Constant) + name = "mass_proportional" + end + + methods + function c = coefficient(~, step, params) + %COEFFICIENT dampingInitial before the switch, dampingFinal after. + c = ldem.solver.dampingCoefficient(step, params); + end + end +end diff --git a/src/+ldem/+solver/NoDamping.m b/src/+ldem/+solver/NoDamping.m new file mode 100644 index 0000000..54a61cd --- /dev/null +++ b/src/+ldem/+solver/NoDamping.m @@ -0,0 +1,21 @@ +classdef NoDamping < ldem.solver.DampingModel + %NODAMPING No damping of the nodes (c = 0). + % + % For free vibration and wave problems. The viscous term inside the law + % (params.constitutiveDamping) is independent and still applies. The + % case-file name is "none"; the keys initial, final and switch_time of + % [damping] do not apply. + % + % See also ldem.solver.DampingModel. + + properties (Constant) + name = "none" + end + + methods + function c = coefficient(~, ~, ~) + %COEFFICIENT Always zero. + c = 0; + end + end +end diff --git a/src/+ldem/+solver/checkStability.m b/src/+ldem/+solver/checkStability.m new file mode 100644 index 0000000..e9f6c09 --- /dev/null +++ b/src/+ldem/+solver/checkStability.m @@ -0,0 +1,41 @@ +function criticalDt = checkStability(barLength, params) +%CHECKSTABILITY Verify that the time step is stable for the actual mesh. +% +% criticalDt = ldem.solver.checkStability(barLength, params) computes the +% largest stable time step of the explicit scheme, minimum bar length +% divided by the elastic wave speed, and throws an error if params.dt is +% larger. +% +% This uses the real bar lengths, so it also covers perturbed meshes. For +% a regular lattice the value equals params.criticalTimeStep. +% +% Inputs: +% barLength Vector of initial bar lengths [m]. +% params ldem.Parameters. +% +% Output: +% criticalDt Largest stable time step [s]. +% +% Errors: +% ldem:params:unstableTimeStep params.dt exceeds the critical value. +% +% Example: +% criticalDt = ldem.solver.checkStability(mesh.barLength, params); +% +% Legacy: stability check at the end of NAYFES0. +% +% See also ldem.Parameters, ldem.mesh.computeBarGeometry. + +arguments + barLength (:,1) double {mustBePositive} + params (1,1) ldem.Parameters +end + +criticalDt = min(barLength) / params.waveSpeed; +if criticalDt < params.dt + error('ldem:params:unstableTimeStep', ... + ['The time step dt = %g s is unstable for this mesh: the shortest ' ... + 'bar (%g m) requires dt <= %g s. Reduce dt.'], ... + params.dt, min(barLength), criticalDt); +end +end diff --git a/src/+ldem/+solver/computeBarForces.m b/src/+ldem/+solver/computeBarForces.m new file mode 100644 index 0000000..7ad5156 --- /dev/null +++ b/src/+ldem/+solver/computeBarForces.m @@ -0,0 +1,90 @@ +function state = computeBarForces(state, mesh, barProps, params, law) +%COMPUTEBARFORCES Axial force of every bar and resulting nodal forces. +% +% state = ldem.solver.computeBarForces(state, mesh, barProps, params) +% measures the strain and strain rate of every bar in the current +% configuration, evaluates the constitutive law (damage included) and +% adds each bar force to its two end nodes. +% +% For a bar from node i to node j with current length L, direction +% cosines c = (xj - xi)/L and axial force F (tension positive), the bar +% pulls node i toward j with +F*c and node j toward i with -F*c. +% The strain is (L - L0)/L0 and the rate is the strain change since the +% previous step divided by dt. +% +% Inputs: +% state Solver state, see ldem.solver.initialState. +% mesh Struct from ldem.mesh.buildMesh. +% barProps Struct from ldem.material.buildBarProperties. +% params ldem.Parameters. +% law Optional ldem.material.MaterialLaw (default: the one named by params.constitutiveLaw). +% +% Output: +% state The input state with force, strain, strainRate, axialForce and +% history updated. +% +% Errors: +% ldem:solver:zeroLengthBar Two end nodes coincide in the current +% configuration. +% +% Legacy: CABAR. +% +% See also ldem.material.MaterialLaw, ldem.material.bilinearLaw, ldem.solver.integrateStep. + +arguments + state (1,1) struct + mesh (1,1) struct + barProps (1,1) struct + params (1,1) ldem.Parameters + law = [] +end + +if isempty(law) + law = ldem.material.lawFromName(params.constitutiveLaw); +end + +first = mesh.bars(:, 1); +second = mesh.bars(:, 2); +initialLength = mesh.barLength; + +% Current configuration and the one of the previous step. +delta = state.displacement(second, :) - state.displacement(first, :); +currentLength = sqrt(delta(:, 1) .* delta(:, 1) + delta(:, 2) .* delta(:, 2) + delta(:, 3) .* delta(:, 3)); + +deltaPrevious = state.previousDisplacement(second, :) - state.previousDisplacement(first, :); +previousLength = sqrt(deltaPrevious(:, 1) .* deltaPrevious(:, 1) + ... + deltaPrevious(:, 2) .* deltaPrevious(:, 2) + deltaPrevious(:, 3) .* deltaPrevious(:, 3)); + +if any(currentLength == 0) + error('ldem:solver:zeroLengthBar', ... + 'Bar %d has zero length at step %d: its two nodes coincide.', ... + find(currentLength == 0, 1), state.step); +end + +directionCosines = delta ./ currentLength; + +strain = (currentLength - initialLength) ./ initialLength; +oldStrain = (previousLength - initialLength) ./ initialLength; +strainRate = (strain - oldStrain) / params.dt; + +[axialForce, history] = law.evaluate(strain, strainRate, barProps, state.history, params); + +% Add the bar forces to the nodes. The contributions are listed bar by bar +% (start node +, end node -) so that, for every node, they are summed in the +% same order as a loop over the bars; this keeps the rounding identical to +% the legacy code. +nNodes = size(state.displacement, 1); +nodeIndex = reshape([first, second].', [], 1); +nodalForce = zeros(nNodes, 3); +for direction = 1:3 + component = axialForce .* directionCosines(:, direction); + contributions = reshape([component, -component].', [], 1); + nodalForce(:, direction) = accumarray(nodeIndex, contributions, [nNodes, 1]); +end + +state.force = nodalForce; +state.strain = strain; +state.strainRate = strainRate; +state.axialForce = axialForce; +state.history = history; +end diff --git a/src/+ldem/+solver/computeEnergies.m b/src/+ldem/+solver/computeEnergies.m new file mode 100644 index 0000000..c79c933 --- /dev/null +++ b/src/+ldem/+solver/computeEnergies.m @@ -0,0 +1,97 @@ +function energy = computeEnergies(state, mesh, barProps, params, law) +%COMPUTEENERGIES Energies of the system at the current state. +% +% energy = ldem.solver.computeEnergies(state, mesh, barProps, params) +% returns the energies [J], all of them scalars. The elastic, damage and +% broken-bar energies come from the constitutive law (ldem.material.MaterialLaw, +% by default the one named by params.constitutiveLaw; pass another as law). +% +% Fields of energy: +% +% time Simulated time [s]. +% kinetic Sum of m*|v|^2/2 over all nodes. +% elastic Sum of E*strain^2*L/2 over the bars (tension or compression stiffness). +% damage Energy dissipated by softening in the damaged bars. +% damping Energy dissipated by damping so far (state.dampingEnergy). +% internal kinetic + elastic + damage + damping. +% brokenBars Total fracture energy of the bars that have broken. +% damageRate Change of the damage energy per unit time since the previous step [W]. +% external Work done so far by the supports and the prescribed motion (state.externalEnergy). +% balance external - internal: the part of the work that is not accounted for. +% +% Energy balance. In a model whose loading acts on degrees of freedom fixed +% by the scenario, the balance is close to zero: the external work becomes +% kinetic, elastic, damage or damping energy. It is not exactly zero because +% the scheme is second-order accurate and because the kinetic energy of the +% prescribed nodes (which the outside world supplies) is included in +% kinetic like in the legacy code; both effects are small. Judge the balance +% relative to the final external work: in the reference tests it is between +% 0.01 % and 0.5 % (it shrinks with the number of steps, because the scheme +% compares the work of the last step with the energy at its end, an error of +% about 1/N for energies that grow like t^2). +% +% In a scenario loaded with forces (ldem.scenarios.ClampedBeam) the work of +% the applied forces on the free degrees of freedom is part of the external +% work. The balance does not close when a prescribed motion is not held by +% the scenario, as happened in the legacy tension test (fixed here, see +% ldem.scenarios.UniaxialTension). +% +% For a damaged bar with critical strain EP, largest strain EM and +% stiffnesses E1 (compression) and E2 (tension), the energy dissipated is +% L/2 times E1*EP^2 - E2*EM^2 + (E1*EP + E2*EM)*(EM - EP). +% For a broken bar the total fracture energy is L/2 * E1*EP^2*KR. +% +% Inputs: +% state Solver state after ldem.solver.integrateStep. +% mesh Struct from ldem.mesh.buildMesh. +% barProps Struct from ldem.material.buildBarProperties. +% params ldem.Parameters. +% +% Output: +% energy Struct with the fields above plus time. +% +% Example: +% energy = ldem.solver.computeEnergies(state, mesh, barProps, params); +% +% Legacy: ENERG2. There the kinetic and damping energies were vectors (one +% entry per node) that were never summed; here they are scalars. The +% external work (ENEX) was never computed in the legacy code. +% +% The kinetic energy of each node is available from +% ldem.solver.nodalKineticEnergy. +% +% See also ldem.solver.simulate, ldem.solver.nodalKineticEnergy. + +arguments + state (1,1) struct + mesh (1,1) struct + barProps (1,1) struct + params (1,1) ldem.Parameters + law = [] +end + +if isempty(law) + law = ldem.material.lawFromName(params.constitutiveLaw); +end + +% Kinetic energy. +kinetic = sum(ldem.solver.nodalKineticEnergy(state, mesh)); + +% Elastic, damage and fracture energy of the bars: they depend on the law. +barEnergy = law.energies(state.strain, barProps, state.history, mesh.barLength); +elastic = barEnergy.elastic; +damage = barEnergy.damage; +brokenBars = barEnergy.brokenBars; + +energy = struct(); +energy.time = state.time; +energy.kinetic = kinetic; +energy.elastic = elastic; +energy.damage = damage; +energy.damping = state.dampingEnergy; +energy.internal = kinetic + elastic + damage + state.dampingEnergy; +energy.brokenBars = brokenBars; +energy.damageRate = (damage - state.previousDamageEnergy) / params.dt; +energy.external = state.externalEnergy; +energy.balance = state.externalEnergy - energy.internal; +end diff --git a/src/+ldem/+solver/dampingCoefficient.m b/src/+ldem/+solver/dampingCoefficient.m new file mode 100644 index 0000000..1ed902c --- /dev/null +++ b/src/+ldem/+solver/dampingCoefficient.m @@ -0,0 +1,39 @@ +function coefficient = dampingCoefficient(step, params) +%DAMPINGCOEFFICIENT Mass-proportional damping coefficient of a time step. +% +% coefficient = ldem.solver.dampingCoefficient(step, params) returns +% params.dampingInitial before the switch step and params.dampingFinal +% from the switch step on (params.dampingSwitchStep = round(TDAF/dt)). +% +% If the switch step is zero (dampingSwitchTime shorter than half a time +% step) the coefficient never changes and dampingInitial is used. This +% reproduces the legacy code, which only switched when STEP == NDAMF and +% steps start at 1. +% +% Inputs: +% step Time step number (1, 2, ...). +% params ldem.Parameters. +% +% Output: +% coefficient Damping coefficient [1/s]. +% +% Example: +% c = ldem.solver.dampingCoefficient(100, params); +% +% Legacy: the damping change at the top of the time loop of the main +% program (DF1 = DF2 when STEP == NDAMF). +% +% See also ldem.solver.integrateStep. + +arguments + step (1,1) double {mustBeInteger, mustBePositive} + params (1,1) ldem.Parameters +end + +switchStep = params.dampingSwitchStep; +if switchStep >= 1 && step >= switchStep + coefficient = params.dampingFinal; +else + coefficient = params.dampingInitial; +end +end diff --git a/src/+ldem/+solver/dampingFromName.m b/src/+ldem/+solver/dampingFromName.m new file mode 100644 index 0000000..b085eae --- /dev/null +++ b/src/+ldem/+solver/dampingFromName.m @@ -0,0 +1,30 @@ +function model = dampingFromName(name) +%DAMPINGFROMNAME Create the damping-model object with a name used in the case files. +% +% model = ldem.solver.dampingFromName(name) returns an instance of the class +% registered under name in ldem.solver.dampingRegistry. +% +% Input: +% name Model name, for example "mass_proportional" (case is ignored). +% +% Output: +% model Object of a subclass of ldem.solver.DampingModel. +% +% Errors: +% ldem:solver:unknownDamping No model has that name. +% +% See also ldem.solver.dampingRegistry, ldem.solver.DampingModel. + +arguments + name (1,1) string +end + +reg = ldem.solver.dampingRegistry(); +k = find([reg.name] == lower(name), 1); +if isempty(k) + error('ldem:solver:unknownDamping', ... + 'There is no damping model named "%s".%s Available: %s.', name, ... + ldem.schema.suggest(name, [reg.name]), strjoin([reg.name], ', ')); +end +model = feval(reg(k).className); +end diff --git a/src/+ldem/+solver/dampingRegistry.m b/src/+ldem/+solver/dampingRegistry.m new file mode 100644 index 0000000..c9cc498 --- /dev/null +++ b/src/+ldem/+solver/dampingRegistry.m @@ -0,0 +1,33 @@ +function reg = dampingRegistry() +%DAMPINGREGISTRY List of the available damping models. +% +% reg = ldem.solver.dampingRegistry() returns one element per damping class. +% It is the only place to edit to register a new model: ldem.solver.dampingFromName, +% the validation of ldem.Parameters and the case-file reader all read it. +% +% Fields of every element: +% +% name Word used in the case file, "type = ..." in [damping]. +% className Class, a subclass of ldem.solver.DampingModel. +% description One line for the messages and the documentation. +% keys Keys of [damping] the model uses (the others are an error in a case file): initial, final, switch_time. +% +% Output: +% reg Struct array. +% +% Example: +% [ldem.solver.dampingRegistry().name] % "mass_proportional" "none" +% +% See also ldem.solver.DampingModel, ldem.solver.dampingFromName. + +reg = struct('name', {}, 'className', {}, 'description', {}, 'keys', {}); +reg(end+1) = makeEntry("mass_proportional", "ldem.solver.MassProportionalDamping", ... + "Constant coefficient that switches once (legacy damping)", ... + ["initial" "final" "switch_time"]); +reg(end+1) = makeEntry("none", "ldem.solver.NoDamping", ... + "No damping of the nodes", strings(1, 0)); +end + +function entry = makeEntry(name, className, description, keys) +entry = struct('name', name, 'className', className, 'description', description, 'keys', keys); +end diff --git a/src/+ldem/+solver/initialState.m b/src/+ldem/+solver/initialState.m new file mode 100644 index 0000000..fc020df --- /dev/null +++ b/src/+ldem/+solver/initialState.m @@ -0,0 +1,71 @@ +function state = initialState(mesh, history) +%INITIALSTATE State of the simulation at time zero. +% +% state = ldem.solver.initialState(mesh, history) creates the struct that +% the time-stepping routines update. All nodes start at their initial +% position, at rest and without forces; the bars start undamaged. +% +% The explicit central-difference scheme needs the displacement of two +% consecutive times, so the state holds both (at time zero they are equal). +% +% Inputs: +% mesh Struct from ldem.mesh.buildMesh. +% history Initial damage state from ldem.material.buildBarProperties. +% +% Output: +% state Struct with the fields listed below. +% +% Fields of state: +% +% step Number of the last completed step (0). +% time Simulated time [s]. +% displacement nNodes-by-3 current positions [m] (legacy U(2,:), V(2,:), W(2,:)). +% previousDisplacement nNodes-by-3 positions one step before (legacy U(1,:), V(1,:), W(1,:)). +% velocity nNodes-by-3 velocities [m/s]. +% acceleration nNodes-by-3 accelerations [m/s^2]. +% force nNodes-by-3 force of the bars on the nodes [N] (legacy FRX, FRY, FRZ). +% strain nBars-by-1 axial strain (legacy SS). +% strainRate nBars-by-1 strain rate [1/s] (legacy DSS). +% axialForce nBars-by-1 axial force [N], tension positive (legacy F). +% history Damage state of the bars. +% dampingEnergy Energy dissipated by damping so far [J]. +% externalEnergy Work of the supports, the prescribed motion and the applied forces so far [J]. +% previousForce nNodes-by-3 nodal force of the previous step [N]. +% appliedForce nNodes-by-3 external force set by the scenario in applyLoads [N]. +% previousAppliedForce nNodes-by-3 applied force of the previous step [N]. +% previousDamageEnergy Energy dissipated by damage at the previous step [J]. +% +% Example: +% state = ldem.solver.initialState(mesh, history); +% +% Legacy: INI_DEM3 (allocation) and the initial values set by COORDSUB. +% +% See also ldem.solver.simulate. + +arguments + mesh (1,1) struct + history (1,1) struct +end + +nNodes = size(mesh.nodes0, 1); +nBars = size(mesh.bars, 1); + +state = struct(); +state.step = 0; +state.time = 0.0; +state.displacement = mesh.nodes0; +state.previousDisplacement = mesh.nodes0; +state.velocity = zeros(nNodes, 3); +state.acceleration = zeros(nNodes, 3); +state.force = zeros(nNodes, 3); +state.strain = zeros(nBars, 1); +state.strainRate = zeros(nBars, 1); +state.axialForce = zeros(nBars, 1); +state.history = history; +state.dampingEnergy = 0.0; +state.externalEnergy = 0.0; +state.previousForce = zeros(nNodes, 3); +state.appliedForce = zeros(nNodes, 3); +state.previousAppliedForce = zeros(nNodes, 3); +state.previousDamageEnergy = 0.0; +end diff --git a/src/+ldem/+solver/integrateStep.m b/src/+ldem/+solver/integrateStep.m new file mode 100644 index 0000000..7464fa0 --- /dev/null +++ b/src/+ldem/+solver/integrateStep.m @@ -0,0 +1,133 @@ +function state = integrateStep(state, mesh, barProps, params, law, damping) +%INTEGRATESTEP Advance the node positions one time step. +% +% state = ldem.solver.integrateStep(state, mesh, barProps, params) solves +% the equation of motion of every free degree of freedom with the explicit +% central-difference scheme +% +% m * (u_next - 2*u + u_prev)/dt^2 + c*m * (u_next - u_prev)/(2*dt) = F +% +% where F is the bar force on the node, m its lumped mass and c the +% mass-proportional damping coefficient of the step, which gives +% +% u_next = (dt^2/m * F + 2*u - (1 - c*dt/2)*u_prev) / (1 + c*dt/2) +% +% F is the sum of the bar force (state.force) and of the force applied by the +% scenario (state.appliedForce, zero when the scenario imposes displacements). +% Degrees of freedom fixed by the scenario keep their current value. After +% the update the velocity and acceleration are obtained with central +% differences, the energy dissipated by damping is accumulated and the two +% stored positions are shifted (current -> previous, next -> current). +% +% External work. A degree of freedom fixed by the scenario follows a +% prescribed path (a support does not move, a loaded node moves with the +% loading velocity). The force that the outside world exerts on it is minus +% the bar force, so the work done on the structure in the step is +% -F*(u - u_prev), with F the average of the bar force of this step and of the +% previous one (trapezoidal rule). It is summed over the fixed degrees of +% freedom: zero for a support that does not move, positive when a prescribed +% motion pushes the structure. The inertia of the prescribed nodes is not +% included; it is negligible against the energy of the structure. Adding up +% the steps gives the external work, which balances the kinetic, elastic, +% damage and damping energies (see ldem.solver.computeEnergies). +% +% A force applied to a free degree of freedom does work on the structure as +% the node moves: the average of the applied force of this step and of the +% previous one times the displacement of the step, summed over the free +% degrees of freedom and added to the same external work. +% +% The energy dissipated in the step has two parts: the mass-proportional +% damping of the nodes, c*(m/2)*v*(u_next - u_prev), and the viscous term +% of the constitutive law, E*CON*rate^2*dt*L for every bar (E is the +% compression stiffness for compressed bars and the tension stiffness +% otherwise). +% +% Inputs: +% state Solver state after ldem.solver.computeBarForces. +% mesh Struct from ldem.mesh.buildMesh (mass, fixed, barLength). +% barProps Struct from ldem.material.buildBarProperties. +% params ldem.Parameters. +% law Optional ldem.material.MaterialLaw (default: params.constitutiveLaw). +% damping Optional ldem.solver.DampingModel (default: params.dampingModel). +% +% Output: +% state Updated: displacement, previousDisplacement, velocity, +% acceleration, dampingEnergy, externalEnergy, previousForce and +% previousAppliedForce. +% +% Errors: +% ldem:solver:zeroMass A node has zero mass. +% +% Legacy: IGN012 (nested function ign012). The legacy acceleration in y +% used a wrong index (V(2,I) instead of V(2,:)); here it is computed like +% the other two components. +% +% See also ldem.solver.computeBarForces, ldem.solver.DampingModel, ldem.material.MaterialLaw. + +arguments + state (1,1) struct + mesh (1,1) struct + barProps (1,1) struct + params (1,1) ldem.Parameters + law = [] + damping = [] +end + +if isempty(law) + law = ldem.material.lawFromName(params.constitutiveLaw); +end +if isempty(damping) + damping = ldem.solver.dampingFromName(params.dampingModel); +end + +if any(mesh.mass == 0) + error('ldem:solver:zeroMass', 'Node %d has zero mass.', find(mesh.mass == 0, 1)); +end + +dt = params.dt; +ddt = 2.0 * dt; +sdt = dt * dt; + +c = damping.coefficient(state.step, params); +dampingPrevious = 1.0 - c * dt / 2.0; +dampingNext = 1.0 + c * dt / 2.0; + +u = state.displacement; +uPrev = state.previousDisplacement; +timeFactor = sdt ./ mesh.mass; % nNodes-by-1, applies to x, y and z + +totalForce = state.force + state.appliedForce; +uNext = (timeFactor .* totalForce + 2.0 .* u - dampingPrevious .* uPrev) ./ dampingNext; +uNext(mesh.fixed) = u(mesh.fixed); + +velocity = (uNext - uPrev) ./ ddt; +acceleration = (uNext - u .* 2.0 + uPrev) ./ sdt; + +% Energy dissipated by mass-proportional damping (all nodes and directions). +nodeDamping = (c .* (mesh.mass ./ 2.0)) .* velocity .* (uNext - uPrev); +dissipated = sum(nodeDamping, 'all'); + +% Energy dissipated by the viscous term of the constitutive law. +stiffness = law.viscousStiffness(state.strain, barProps, state.history); +barViscous = 2.0 * (stiffness .* params.constitutiveDamping .* state.strainRate .* ... + state.strainRate .* dt .* mesh.barLength ./ 2.0); +dissipated = dissipated + sum(barViscous); + +% Work of the outside world on the fixed degrees of freedom (trapezoidal rule). +averageForce = (state.force(mesh.fixed) + state.previousForce(mesh.fixed)) / 2.0; +externalWork = -sum(averageForce .* (u(mesh.fixed) - uPrev(mesh.fixed))); + +% Work of the applied forces on the free degrees of freedom. +averageApplied = (state.appliedForce + state.previousAppliedForce) / 2.0; +free = ~mesh.fixed; +externalWork = externalWork + sum(averageApplied(free) .* (u(free) - uPrev(free))); + +state.externalEnergy = state.externalEnergy + externalWork; +state.previousForce = state.force; +state.previousAppliedForce = state.appliedForce; +state.dampingEnergy = state.dampingEnergy + dissipated; +state.previousDisplacement = u; +state.displacement = uNext; +state.velocity = velocity; +state.acceleration = acceleration; +end diff --git a/src/+ldem/+solver/nodalKineticEnergy.m b/src/+ldem/+solver/nodalKineticEnergy.m new file mode 100644 index 0000000..c49b1d2 --- /dev/null +++ b/src/+ldem/+solver/nodalKineticEnergy.m @@ -0,0 +1,31 @@ +function energy = nodalKineticEnergy(state, mesh) +%NODALKINETICENERGY Kinetic energy of every node. +% +% energy = ldem.solver.nodalKineticEnergy(state, mesh) returns the kinetic +% energy [J] of each node, m*|v|^2/2, with the lumped mass of the node and +% its current velocity. The kinetic energy of the whole model is the sum of +% the vector (it is energy.kinetic of ldem.solver.computeEnergies). +% +% Inputs: +% state Solver state (uses velocity). +% mesh Struct from ldem.mesh.buildMesh (uses mass). +% +% Output: +% energy nNodes-by-1 vector [J]. +% +% Example: +% perNode = ldem.solver.nodalKineticEnergy(state, mesh); +% total = sum(perNode); +% +% Legacy: ENCN of ENERG2, which was left as a vector and never summed. +% +% See also ldem.solver.computeEnergies. + +arguments + state (1,1) struct + mesh (1,1) struct +end + +speedSquared = state.velocity(:, 1).^2 + state.velocity(:, 2).^2 + state.velocity(:, 3).^2; +energy = mesh.mass .* speedSquared ./ 2.0; +end diff --git a/src/+ldem/+solver/simulate.m b/src/+ldem/+solver/simulate.m new file mode 100644 index 0000000..2888b84 --- /dev/null +++ b/src/+ldem/+solver/simulate.m @@ -0,0 +1,166 @@ +function [state, record] = simulate(params, mesh, barProps, history, scenario, options) +%SIMULATE Run the explicit time integration of an LDEM model. +% +% [state, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario) +% advances the model from time zero to params.totalTime and returns the +% final state and the results recorded along the way. +% +% Every step does, in this order: +% 1. advance the time, +% 2. impose the loading of the scenario, +% 3. compute the bar forces (damage included), +% 4. integrate the equations of motion, +% 5. compute the energies and store the requested results. +% +% Inputs: +% params ldem.Parameters. +% mesh Struct from ldem.mesh.buildMesh. +% barProps Struct from ldem.material.buildBarProperties. +% history Initial damage state, second output of buildBarProperties. +% scenario Object of a subclass of ldem.scenarios.Scenario. +% +% Name-value options: +% +% SnapshotFcn Function handle f(state) for the snapshots (see below). +% Verbose Print the progress every 10 % (default false). +% +% SnapshotFcn is called at time zero and every params.output.snapshotEvery +% steps, and never if that value is 0. +% +% Outputs: +% state Final solver state, see ldem.solver.initialState. +% record Struct with the results stored along the run, see below. +% +% Fields of record: +% +% controlNodes time (n-by-1) and displacement, velocity, acceleration (n-by-k-by-3 for k nodes). +% reactions time (n-by-1) and force (n-by-3), the scenario reaction. +% energy time and the energies of ldem.solver.computeEnergies as column vectors. +% trackedBar bar number, time, strain, criticalStrain, ruptureStrain, force, damageEnergy. +% +% controlNodes and reactions are stored every params.output.controlNodesEvery +% steps and energy every energyEvery steps. trackedBar is stored at every +% step, only when trackedBarEvery is 1 and the bar exists in the mesh. +% +% Errors: +% ldem:solver:nonFinite A displacement became NaN or Inf (unstable +% time step or coincident nodes). +% +% Example: +% params = ldem.Parameters(); +% mesh = ldem.mesh.buildMesh(params); +% [barProps, history] = ldem.material.buildBarProperties(mesh, params); +% scenario = ldem.scenarios.fromTestId(params.testId); +% [state, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario); +% +% Legacy: the time loop of the main program (main1) with CALOAD, CABAR, +% IGN012, CALRES, WRIDIPO, ENERG2 and WRIENE. +% +% See also ldem.solver.computeBarForces, ldem.solver.integrateStep, +% ldem.solver.computeEnergies. + +arguments + params (1,1) ldem.Parameters + mesh (1,1) struct + barProps (1,1) struct + history (1,1) struct + scenario (1,1) ldem.scenarios.Scenario + options.SnapshotFcn = [] + options.Verbose (1,1) logical = false +end + +ldem.solver.checkStability(mesh.barLength, params); +law = ldem.material.lawFromName(params.constitutiveLaw); +damping = ldem.solver.dampingFromName(params.dampingModel); + +nSteps = params.nSteps; +controlEvery = params.output.controlNodesEvery; +energyEvery = params.output.energyEvery; +snapshotEvery = params.output.snapshotEvery; +trackBar = params.output.trackedBarEvery > 0 && params.trackedBar <= size(mesh.bars, 1); + +nControl = numel(params.controlNodes); +nControlRows = floor(nSteps / max(controlEvery, 1)) * (controlEvery > 0); +nEnergyRows = floor(nSteps / max(energyEvery, 1)) * (energyEvery > 0); + +record = struct(); +record.controlNodes = struct( ... + 'time', zeros(nControlRows, 1), ... + 'displacement', zeros(nControlRows, nControl, 3), ... + 'velocity', zeros(nControlRows, nControl, 3), ... + 'acceleration', zeros(nControlRows, nControl, 3)); +record.reactions = struct('time', zeros(nControlRows, 1), 'force', zeros(nControlRows, 3)); +record.energy = struct('time', zeros(nEnergyRows, 1), 'kinetic', zeros(nEnergyRows, 1), ... + 'elastic', zeros(nEnergyRows, 1), 'damage', zeros(nEnergyRows, 1), ... + 'damping', zeros(nEnergyRows, 1), 'internal', zeros(nEnergyRows, 1), ... + 'brokenBars', zeros(nEnergyRows, 1), 'damageRate', zeros(nEnergyRows, 1), ... + 'external', zeros(nEnergyRows, 1), 'balance', zeros(nEnergyRows, 1)); +nTracked = nSteps * trackBar; +record.trackedBar = struct('bar', params.trackedBar, 'time', zeros(nTracked, 1), ... + 'strain', zeros(nTracked, 1), 'criticalStrain', zeros(nTracked, 1), ... + 'ruptureStrain', zeros(nTracked, 1), 'force', zeros(nTracked, 1), ... + 'damageEnergy', zeros(nTracked, 1)); + +state = ldem.solver.initialState(mesh, history); +if snapshotEvery > 0 && ~isempty(options.SnapshotFcn) + options.SnapshotFcn(state); +end + +controlRow = 0; +energyRow = 0; +progressStep = max(1, floor(nSteps / 10)); + +for step = 1:nSteps + state.step = step; + state.time = state.time + params.dt; + + state = scenario.applyLoads(state, mesh, params); + state = ldem.solver.computeBarForces(state, mesh, barProps, params, law); + state = ldem.solver.integrateStep(state, mesh, barProps, params, law, damping); + + if ~all(isfinite(state.displacement), 'all') + error('ldem:solver:nonFinite', ... + ['Displacements are not finite at step %d (time %g s). The time ' ... + 'step may be unstable or two nodes coincide.'], step, state.time); + end + + energy = ldem.solver.computeEnergies(state, mesh, barProps, params, law); + state.previousDamageEnergy = energy.damage; + + if controlEvery > 0 && mod(step, controlEvery) == 0 + controlRow = controlRow + 1; + record.controlNodes.time(controlRow) = state.time; + record.controlNodes.displacement(controlRow, :, :) = reshape(state.displacement(params.controlNodes, :), 1, nControl, 3); + record.controlNodes.velocity(controlRow, :, :) = reshape(state.velocity(params.controlNodes, :), 1, nControl, 3); + record.controlNodes.acceleration(controlRow, :, :) = reshape(state.acceleration(params.controlNodes, :), 1, nControl, 3); + record.reactions.time(controlRow) = state.time; + record.reactions.force(controlRow, :) = scenario.reactions(state, mesh, params); + end + + if energyEvery > 0 && mod(step, energyEvery) == 0 + energyRow = energyRow + 1; + names = fieldnames(record.energy); + for k = 1:numel(names) + record.energy.(names{k})(energyRow) = energy.(names{k}); + end + end + + if trackBar + b = params.trackedBar; + record.trackedBar.time(step) = state.time; + record.trackedBar.strain(step) = state.strain(b); + record.trackedBar.criticalStrain(step) = barProps.criticalStrain(b); + record.trackedBar.ruptureStrain(step) = barProps.ruptureStrain(b); + record.trackedBar.force(step) = state.axialForce(b); + record.trackedBar.damageEnergy(step) = law.barDamageEnergy(b, barProps, state.history, mesh.barLength); + end + + if snapshotEvery > 0 && mod(step, snapshotEvery) == 0 && ~isempty(options.SnapshotFcn) + options.SnapshotFcn(state); + end + + if options.Verbose && mod(step, progressStep) == 0 + fprintf(' step %d / %d (t = %.4g s)\n', step, nSteps, state.time); + end +end +end diff --git a/src/+ldem/Parameters.m b/src/+ldem/Parameters.m new file mode 100644 index 0000000..6cb20ef --- /dev/null +++ b/src/+ldem/Parameters.m @@ -0,0 +1,342 @@ +classdef Parameters + %PARAMETERS Validated input parameters of an LDEM simulation. + % + % p = ldem.Parameters() creates a parameter set with default values + % (a small tension test that runs in seconds). + % + % p = ldem.Parameters(Name=Value, ...) overrides any property, for + % example: + % + % p = ldem.Parameters(testId=102, nModules=[70 4 3], dt=2e-7); + % + % p = ldem.Parameters.fromFile("DATA0.DAT") reads the legacy input + % file format, see ldem.io.readInputFile. + % + % Every property is validated when it is assigned (type, size and + % range). Rules that involve several properties, such as the + % stability of the time step, are checked by validate(), which the + % constructor and ldem.runSimulation call for you. + % + % Units are SI (m, s, kg, Pa, N) unless stated otherwise. + % + % Legacy names: the comment on each property gives the variable of the + % original code (DATA0.DAT / global variables) it replaces. + % + % See also ldem.io.readInputFile, ldem.runSimulation. + + properties + % Test identifier selecting the boundary conditions and loads + % (101 = uniaxial tension, 102 = four-point bending, 103 = beam + % clamped at both ends loaded with a force). Legacy: TEST. + testId (1,1) double {mustBeInteger, mustBePositive} = 101 + + % Seed of the random number generator used for the optional mesh + % perturbation. Legacy: SEED. + seed (1,1) double {mustBeInteger, mustBeNonnegative} = 123 + + % Edge length of the cubic module [m]. Legacy: LCO. + moduleLength (1,1) double {mustBePositive, mustBeFinite} = 0.003 + + % Number of nodes along x, y and z of the prism, [M N L]; the prism + % has (M-1)*(N-1)*(L-1) cubic modules. Legacy: M, N, L. + nModules (1,3) double {mustBeInteger, mustBeGreaterThanOrEqual(nModules, 2)} = [6 3 3] + + % Mass-proportional damping coefficient before the switch time + % [1/s]. Legacy: DF1. + dampingInitial (1,1) double {mustBeNonnegative, mustBeFinite} = 25000 + + % Mass-proportional damping coefficient after the switch time + % [1/s]. Legacy: DF2. + dampingFinal (1,1) double {mustBeNonnegative, mustBeFinite} = 25000 + + % Time at which the damping changes from dampingInitial to + % dampingFinal [s]. Legacy: TDAF. + dampingSwitchTime (1,1) double {mustBeNonnegative, mustBeFinite} = 0.015 + + % Damping coefficient inside the constitutive law, proportional to + % the stiffness [s]. Legacy: CON. + constitutiveDamping (1,1) double {mustBeNonnegative, mustBeFinite} = 0 + + % Constitutive law of the bars: a name of ldem.material.lawRegistry + % ("bilinear", the legacy law, or "linear_elastic"). Checked by + % validate(). + constitutiveLaw (1,1) string = "bilinear" + + % Damping model of the nodes: a name of ldem.solver.dampingRegistry + % ("mass_proportional", the legacy damping, or "none"). Checked by + % validate(). + dampingModel (1,1) string = "mass_proportional" + + % Integration time step [s]. Legacy: DT. + dt (1,1) double {mustBePositive, mustBeFinite} = 2e-7 + + % Total simulated time [s]. Legacy: TTOT. + totalTime (1,1) double {mustBePositive, mustBeFinite} = 4e-5 + + % Node numbers of the control points whose motion is recorded, as a + % row vector (at most 10). Legacy: INCO, NCON. + controlNodes (1,:) double {mustBeInteger, mustBePositive} = [1 2] + + % Young's modulus [Pa]. Legacy: YNG. + youngModulus (1,1) double {mustBePositive, mustBeFinite} = 32e9 + + % Mass density [kg/m^3]. Legacy: ROH. + density (1,1) double {mustBePositive, mustBeFinite} = 2000 + + % Poisson's ratio, from 0 up to (not including) 0.5. The upper + % limit is checked by validate(). Legacy: PSN. + poissonRatio (1,1) double {mustBeNonnegative, mustBeFinite} = 0.25 + + % Specific fracture energy [N/m]. Legacy: GFR. + fractureEnergy (1,1) double {mustBePositive, mustBeFinite} = 50 + + % Equivalent (critical) distance [m]. Legacy: DEQ. + criticalDistance (1,1) double {mustBePositive, mustBeFinite} = 0.028 + + % Fraction of the module face that fails per bar (area of failure is + % failureAreaFactor*length). Legacy: CAF, hardcoded to 0.1385. + failureAreaFactor (1,1) double {mustBePositive, mustBeFinite} = 0.1385 + + % Number of the bar whose strain history is recorded. + % Legacy: hardcoded 7014 in CABAR and ENERG2. + trackedBar (1,1) double {mustBeInteger, mustBePositive} = 7014 + + % Text file with one multiplier of the critical strain per bar + % (random field). Empty means "no random field" (all multipliers 1) + % unless randomFieldCv is positive. Legacy: file + % "arquivo_3lc_rnao_cv05". + randomFieldFile (1,1) string = "" + + % Coefficient of variation of the random field generated in memory + % (see ldem.material.generateRandomField). 0 (the default) generates + % nothing; a positive value, between 1e-4 and 3, generates the field + % and cannot be combined with randomFieldFile. Legacy: Cv of + % Aleat_novo4.m (0.05 for "arquivo_3lc_rnao_cv05"). + randomFieldCv (1,1) double {mustBeNonnegative, mustBeFinite} = 0 + + % Correlation length of the generated random field, that is the + % spacing of its pole grid, in module lengths (multiples of + % moduleLength): a scalar or [x y z]. Legacy: lcorx, lcory, lcorz + % of Aleat_novo4.m divided by Lc ("3lc" means 3). + randomFieldCorrelationLength (1,:) double {mustBePositive, mustBeFinite} = 3 + + % Seed of the random numbers of the generated random field. + % Legacy: semente of Aleat_novo4.m. + randomFieldSeed (1,1) double {mustBeInteger, mustBeNonnegative} = 515 + + % Random perturbation of the node coordinates, as the standard + % deviation expressed as a fraction of the module length. 0 (the + % default) switches the perturbation off; any positive value + % switches it on with that value (for example 0.02 displaces the + % nodes by about 2 % of the module length). Legacy: LABELN (always + % 0, so the legacy results have no perturbation) and CVUVW = 0.02. + meshPerturbation (1,1) double {mustBeNonnegative, mustBeFinite} = 0 + + % How often each result is stored, in time steps (0 = never): + % + % * snapshotEvery: ANSYS/VTK files and full-field snapshots (OU3). + % * controlNodesEvery: control nodes and reactions (OU6). + % * energyEvery: global energies (OU8). + % * trackedBarEvery: tracked bar, 0 or 1; the legacy code stores it + % at every step when OU9 > 0 (OU9). + output (1,1) struct = struct('snapshotEvery', 0, ... + 'controlNodesEvery', 10, 'energyEvery', 10, 'trackedBarEvery', 0) + end + + properties (Dependent, SetAccess = private) + % Number of time steps, round(totalTime/dt). Legacy: NSTEP. + nSteps + + % Step at which the damping changes, round(dampingSwitchTime/dt). + % Legacy: NDAMF. + dampingSwitchStep + + % Total number of nodes: grid nodes plus module-centre nodes. + % Legacy: NNT. + nNodes + + % Elastic wave speed sqrt(E/rho) [m/s]. + waveSpeed + + % Largest stable time step for a regular (unperturbed) lattice [s]. + % The shortest bar joins a module centre to a corner and measures + % sqrt(3)/2 times the module length. + criticalTimeStep + end + + methods + function obj = Parameters(props) + %PARAMETERS Create and validate a parameter set. + arguments + props.?ldem.Parameters + end + names = fieldnames(props); + for k = 1:numel(names) + obj.(names{k}) = props.(names{k}); + end + obj.validate(); + end + + function validate(obj) + %VALIDATE Check the rules that involve several properties. + % + % p.validate() throws an error with an identifier of the form + % "ldem:params:" and a message that says how to fix + % it. It returns silently when the parameters are consistent. + + % The lattice stiffness formulas diverge as the ratio approaches 1/2. + if obj.poissonRatio >= 0.5 + error('ldem:params:badPoissonRatio', ... + 'poissonRatio must be smaller than 0.5, got %g.', obj.poissonRatio); + end + + % The law and the damping model must be registered. + if ~any([ldem.material.lawRegistry().name] == lower(obj.constitutiveLaw)) + error('ldem:params:unknownLaw', ... + 'constitutiveLaw "%s" does not exist. Available: %s.', obj.constitutiveLaw, ... + strjoin([ldem.material.lawRegistry().name], ', ')); + end + if ~any([ldem.solver.dampingRegistry().name] == lower(obj.dampingModel)) + error('ldem:params:unknownDampingModel', ... + 'dampingModel "%s" does not exist. Available: %s.', obj.dampingModel, ... + strjoin([ldem.solver.dampingRegistry().name], ', ')); + end + + % Control nodes must exist and be few. + if numel(obj.controlNodes) > 10 + error('ldem:params:tooManyControlNodes', ... + 'At most 10 control nodes are supported, got %d.', ... + numel(obj.controlNodes)); + end + if any(obj.controlNodes > obj.nNodes) + error('ldem:params:controlNodeOutOfRange', ... + ['Control node %d does not exist: the mesh has only ' ... + '%d nodes.'], max(obj.controlNodes), obj.nNodes); + end + + % Output settings. + required = {'snapshotEvery','controlNodesEvery','energyEvery','trackedBarEvery'}; + if ~all(isfield(obj.output, required)) || numel(fieldnames(obj.output)) ~= numel(required) + error('ldem:params:badOutput', ... + 'output must have exactly the fields: %s.', strjoin(required, ', ')); + end + for k = 1:numel(required) + v = obj.output.(required{k}); + if ~(isnumeric(v) && isscalar(v) && isfinite(v) && v >= 0 && v == fix(v)) + error('ldem:params:badOutput', ... + 'output.%s must be a non-negative integer.', required{k}); + end + end + if obj.output.trackedBarEvery > 1 + error('ldem:params:badOutput', ... + 'output.trackedBarEvery must be 0 or 1 (the tracked bar is stored at every step).'); + end + + % Random field: from a file or generated, not both. + if obj.randomFieldCv > 0 && strlength(obj.randomFieldFile) > 0 + error('ldem:params:twoRandomFields', ... + ['Set either randomFieldFile (read the field) or randomFieldCv ' ... + '(generate it), not both.']); + end + if obj.randomFieldCv > 0 && (obj.randomFieldCv < 1e-4 || obj.randomFieldCv > 3) + error('ldem:params:badRandomFieldCv', ... + 'randomFieldCv must be 0 or between 1e-4 and 3, got %g.', obj.randomFieldCv); + end + if ~any(numel(obj.randomFieldCorrelationLength) == [1 3]) + error('ldem:params:badCorrelationLength', ... + ['randomFieldCorrelationLength must be a scalar or have 3 values ' ... + '[x y z], got %d values.'], numel(obj.randomFieldCorrelationLength)); + end + + % Time integration. + if obj.totalTime < obj.dt + error('ldem:params:totalTimeTooShort', ... + 'totalTime (%g s) must be at least one time step (dt = %g s).', ... + obj.totalTime, obj.dt); + end + if obj.meshPerturbation == 0 && obj.dt > obj.criticalTimeStep + error('ldem:params:unstableTimeStep', ... + ['The time step dt = %g s is unstable. For moduleLength = %g m, ' ... + 'youngModulus = %g Pa and density = %g kg/m^3 it must not exceed ' ... + '%g s. Reduce dt or increase moduleLength.'], ... + obj.dt, obj.moduleLength, obj.youngModulus, obj.density, obj.criticalTimeStep); + end + end + + function s = toStruct(obj) + %TOSTRUCT Convert the parameters (and derived values) to a plain struct. + % + % s = p.toStruct() returns a struct with one field per property, + % derived values included. Unlike the object it can be loaded + % from a MAT-file without the ldem package on the path, so it + % is what ldem.runSimulation stores in the results. + names = properties(obj); + s = struct(); + for k = 1:numel(names) + s.(names{k}) = obj.(names{k}); + end + end + + function value = get.nSteps(obj) + value = round(obj.totalTime / obj.dt); + end + + function value = get.dampingSwitchStep(obj) + value = round(obj.dampingSwitchTime / obj.dt); + end + + function value = get.nNodes(obj) + gridNodes = prod(obj.nModules); + centreNodes = prod(obj.nModules - 1); + value = gridNodes + centreNodes; + end + + function value = get.waveSpeed(obj) + value = sqrt(obj.youngModulus / obj.density); + end + + function value = get.criticalTimeStep(obj) + shortestBar = obj.moduleLength * sqrt(3) / 2; + value = shortestBar / obj.waveSpeed; + end + end + + methods (Static) + function obj = fromFile(path, overrides) + %FROMFILE Read an input file: a case file or the legacy DATA0.DAT. + % + % p = ldem.Parameters.fromFile(path) reads the file and + % returns a validated parameter set. A path ending in .ldem or + % .json is a case file (see ldem.io.readCase, which also gives + % the scenario and the output options); any other file is read + % in the legacy DATA0.DAT format. + % + % p = ldem.Parameters.fromFile(path, Name=Value) additionally + % overrides properties that are not stored in the file, for + % example randomFieldFile or trackedBar. + % + % See also ldem.io.readCase, ldem.io.readInputFile. + arguments + path (1,1) string + overrides.?ldem.Parameters + end + [~, ~, extension] = fileparts(path); + if any(lower(extension) == [".ldem" ".json"]) + obj = ldem.io.readCase(path).params; + names = fieldnames(overrides); + for k = 1:numel(names) + obj.(names{k}) = overrides.(names{k}); + end + obj.validate(); + return + end + fromFile = ldem.io.readInputFile(path); + names = fieldnames(overrides); + for k = 1:numel(names) + fromFile.(names{k}) = overrides.(names{k}); + end + args = namedargs2cell(fromFile); + obj = ldem.Parameters(args{:}); + end + end +end diff --git a/src/+ldem/check.m b/src/+ldem/check.m new file mode 100644 index 0000000..9012037 --- /dev/null +++ b/src/+ldem/check.m @@ -0,0 +1,107 @@ +function report = check(casePath) +%CHECK Dry run of a case file: validate it and report the model without simulating. +% +% ldem.check(casePath) reads the case file, builds the lattice (without +% integrating in time) and prints what the simulation would do: size of the +% model, stability margin of the time step, where each "at" control node +% landed, the state of the random-field file, and the memory that the +% snapshots will need. +% +% report = ldem.check(casePath) returns the same information in a struct +% and prints nothing. +% +% Input: +% casePath Path of the case file (.ldem or .json). +% +% Output: +% report Struct with the fields +% params, scenario As returned by ldem.io.readCase. +% model ldem.mesh.summarizeModel of the lattice. +% timeStepRatio dt divided by the critical time step. +% nSteps Number of time steps. +% nSnapshots Snapshots taken (0 if never). +% snapshotMemoryMB Memory of the snapshots kept in results. +% randomField Text: "none", "generated" or the state of the file. +% controlNodes Struct array: number, name and position [x y z] in modules. +% +% Errors: +% The ones of ldem.io.readCase, and ldem:scenarios:noNodesSelected when +% the scenario selects no node of the lattice. +% +% Example: +% ldem.check("examples/example1_clamped_beam/case.ldem") +% +% See also ldem.run, ldem.io.readCase. + +arguments + casePath (1,1) string +end + +c = ldem.io.readCase(casePath); +p = c.params; +mesh = ldem.mesh.buildMesh(p, c.scenario); +model = ldem.mesh.summarizeModel(mesh, p); + +report = struct(); +report.params = p; +report.scenario = c.scenario; +report.model = model; +report.timeStepRatio = p.dt / p.criticalTimeStep; +report.nSteps = p.nSteps; + +every = p.output.snapshotEvery; +if every > 0 + report.nSnapshots = floor(p.nSteps / every) + 1; +else + report.nSnapshots = 0; +end +bytesPerSnapshot = 4 * 3 * model.nNodes + model.nBars + 4 * model.nNodes; +report.snapshotMemoryMB = report.nSnapshots * bytesPerSnapshot / 2^20; + +if strlength(p.randomFieldFile) > 0 + try + ldem.io.readRandomField(p.randomFieldFile, model.nBars); + report.randomField = "file OK: " + p.randomFieldFile + " has at least " + string(model.nBars) + " values"; + catch err + report.randomField = "file PROBLEM: " + string(err.message); + end +elseif p.randomFieldCv > 0 + report.randomField = "generated in memory (cv " + string(p.randomFieldCv) + ")"; +else + report.randomField = "none"; +end + +nodes = mesh.nodes0 / p.moduleLength; +report.controlNodes = struct('number', num2cell(p.controlNodes), ... + 'name', cellstr(c.info.controlNodeNames), ... + 'position', num2cell(nodes(p.controlNodes, :), 2).'); + +if nargout == 0 + printReport(report, c, casePath); + clear report +end +end + +function printReport(report, c, casePath) +p = report.params; +m = report.model; +fprintf('Case file %s\n', casePath); +if strlength(c.info.title) > 0 + fprintf('Title %s\n', c.info.title); +end +fprintf('Scenario %s (testId %d)\n', class(report.scenario), p.testId); +fprintf('Model %d x %d x %d modules of %g m, %d nodes, %d bars, mass %.4g kg\n', ... + m.nModules, p.moduleLength, m.nNodes, m.nBars, m.totalMass); +fprintf('Time %d steps of %g s (%.0f %% of the critical step %g s), %g s in total\n', ... + report.nSteps, p.dt, 100 * report.timeStepRatio, p.criticalTimeStep, p.totalTime); +fprintf('Random field %s\n', report.randomField); +fprintf('Snapshots %d (about %.1f MB kept in results)\n', ... + report.nSnapshots, report.snapshotMemoryMB); +for node = report.controlNodes + fprintf('Control node %-12s number %d at [%g %g %g] modules\n', ... + node.name, node.number, node.position); +end +for note = c.info.nodeNotes.' + fprintf('Note %s\n', note); +end +end diff --git a/src/+ldem/run.m b/src/+ldem/run.m new file mode 100644 index 0000000..9f62025 --- /dev/null +++ b/src/+ldem/run.m @@ -0,0 +1,104 @@ +function results = run(casePath, options) +%RUN Run a simulation described by a case file (.ldem or .json). +% +% results = ldem.run(casePath) reads the case file with ldem.io.readCase and +% runs it with ldem.runSimulation, writing the files requested in its +% [output] section (relative to the case file). It is the one-line way to +% run a model: +% +% results = ldem.run("examples/example1_clamped_beam/case.ldem"); +% +% results = ldem.run(casePath, Name=Value) overrides parts of the case: +% +% OutputFolder Other output folder ("" writes nothing). +% Formats Other files to write, for example "mat". +% Verbose Print the progress (default true). +% Overrides Struct array (fields path = "section.key" and value) that replaces keys of the case. +% +% To make the run reproducible, results.info.case keeps +% +% source Path of the case file. +% sha256 SHA-256 hash of the file that was read (text, 64 hex digits). +% original Text of that file. +% resolved Complete case with every default and the overrides, as ldem.io.writeCase writes it. +% parents Struct array (source, sha256) of the case files inherited through extends. +% overrides Text lines "key = value" of the Overrides option. +% +% and, when files are written, the resolved case is also saved as +% "case.ldem" in the output folder, so a result folder can be run again with +% ldem.run(fullfile(folder, "case.ldem")). +% +% Input: +% casePath Path of the case file. +% +% Output: +% results Struct returned by ldem.runSimulation. +% +% Example: +% results = ldem.run("my_test.ldem", OutputFolder=tempname); +% +% See also ldem.check, ldem.io.readCase, ldem.runSimulation. + +arguments + casePath (1,1) string + options.OutputFolder = [] + options.Formats = [] + options.Verbose (1,1) logical = true + options.Overrides = [] +end + +c = ldem.io.readCase(casePath, Overrides = options.Overrides); +if ~isempty(c.info.sweep) && isempty(options.Overrides) + warning('ldem:run:sweepIgnored', ... + '%s defines a sweep of %d key(s); ldem.run runs only the base case. Use ldem.sweep to run them all.', ... + casePath, numel(c.info.sweep)); +end +folder = c.options.OutputFolder; +formats = c.options.Formats; +if ~isempty(options.OutputFolder) + folder = string(options.OutputFolder); +end +if ~isempty(options.Formats) + formats = string(options.Formats); +end + +original = string(fileread(c.info.source)); +resolvedFormats = formats; +if isempty(resolvedFormats) + resolvedFormats = "mat"; +end +resolved = ldem.io.writeCase("", c.params, c.scenario, ... + Title = c.info.title, Authors = c.info.authors, ... + ControlNodeNames = c.info.controlNodeNames, ... + Header = "Resolved from " + c.info.source + " by ldem.run.", ... + Formats = resolvedFormats); +parents = struct('source', {}, 'sha256', {}); +for parent = c.info.parents.' + parents(end+1) = struct('source', parent, 'sha256', sha256Of(string(fileread(parent)))); %#ok +end +overrideLines = strings(0, 1); +for k = 1:numel(options.Overrides) + overrideLines(end+1, 1) = string(options.Overrides(k).path) + " = " + string(options.Overrides(k).value); %#ok +end +caseInfo = struct('source', c.info.source, 'sha256', sha256Of(original), ... + 'original', original, 'resolved', resolved, 'parents', parents, 'overrides', overrideLines); + +results = ldem.runSimulation(c.params, Scenario = c.scenario, ... + OutputFolder = folder, Formats = formats, Verbose = options.Verbose, ... + CaseInfo = caseInfo); + +if strlength(folder) > 0 + ldem.io.writeCase(fullfile(folder, "case.ldem"), c.params, c.scenario, ... + Title = c.info.title, Authors = c.info.authors, ... + ControlNodeNames = c.info.controlNodeNames, ... + Header = "Resolved from " + c.info.source + " by ldem.run.", ... + OutputFolder = ".", Formats = resolvedFormats); +end +end + +function hash = sha256Of(text) +%SHA256OF SHA-256 of a text as 64 lower-case hexadecimal digits. +digest = java.security.MessageDigest.getInstance('SHA-256'); +bytes = typecast(digest.digest(uint8(char(text))), 'uint8'); +hash = string(lower(reshape(dec2hex(bytes, 2).', 1, []))); +end diff --git a/src/+ldem/runSimulation.m b/src/+ldem/runSimulation.m new file mode 100644 index 0000000..f786a40 --- /dev/null +++ b/src/+ldem/runSimulation.m @@ -0,0 +1,146 @@ +function results = runSimulation(params, options) +%RUNSIMULATION Run a complete LDEM simulation. +% +% results = ldem.runSimulation(params) builds the lattice model described +% by params, integrates it in time and returns all the useful information +% in one struct. +% +% results = ldem.runSimulation(params, Name=Value) accepts options, for +% example +% +% results = ldem.runSimulation(params, OutputFolder="output", ... +% Formats=["mat" "ansys" "vtk"]); +% +% writes results.mat, ANSYS macro files and a VTK series (to open in +% ParaView) to the folder "output". +% +% Name-value options: +% +% OutputFolder Folder for the output files (empty: nothing is written). +% Formats Files to write: "mat", "ansys" and/or "vtk" (default "mat"). +% Scenario Scenario object (default: the one registered for params.testId). +% Verbose Print the progress (default false). +% CaseInfo Struct stored in results.info.case (ldem.run keeps the case file that was run there). +% +% With an empty OutputFolder the results are only returned. The ANSYS and +% VTK files are written at time zero and every params.output.snapshotEvery +% steps, so that value must be positive to obtain them. +% +% Output: +% results Struct with the parts listed below. +% +% Fields of results: +% +% info Version of ldem, date, MATLAB release, run time. +% params Input parameters (plain struct, derived values included). +% model Counts and mass of the model (ldem.mesh.summarizeModel). +% material Material data and statistics (ldem.material.summarizeMaterial). +% mesh Nodes, supports, masses, bars and bar geometry. +% barProps Constant properties of the bars. +% controlNodes Motion of the control nodes versus time. +% reactions Reaction force of the test versus time. +% energy Energies versus time. +% trackedBar History of the bar params.trackedBar (may be empty). +% snapshots Compact copies of the state at the snapshot steps. +% final Final state of nodes and bars, with the kinetic energy of each node. +% +% The fields of each part are described in ldem.solver.simulate, +% ldem.mesh.buildMesh, ldem.material.buildBarProperties and +% ldem.io.SnapshotWriter. +% +% Example: +% params = ldem.Parameters(testId=101, nModules=[6 3 3], totalTime=2e-4); +% results = ldem.runSimulation(params); +% ldem.post.plotEnergy(results); +% +% Legacy: the main program (main1) and its input/output routines. +% +% See also ldem.Parameters, ldem.solver.simulate, ldem.io.saveResults. + +arguments + params (1,1) ldem.Parameters + options.OutputFolder (1,1) string = "" + options.Formats (1,:) string {mustBeMember(options.Formats, ["mat", "ansys", "vtk"])} = "mat" + options.Scenario = [] + options.Verbose (1,1) logical = false + options.CaseInfo = [] +end + +params.validate(); +if isempty(options.Scenario) + scenario = ldem.scenarios.fromTestId(params.testId); +else + scenario = options.Scenario; +end + +writeFiles = strlength(options.OutputFolder) > 0; +snapshotFormats = intersect(options.Formats, ["ansys", "vtk"], 'stable'); +if ~writeFiles + snapshotFormats = string.empty; +elseif ~isempty(snapshotFormats) && params.output.snapshotEvery == 0 + warning('ldem:output:noSnapshots', ... + ['%s files were requested but params.output.snapshotEvery is 0, so ' ... + 'none will be written. Set snapshotEvery to the number of steps ' ... + 'between files.'], strjoin(upper(snapshotFormats), ' and ')); +end +if writeFiles && ~isfolder(options.OutputFolder) + mkdir(options.OutputFolder); +end + +timer = tic; +if options.Verbose + fprintf('Building the model (%d nodes) ...\n', params.nNodes); +end +mesh = ldem.mesh.buildMesh(params, scenario); +[barProps, history] = ldem.material.buildBarProperties(mesh, params); + +writer = ldem.io.SnapshotWriter(mesh, options.OutputFolder, snapshotFormats); +if options.Verbose + fprintf('Integrating %d steps ...\n', params.nSteps); +end +[state, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario, ... + SnapshotFcn=@writer.write, Verbose=options.Verbose); + +results = struct(); +results.info = struct( ... + 'version', ldem.version(), ... + 'date', string(datetime('now', 'Format', 'yyyy-MM-dd HH:mm:ss')), ... + 'matlabRelease', string(version('-release')), ... + 'elapsedSeconds', toc(timer)); +if ~isempty(options.CaseInfo) + results.info.case = options.CaseInfo; +end +results.params = params.toStruct(); +results.model = ldem.mesh.summarizeModel(mesh, params); +results.material = ldem.material.summarizeMaterial(barProps, params); +results.mesh = mesh; +results.barProps = barProps; +results.controlNodes = record.controlNodes; +results.reactions = record.reactions; +results.energy = record.energy; +results.trackedBar = record.trackedBar; +results.snapshots = writer.finish(); +results.final = finalState(state, mesh); + +if writeFiles && any(options.Formats == "mat") + ldem.io.saveResults(fullfile(options.OutputFolder, "results.mat"), results); +end +if options.Verbose + fprintf('Done in %.1f s.\n', results.info.elapsedSeconds); +end +end + +function final = finalState(state, mesh) +%FINALSTATE Fields of the solver state worth keeping after the run. +final = struct( ... + 'step', state.step, ... + 'time', state.time, ... + 'displacement', state.displacement, ... + 'velocity', state.velocity, ... + 'acceleration', state.acceleration, ... + 'kineticEnergy', ldem.solver.nodalKineticEnergy(state, mesh), ... + 'force', state.force, ... + 'strain', state.strain, ... + 'axialForce', state.axialForce, ... + 'damage', state.history); +end diff --git a/src/+ldem/sweep.m b/src/+ldem/sweep.m new file mode 100644 index 0000000..6c7a987 --- /dev/null +++ b/src/+ldem/sweep.m @@ -0,0 +1,195 @@ +function [summary, results] = sweep(casePath, options) +%SWEEP Run a case once for every combination of values of some keys. +% +% summary = ldem.sweep(casePath) runs the case file once for each value of the +% keys listed in its [[sweep]] blocks and returns a table with one row per run: +% +% [[sweep]] +% key = "material.fracture_energy" +% values = ["0.1 N/m", "0.5 N/m", "1 N/m"] +% +% [[sweep]] +% key = "scenario.force_rate" +% values = ["1 kN/s", "2 kN/s"] +% +% Several blocks give every combination (3 x 2 = 6 runs); with sweep_mode = +% "zip" they are taken one by one instead (all lists must have the same +% length). A key can be any single-valued key of the case file, or a key of the +% scenario ("scenario."); values are numbers or texts with units, as in +% the file. Every run is validated before the first one starts, so a bad value +% stops the sweep at once. +% +% Each run writes its files to /run_001, run_002, ... with the +% resolved case as case.ldem, and the table is saved as sweep_summary.csv in +% OutputFolder. A run that fails is recorded in the table (status "failed", +% with the message) and the sweep goes on. +% +% Inputs: +% casePath Path of the case file. +% +% Name-value options: +% Vary Cell {key1, values1, key2, values2, ...} with more keys to vary besides the [[sweep]] blocks. +% Mode "product" or "zip" (default: sweep_mode of the file, product). +% OutputFolder Folder of the runs (default "_sweep" next to the file). +% Formats Files to write in each run, for example "mat" (default: the ones of the case). +% Verbose Print one line per run (default true). +% DryRun Only validate and list the runs, without running them. +% KeepResults Return the results struct of every run as the second output. +% +% Outputs: +% summary Table: run, one column per varied key, folder, status, message, seconds, damagedBars, brokenBars. +% results Cell with the results of each run (empty cells unless KeepResults). +% +% Errors: +% ldem:sweep:noKeys There is nothing to vary. +% ldem:sweep:zipLengths The lists have different lengths in zip mode. +% ldem:sweep:invalidRun A combination makes an invalid case. +% +% Example: +% summary = ldem.sweep("examples/sweeps/fracture_energy.ldem"); +% plot(summary.material_fracture_energy, summary.brokenBars) +% +% See also ldem.run, ldem.io.readCase. + +arguments + casePath (1,1) string + options.Vary = {} + options.Mode (1,1) string {mustBeMember(options.Mode, ["" "product" "zip"])} = "" + options.OutputFolder = [] + options.Formats = [] + options.Verbose (1,1) logical = true + options.DryRun (1,1) logical = false + options.KeepResults (1,1) logical = false +end + +base = ldem.io.readCase(casePath); +blocks = base.info.sweep; +extra = options.Vary; +if ~iscell(extra) || mod(numel(extra), 2) ~= 0 + error('ldem:sweep:invalidRun', 'Vary must be a cell {key1, values1, key2, values2, ...}.'); +end +for k = 1:2:numel(extra) + values = extra{k + 1}; + if isnumeric(values) + items = num2cell(reshape(values, 1, [])); + else + items = num2cell(reshape(string(values), 1, [])); + end + blocks(end+1) = struct('key', string(extra{k}), 'values', {items}); %#ok +end +if isempty(blocks) + error('ldem:sweep:noKeys', ... + 'There is nothing to vary: add [[sweep]] blocks to the case file or use the Vary option.'); +end +mode = base.info.sweepMode; +if options.Mode ~= "" + mode = options.Mode; +end + +combinations = combine(blocks, mode); % nRuns-by-nKeys indices into the lists +nRuns = size(combinations, 1); +keys = string({blocks.key}); + +if isempty(options.OutputFolder) + [folder, name] = fileparts(base.info.source); + outputBase = string(fullfile(folder, name + "_sweep")); +else + outputBase = string(options.OutputFolder); +end + +% Build and validate every run before running any. +overrides = cell(nRuns, 1); +for r = 1:nRuns + list = struct('path', {}, 'value', {}); + for k = 1:numel(keys) + list(end+1) = struct('path', keys(k), 'value', blocks(k).values(combinations(r, k))); %#ok + end + overrides{r} = list; + try + ldem.io.readCase(casePath, Overrides = list); + catch err + error('ldem:sweep:invalidRun', 'Run %d (%s) is not a valid case: %s', ... + r, describe(list), err.message); + end +end + +summary = table((1:nRuns).', 'VariableNames', {'run'}); +for k = 1:numel(keys) + column = strings(nRuns, 1); + for r = 1:nRuns + column(r) = string(overrides{r}(k).value); + end + summary.(matlab.lang.makeValidName(replace(keys(k), ".", "_"))) = column; +end +summary.folder = strings(nRuns, 1); +summary.status = repmat("planned", nRuns, 1); +summary.message = strings(nRuns, 1); +summary.seconds = NaN(nRuns, 1); +summary.damagedBars = NaN(nRuns, 1); +summary.brokenBars = NaN(nRuns, 1); +results = cell(nRuns, 1); + +if options.DryRun + summary.folder = outputBase + filesep + compose("run_%03d", (1:nRuns).'); + return +end + +for r = 1:nRuns + runFolder = outputBase + filesep + compose("run_%03d", r); + summary.folder(r) = runFolder; + if options.Verbose + fprintf('Run %d of %d: %s\n', r, nRuns, describe(overrides{r})); + end + timer = tic; + try + runResults = ldem.run(casePath, Overrides = overrides{r}, OutputFolder = runFolder, ... + Formats = options.Formats, Verbose = false); + summary.status(r) = "done"; + summary.damagedBars(r) = nnz(~runResults.final.damage.isUndamaged); + summary.brokenBars(r) = nnz(~runResults.final.damage.isUnbroken); + if options.KeepResults + results{r} = runResults; + end + catch err + summary.status(r) = "failed"; + summary.message(r) = string(strtok(err.message, newline)); + if options.Verbose + fprintf(' failed: %s\n', summary.message(r)); + end + end + summary.seconds(r) = toc(timer); +end + +if ~isfolder(outputBase) + mkdir(outputBase); +end +writetable(summary, fullfile(outputBase, "sweep_summary.csv")); +end + +function combinations = combine(blocks, mode) +%COMBINE Index of the value of every key in each run. +lengths = arrayfun(@(b) numel(b.values), blocks); +if mode == "zip" + if any(lengths ~= lengths(1)) + error('ldem:sweep:zipLengths', ... + 'In zip mode all the lists must have the same length, got %s.', mat2str(lengths)); + end + combinations = repmat((1:lengths(1)).', 1, numel(blocks)); +else + ranges = arrayfun(@(n) 1:n, lengths, 'UniformOutput', false); + grids = cell(1, numel(blocks)); + [grids{:}] = ndgrid(ranges{:}); + combinations = zeros(numel(grids{1}), numel(blocks)); + for k = 1:numel(blocks) + combinations(:, k) = grids{k}(:); + end +end +end + +function text = describe(list) +parts = strings(1, numel(list)); +for k = 1:numel(list) + parts(k) = string(list(k).path) + " = " + string(list(k).value); +end +text = strjoin(parts, ", "); +end diff --git a/src/+ldem/version.m b/src/+ldem/version.m new file mode 100644 index 0000000..25b422b --- /dev/null +++ b/src/+ldem/version.m @@ -0,0 +1,14 @@ +function v = version() +%VERSION Version of the ldem package. +% +% v = ldem.version() returns the version string that is stored in the +% results of every simulation, so that a result file can be traced back to +% the code that produced it. +% +% Example: +% disp(ldem.version()) +% +% See also ldem.runSimulation. + +v = "0.2.0-dev"; +end diff --git a/src/ldem/ANSYS.m b/src/ldem/ANSYS.m deleted file mode 100644 index fa65e2f..0000000 --- a/src/ldem/ANSYS.m +++ /dev/null @@ -1,392 +0,0 @@ - -function ini= ANSYS(IFILE,CONT1,CONT2,CONT3,CONT4,CONT5,CONT6) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED DM DS - -% SUBROUTINE ANSYS (IFILE,CONT1,CONT2,CONT3,CONT4,CONT5,CONT6) -% ! ================ -% ! -% ! DATA: 14/10/1992 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina gera arquivos *.ans (arquivos que permitem realizar -% ! saída gráfica compatível com o Ansys). -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER NOI,NOF -% LOGICAL LABEL1,LABEL2,LABEL3,LABEL4,LABEL5,LABEL6 -% DOUBLE PRECISION ro,ri(INN),aba -% LOGICAL logic1,logic2,logic3,Logic4,logic5 -% integer cont1,cont2,cont3,cont4,cont5,cont6 -% !variables for the test 5102( fretting test) -% LOGICAL LABEL31,LABEL32,LABEL41,LABEL42 -% DOUBLE PRECISION Asigmax,a,th,AP,AQ,cfric,alph_sig,alph_q,Qast -% DOUBLE PRECISION Past,po,c,xmid,Q,cp,sigmab,eep,pp,xi,ee -% DOUBLE PRECISION Atemp,Qtpdt,qq,coef,rad_noi,rad_nof -% !-------------------------------------------------------------------------- -% ! -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*) '/PREP7' -% WRITE (IFILE,*) '/TITLE, TEMPO =',TIME -% WRITE (IFILE,*) 'ET,1,4' -% WRITE (IFILE,*) 'ET,2,4' -% WRITE (IFILE,*) 'ET,IFILE,4' -% WRITE (IFILE,*) 'ET,4,4' -% WRITE (IFILE,*) 'ET,5,4' -% WRITE (IFILE,*) 'ET,6,4' -% WRITE (IFILE,*) 'ET,8,4' -% WRITE (IFILE,*) 'ET,9,4' -% WRITE (IFILE,*) 'ET,10,4' -% WRITE (IFILE,*) 'ET,11,4' -% WRITE (IFILE,*) 'ET,12,4' -% WRITE (IFILE,*) 'MP,EX,1,2E10' -% WRITE (IFILE,*) 'MP,PRXY,1,0.25' -% WRITE (IFILE,*) 'MP,DENS,1,2500' -% WRITE (IFILE,*) 'R,1,0.13,0.0014,0.36' -% WRITE (IFILE,*) -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*) '!COORDENADAS NODAIS' -% !-------------------------------------------------------------------------- -% DO I=1,NNT -% -% WRITE (IFILE,*) 'N,',I,',',SNGL(U(3,I)),',',SNGL(V(3,I)),',', & -% & SNGL(W(3,I)) -% END DO -% WRITE (IFILE,*) -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*) '!CONECTIVIDADES DOS ELEMENTOS' -% !-------------------------------------------------------------------------- -% CONT1=0 -% CONT2=0 -% CONT3=0 -% CONT4=0 -% CONT5=0 -% CONT6=0 -% CONT7=0 -% -% Write(*,*)DM(1),FS(1) -% -% DO I=1,NBT -% NOI=CN(2*I-1) -% NOF=CN(2*I) -% -% ! -% -% !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -% -% IF((DM(I)))THEN -% -% WRITE (IFILE,*) 'TYPE,1' -% WRITE (IFILE,*) 'E',',',CN(2*I-1),',',CN(2*I),',!EL',I -% CONT1=CONT1+1 -% else -% -% IF (FS(I)) THEN -% ! BARRAS DANIFICADAS - COR LARANJA -% WRITE (IFILE,*) 'TYPE,2' -% WRITE (IFILE,*) 'E',',',CN(2*I-1),',',CN(2*I),',!EL',I -% CONT2=CONT2+1 -% ELSE -% ! BARRAS ROMPIDAS - COR VERMELHA -% WRITE (IFILE,*) 'TYPE,5' -% WRITE (IFILE,*) 'E',',',CN(2*I-1),',',CN(2*I),',!EL',I -% CONT5=CONT5+1 -% END IF -% END IF -% ! -% END DO -% -% WRITE (IFILE,*) -% WRITE (IFILE,*) '!CORES DOS ELEMENTOS' -% !-------------------------------------------------------------------------- -% -% -% WRITE (IFILE,*) 'ESEL,S,TYPE,,1' -% WRITE (IFILE,*) '/COLOR,ELEM,GCYA' -% WRITE (IFILE,*) '/PNUM,TYPE,0' -% WRITE (IFILE,*) '/NUMBER,1' -% WRITE (IFILE,*) 'ESEL,ALL' -% -% WRITE (IFILE,*) 'ESEL,S,TYPE,,2' -% WRITE (IFILE,*) '/COLOR,ELEM,ORAN' -% WRITE (IFILE,*) '/PNUM,TYPE,0' -% WRITE (IFILE,*) '/NUMBER,1' -% WRITE (IFILE,*) 'ESEL,ALL' -% ! -% WRITE (IFILE,*) 'ESEL,S,TYPE,,5' -% WRITE (IFILE,*) '/COLOR,ELEM,RED' -% WRITE (IFILE,*) '/PNUM,TYPE,0' -% WRITE (IFILE,*) '/NUMBER,1' -% WRITE (IFILE,*) 'ESEL,ALL' -% -% WRITE (IFILE,*) 'ESEL,S,TYPE,,6' -% WRITE (IFILE,*) '/COLOR,ELEM,GREE' -% WRITE (IFILE,*) '/PNUM,TYPE,0' -% WRITE (IFILE,*) '/NUMBER,1' -% WRITE (IFILE,*) 'ESEL,ALL' -% -% -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*) '!CONDIÇÕES DE CONTORNO' -% !-------------------------------------------------------------------------- -% IF (TEST.EQ.102) THEN -% DO I=1,NNT -% IF (BDX(I).EQ.1) THEN -% WRITE (IFILE,*) 'D,',I,',','UX' -% END IF -% IF (BDY(I).EQ.1) THEN -% WRITE (IFILE,*) 'D,',I,',','UY' -% END IF -% IF (BDZ(I).EQ.1) THEN -% WRITE (IFILE,*) 'D,',I,',','UZ' -% END IF -% END DO -% END IF -% WRITE (IFILE,*) -% !WRITE (IFILE,*) 'D,',ncon(1),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(2),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(3),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(4),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(5),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(6),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(7),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(8),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(9),',','UY' -% !WRITE (IFILE,*) 'D,',ncon(10),',','UY' -% -% -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*) '!CARGAS APLICADAS' -% !-------------------------------------------------------------------------- -% IF (TEST.EQ.102) THEN -% -% -% -% DO I=1,NNT -% LOGIC1=u0(I).LT.((M1-0.49)*LCo).AND.u0(I).GT.((M1-0.51)*LCo) -% LOGIC2=(V0(i).GT.(50.5-0.1)*Lco).AND.(V0(i).LT.(51.5+0.1)*Lco) -% IF(LOGIC1.AND.LOGIC2)THEN -% -% WRITE (IFILE,*) 'F,',I,',','Fx',',',-10 -% END IF -% ENDDO -% END IF -% ! -% WRITE (IFILE,*) -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*) '/VIEW,1,0,-1,0' -% WRITE (IFILE,*) 'EPLOT' -% WRITE (IFILE,*) -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*) '!ESTADO DAS BARRAS' -% !-------------------------------------------------------------------------- -% WRITE (IFILE,*)'!BARRAS INTACTAS =',' ',CONT1+CONT3+CONT6 -% WRITE (IFILE,*)'!BARRAS DANIFICADAS =',' ',CONT2+CONT4 -% WRITE (IFILE,*)'!BARRAS ROMPIDAS =',' ',CONT5 -% WRITE (IFILE,*) -% -% ! Imprimir número de barras e em que estado estão -% OPEN (UNIT=30,ACCESS='SEQUENTIAL',FILE='BARR_ROMP.dat', & -% & STATUS='UNKNOWN') -% WRITE (30,100) TIME,VF,CONT1,CONT2,CONT5 -% 100 FORMAT (E12.6,3X,E12.6,3X,I7,3X,I7,3X,I7) -% ! -% -% RETURN -% END -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% -% DATA: 14/10/1992 -% AUTOR: IGNACIO ITURRIOZ -% -% Esta subrotina gera arquivos *.ans (arquivos que permitem realizar -% saída gráfica compatível com o Ansys). -% -% Translates the Fortran SUBROUTINE ANSYS. -% IFILE = open file handle for the *.ans output file. - -%========================================================================== -% HEADER / SETUP -%========================================================================== -fprintf(IFILE, '/PREP7\n'); -fprintf(IFILE, '/TITLE, TEMPO =%g\n', TIME); -fprintf(IFILE, 'ET,1,4\n'); -fprintf(IFILE, 'ET,2,4\n'); -fprintf(IFILE, 'ET,IFILE,4\n'); -fprintf(IFILE, 'ET,4,4\n'); -fprintf(IFILE, 'ET,5,4\n'); -fprintf(IFILE, 'ET,6,4\n'); -fprintf(IFILE, 'ET,8,4\n'); -fprintf(IFILE, 'ET,9,4\n'); -fprintf(IFILE, 'ET,10,4\n'); -fprintf(IFILE, 'ET,11,4\n'); -fprintf(IFILE, 'ET,12,4\n'); -fprintf(IFILE, 'MP,EX,1,2E10\n'); -fprintf(IFILE, 'MP,PRXY,1,0.25\n'); -fprintf(IFILE, 'MP,DENS,1,2500\n'); -fprintf(IFILE, 'R,1,0.13,0.0014,0.36\n'); -fprintf(IFILE, '\n'); - -%-------------------------------------------------------------------------- -% NODAL COORDINATES -%-------------------------------------------------------------------------- -fprintf(IFILE, '!COORDENADAS NODAIS\n'); - -for I = 1:NNT - fprintf(IFILE, 'N,%d,%g,%g,%g\n', ... - I, single(U(3,I)), single(V(3,I)), single(W(3,I))); -end -fprintf(IFILE, '\n'); - -%-------------------------------------------------------------------------- -% ELEMENT CONNECTIVITIES -%-------------------------------------------------------------------------- -fprintf(IFILE, '!CONECTIVIDADES DOS ELEMENTOS\n'); - -CONT1 = 0; -CONT2 = 0; -CONT3 = 0; -CONT4 = 0; -CONT5 = 0; -CONT6 = 0; -CONT7 = 0; - -fprintf(1, '%d %d\n', DM(1), FS(1)); - -for I = 1:NBT - NOI = CN(2*I - 1); - NOF = CN(2*I); - - if DM(I) - % --- intact bars (not yet damaged) ------------------------------ - fprintf(IFILE, 'TYPE,1\n'); - fprintf(IFILE, 'E,%d,%d,!EL%d\n', CN(2*I-1), CN(2*I), I); - CONT1 = CONT1 + 1; - - elseif FS(I) - % --- damaged bars (orange) -------------------------------------- - fprintf(IFILE, 'TYPE,2\n'); - fprintf(IFILE, 'E,%d,%d,!EL%d\n', CN(2*I-1), CN(2*I), I); - CONT2 = CONT2 + 1; - - else - % --- broken bars (red) ------------------------------------------ - fprintf(IFILE, 'TYPE,5\n'); - fprintf(IFILE, 'E,%d,%d,!EL%d\n', CN(2*I-1), CN(2*I), I); - CONT5 = CONT5 + 1; - end -end - -fprintf(IFILE, '\n'); -fprintf(IFILE, '!CORES DOS ELEMENTOS\n'); - -%-------------------------------------------------------------------------- -% ELEMENT COLORS (per TYPE) -%-------------------------------------------------------------------------- -fprintf(IFILE, 'ESEL,S,TYPE,,1\n'); -fprintf(IFILE, '/COLOR,ELEM,GCYA\n'); -fprintf(IFILE, '/PNUM,TYPE,0\n'); -fprintf(IFILE, '/NUMBER,1\n'); -fprintf(IFILE, 'ESEL,ALL\n'); - -fprintf(IFILE, 'ESEL,S,TYPE,,2\n'); -fprintf(IFILE, '/COLOR,ELEM,ORAN\n'); -fprintf(IFILE, '/PNUM,TYPE,0\n'); -fprintf(IFILE, '/NUMBER,1\n'); -fprintf(IFILE, 'ESEL,ALL\n'); - -fprintf(IFILE, 'ESEL,S,TYPE,,5\n'); -fprintf(IFILE, '/COLOR,ELEM,RED\n'); -fprintf(IFILE, '/PNUM,TYPE,0\n'); -fprintf(IFILE, '/NUMBER,1\n'); -fprintf(IFILE, 'ESEL,ALL\n'); - -fprintf(IFILE, 'ESEL,S,TYPE,,6\n'); -fprintf(IFILE, '/COLOR,ELEM,GREE\n'); -fprintf(IFILE, '/PNUM,TYPE,0\n'); -fprintf(IFILE, '/NUMBER,1\n'); -fprintf(IFILE, 'ESEL,ALL\n'); - -%-------------------------------------------------------------------------- -% BOUNDARY CONDITIONS -%-------------------------------------------------------------------------- -fprintf(IFILE, '!CONDIÇÕES DE CONTORNO\n'); - -if TEST == 102 - for I = 1:NNT - if BDX(I) == 1 - fprintf(IFILE, 'D,%d,UX\n', I); - end - if BDY(I) == 1 - fprintf(IFILE, 'D,%d,UY\n', I); - end - if BDZ(I) == 1 - fprintf(IFILE, 'D,%d,UZ\n', I); - end - end -end - -fprintf(IFILE, '\n'); -% --- Commented-out D-constraints from original code kept here for reference -% fprintf(IFILE, 'D,%d,UY\n', ncon(1)); -% ... (etc.) - -%-------------------------------------------------------------------------- -% APPLIED LOADS -%-------------------------------------------------------------------------- -fprintf(IFILE, '!CARGAS APLICADAS\n'); - -if TEST == 102 - for I = 1:NNT - LOGIC1 = (U0(I) < (M1 - 0.49) * LCO) && (U0(I) > (M1 - 0.51) * LCO); - LOGIC2 = (V0(I) > (50.5 - 0.1) * LCO) && (V0(I) < (51.5 + 0.1) * LCO); - - if LOGIC1 && LOGIC2 - fprintf(IFILE, 'F,%d,Fx,%d\n', I, -10); - end - end -end - -fprintf(IFILE, '\n'); - -%-------------------------------------------------------------------------- -% VIEW / PLOT -%-------------------------------------------------------------------------- -fprintf(IFILE, '/VIEW,1,0,-1,0\n'); -fprintf(IFILE, 'EPLOT\n'); -fprintf(IFILE, '\n'); - -%-------------------------------------------------------------------------- -% BAR STATE SUMMARY -%-------------------------------------------------------------------------- -fprintf(IFILE, '!ESTADO DAS BARRAS\n'); -fprintf(IFILE, '!BARRAS INTACTAS = %d\n', CONT1 + CONT3 + CONT6); -fprintf(IFILE, '!BARRAS DANIFICADAS = %d\n', CONT2 + CONT4); -fprintf(IFILE, '!BARRAS ROMPIDAS = %d\n', CONT5); -fprintf(IFILE, '\n'); - -%-------------------------------------------------------------------------- -% Separate bar-state summary file -% Fortran: OPEN (UNIT=30,FILE='BARR_ROMP.dat',STATUS='UNKNOWN') -% FORMAT (E12.6,3X,E12.6,3X,I7,3X,I7,3X,I7) -%-------------------------------------------------------------------------- -VF=1.0 -fid30 = fopen('BARR_ROMP.dat', 'w'); -fprintf(fid30, '%12.6E %12.6E %7d %7d %7d\n', ... - TIME, VF, CONT1, CONT2, CONT5); -fclose(fid30); - ini=1; - end diff --git a/src/ldem/BARR_ROMP.dat b/src/ldem/BARR_ROMP.dat deleted file mode 100644 index 927363e..0000000 --- a/src/ldem/BARR_ROMP.dat +++ /dev/null @@ -1 +0,0 @@ -0.000000E+00 1.000000E+00 1126960 0 0 diff --git a/src/ldem/BOUND.m b/src/ldem/BOUND.m deleted file mode 100644 index 6b9fdee..0000000 --- a/src/ldem/BOUND.m +++ /dev/null @@ -1,131 +0,0 @@ - -function ini=BOUND() -% BOUND Determina as condições de contorno da estrutura. -% Deve ser adaptada para cada exemplo testado. -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED DM FS - -%! Esta subrotina determina as condições de contorno da estrutura. - -%!-------------------------------------------------------------------------- - - -BDX=zeros(NNT,1); -BDY=zeros(NNT,1); -BDZ=zeros(NNT,1); -%!-------------------------------------------------------------------------- -%! ADAPTAR PARA CADA EXEMPLO TESTADO -%!-------------------------------------------------------------------------- -%! - - -% -% ! -% ! TEST = 101 -% IF (TEST.EQ.101) THEN -% -% DO I=1,NNT -% -% Logic2=(u0(I).LT.(0.51*LCO)).AND.(u0(I).GT.(0.49*LCO)) -% -% IF (Logic2) THEN -% BDX(I)=1 -% ! BDY(I)=1 -% ! BDZ(I)=1 -% ! write(*,*) "nobound=",I -% END IF -% -% Logic2=(u0(I).GT.(M1-0.51*LCO)).AND.(u0(I).LT.(M1-0.49*LCO)) -% -% IF (Logic2) THEN -% BDX(I)=1 -% ! BDY(I)=1 -% ! BDZ(I)=1 -% ! write(*,*) "nobound=",I -% END IF -% -% END DO -% END IF -% -% IF (TEST.EQ.102) THEN -% -% DO I=1,NNT -% Logic1=(v0(I).GT.(0.49*LCO)).AND.(v0(I).LT.(0.51*LCO)) -% Logic2=(u0(I).LT.(4.51*LCO)).AND.(u0(I).GT.(4.49*LCO)) -% IF (Logic1.AND.Logic2) THEN -% BDX(I)=1 -% BDY(I)=1 -% epsL! BDZ(I)=1 -% ! write(*,*) "nobound=",I -% END IF -% Logic1=(u0(I).GT.((M1-4.51)*LCO)).AND.(u0(I).LT.((M1-4.49)*LCO)) -% Logic2=(v0(I).LT.(0.51*LCO)).AND.(v0(I).GT.(0.49*LCO)) -% IF(Logic1.AND.Logic2) THEN -% BDy(I)=1 -% ! BDZ(I)=1 -% ! write(*,*) "nobound2=",I -% END IF -% END DO -% DO I=1,NNT -% LOGIC1=u0(I).LT.((M1-33.49)*LCO).AND.u0(I).GT.((M1-33.51)*LCO) -% LOGIC3=v0(I).LT.((N1-0.49)*LCO).AND.v0(I).GT.((N1-0.51)*LCO) -% LOGIC2=u0(I).LT.((33.51)*LCO).AND.u0(I).GT.((33.49)*LCO) -% IF(LOGIC1.AND.LOGIC3)THEN -% BDy(I)=1 -% endif -% IF(LOGIC2.AND.LOGIC3)THEN -% BDy(I)=1 -% endif -% -% END DO -% END IF -% RETURN -% END -% -if TEST == 101 - - % Masks for the two conditions (operate on all elements at once) - mask1 = (U0 < (0.51 * LCO)) & (U0 > (0.49 * LCO)); - mask2 = (U0 > (M1 - 0.51 * LCO)) & (U0 < (M1 - 0.49 * LCO)); - - % Apply BDX=1 where either condition is true - BDX(mask1 | mask2) = 1; - -end - -if TEST == 102 - - % --- First block of conditions (replaces the first loop) --- - mask1 = (V0 > (0.49 * LCO)) & (V0 < (0.51 * LCO)) & ... - (U0 < (4.51 * LCO)) & (U0 > (4.49 * LCO)); - - mask2 = (U0 > ((M1 - 4.51) * LCO)) & (U0 < ((M1 - 4.49) * LCO)) & ... - (V0 < (0.51 * LCO)) & (V0 > (0.49 * LCO)); - - % Apply the assignments - BDX(mask1) = 1; - BDY(mask1) = 1; - BDY(mask2) = 1; % Originally BDy -> unified to BDY (Fortran is case-insensitive) - - - % --- S econd block of conditions (replaces the second loop) --- - mask3 = (U0 < ((M1 - 33.49) * LCO)) & (U0 > ((M1 - 33.51) * LCO)) & ... - (V0 < ((N1 - 0.49) * LCO)) & (V0 > ((N1 - 0.51) * LCO)); - - mask4 = (U0 < (33.51 * LCO)) & (U0 > (33.49 * LCO)) & ... - (V0 < ((N1 - 0.49) * LCO)) & (V0 > ((N1 - 0.51) * LCO)); - - % Apply BDY=1 where mask3 or mask4 are true - BDY(mask3 | mask4) = 1; - - - ini=1; - end diff --git a/src/ldem/CABAR.m b/src/ldem/CABAR.m deleted file mode 100644 index 69b0a3a..0000000 --- a/src/ldem/CABAR.m +++ /dev/null @@ -1,204 +0,0 @@ - -function ini= CABAR (fid_Lei) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%global FORCE,STR,STRRT,R -%!-------------------------------------------------------------------------- -% SUBROUTINE CABAR -% ! ================ -% -% ! -% ! DATA: 22/03/1993 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina realiza um loop sobre todas as barras para calcular as -% ! novas forças atuantes a partir da nova configuração. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=20,INCON=8) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER B,NOI,NOF,R,II,JJ,KK,IMOD -% INTEGER VB(26) -% DOUBLE PRECISION DU,DV,DW,DU1,DV1,DW1,DCX,DCY,DCZ -% DOUBLE PRECISION LBAR,LBAR1,STR,LSTR,STRRT,FORCE -% !-------------------------------------------------------------------------- -% DO B=1,NBT -% NOI=CN(2*B-1) -% NOF=CN(2*B) -% DU=U(2,NOF)-U(2,NOI) -% DV=V(2,NOF)-V(2,NOI) -% DW=W(2,NOF)-W(2,NOI) -% LBAR=DSQRT(DU*DU+DV*DV+DW*DW) -% DU1=U(1,NOF)-U(1,NOI) -% DV1=V(1,NOF)-V(1,NOI) -% DW1=W(1,NOF)-W(1,NOI) -% LBAR1=DSQRT(DU1*DU1+DV1*DV1+DW1*DW1) -% DCX=DU/LBAR -% DCY=DV/LBAR -% DCZ=DW/LBAR -% STR=(LBAR-LI(B))/LI(B) -% LSTR=(LBAR1-LI(B))/LI(B) -% STRRT=(STR-LSTR)/DT -% DSS(B)=STRRT -% CALL CONSTIT (B,STR,STRRT,FORCE,R) -% ! CALL CONSTIT9(B,STR,STRRT,FORCE,R) -% FRX(NOI)=FRX(NOI)+FORCE*DCX -% FRX(NOF)=FRX(NOF)-FORCE*DCX -% FRY(NOI)=FRY(NOI)+FORCE*DCY -% FRY(NOF)=FRY(NOF)-FORCE*DCY -% FRZ(NOI)=FRZ(NOI)+FORCE*DCZ -% FRZ(NOF)=FRZ(NOF)-FORCE*DCZ -% ! -% ! ISSO GRAVA A FORÇA DE CADA BARRA -% F(B)=FORCE -% ! -% !if (b.eq.1) then -% ! write(*,*)b,str,force,LBAR -% !endif -% END DO -% RETURN -% END - -% CABAR -% ===== -% -% DATA: 22/03/1993 -% AUTOR: IGNACIO ITURRIOZ -% -% Esta subrotina realiza um loop sobre todas as barras para calcular as -% novas forças atuantes a partir da nova configuração. -% -% MATLAB translation. The original Fortran used a COMMON block; here the -% shared data is passed in/out via a struct S with fields: -% S.NBT, S.CN, S.U, S.V, S.W, S.LI, S.DT, -% S.DSS, S.FRX, S.FRY, S.FRZ, S.F -% (and any other fields needed by the CONSTIT routine). - -%-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6, INB=6E6, IRU=20, INCON=8) -% These parameters are not used in this routine. -%-------------------------------------------------------------------------- - -%-------------------------------------------------------------------------- -% Loop over all bars -%-------------------------------------------------------------------------- - -% CABAR -% ===== -% -% DATA: 22/03/1993 -% AUTOR: IGNACIO ITURRIOZ -% -% Esta subrotina realiza um loop sobre todas as barras para calcular as -% novas forças atuantes a partir da nova configuração. -% -% MATLAB translation using GLOBAL variables instead of COMMON. -% The following global variables must be defined in the workspace: -% NBT, CN, U, V, W, LI, DT, DSS, FRX, FRY, FRZ, F -% (and any others required by CONSTIT). - - - -%-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6, INB=6E6, IRU=20, INCON=8) -% These parameters are not used in this routine. -%-------------------------------------------------------------------------- -NUMBAR = 7014; - -for B = 1:NBT - NOI = CN(2*B - 1); - NOF = CN(2*B); - - % Cinemática atual (U,V,W no tempo 2) - DU = U(2, NOF) - U(2, NOI); - DV = V(2, NOF) - V(2, NOI); - DW = W(2, NOF) - W(2, NOI); - LBAR = sqrt(DU*DU + DV*DV + DW*DW); - - % Cinemática do passo anterior (U,V,W no tempo 1) - DU1 = U(1, NOF) - U(1, NOI); - DV1 = V(1, NOF) - V(1, NOI); - DW1 = W(1, NOF) - W(1, NOI); - LBAR1 = sqrt(DU1*DU1 + DV1*DV1 + DW1*DW1); - - % Cossenos diretores - DCX = DU / LBAR; - DCY = DV / LBAR; - DCZ = DW / LBAR; - - % Deformações (Strain) - STR = (LBAR - LI(B)) / LI(B); - LSTR = (LBAR1 - LI(B)) / LI(B); - STRRT = (STR - LSTR) / DT; - - DSS(B) = STRRT; - - % ================================================================= - % RELAÇÃO CONSTITUTIVA INCORPORADA (Substitui chamada ao CONSTIT.m) - % ================================================================= - SS(B) = STR; - ER = KR(B) * EP(B); - - if STR >= ER - % Ramo 1: Barra totalmente rompida - E2(B) = 0.0; - FORCE = 0.0; - EM(B) = ER; - - if FS(B) - FS(B) = false; - DM(B) = false; - end - - elseif STR >= EM(B) - % Ramo 2: Amolecimento (Strain softening) - AUX = (STR - EP(B)) / (KR(B) - 1.0); - AUX = E1(B) * (EP(B) - AUX); - E2(B) = AUX / STR; - EM(B) = STR; - FORCE = AUX + E2(B) * CON * STRRT; - - if DM(B) - DM(B) = false; - end - - elseif STR >= 0.0 - % Ramo 3: Tração elástica (carga/descarga) - FORCE = E2(B) * STR + E2(B) * CON * STRRT; - - else - % Ramo 4: Compressão - FORCE = E1(B) * STR + E1(B) * CON * STRRT; - end - - % Gravação isolada da barra de rastreio - if B == NUMBAR && fid_Lei ~= -1 - fprintf(fid_Lei, '%25.12E %25.12E %25.12E %25.12E %25.12E %25.12E\n', ... - TIME, STR, SS(B), ER, FORCE, EP(B)); - end - % ================================================================= - - % Montagem do vetor de forças globais nos nós - FRX(NOI) = FRX(NOI) + FORCE*DCX; - FRX(NOF) = FRX(NOF) - FORCE*DCX; - FRY(NOI) = FRY(NOI) + FORCE*DCY; - FRY(NOF) = FRY(NOF) - FORCE*DCY; - FRZ(NOI) = FRZ(NOI) + FORCE*DCZ; - FRZ(NOF) = FRZ(NOF) - FORCE*DCZ; - - F(B) = FORCE; - end - - ini = 1; -end \ No newline at end of file diff --git a/src/ldem/CACOEV.m b/src/ldem/CACOEV.m deleted file mode 100644 index afc5015..0000000 --- a/src/ldem/CACOEV.m +++ /dev/null @@ -1,25 +0,0 @@ - -function ini= CALCOEV() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED C - - -%-------------------------------------------------------------------------- -% Compute the mean of EP -%-------------------------------------------------------------------------- -MEAN = mean(EP); -%-------------------------------------------------------------------------- -% Compute the coefficient of variation of EP -%-------------------------------------------------------------------------- -COEF=std(EP)/MEAN; -end - ini=1; - end diff --git a/src/ldem/CALAUX.m b/src/ldem/CALAUX.m deleted file mode 100644 index 4f7fa6c..0000000 --- a/src/ldem/CALAUX.m +++ /dev/null @@ -1,32 +0,0 @@ - -function ini=CALAUX() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - DM = true(NBT, 1); - FS = true(NBT, 1); - for B = 1:NBT - - NOI = CN(2*B - 1); - NOF = CN(2*B); - - DU = U(1,NOF) - U(1,NOI); - DV = V(1,NOF) - V(1,NOI); - DW = W(1,NOF) - W(1,NOI); - - LI(B) = sqrt(DU*DU + DV*DV + DW*DW); - EM(B) = 0.0; - - XB(B) = (U(1,NOF) + U(1,NOI)) / 2.0; - YB(B) = (V(1,NOF) + V(1,NOI)) / 2.0; - ZB(B) = (W(1,NOF) + W(1,NOI)) / 2.0; - end - ini=1; - end diff --git a/src/ldem/CALCOEV.m b/src/ldem/CALCOEV.m deleted file mode 100644 index 0ce12c6..0000000 --- a/src/ldem/CALCOEV.m +++ /dev/null @@ -1,25 +0,0 @@ - -function ini= CALCOEV() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED C - - -%-------------------------------------------------------------------------- -% Compute the mean of EP -%-------------------------------------------------------------------------- -MEAN = mean(EP); -%-------------------------------------------------------------------------- -% Compute the coefficient of variation of EP -%-------------------------------------------------------------------------- -COEF=std(EP)/MEAN; - - ini=1; - end diff --git a/src/ldem/CALOAD.m b/src/ldem/CALOAD.m deleted file mode 100644 index e713c28..0000000 --- a/src/ldem/CALOAD.m +++ /dev/null @@ -1,146 +0,0 @@ - -function ini=CALOAD() -% CALOAD Aplica as cargas nos nós em cada passo de tempo. -% Calcula também a energia externa fornecida ao sistema. -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - -% SUBROUTINE CALOAD -% ! ================= -% ! -% ! DATA: 22/03/1993 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina aplica as cargas nos nós em cada passo de tempo e calcula -% ! a energia externa fornecida ao sistema. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% DOUBLE PRECISION TINI -% LOGICAL Logic1,logic2,logic3 -% -% !-------------------------------------------------------------------------- -% DO NO=1,NNT -% FX(NO)=FRX(NO) -% FY(NO)=FRY(NO) -% FZ(NO)=FRZ(NO) -% FRX(NO)=0.0D00 -% FRY(NO)=0.0D00 -% FRZ(NO)=0.0D00 -% END DO -% ! -% !-------------------------------------------------------------------------- -% ! -% !-------------------------------------------------------------------------- -% -% IF (TEST.EQ.101) THEN ! prism solicited by prescribed displacement to traction if Vf2 >0 , or to compression if Vf2<0, Vf2 is the displacement velocity -% !applied in the last column of dentral nodes -% VF2=400.e-5!m/s -% -% DO I=1,NNT -% LOGIC1=u0(I).LT.((M1-0.49)*LCo).AND.u0(I).GT.((M1-0.51)*LCo) -% -% IF(LOGIC1)THEN -% -% U(2,I)=U0(I)-VF2*TIME -% -% ! end if -% -% -% ! IF(time.GT.5000*DT)THEN -% ! ! W(2,I)=W(2,I)-(2*v0(I)/(N1*LCO)-1)*VF2*10.0*(time-5000*DT) -% ! W(2,I)=W(2,I)-(2*v0(I)/(N1*LCO)-1)*VF2*1.0*DT -% ! END IF -% END IF -% -% END DO -% -% ENDIF ! -% IF (TEST.EQ.102) THEN ! prism solicited as beam with two vertical displacement in L/4 and (3/4)L by prescribed displacement, -% !the prism are supported by vertical support in the endsx=L/2 to rpoduce a to traction if Vf2 >0 , or to compression if Vf2<0, Vf2 is the displacement velocity -% -% VF2=400.e-5!m/s -% -% DO I=1,NNT -% LOGIC1=u0(I).LT.((M1-33.49)*LCo).AND.u0(I).GT.((M1-33.51)*LCo) -% LOGIC3=v0(I).LT.((N1-0.49)*LCo).AND.v0(I).GT.((N1-0.51)*LCo) -% LOGIC2=u0(I).LT.((33.51)*LCo).AND.u0(I).GT.((33.49)*LCo) -% IF(LOGIC1.AND.LOGIC3)THEN -% V(2,I)=V0(I)-VF2*TIME -% endif -% IF(LOGIC1.AND.LOGIC2)THEN -% V(2,I)=V0(I)-VF2*TIME -% endif -% -% END DO -% -% ENDIF ! -% RETURN -% END -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - FX = FRX; - FY = FRY; - FZ = FRZ; - FRX = zeros(1,NNT); - FRY = zeros(1,NNT); - FRZ = zeros(1,NNT); - - -%========================================================================== -% TEST 101: prism under prescribed axial (X) displacement -%========================================================================== -if TEST == 101 - VF2 = 400.0e-5; % m/s displacement velocity - - for I = 1:NNT - LOGIC1 = (U0(I) < (M1 - 0.49) * LCO) && ... - (U0(I) > (M1 - 0.51) * LCO); - - if LOGIC1 - U(2,I) = U0(I) - VF2 * TIME; - - % --- commented-out block from Fortran, kept for reference ---- - % if TIME > 5000*DT - % W(2,I) = W(2,I) - (2*V0(I)/(N1*LCO) - 1) * VF2 * 1.0 * DT; - % end - end - end -end - -%========================================================================== -% TEST 102: prism as beam, prescribed vertical displacements at L/4 & 3L/4 -%========================================================================== -if TEST == 102 - VF2 = 400.0e-5; % m/s - - for I = 1:NNT - LOGIC1 = (U0(I) < (M1 - 33.49) * LCO) && ... - (U0(I) > (M1 - 33.51) * LCO); - LOGIC3 = (V0(I) < (N1 - 0.49) * LCO) && ... - (V0(I) > (N1 - 0.51) * LCO); - LOGIC2 = (U0(I) < 33.51 * LCO) && ... - (U0(I) > 33.49 * LCO); - - if LOGIC1 && LOGIC3 - V(2,I) = V0(I) - VF2 * TIME; - end - if LOGIC1 && LOGIC2 - V(2,I) = V0(I) - VF2 * TIME; - end - end -end - -ini=1; - end diff --git a/src/ldem/CALRES.m b/src/ldem/CALRES.m deleted file mode 100644 index 330f13d..0000000 --- a/src/ldem/CALRES.m +++ /dev/null @@ -1,130 +0,0 @@ - -function ini=CALRES() -% CALRES Calcula valores que serão guardados no arquivo de resultados. -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - -% !-------------------------------------------------------------------------- -% !-------------------------------------------------------------------------- -% ! -% SUBROUTINE CALRES -% ! ================= -% ! -% ! DATA: 22/03/1993 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina calcula valores que serão guardados no arquivo RESNAME. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% -% DOUBLE PRECISION ReacaoX2,COD_L,COD_R,DELTA -% -% -% CHARACTER*20 NAME -% !-------------------------------------------------------------------------- -% ! ADAPTAR PARA CADA EXEMPLO TESTADO -% !-------------------------------------------------------------------------- -% if (test.eq.102)then -% -% REACAOX = 0.0D00 -% REACAOY = 0.0D00 -% REACAOZ = 0.0D00 -% REACAOX2 = 0.0D00 -% SOMADESZ = 0.0D00 -% SOMADESY = 0.0D00 -% SOMADESX = 0.0D00 -% COD_L=0.0D00 -% COD_R=0.0D00 -% DELTA=0.0D00 -% ! -% DO I=1,NNT -% -% IF((BDY(I).EQ.1).AND.(V0(I).GE.(LCO*(N1-0.51)) ))then -% -% REACAOY=REACAOY+FRY(I) -% -% END IF -% END DO -% -% ! -% IF (PR9.EQ.OU8) THEN -% NAME = 'SIM01.DAT' -% OPEN (21,FILE=NAME) -% WRITE(21,'(4(E25.12,3X))')TIME,REACAOY,Acz(89214),V(2,154928) -% PR9=1 -% ELSE -% PR9=PR9+1 -% END IF -% ENDIF -% RETURN -% END -% !-------------------------------------------------------------------------- - -% CALRES -% ====== -% -% DATA: 22/03/1993 -% AUTOR: IGNACIO ITURRIOZ -% -% Esta subrotina calcula valores que serão guardados no arquivo RESNAME. -% -% MATLAB translation using GLOBAL variables instead of COMMON. - -% ------------------------------------------------------------------------- -% Global variables (equivalent to the COMMON block) -% ------------------------------------------------------------------------- -%----------------------------------------------------- -% - -% ------------------------------------------------------------------------- -% ADAPT FOR EACH TEST EXAMPLE -% ------------------------------------------------------------------------- -if TEST == 102 - - REACAOX = 0.0; - REACAOY = 0.0; - REACAOZ = 0.0; - REACAOX2 = 0.0; - SOMADESZ = 0.0; - SOMADESY = 0.0; - SOMADESX = 0.0; - COD_L = 0.0; - COD_R = 0.0; - DELTA = 0.0; - - % --------------------------------------------------------------------- - for I = 1:NNT - if (BDY(I) == 1) && (V0(I) >= (LCO*(N1 - 0.51))) - REACAOY = REACAOY + FRY(I); - end - end - - % --------------------------------------------------------------------- -% if PR9 == OU8 - NAME = 'SIM01.DAT'; - fid21 = fopen(NAME, 'w'); - fprintf(fid21, '%25.12e %25.12e %25.12e %25.12e\n', ... - TIME, REACAOY, ACZ(100), V(2,100)); - fclose(fid21); - % PR9 = 1; - % else - % PR9 = PR9 + 1; - % end - -end - - ini=1; - end diff --git a/src/ldem/CONECTI.m b/src/ldem/CONECTI.m deleted file mode 100644 index 2aea010..0000000 --- a/src/ldem/CONECTI.m +++ /dev/null @@ -1,44 +0,0 @@ - -function ini=CONECTI() -% CONECTI Define as conectividades de cada barra do reticulado. -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% %--------------------------------------------------- -% Esta subrotina define as conectividades de cada barra. -% ------------------------------------------------------------ - NBA=0; - NBS=0; - NBT=0; -% ! - M2=M-2; - N2=N-2; - L2=L-2; - MN=M*N; - MN1=M1*N1; -% ! - ini=EXTCO1(M1,N,L,0,1,1,1); - ini=EXTCO1(M,N1,L,1,0,1,M); - ini=EXTCO1(M,N,L1,1,1,0,MN); -% ! - ini=INTCO1(M2,N1,L1,1); - ini=INTCO1(M1,N2,L1,M1); - ini=INTCO1(M1,N1,L2,MN1); -% ! - ini=DIACO1; -% ! - NBS=NBA; - NI=NNO; -% ! - NBT=NBS; - -% - ini=1; - end diff --git a/src/ldem/CONSTIT.m b/src/ldem/CONSTIT.m deleted file mode 100644 index 2112609..0000000 --- a/src/ldem/CONSTIT.m +++ /dev/null @@ -1,221 +0,0 @@ -function ini= CONSTIT (B,STR,STRRT,FORCE,R,fid_Lei) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - -% SUBROUTINE CONSTIT (B,STR,STRRT,FORCE,R) -% ! ================== -% ! -% ! Esta subrotina é chamada pela subrotina cabar para modelar a relação -% ! constitutiva de cada barra de acordo com um diagrama bilinear força vs. -% ! deformação, com amolecimento ("strain softening'). O processo de -% ! descarga é modelado de acordo com a hipótese de dano-elástico. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=20,INCON=8) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER B,R,RESP,NUMBAR -% DOUBLE PRECISION AUX,STR,STRRT,ER,FORCE -% !-------------------------------------------------------------------------- -% SS(B)=STR -% ER=KR(B)*EP(B) -% -% R=0 -% -% !-------------------------------------------------------------------------- -% ! VERIFICA SE OCORRE FRATURA -% !-------------------------------------------------------------------------- -% ! IF (STR.GE.EM(B)) THEN -% ! IF (RESP.EQ.1) THEN -% ! GO TO 5 -% ! END IF -% ! ! WRITE (*,*) -% ! ! WRITE (*,*) ' OCORREU FRATURA. DESEJA CONTINUAR? ' -% ! ! WRITE (*,*) ' SE SIM, DIGITE 1. SE NAO, DIGITE 2. ' -% !! READ (*,*) RESP -% ! ! WRITE (*,*) -% ! resp=1 -% ! IF (RESP.EQ.1) THEN -% ! GO TO 5 -% ! ELSE -% ! STOP -% ! END IF -% ! 5 END IF -% !-------------------------------------------------------------------------- -% IF (STR.GE.ER) GO TO 30 -% IF (STR.GE.EM(B)) GO TO 20 -% IF (STR.GE.0.0D00) GO TO 10 -% ! PARA ACOMPANHAR A EVOLUCAO DE UMA BARRA, DEFINIR SEU NUMERO EM NUMBAR -% NUMBAR=7014 -% !-------------------------------------------------------------------------- -% ! Consideração do amortecimento na relação constitutiva: CON > 0.0D00 -% !-------------------------------------------------------------------------- -% FORCE=E1(B)*STR+E1(B)*CON*STRRT -% -% ! Para acompanhar uma barra -% IF (B.EQ.NUMBAR) THEN ! colocar número da barra que se quer seguir -% WRITE (19,'(6(E25.12,3X))') TIME,STR,SS(B),ER,Force,EP(B) -% -% END IF -% -% -% GO TO 40 -% !-------------------------------------------------------------------------- -% -% 10 FORCE=E2(B)*STR+E2(B)*CON*STRRT -% !! Para acompanhar uma barra -% IF (B.EQ.NUMBAR) THEN -% WRITE (19,'(6(E25.12,3X))') TIME,STR,SS(B),ER,Force,EP(B) -% ! -% END IF -% -% -% GO TO 40 -% !-------------------------------------------------------------------------- -% 20 AUX=(STR-EP(B))/(KR(B)-1.0D00) -% AUX=E1(B)*(EP(B)-AUX) -% E2(B)=AUX/STR -% EM(B)=STR -% FORCE=AUX+E2(B)*CON*STRRT -% -% IF (B.EQ.NUMBAR) THEN ! colocar número da barra que se quer seguir -% WRITE (19,'(6(E25.12,3X))') TIME,STR,SS(B),ER,Force,EP(B) -% -% -% END IF -% -% -% IF (DM(B)) THEN -% DM(B)=.FALSE. -% END IF -% -% GO TO 40 -% !-------------------------------------------------------------------------- -% 30 E2(B)=0.0D00 -% FORCE=0.0D00 -% EM(B)=ER -% -% ! ! Para acompanhar uma barra -% IF (B.EQ.NUMBAR) THEN ! colocar número da barra que se quer seguir -% WRITE (19,'(6(E25.12,3X))') TIME,STR,SS(B),ER,Force,EP(B) -% -% -% END IF -% -% IF (FS(B)) THEN -% R=1 -% FS(B)=.FALSE. -% DM(B)=.FALSE. -% END IF -% -% 40 RETURN -% END -% ! -% ================== -% -% Esta subrotina é chamada pela subrotina CABAR para modelar a relação -% constitutiva de cada barra de acordo com um diagrama bilinear força vs. -% deformação, com amolecimento ("strain softening"). O processo de -% descarga é modelado de acordo com a hipótese de dano-elástico. -% -% Translates the Fortran SUBROUTINE CONSTIT. - - -%-------------------------------------------------------------------------- -% Parameters (preserved for fidelity; unused here) -%-------------------------------------------------------------------------- - -%-------------------------------------------------------------------------- -% Record current strain and compute the fracture reference strain -%-------------------------------------------------------------------------- -SS(B) = STR; -ER = KR(B) * EP(B); -R = 0; - -%-------------------------------------------------------------------------- -% Bar to be tracked (writes diagnostic rows to Lei_Barra.TXT) -%-------------------------------------------------------------------------- -NUMBAR = 7014; % change to follow a different bar -TrackBar = (B == NUMBAR); - -%========================================================================== -% Branch 1: STR >= ER --> bar fully broken (Fortran label 30) -%========================================================================== -if STR >= ER - - E2(B) = 0.0; - FORCE = 0.0; - EM(B) = ER; - - if TrackBar - fprintf(fid_Lei, '%25.12E %25.12E %25.12E %25.12E %25.12E %25.12E\n', ... - TIME, STR, SS(B), ER, FORCE, EP(B)); - end - - if FS(B) - R = 1; - FS(B) = false; - DM(B) = false; - end - -%========================================================================== -% Branch 2: EM(B) <= STR < ER --> strain softening (Fortran label 20) -%========================================================================== -elseif STR >= EM(B) - - AUX = (STR - EP(B)) / (KR(B) - 1.0); - AUX = E1(B) * (EP(B) - AUX); - E2(B) = AUX / STR; - EM(B) = STR; - FORCE = AUX + E2(B) * CON * STRRT; - - if TrackBar - fprintf(fid_Lei, '%25.12E %25.12E %25.12E %25.12E %25.12E %25.12E\n', ... - TIME, STR, SS(B), ER, FORCE, EP(B)); - end - - if DM(B) - DM(B) = false; - end - -%========================================================================== -% Branch 3: 0 <= STR < EM --> elastic reload/unload in tension -% (Fortran label 10) -%========================================================================== -elseif STR >= 0.0 - - FORCE = E2(B) * STR + E2(B) * CON * STRRT; - - if TrackBar - fprintf(fid_Lei, '%25.12E %25.12E %25.12E %25.12E %25.12E %25.12E\n', ... - TIME, STR, SS(B), ER, FORCE, EP(B)); - end - -%========================================================================== -% Branch 4 (default): STR < 0 --> linear elastic in compression -%========================================================================== -else - - FORCE = E1(B) * STR + E1(B) * CON * STRRT; - - if TrackBar - fprintf(fid_Lei, '%25.12E %25.12E %25.12E %25.12E %25.12E %25.12E\n', ... - TIME, STR, SS(B), ER, FORCE, EP(B)); - end - -end - - - -ini=1; - end diff --git a/src/ldem/COORD.m b/src/ldem/COORD.m deleted file mode 100644 index 5d196b0..0000000 --- a/src/ldem/COORD.m +++ /dev/null @@ -1,42 +0,0 @@ - -function ini=COORD() -global U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%--------------------------------------------------- -% ! -% ! Esta subrotina faz a geração automática de coordenadas nodais. -% ! -% !-------------------------------------------------------------------------- -%!-------------------------------------------------------------------------- -%! DEFINIÇÃO DA QUANTIDADE TOTAL DE NÓS - NNO=MNL+M1*N1*L1 - NNS=NNO - NNT=NNS -% - ini=COORDSUB(2,M1,1,N,1,L,0,M,N,1,2,1,2,1,2,0,0,0) - ini=COORDSUB(1,1,1,N,1,L,0,M,N,0,0,1,2,1,2,0,0,0) - ini=COORDSUB(M,M,1,N,1,L,0,M,N,0,-2*M1,1,2,1,2,0,0,0) - ini=COORDSUB(1,M1,1,N1,1,L1,MNL,M1,N1,1,1,1,1,1,1,0,0,0) -% - NI=NNO -%! -% DO NO=1,NNT -% U0(NO)=U(1,NO) -% V0(NO)=V(1,NO) -% W0(NO)=W(1,NO) -% END DO -U0=U(1,:); -V0=V(1,:); -W0=W(1,:); -% -% - ini=1; - end diff --git a/src/ldem/COORDSUB.m b/src/ldem/COORDSUB.m deleted file mode 100644 index dd78d7a..0000000 --- a/src/ldem/COORDSUB.m +++ /dev/null @@ -1,50 +0,0 @@ - -function ini=COORDSUB (MI,MF,NI,NF,LLI,LF,ST,MX,NX,X1,Y1,X2,Y2,X3,Y3,C1,C2,C3) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%--------------------------------------------------- -% -% ! -% ! Esta subrotina é chamada pela subrotina coord para fazer a geração -% ! automática de coordenadas nodais. -% ! -% !-------------------------------------------------------------------------- - - - %INTEGER I,J,K,LLI,LF,NI,NF,MI,MF,MX,NX - %INTEGER X1,Y1,X2,Y2,X3,Y3,C1,C2,C3,NO,ST -%!-------------------------------------------------------------------------- - for K=LLI:LF - for J=NI:NF - for I=MI:MF -% - NO=ST+(K-1)*MX*NX+(J-1)*MX+I; -%! - U(1,NO)=(X1*I-Y1/2.0D00)*LCO; - U(2,NO)=U(1,NO); - U(3,NO)=U(2,NO); - V(1,NO)=(X2*J-Y2/2.0D00)*LCO; - V(2,NO)=V(1,NO); - V(3,NO)=V(2,NO); - W(1,NO)=(X3*K-Y3/2.0D00)*LCO; - W(2,NO)=W(1,NO); - W(3,NO)=W(2,NO); -%! - BDX(NO)=C1; - BDY(NO)=C2; - BDZ(NO)=C3; -%! - end - end - end -%! - ini=1; - end diff --git a/src/ldem/Copy_of_COORDSUB.m b/src/ldem/Copy_of_COORDSUB.m deleted file mode 100644 index dd78d7a..0000000 --- a/src/ldem/Copy_of_COORDSUB.m +++ /dev/null @@ -1,50 +0,0 @@ - -function ini=COORDSUB (MI,MF,NI,NF,LLI,LF,ST,MX,NX,X1,Y1,X2,Y2,X3,Y3,C1,C2,C3) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%--------------------------------------------------- -% -% ! -% ! Esta subrotina é chamada pela subrotina coord para fazer a geração -% ! automática de coordenadas nodais. -% ! -% !-------------------------------------------------------------------------- - - - %INTEGER I,J,K,LLI,LF,NI,NF,MI,MF,MX,NX - %INTEGER X1,Y1,X2,Y2,X3,Y3,C1,C2,C3,NO,ST -%!-------------------------------------------------------------------------- - for K=LLI:LF - for J=NI:NF - for I=MI:MF -% - NO=ST+(K-1)*MX*NX+(J-1)*MX+I; -%! - U(1,NO)=(X1*I-Y1/2.0D00)*LCO; - U(2,NO)=U(1,NO); - U(3,NO)=U(2,NO); - V(1,NO)=(X2*J-Y2/2.0D00)*LCO; - V(2,NO)=V(1,NO); - V(3,NO)=V(2,NO); - W(1,NO)=(X3*K-Y3/2.0D00)*LCO; - W(2,NO)=W(1,NO); - W(3,NO)=W(2,NO); -%! - BDX(NO)=C1; - BDY(NO)=C2; - BDZ(NO)=C3; -%! - end - end - end -%! - ini=1; - end diff --git a/src/ldem/Copy_of_main - Copia.m b/src/ldem/Copy_of_main - Copia.m deleted file mode 100644 index d809786..0000000 --- a/src/ldem/Copy_of_main - Copia.m +++ /dev/null @@ -1,16 +0,0 @@ -clear all -clc -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ - -% FRX FRY FRZ FX FY FZ MAS MSS CN ENR -% global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -% global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -% global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -% global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -% global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -% global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -% global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -% global STRAIN STRESS -ini=ini_DEM2() -ACX \ No newline at end of file diff --git a/src/ldem/Copy_of_main.m b/src/ldem/Copy_of_main.m deleted file mode 100644 index d809786..0000000 --- a/src/ldem/Copy_of_main.m +++ /dev/null @@ -1,16 +0,0 @@ -clear all -clc -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ - -% FRX FRY FRZ FX FY FZ MAS MSS CN ENR -% global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -% global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -% global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -% global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -% global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -% global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -% global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -% global STRAIN STRESS -ini=ini_DEM2() -ACX \ No newline at end of file diff --git a/src/ldem/DEFEP.m b/src/ldem/DEFEP.m deleted file mode 100644 index c309599..0000000 --- a/src/ldem/DEFEP.m +++ /dev/null @@ -1,88 +0,0 @@ - -function ini=DEFEP(B, TYPES) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% SUBROUTINE DEFEP(B,TYPES) -% ! =================== -% ! -% ! Esta subrotina é chamada pelas subrotinas rmecex, rmecin e rmecdi para -% ! definir a aleatoriedade das propriedades mecânicas das barras. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER B,TYPES -% DOUBLE PRECISION RED,NOR,AUX,NOI,NOF -% !-------------------------------------------------------------------------- -% IF (TYPES.EQ.0) RED=1.00D00 -% IF (TYPES.EQ.1) RED=0.50D00 -% IF (TYPES.EQ.2) RED=0.25D00 -% ! -% IF (TYPES.LT.3) THEN -% E1(B)=ENR(B)*RED -% -% ELSE -% E1(B)=EDG(B) -% END IF -% ! -% -% E2(B)=E1(B) -% EP(B)=EPRB(B) -% KR(B)=(LCRB(B)/LI(B)) -% -% -% IF (KR(B).LT.1.01) THEN -% WRITE (*,*) -% WRITE (*,*) ' KR < 1.01CCC ' -% WRITE (*,*) -% STOP ! CUIDADO COM ISTO. VER EXPLICAÇÃO NA DISSERTAÇÃO DO MARCELO -% END IF -% RETURN -% END -if TYPES == 0 - RED = 1.00; -elseif TYPES == 1 - RED = 0.50; -elseif TYPES == 2 - RED = 0.25; -end - -%-------------------------------------------------------------------------- -% Assign E1 (random for exterior/interior bars; deterministic for diagonals) -%-------------------------------------------------------------------------- -if TYPES < 3 - E1(B) = ENR(B)*RED; -else - E1(B) = EDG(B); -end - -%-------------------------------------------------------------------------- -% Other mechanical properties -%-------------------------------------------------------------------------- -E2(B) = E1(B); -EP(B) = EPRB(B); -KR(B) = LCRB(B)/ LI(B); - -%-------------------------------------------------------------------------- -% Sanity check on the stiffness ratio KR -%-------------------------------------------------------------------------- -if KR(B)< 1.01 - fprintf('\n'); - fprintf(' KR < 1.01CCC \n'); - fprintf('\n'); - error('DEFEP: KR < 1.01 — see explanation in Marcelo''s dissertation.'); -end - - ini=1; - end diff --git a/src/ldem/DIACO1.m b/src/ldem/DIACO1.m deleted file mode 100644 index a73cf02..0000000 --- a/src/ldem/DIACO1.m +++ /dev/null @@ -1,121 +0,0 @@ - -function ini=DIACO1() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% SUBROUTINE DIACO1 -% ! ================= -% ! -% ! Esta subrotina é chamada pela subrotina conecti para definir as -% ! conectividades das barras diagonais dos módulos cúbicos. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER G,I,J,K,NOI,NOF,B,ST(8),REF -% !-------------------------------------------------------------------------- -% REF=NBA -% ST(1)=0 -% ST(2)=1 -% ST(3)=M -% ST(4)=M+1 -% ST(5)=N*M -% ST(6)=N*M+1 -% ST(7)=N*M+M -% ST(8)=N*M+M+1 -% ! -% DO 20 K=1,L1 -% DO 20 J=1,N1 -% DO 20 I=1,M1 -% ! -% NOI=(K-1)*M1*N1+(J-1)*M1+I -% NOF=(K-1)*M*N+(J-1)*M+I -% B=REF+(NOI-1)*8 -% NOI=NOI+MNL -% ! -% DO 10 G=1,8 -% B=B+1 -% CN(2*B-1)=NOI -% CN(2*B)=NOF+ST(G) -% 10 CONTINUE -% ! -% NBA=NBA+8 -% ! -% 20 CONTINUE -% ! -% RETURN -% END -% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% ================= -% -% Esta subrotina é chamada pela subrotina CONECTI para definir as -% conectividades das barras diagonais dos módulos cúbicos. -% -% Translates the Fortran SUBROUTINE DIACO1. - -%-------------------------------------------------------------------------- -% Local variables -%-------------------------------------------------------------------------- -ST = zeros(1, 8); % 1-based, matches Fortran ST(1..8) - -%-------------------------------------------------------------------------- -% Reference offset and ST table -%-------------------------------------------------------------------------- -REF = NBA; - -ST(1) = 0; -ST(2) = 1; -ST(3) = M; -ST(4) = M + 1; -ST(5) = N * M; -ST(6) = N * M + 1; -ST(7) = N * M + M; -ST(8) = N * M + M + 1; - -%========================================================================== -% Outer nest: K (outer), J (middle), I (inner) -- all share label 20 -%========================================================================== -for K = 1:L1 - for J = 1:N1 - for I = 1:M1 - - NOI = (K - 1) * M1 * N1 + (J - 1) * M1 + I; - NOF = (K - 1) * M * N + (J - 1) * M + I; - B = REF + (NOI - 1) * 8; - NOI = NOI + MNL; - - %-------------------------------------------------------------- - % Inner loop over G = 1..8 (label 10) - %-------------------------------------------------------------- - for G = 1:8 - B = B + 1; - CN(2*B - 1) = NOI; - CN(2*B) = NOF + ST(G); - end - - %-------------------------------------------------------------- - % Executed once per (K, J, I) triple - %-------------------------------------------------------------- - NBA = NBA + 8; - - end - end - - -end - - -ini=1; - end \ No newline at end of file diff --git a/src/ldem/ENERG2.m b/src/ldem/ENERG2.m deleted file mode 100644 index a10cfc6..0000000 --- a/src/ldem/ENERG2.m +++ /dev/null @@ -1,221 +0,0 @@ - -function ini=ENERG2(fid_EnB) -% ENERG2 Avalia o balanço de energia a cada passo de integração. -% Grava as energias (externa, interna, cinética, elástica, dissipada) em fid_EnB. -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% !! -% SUBROUTINE ENERG2 -% ! ================= -% ! -% ! Esta subrotina avalia o desempenho da energia a cada passo de -% ! integração. -% ! -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DAS VARIÁVEIS REFERENTES A DIFERENTES TIPOS DE ENERGIA QUE -% ! SERÃO CALCULADAS -% ! -% ! ENEX = Trabalho externo realizado sobre o modelo -% ! ENIN = Energia interna total dissipada ou acumulada -% ! ENCN = Energia cinética total do modelo -% ! ENEL = Energia elástica total presente no modelo -% ! ENDP = Energia dissipada por amortecimento -% ! ENGD = Energia dissipada pelo efeito de amolecimento (strain softening) -% ! (somatória sobre todas as barras) -% ! DEN = Diferença entre energia externa e interna -% ! (quanto menor este valor, mais preciso é o resultado) -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER B,KL -% DOUBLE PRECISION DU1,DU2 -% DOUBLE PRECISION DEF,AREA -% !-------------------------------------------------------------------------- -% ENCN=0.0D00 -% ENEL=0.0D00 -% ENGD=0.0D00 -% DERIV=0.0D00 -% DEN=0.0D00 -% IF (STEP.EQ.1) DU1=0.0D00 -% IF (STEP.EQ.1) DU2=0.0D00 -% !-------------------------------------------------------------------------- -% ! CÁLCULO DA ENERGIA CINÉTICA ENCN -% !-------------------------------------------------------------------------- -% DO I=1,NNT -% IF ((I.LE.NNO)) THEN -% ENCN=ENCN+MAS(I)*VLX(I)*VLX(I)/2.0D00 -% ENCN=ENCN+MAS(I)*VLY(I)*VLY(I)/2.0D00 -% ENCN=ENCN+MAS(I)*VLZ(I)*VLZ(I)/2.0D00 -% END IF -% END DO -% !-------------------------------------------------------------------------- -% ! CÁLCULO DA ENERGIA ELÁSTICA ENEL -% !-------------------------------------------------------------------------- -% DO B=1,NBT -% ! -% KL=2 -% ! Divide-se por 2 a expressão se as barras são as da borda ou simétrica -% ! Isto implica KL=4 -% IF (B.GT.NBA) KL=4 -% DEF=SS(B)*SS(B)*LI(B)/KL -% IF (SS(B).GE.0.0D00) THEN -% ENEL=ENEL+E2(B)*DEF -% EN(1,B)=E2(B)*DEF -% ELSE -% ENEL=ENEL+E1(B)*DEF -% EN(1,B)=E1(B)*DEF -% END IF -% !-------------------------------------------------------------------------- -% ! CÁLCULO DA ENERGIA DISSIPADA POR AMOLECIMENTO (STRAIN SOFTENING) ENGD -% !-------------------------------------------------------------------------- -% ! Barras rompidas e danificadas -% IF (.NOT.DM(B)) THEN -% AREA=E1(B)*EP(B)*EP(B)-E2(B)*EM(B)*EM(B)+(E1(B)*EP(B)+E2(B)* & -% & EM(B))*(EM(B)-EP(B)) -% AREA=LI(B)*AREA/KL -% -% IF (B.EQ.7014) THEN ! colocar número da barra que se quer seguir -% WRITE (20,'(2(E12.6,3X))') TIME,AREA -% END IF -% -% ENGD=ENGD+AREA -% EN(2,B)=AREA -% -% !--------------------------------------------------------------- -% -% END IF -% ! -% ! Armazena só energia dissipada pelas barras rompidas -% IF ((.NOT.DM(B)).AND.(.NOT.FS(B))) THEN -% DEN=DEN+E1(B)*EP(B)*EP(B)*KR(B)*LI(B)/KL -% END IF -% ! -% END DO -% ! -% DU2=ENGD -% DERIV=(DU2-DU1)/DT -% DU1=DU2 -% ! -% RETURN -% END -% !------------- - -% ENERG2 -% ====== -% -% Esta subrotina avalia o desempenho da energia a cada passo de -% integração. -% -% MATLAB translation using GLOBAL variables instead of COMMON. -% -% Energy types: -% ENEX = External work done on the model -% ENIN = Total internal energy dissipated or accumulated -% ENCN = Total kinetic energy of the model -% ENEL = Total elastic energy present in the model -% ENDP = Energy dissipated by damping -% ENGD = Energy dissipated by strain-softening effects -% DEN = Difference between external and internal energy - -% ------------------------------------------------------------------------- -% Global variables (equivalent to the COMMON block) -% ------------------------------------------------------------------------- - - -% ------------------------------------------------------------------------- -% Persistent local variables (keep DU1, DU2 between calls, like Fortran -% SAVE-less but preserved in the calling program's memory) -% ------------------------------------------------------------------------- -persistent DU1 DU2 -if isempty(DU1), DU1 = 0.0; end -if isempty(DU2), DU2 = 0.0; end - -% ------------------------------------------------------------------------- -% Local variables -% ------------------------------------------------------------------------- -DEF = 0.0; -AREA = 0.0; - -ENCN = 0.0; -ENEL = 0.0; -ENGD = 0.0; -DERIV = 0.0; -DEN = 0.0; - -if STEP == 1 - DU1 = 0.0; - DU2 = 0.0; -end - -% ------------------------------------------------------------------------- -% Kinetic energy ENCN -% ------------------------------------------------------------------------- -% for I = 1:NNT -% if I <= NNO -% ENCN = ENCN + MAS(I)*VLX(I)*VLX(I)/2.0; -% ENCN = ENCN + MAS(I)*VLY(I)*VLY(I)/2.0; -% ENCN = ENCN + MAS(I)*VLZ(I)*VLZ(I)/2.0; -% end -% end -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -ENCN=ENCN+(MAS.*(VLX.^2.0))./2.0; -ENCN=ENCN+(MAS.*(VLY.^2.0))./2.0; -ENCN=ENCN+(MAS.*(VLZ.^2.0))./2.0; -% ------------------------------------------------------------------------- -% Elastic energy ENEL -% ------------------------------------------------------------------------- -for B = 1:NBT - KL = 2; - % Divide by 2 the expression if bars are edge or symmetric bars. - % This implies KL = 4. - if B > NBA - KL = 4; - end - - DEF = SS(B)*SS(B)*LI(B)/KL; - - if SS(B) >= 0.0 - ENEL = ENEL + E2(B)*DEF; - EN(1,B) = E2(B)*DEF; - else - ENEL = ENEL + E1(B)*DEF; - EN(1,B) = E1(B)*DEF; - end - % --------------------------------------------------------------------- - % Strain-softening dissipated energy ENGD - % --------------------------------------------------------------------- - % Broken and damaged bars - if ~DM(B) - AREA = E1(B)*EP(B)*EP(B) - E2(B)*EM(B)*EM(B) + ... - (E1(B)*EP(B) + E2(B)*EM(B))*(EM(B) - EP(B)); - AREA = LI(B)*AREA/KL; - - if B == 7014 % bar number to be followed - fprintf(fid_EnB, '%12.6e %12.6e\n', TIME, AREA); - end - ENGD = ENGD + AREA; - EN(2,B) = AREA; - end - % Store only energy dissipated by broken bars - if (~DM(B)) && (~FS(B)) - DEN = DEN + E1(B)*EP(B)*EP(B)*KR(B)*LI(B)/KL; - end -end - -DU2 = ENGD; -DERIV = (DU2 - DU1)/DT; -DU1 = DU2; - - ini=1; - end diff --git a/src/ldem/EXTCO1.m b/src/ldem/EXTCO1.m deleted file mode 100644 index f4d716a..0000000 --- a/src/ldem/EXTCO1.m +++ /dev/null @@ -1,70 +0,0 @@ -function ini=EXTCO1(MX,NX,LX,C1,C2,C3,ST) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%--------------------------------------------------- -% ! Esta subrotina é chamada pela subrotina conecti para definir as -% ! conectividades das barras externas dos módulos cúbicos. -% ! -%------------------------------------------------------------------------ -% DO 10 K=1,LX -% DO 10 J=1,NX -% DO 10 I=1,MX -% ! -% TYPES=0 -% IF ((I.EQ.1).OR.(I.EQ.M)) TYPES=TYPES+C1 -% IF ((J.EQ.1).OR.(J.EQ.N)) TYPES=TYPES+C2 -% IF ((K.EQ.1).OR.(K.EQ.L)) TYPES=TYPES+C3 -% ! -% NO=(K-1)*M*N+(J-1)*M+I -% B=NBA+(K-1)*MX*NX+(J-1)*MX+I -% ! -% CN(2*B-1)=NO -% CN(2*B)=NO+ST -% ! -% 10 CONTINUE -% ! -% NBA=NBA+MX*NX*LX - - % ----- Triple loop: K=1..LX, J=1..NX, I=1..MX ----- -for K = 1:LX - for J = 1:NX - for I = 1:MX - - % Compute TYPES (unused afterwards, but kept for faithful translation) - TYPES = 0; - if (I == 1) || (I == M) - TYPES = TYPES + C1; - end - if (J == 1) || (J == N) - TYPES = TYPES + C2; - end - if (K == 1) || (K == L) - TYPES = TYPES + C3; - end - - % Linear index into the full-size array (dimensions M x N x L) - NO = (K - 1) * M * N + (J - 1) * M + I; - - % Index into the CN array (based on the subdomain MX x NX x LX) - B = NBA + (K - 1) * MX * NX + (J - 1) * MX + I; - - % Store the pair (NO, NO+ST) in consecutive positions of CN - CN(2 * B - 1) = NO; - CN(2 * B) = NO + ST; - - end - end -end - -% Update the starting offset in CN for a possible next block -NBA = NBA + MX * NX * LX; - ini=1; - end diff --git a/src/ldem/Energia_Barra.TXT b/src/ldem/Energia_Barra.TXT deleted file mode 100644 index e69de29..0000000 diff --git a/src/ldem/Energy_balance.m b/src/ldem/Energy_balance.m deleted file mode 100644 index 21b89d8..0000000 --- a/src/ldem/Energy_balance.m +++ /dev/null @@ -1,14 +0,0 @@ -clear all -close all -clc - -[Tempo,enex,Cinetica,Elastica,Dano,amort,Den]=textread('LET.ENE','%f %f %f %f %f %f %f'); - -figure(1) -plot(Tempo,Cinetica,'b.-',Tempo,Elastica,'m.-',Tempo,Dano,'r.-') -title(' ','FontName','Times New Roman Negrito','FontSize',16) -xlabel('Time [s]','FontName','Times New Roman','FontSize',18,'Rotation',0) -ylabel('Energy [Nm]','FontName','Times New Roman','FontSize',18,'Rotation',90) -legend('Kinetic','Elástic','Dissipate') -grid on - diff --git a/src/ldem/IGN012.m b/src/ldem/IGN012.m deleted file mode 100644 index 3eedcf2..0000000 --- a/src/ldem/IGN012.m +++ /dev/null @@ -1,285 +0,0 @@ - -function ini=IGN012() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%! -% SUBROUTINE IGN012 -% ! ================= -% ! -% ! DATA: 08/04/1994 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina redefine as posições a cada passo de integração. -% ! -% !-------------------------------------------------------------------------- -% ! DESCRIÇÃO DAS VARIÁVEIS -% !-------------------------------------------------------------------------- -% ! -% ! (C) ==> O VALOR DAS VARIÁVEIS MUDAM DENTRO DESTA SUBROTINA -% ! (NC) ==> O VALOR DAS VARIÁVEIS NÃO MUDAM DENTRO DESTA SUBROTINA -% ! (INB) ==> ÍNDICE DE BARRAS -% ! (INN) ==> ÍNDICE DE NÓS -% ! -% ! EST:(NC) int.var Índice que identifica o tipo de amortecimento -% ! EST=0 ==> Amortecimento padrão (C=DF*M) -% ! EST=1 ==> EST=0 + um amortecimento introduzido -% ! na equação constitutiva com CON -% ! EST=2 ==> EST=0, mas o coefic. de amortecimento -% ! DF é multiplicado pelo índice de dano -% ! NNO: -% ! NNT:(NC) int.var Número de nós -% ! NBA: -% ! NBS: -% ! NBT:(NC) int.var Número de barras -% ! CN(2*INB):(NC) int.arr Conectividade das barras -% ! E2(INB): -% ! E1(INB):(NC) dp.arr Módulo de Young das barras inalteradas -% ! -% ! U0(INN): -% ! V0(INN): -% ! W0(INN):(NC) dp.arr Coordenadas nodais na forma inalterada -% ! U(3,INN): -% ! V(3,INN): -% ! W(3,INN): dp.arr Coordenadas nodais da estrutura -% ! BDX(INN): -% ! BDY(INN): -% ! BDZ(INN):(NC) int.arr Condições de contorno aplicadas sobre os nós -% ! ACX(INN): -% ! ACY(INN): -% ! ACZ(INN):(C) dp.arr Acelerações nodais -% ! VLX(INN): -% ! VLY(INN): -% ! VLZ(INN):(C) dp.arr Velocidades nodais -% ! MAS(INN):(NC) dp.arr Massa nodal -% ! FRX(INN): -% ! FRY(INN): -% ! FRZ(INN):(NC) dp.arr Forças nodais -% ! DF1:(C) dp.var Coeficiente de amortecimento -% ! ENDP:(C) dp.var Porção da energia dissipada por amortecimento -% ! LCO:(C) dp.var Comprimento original do elemento -% ! LI(INB):(NC) dp.var Comprimento de cada elemento -% ! DT:(NC) dp.var Incremento de integração -% ! CON:(NC) dp.var Coeficiente de amortecimento se EST=1 -% ! DSS(INB):(NC) dp.arr Velocidades de deformação em cada elemento -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=20,INCON=8) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% DOUBLE PRECISION DDT,SDT,DF11,TM,DISS -% !-------------------------------------------------------------------------- -% ! -% DO I=1,NNT -% !-------------------------------------------------------------------------- -% ! CÁLCULO DE COEFICIENTES -% !-------------------------------------------------------------------------- -% DDT=2.0D00*DT -% SDT=DT*DT -% DF11=DF1 -% ! -% IF (MAS(I).NE.0.0D00) THEN -% TM=SDT/MAS(I) -% END IF -% ! -% DMP1=(1.0D00-DF11*DT/2.0D00) -% DMP2=(1.0D00+DF11*DT/2.0D00) -% !-------------------------------------------------------------------------- -% ! CÁLCULO DAS NOVAS COORDENADAS POR DIFERENÇAS FINITAS CENTRAIS -% !-------------------------------------------------------------------------- -% IF (BDX(I)) 10,10,20 -% 10 U(3,I)=(TM*FRX(I)+2.0D00*U(2,I)-DMP1*U(1,I))/DMP2 -% GO TO 30 -% 20 U(3,I)=U(2,I) -% 30 CONTINUE -% ! -% IF (BDY(I)) 40,40,50 -% 40 V(3,I)=(TM*FRY(I)+2.0D00*V(2,I)-DMP1*V(1,I))/DMP2 -% GO TO 60 -% 50 V(3,I)=V(2,I) -% 60 CONTINUE -% ! -% IF (BDZ(I)) 70,70,80 -% 70 W(3,I)=(TM*FRZ(I)+2.0D00*W(2,I)-DMP1*W(1,I))/DMP2 -% GO TO 90 -% 80 W(3,I)=W(2,I) -% 90 CONTINUE -% !-------------------------------------------------------------------------- -% END DO -% !-------------------------------------------------------------------------- -% ! CÁLCULO DAS VELOCIDADES E ACELERAÇÕES -% !-------------------------------------------------------------------------- -% DO I=1,NNT -% ! -% VLX(I)=(U(3,I)-U(1,I))/DDT -% VLY(I)=(V(3,I)-V(1,I))/DDT -% VLZ(I)=(W(3,I)-W(1,I))/DDT -% ACX(I)=(U(3,I)-2.0D00*U(2,I)+U(1,I))/SDT -% ACY(I)=(V(3,I)-2.0D00*V(2,I)+V(1,I))/SDT -% ACZ(I)=(W(3,I)-2.0D00*W(2,I)+W(1,I))/SDT -% !-------------------------------------------------------------------------- -% ! CÁLCULO DA ENERGIA DISSIPADA POR AMORTECIMENTO ENDP -% !-------------------------------------------------------------------------- -% DISS=DF11*MAS(I)/2.0D00 -% ENDP=ENDP+DISS*VLX(I)*(U(3,I)-U(1,I)) -% ENDP=ENDP+DISS*VLY(I)*(V(3,I)-V(1,I)) -% ENDP=ENDP+DISS*VLZ(I)*(W(3,I)-W(1,I)) -% ! -% END DO -% !-------------------------------------------------------------------------- -% ! -% !-------------------------------------------------------------------------- -% DO B=1,NBT -% KL=2 -% IF ((B.GT.NBA).AND.(B.LE.NBS)) KL=4 -% IF (SS(B).LT.0.0D00) THEN -% ENDP=ENDP+2.0D00*(E1(B)*CON*DSS(B)*DSS(B)*DT*LI(B)/KL) -% ELSE -% ENDP=ENDP+2.0D00*(E2(B)*CON*DSS(B)*DSS(B)*DT*LI(B)/KL) -% END IF -% END DO -% !-------------------------------------------------------------------------- -% ! ATUALIZA AS COORDENADAS -% !-------------------------------------------------------------------------- -% DO I=1,NNT -% U(1,I)=U(2,I) -% U(2,I)=U(3,I) -% V(1,I)=V(2,I) -% V(2,I)=V(3,I) -% W(1,I)=W(2,I) -% W(2,I)=W(3,I) -% END DO -% ! -% RETURN -% END -% ! -function ign012 -% IGN012 -% ====== -% -% DATA: 08/04/1994 -% AUTOR: IGNACIO ITURRIOZ -% -% Esta subrotina redefine as posições a cada passo de integração. -% -% MATLAB translation using GLOBAL variables instead of COMMON. -% The following globals must be defined in the workspace: -% NNT, NBT, NBA, NBS, DT, DF1, MAS, -% BDX, BDY, BDZ, FRX, FRY, FRZ, -% U, V, W, VLX, VLY, VLZ, ACX, ACY, ACZ, -% ENDP, SS, E1, E2, CON, DSS, LI -% -% Note: The Fortran PARAMETER statement is not used here. - - -%-------------------------------------------------------------------------- -% Local variables -%-------------------------------------------------------------------------- -TM = 0.0; % initialize to avoid undefined use (Fortran local variable) - -DDT = 2.0 * DT; -SDT = DT * DT; -DF11 = DF1; - -DMP1 = (1.0 - DF11*DT/2.0); -DMP2 = (1.0 + DF11*DT/2.0); - -%-------------------------------------------------------------------------- -% Calculate new coordinates by central finite differences -%-------------------------------------------------------------------------- -for I = 1:NNT - if MAS(I) ~= 0.0 - TM = SDT / MAS(I); - end - % If MAS(I) == 0, TM retains its previous value (as in Fortran) - - % X direction - if BDX(I) <= 0 - U(3,I) = (TM*FRX(I) + 2.0*U(2,I) - DMP1*U(1,I)) / DMP2; - else - U(3,I) = U(2,I); - end - - % Y direction - if BDY(I) <= 0 - V(3,I) = (TM*FRY(I) + 2.0*V(2,I) - DMP1*V(1,I)) / DMP2; - else - V(3,I) = V(2,I); - end - - % Z direction - if BDZ(I) <= 0 - W(3,I) = (TM*FRZ(I) + 2.0*W(2,I) - DMP1*W(1,I)) / DMP2; - else - W(3,I) = W(2,I); - end -end - -%-------------------------------------------------------------------------- -% Calculate velocities and accelerations -%-------------------------------------------------------------------------- -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% for I = 1:NNT -% VLX(I) = (U(3,I) - U(1,I)) / DDT; -% VLY(I) = (V(3,I) - V(1,I)) / DDT; -% VLZ(I) = (W(3,I) - W(1,I)) / DDT; -% -% ACX(I) = (U(3,I) - 2.0*U(2,I) + U(1,I)) / SDT; -% ACY(I) = (V(3,I) - 2.0*V(2,I) + V(1,I)) / SDT; -% ACZ(I) = (W(3,I) - 2.0*W(2,I) + W(1,I)) / SDT; -% -% % Dissipated energy by damping ENDP -% DISS = DF11 * MAS(I) / 2.0; -% ENDP = ENDP + DISS*VLX(I)*(U(3,I) - U(1,I)); -% ENDP = ENDP + DISS*VLY(I)*(V(3,I) - V(1,I)); -% ENDP = ENDP + DISS*VLZ(I)*(W(3,I) - W(1,I)); -% end -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - VLX = (U(3,:) - U(1,:))./ DDT; - VLY = (V(3,:) - V(1,:))./ DDT; - VLZ = (W(3,:) - W(1,:))./ DDT; - ACX = (U(3,:) -U(2,:).*2.0 + U(1,:))./ SDT; - ACY = (V(3,:) - V(2,I).*2.0 + V(1,:))./ SDT; - ACZ = (W(3,:) - W(2,:).*2.0 + W(1,:))./ SDT; - % Dissipated energy by damping ENDP - ENDP = ENDP + (DF11.*(MAS./2.0)).*VLX.*(U(3,:)-U(1,:)); - ENDP = ENDP + (DF11.*(MAS./2.0)).*VLY.*(V(3,:)-V(1,:)); - ENDP = ENDP + (DF11.*(MAS./2.0)).*VLZ.*(W(3,:)-W(1,:)); -%-------------------------------------------------------------------------- -% Additional damping energy in bars -%-------------------------------------------------------------------------- -for B = 1:NBT - KL = 2; - if (B > NBA) && (B <= NBS) - KL = 4; - end - - if SS(B) < 0.0 - ENDP = ENDP + 2.0*(E1(B)*CON*DSS(B)*DSS(B)*DT*LI(B)/KL); - else - ENDP = ENDP + 2.0*(E2(B)*CON*DSS(B)*DSS(B)*DT*LI(B)/KL); - end -end - -%-------------------------------------------------------------------------- -% Update coordinates -%-------------------------------------------------------------------------- - U(1,:) = U(2,:); - U(2,:) = U(3,:); - V(1,:) = V(2,:); - V(2,:) = V(3,:); - W(1,:) = W(2,:); - W(2,:) = W(3,:); -end - - -ini=1; - end diff --git a/src/ldem/IMPERF.m b/src/ldem/IMPERF.m deleted file mode 100644 index 19fd74e..0000000 --- a/src/ldem/IMPERF.m +++ /dev/null @@ -1,108 +0,0 @@ - -function ini=IMPERF() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% %--------------------------------------------------- -% ! -% SUBROUTINE IMPERF - -% ! Esta subrotina introduz imperfeições na malha. - -% !-------------------------------------------------------------------------- -% INTEGER NI,NO -% !-------------------------------------------------------------------------- -% DOUBLE PRECISION FUVW,CVUVW,UNIF,STA101 -% !-------------------------------------------------------------------------- -% ! GERAÇÃO DO CAMPO ALEATÓRIO PARA PERTUBAR A MALHA -% !-------------------------------------------------------------------------- -% ! - -% ! - -rng(SEED)% define the SEED of the Mesh perturbation randon field. - LABELN=1 % The mesh perturbation is active - LABELN=0 % inactive - CVUVW=2.0e-2 ;% define the variation coeficient of the mesh perturbation - % CUVW= 2.75D-02; - -if LABELN == 1; %&&&&&&&& - % ! - U(1,:)=U(1,:)+randn(1,NNT)*CVUVW*LCO; - U(2,:)=U(1,:); - U(3,:)=U(1,:); - V(1,:)=V(1,:)+randn(1,NNT)*CVUVW*LCO; - V(2,:)=V(1,:); - V(3,:)=V(1,:); - W(1,:)=W(1,:)+randn(1,NNT)*CVUVW*LCO; - W(2,:)=W(1,:); - W(3,:)=W(1,:); -% DO I=1,NNT -% UNIF=RAN0(SEED) -% FUVW=STA101(UNIF,1.0D-50) -% U(1,I)=U(1,I)+FUVW*CVUVW*LCO -% U(2,I)=U(1,I) -% U(3,I)=U(1,I) -% UNIF=RAN0(SEED) -% FUVW=STA101(UNIF,1.0D-50) -% V(1,I)=V(1,I)+FUVW*CVUVW*LCO -% V(2,I)=V(1,I) -% V(3,I)=V(1,I) -% UNIF=RAN0(SEED) -% FUVW=STA101(UNIF,1.0D-50) -% W(1,I)=W(1,I)+FUVW*CVUVW*LCO -% W(2,I)=W(1,I) -% W(3,I)=W(1,I) -% !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% condition to create a border with no perturbed mesh -% -% Create a logical vector (mask) that is TRUE where ANY condition is satisfied -% (Equivalent to having separate IFs, as the assignments are identical) -mask = (W0 >= (L1 - 1.01) * LCO) | ... % Condition 1 - (W0 <= (1.01 * LCO)) | ... % Condition 2 - (U0 >= (M1 - 1.01) * LCO) | ... % Condition 3 - (U0 <= (1.01 * LCO)) | ... % Condition 4 - (V0 >= (N1 - 1.01) * LCO) | ... % Condition 5 - (V0 <= (1.01 * LCO)); % Condition 6 - -% Apply the assignments ONLY to the columns where mask = true - -% Note: This code assumes U0, V0, W0 are ROW vectors (1 x NNT). -% If they are COLUMN vectors (NNT x 1), use U0(mask).' to transpose. - U(1, mask) = U0(mask); - U(2, mask) = U0(mask); - U(3, mask) = U0(mask); - - V(1, mask) = V0(mask); - V(2, mask) = V0(mask); - V(3, mask) = V0(mask); - - W(1, mask) = W0(mask); - W(2, mask) = W0(mask); - W(3, mask) = W0(mask); -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -end % here finish the first if condition &&&&&&& -% DO NO=1,NNT -% U0(NO)=U(1,NO) -% V0(NO)=V(1,NO) -% W0(NO)=W(1,NO) -% END DO -U0=U(1,:); -V0=V(1,:); -W0=W(1,:); - -% ! -% END IF -% -% RETURN -% END -%! - ini=1; - end diff --git a/src/ldem/INTCO1.m b/src/ldem/INTCO1.m deleted file mode 100644 index 0a792ec..0000000 --- a/src/ldem/INTCO1.m +++ /dev/null @@ -1,51 +0,0 @@ - -function ini=INTCO1 (MX,NX,LX,ST) -% INTCO1 Define a conectividade das barras internas dos módulos cúbicos. -% Chamada por CONECTI. -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%--------------------------------------------------- -% ! -% ! Esta subrotina é chamada pela subrotina conecti para definir as -% ! conectividades das barras internas dos módulos cúbicos. -% ! - -%!-------------------------------------------------------------------------- -% DO 10 K=1,LX -% DO 10 J=1,NX -% DO 10 I=1,MX -% ! -% NO=MNL+(K-1)*M1*N1+(J-1)*M1+I -% B=NBA+(K-1)*MX*NX+(J-1)*MX+I -% ! -% CN(2*B-1)=NO -% CN(2*B)=NO+ST -% ! -% 10 CONTINUE -% ! -% NBA=NBA+MX*NX*LX - -% Create 3D index grids (I varies fastest) -[I, J, K] = ndgrid(1:MX, 1:NX, 1:LX); - -% Compute all NO and B indices at once -NO = MNL + (K - 1) * M1 * N1 + (J - 1) * M1 + I; -B = NBA + (K - 1) * MX * NX + (J - 1) * MX + I; - -% Flatten and assign to CN -CN(2 * B(:) - 1) = NO(:); -CN(2 * B(:)) = NO(:) + ST; - -% Update NBA -NBA = NBA + MX * NX * LX; - - ini=1; - end diff --git a/src/ldem/LET.AN1 b/src/ldem/LET.AN1 deleted file mode 100644 index 9bdbe3f..0000000 --- a/src/ldem/LET.AN1 +++ /dev/null @@ -1,700 +0,0 @@ - ANSYS00.MAC - ANSYS01.MAC - ANSYS02.MAC - ANSYS03.MAC - ANSYS04.MAC - ANSYS05.MAC - ANSYS06.MAC - ANSYS07.MAC - ANSYS08.MAC - ANSYS09.MAC - ANSYS10.MAC - ANSYS11.MAC - ANSYS12.MAC - ANSYS13.MAC - ANSYS14.MAC - ANSYS15.MAC - ANSYS16.MAC - ANSYS17.MAC - ANSYS18.MAC - ANSYS19.MAC - ANSYS20.MAC - ANSYS21.MAC - ANSYS22.MAC - ANSYS23.MAC - ANSYS24.MAC - ANSYS25.MAC - ANSYS26.MAC - ANSYS27.MAC - ANSYS28.MAC - ANSYS29.MAC - ANSYS30.MAC - ANSYS31.MAC - ANSYS32.MAC - ANSYS33.MAC - ANSYS34.MAC - ANSYS35.MAC - ANSYS36.MAC - ANSYS37.MAC - ANSYS38.MAC - ANSYS39.MAC - ANSYS40.MAC - ANSYS41.MAC - ANSYS42.MAC - ANSYS43.MAC - ANSYS44.MAC - ANSYS45.MAC - ANSYS46.MAC - ANSYS47.MAC - ANSYS48.MAC - ANSYS49.MAC - ANSYS50.MAC - ANSYS51.MAC - ANSYS52.MAC - ANSYS53.MAC - ANSYS54.MAC - ANSYS55.MAC - ANSYS56.MAC - ANSYS57.MAC - ANSYS58.MAC - ANSYS59.MAC - ANSYS60.MAC - ANSYS61.MAC - ANSYS62.MAC - ANSYS63.MAC - ANSYS64.MAC - ANSYS65.MAC - ANSYS66.MAC - ANSYS67.MAC - ANSYS68.MAC - ANSYS69.MAC - ANSYS70.MAC - ANSYS71.MAC - ANSYS72.MAC - ANSYS73.MAC - ANSYS74.MAC - ANSYS75.MAC - ANSYS76.MAC - ANSYS77.MAC - ANSYS78.MAC - ANSYS79.MAC - ANSYS80.MAC - ANSYS81.MAC - ANSYS82.MAC - ANSYS83.MAC - ANSYS84.MAC - ANSYS85.MAC - ANSYS86.MAC - ANSYS87.MAC - ANSYS88.MAC - ANSYS89.MAC - ANSYS90.MAC - ANSYS91.MAC - ANSYS92.MAC - ANSYS93.MAC - ANSYS94.MAC - ANSYS95.MAC - ANSYS96.MAC - ANSYS97.MAC - ANSYS98.MAC - ANSYS99.MAC - ANSYS100.MAC - ANSYS101.MAC - ANSYS102.MAC - ANSYS103.MAC - ANSYS104.MAC - ANSYS105.MAC - ANSYS106.MAC - ANSYS107.MAC - ANSYS108.MAC - ANSYS109.MAC - ANSYS110.MAC - ANSYS111.MAC - ANSYS112.MAC - ANSYS113.MAC - ANSYS114.MAC - ANSYS115.MAC - ANSYS116.MAC - ANSYS117.MAC - ANSYS118.MAC - ANSYS119.MAC - ANSYS120.MAC - ANSYS121.MAC - ANSYS122.MAC - ANSYS123.MAC - ANSYS124.MAC - ANSYS125.MAC - ANSYS126.MAC - ANSYS127.MAC - ANSYS128.MAC - ANSYS129.MAC - ANSYS130.MAC - ANSYS131.MAC - ANSYS132.MAC - ANSYS133.MAC - ANSYS134.MAC - ANSYS135.MAC - ANSYS136.MAC - ANSYS137.MAC - ANSYS138.MAC - ANSYS139.MAC - ANSYS140.MAC - ANSYS141.MAC - ANSYS142.MAC - ANSYS143.MAC - ANSYS144.MAC - ANSYS145.MAC - ANSYS146.MAC - ANSYS147.MAC - ANSYS148.MAC - ANSYS149.MAC - ANSYS150.MAC - ANSYS151.MAC - ANSYS152.MAC - ANSYS153.MAC - ANSYS154.MAC - ANSYS155.MAC - ANSYS156.MAC - ANSYS157.MAC - ANSYS158.MAC - ANSYS159.MAC - ANSYS160.MAC - ANSYS161.MAC - ANSYS162.MAC - ANSYS163.MAC - ANSYS164.MAC - ANSYS165.MAC - ANSYS166.MAC - ANSYS167.MAC - ANSYS168.MAC - ANSYS169.MAC - ANSYS170.MAC - ANSYS171.MAC - ANSYS172.MAC - ANSYS173.MAC - ANSYS174.MAC - ANSYS175.MAC - ANSYS176.MAC - ANSYS177.MAC - ANSYS178.MAC - ANSYS179.MAC - ANSYS180.MAC - ANSYS181.MAC - ANSYS182.MAC - ANSYS183.MAC - ANSYS184.MAC - ANSYS185.MAC - ANSYS186.MAC - ANSYS187.MAC - ANSYS188.MAC - ANSYS189.MAC - ANSYS190.MAC - ANSYS191.MAC - ANSYS192.MAC - ANSYS193.MAC - ANSYS194.MAC - ANSYS195.MAC - ANSYS196.MAC - ANSYS197.MAC - ANSYS198.MAC - ANSYS199.MAC - ANSYS200.MAC - ANSYS201.MAC - ANSYS202.MAC - ANSYS203.MAC - ANSYS204.MAC - ANSYS205.MAC - ANSYS206.MAC - ANSYS207.MAC - ANSYS208.MAC - ANSYS209.MAC - ANSYS210.MAC - ANSYS211.MAC - ANSYS212.MAC - ANSYS213.MAC - ANSYS214.MAC - ANSYS215.MAC - ANSYS216.MAC - ANSYS217.MAC - ANSYS218.MAC - ANSYS219.MAC - ANSYS220.MAC - ANSYS221.MAC - ANSYS222.MAC - ANSYS223.MAC - ANSYS224.MAC - ANSYS225.MAC - ANSYS226.MAC - ANSYS227.MAC - ANSYS228.MAC - ANSYS229.MAC - ANSYS230.MAC - ANSYS231.MAC - ANSYS232.MAC - ANSYS233.MAC - ANSYS234.MAC - ANSYS235.MAC - ANSYS236.MAC - ANSYS237.MAC - ANSYS238.MAC - ANSYS239.MAC - ANSYS240.MAC - ANSYS241.MAC - ANSYS242.MAC - ANSYS243.MAC - ANSYS244.MAC - ANSYS245.MAC - ANSYS246.MAC - ANSYS247.MAC - ANSYS248.MAC - ANSYS249.MAC - ANSYS250.MAC - ANSYS251.MAC - ANSYS252.MAC - ANSYS253.MAC - ANSYS254.MAC - ANSYS255.MAC - ANSYS256.MAC - ANSYS257.MAC - ANSYS258.MAC - ANSYS259.MAC - ANSYS260.MAC - ANSYS261.MAC - ANSYS262.MAC - ANSYS263.MAC - ANSYS264.MAC - ANSYS265.MAC - ANSYS266.MAC - ANSYS267.MAC - ANSYS268.MAC - ANSYS269.MAC - ANSYS270.MAC - ANSYS271.MAC - ANSYS272.MAC - ANSYS273.MAC - ANSYS274.MAC - ANSYS275.MAC - ANSYS276.MAC - ANSYS277.MAC - ANSYS278.MAC - ANSYS279.MAC - ANSYS280.MAC - ANSYS281.MAC - ANSYS282.MAC - ANSYS283.MAC - ANSYS284.MAC - ANSYS285.MAC - ANSYS286.MAC - ANSYS287.MAC - ANSYS288.MAC - ANSYS289.MAC - ANSYS290.MAC - ANSYS291.MAC - ANSYS292.MAC - ANSYS293.MAC - ANSYS294.MAC - ANSYS295.MAC - ANSYS296.MAC - ANSYS297.MAC - ANSYS298.MAC - ANSYS299.MAC - ANSYS300.MAC - ANSYS301.MAC - ANSYS302.MAC - ANSYS303.MAC - ANSYS304.MAC - ANSYS305.MAC - ANSYS306.MAC - ANSYS307.MAC - ANSYS308.MAC - ANSYS309.MAC - ANSYS310.MAC - ANSYS311.MAC - ANSYS312.MAC - ANSYS113.MAC - ANSYS114.MAC - ANSYS115.MAC - ANSYS116.MAC - ANSYS117.MAC - ANSYS118.MAC - ANSYS119.MAC - ANSYS120.MAC - ANSYS121.MAC - ANSYS122.MAC - ANSYS123.MAC - ANSYS124.MAC - ANSYS125.MAC - ANSYS126.MAC - ANSYS127.MAC - ANSYS128.MAC - ANSYS129.MAC - ANSYS130.MAC - ANSYS131.MAC - ANSYS132.MAC - ANSYS133.MAC - ANSYS134.MAC - ANSYS135.MAC - ANSYS136.MAC - ANSYS137.MAC - ANSYS138.MAC - ANSYS139.MAC - ANSYS140.MAC - ANSYS141.MAC - ANSYS142.MAC - ANSYS143.MAC - ANSYS144.MAC - ANSYS145.MAC - ANSYS146.MAC - ANSYS147.MAC - ANSYS148.MAC - ANSYS149.MAC - ANSYS150.MAC - ANSYS151.MAC - ANSYS152.MAC - ANSYS153.MAC - ANSYS154.MAC - ANSYS155.MAC - ANSYS156.MAC - ANSYS157.MAC - ANSYS158.MAC - ANSYS159.MAC - ANSYS160.MAC - ANSYS161.MAC - ANSYS162.MAC - ANSYS163.MAC - ANSYS164.MAC - ANSYS165.MAC - ANSYS166.MAC - ANSYS167.MAC - ANSYS168.MAC - ANSYS169.MAC - ANSYS170.MAC - ANSYS171.MAC - ANSYS172.MAC - ANSYS173.MAC - ANSYS174.MAC - ANSYS175.MAC - ANSYS176.MAC - ANSYS177.MAC - ANSYS178.MAC - ANSYS179.MAC - ANSYS180.MAC - ANSYS181.MAC - ANSYS182.MAC - ANSYS183.MAC - ANSYS184.MAC - ANSYS185.MAC - ANSYS186.MAC - ANSYS187.MAC - ANSYS188.MAC - ANSYS189.MAC - ANSYS190.MAC - ANSYS191.MAC - ANSYS192.MAC - ANSYS193.MAC - ANSYS194.MAC - ANSYS195.MAC - ANSYS196.MAC - ANSYS197.MAC - ANSYS198.MAC - ANSYS199.MAC - ANSYS200.MAC - ANSYS201.MAC - ANSYS202.MAC - ANSYS203.MAC - ANSYS204.MAC - ANSYS205.MAC - ANSYS206.MAC - ANSYS207.MAC - ANSYS208.MAC - ANSYS209.MAC - ANSYS210.MAC - ANSYS211.MAC - ANSYS212.MAC - ANSYS213.MAC - ANSYS214.MAC - ANSYS215.MAC - ANSYS216.MAC - ANSYS217.MAC - ANSYS218.MAC - ANSYS219.MAC - ANSYS220.MAC - ANSYS221.MAC - ANSYS222.MAC - ANSYS223.MAC - ANSYS224.MAC - ANSYS225.MAC - ANSYS226.MAC - ANSYS227.MAC - ANSYS228.MAC - ANSYS229.MAC - ANSYS230.MAC - ANSYS231.MAC - ANSYS232.MAC - ANSYS233.MAC - ANSYS234.MAC - ANSYS235.MAC - ANSYS236.MAC - ANSYS237.MAC - ANSYS238.MAC - ANSYS239.MAC - ANSYS240.MAC - ANSYS241.MAC - ANSYS242.MAC - ANSYS243.MAC - ANSYS244.MAC - ANSYS245.MAC - ANSYS246.MAC - ANSYS247.MAC - ANSYS248.MAC - ANSYS249.MAC - ANSYS250.MAC - ANSYS251.MAC - ANSYS252.MAC - ANSYS253.MAC - ANSYS254.MAC - ANSYS255.MAC - ANSYS256.MAC - ANSYS257.MAC - ANSYS258.MAC - ANSYS259.MAC - ANSYS260.MAC - ANSYS261.MAC - ANSYS262.MAC - ANSYS263.MAC - ANSYS264.MAC - ANSYS265.MAC - ANSYS266.MAC - ANSYS267.MAC - ANSYS268.MAC - ANSYS269.MAC - ANSYS270.MAC - ANSYS271.MAC - ANSYS272.MAC - ANSYS273.MAC - ANSYS274.MAC - ANSYS275.MAC - ANSYS276.MAC - ANSYS277.MAC - ANSYS278.MAC - ANSYS279.MAC - ANSYS280.MAC - ANSYS281.MAC - ANSYS282.MAC - ANSYS283.MAC - ANSYS284.MAC - ANSYS285.MAC - ANSYS286.MAC - ANSYS287.MAC - ANSYS288.MAC - ANSYS289.MAC - ANSYS290.MAC - ANSYS291.MAC - ANSYS292.MAC - ANSYS293.MAC - ANSYS294.MAC - ANSYS295.MAC - ANSYS296.MAC - ANSYS297.MAC - ANSYS298.MAC - ANSYS299.MAC - ANSYS300.MAC - ANSYS301.MAC - ANSYS302.MAC - ANSYS303.MAC - ANSYS304.MAC - ANSYS305.MAC - ANSYS306.MAC - ANSYS307.MAC - ANSYS308.MAC - ANSYS309.MAC - ANSYS310.MAC - ANSYS311.MAC - ANSYS312.MAC - ANSYS313.MAC - ANSYS314.MAC - ANSYS315.MAC - ANSYS316.MAC - ANSYS317.MAC - ANSYS318.MAC - ANSYS319.MAC - ANSYS320.MAC - ANSYS321.MAC - ANSYS322.MAC - ANSYS323.MAC - ANSYS324.MAC - ANSYS325.MAC - ANSYS326.MAC - ANSYS327.MAC - ANSYS328.MAC - ANSYS329.MAC - ANSYS330.MAC - ANSYS331.MAC - ANSYS332.MAC - ANSYS333.MAC - ANSYS334.MAC - ANSYS335.MAC - ANSYS336.MAC - ANSYS337.MAC - ANSYS338.MAC - ANSYS339.MAC - ANSYS340.MAC - ANSYS341.MAC - ANSYS342.MAC - ANSYS343.MAC - ANSYS344.MAC - ANSYS345.MAC - ANSYS346.MAC - ANSYS347.MAC - ANSYS348.MAC - ANSYS349.MAC - ANSYS350.MAC - ANSYS351.MAC - ANSYS352.MAC - ANSYS353.MAC - ANSYS354.MAC - ANSYS355.MAC - ANSYS356.MAC - ANSYS357.MAC - ANSYS358.MAC - ANSYS359.MAC - ANSYS360.MAC - ANSYS361.MAC - ANSYS362.MAC - ANSYS363.MAC - ANSYS364.MAC - ANSYS365.MAC - ANSYS366.MAC - ANSYS367.MAC - ANSYS368.MAC - ANSYS369.MAC - ANSYS370.MAC - ANSYS371.MAC - ANSYS372.MAC - ANSYS373.MAC - ANSYS374.MAC - ANSYS375.MAC - ANSYS376.MAC - ANSYS377.MAC - ANSYS378.MAC - ANSYS379.MAC - ANSYS380.MAC - ANSYS381.MAC - ANSYS382.MAC - ANSYS383.MAC - ANSYS384.MAC - ANSYS385.MAC - ANSYS386.MAC - ANSYS387.MAC - ANSYS388.MAC - ANSYS389.MAC - ANSYS390.MAC - ANSYS391.MAC - ANSYS392.MAC - ANSYS393.MAC - ANSYS394.MAC - ANSYS395.MAC - ANSYS396.MAC - ANSYS397.MAC - ANSYS398.MAC - ANSYS399.MAC - ANSYS400.MAC - ANSYS401.MAC - ANSYS402.MAC - ANSYS403.MAC - ANSYS404.MAC - ANSYS405.MAC - ANSYS406.MAC - ANSYS407.MAC - ANSYS408.MAC - ANSYS409.MAC - ANSYS410.MAC - ANSYS411.MAC - ANSYS412.MAC - ANSYS413.MAC - ANSYS414.MAC - ANSYS415.MAC - ANSYS416.MAC - ANSYS417.MAC - ANSYS418.MAC - ANSYS419.MAC - ANSYS420.MAC - ANSYS421.MAC - ANSYS422.MAC - ANSYS423.MAC - ANSYS424.MAC - ANSYS425.MAC - ANSYS426.MAC - ANSYS427.MAC - ANSYS428.MAC - ANSYS429.MAC - ANSYS430.MAC - ANSYS431.MAC - ANSYS432.MAC - ANSYS433.MAC - ANSYS434.MAC - ANSYS435.MAC - ANSYS436.MAC - ANSYS437.MAC - ANSYS438.MAC - ANSYS439.MAC - ANSYS440.MAC - ANSYS441.MAC - ANSYS442.MAC - ANSYS443.MAC - ANSYS444.MAC - ANSYS445.MAC - ANSYS446.MAC - ANSYS447.MAC - ANSYS448.MAC - ANSYS449.MAC - ANSYS450.MAC - ANSYS451.MAC - ANSYS452.MAC - ANSYS453.MAC - ANSYS454.MAC - ANSYS455.MAC - ANSYS456.MAC - ANSYS457.MAC - ANSYS458.MAC - ANSYS459.MAC - ANSYS460.MAC - ANSYS461.MAC - ANSYS462.MAC - ANSYS463.MAC - ANSYS464.MAC - ANSYS465.MAC - ANSYS466.MAC - ANSYS467.MAC - ANSYS468.MAC - ANSYS469.MAC - ANSYS470.MAC - ANSYS471.MAC - ANSYS472.MAC - ANSYS473.MAC - ANSYS474.MAC - ANSYS475.MAC - ANSYS476.MAC - ANSYS477.MAC - ANSYS478.MAC - ANSYS479.MAC - ANSYS480.MAC - ANSYS481.MAC - ANSYS482.MAC - ANSYS483.MAC - ANSYS484.MAC - ANSYS485.MAC - ANSYS486.MAC - ANSYS487.MAC - ANSYS488.MAC - ANSYS489.MAC - ANSYS490.MAC - ANSYS491.MAC - ANSYS492.MAC - ANSYS493.MAC - ANSYS494.MAC - ANSYS495.MAC - ANSYS496.MAC - ANSYS497.MAC - ANSYS498.MAC - ANSYS499.MAC diff --git a/src/ldem/LET.CON b/src/ldem/LET.CON deleted file mode 100644 index de3dba8..0000000 --- a/src/ldem/LET.CON +++ /dev/null @@ -1,65 +0,0 @@ - - ********************* DEM ********************* - - Discrete Element Method - - All Rights Reserved - PPGEC / UFRGS - - DATA CONTROL OUTPUT - ******************* - - Simulation =======================> 0 - - Test simulated...................... 102 - Truss modules in X-direction........ 100 - Truss modules in Y-direction........ 40 - Truss modules in Z-direction........ 20 - - Principal nodes number.............. 166961 - Symmetry nodes number............... 166961 - Total nodes number.................. 166961 - Principal bars number............... 1126960 - Symmetry bars number................ 1126960 - Total bars number................... 1126960 - - Control node number................. 1 - Control node number................. 2 - Control node number................. 3 - Control node number................. 4 - Control node number................. 5 - - - Initial damping factor.............. 2.500000E+04 - Final damping factor................ 2.500000E+04 - Time of damping change.............. 1.500000E-02 - Stiffness proportional damping...... 0.000000E+00 - - Truss module length................. 3.000000E-03 - Time increment...................... 2.000000E-07 - Total time of integration........... 3.000000E-02 - - Poissons ratio...................... 2.500000E-01 - Mass density........................ 2.000000E+03 - Total mass.......................... 4.320000E+00 - Youngs modulus...................... 3.200000E+10 - Element normal stiffness............ 1.152000E+05 - Element diagonal stiffness.......... 1.995323E+05 - Specific fracture energy............ 5.000000E+01 - equivalent d ........ 2.800000E-02 - Proportionality mean strain......... 2.312311E-04 - Critical value for Lc............... 1.939000E-02 - Kr value for normal bars............ 6.463333E+00 - Delta coefficient................... 1.125000E+00 - Alfa coefficient.................... 4.000000E-01 - - Maximum value for ep................ 0.000000E+00 - Minimum value for ep................ 9.900000E+99 - - - GENERAL REMARKS - *************** - - Mean ep............................. 2.263162E-04 - Coefficient of variation for ep..... 0.000000E+00 - - diff --git a/src/ldem/LET.DIS b/src/ldem/LET.DIS deleted file mode 100644 index e69de29..0000000 diff --git a/src/ldem/LET.ENE b/src/ldem/LET.ENE deleted file mode 100644 index 37cd833..0000000 --- a/src/ldem/LET.ENE +++ /dev/null @@ -1 +0,0 @@ - 2.000000000000e-07 0.000000000000e+00 0.000000000000e+00 0.000000000000e+00 \ No newline at end of file diff --git a/src/ldem/LET.POS b/src/ldem/LET.POS deleted file mode 100644 index 7507abe..0000000 --- a/src/ldem/LET.POS +++ /dev/null @@ -1 +0,0 @@ - 2.000000000000e-07 0.000000000000e+00 0.000000000000e+00 diff --git a/src/ldem/Lei_Barra.TXT b/src/ldem/Lei_Barra.TXT deleted file mode 100644 index c78a85d..0000000 --- a/src/ldem/Lei_Barra.TXT +++ /dev/null @@ -1,2 +0,0 @@ - 2.000000000000E-07 0.000000000000E+00 0.000000000000E+00 1.438338298716E-03 0.000000000000E+00 2.225381586462E-04 - 4.000000000000E-07 0.000000000000E+00 0.000000000000E+00 1.438338298716E-03 0.000000000000E+00 2.225381586462E-04 diff --git a/src/ldem/NAYFES0.m b/src/ldem/NAYFES0.m deleted file mode 100644 index 33a0023..0000000 --- a/src/ldem/NAYFES0.m +++ /dev/null @@ -1,46 +0,0 @@ - -function ini=NAYFES0() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - - -%---------------------------------------------------------------------- -% Local constants and derived parameters -%---------------------------------------------------------------------- -DELTA = 9.0 * PSN / (4.0 - 8.0 * PSN); -ALFA = (9.0 + 8.0 * DELTA) / (18.0 + 24.0 * DELTA); -%---------------------------------------------------------------------- -% Initialize output arrays -%---------------------------------------------------------------------- -YNGB = ones(1, NBT); -YNGB=YNGB.*YNG; -E1 = ones(1, NBT); -E2 = ones(1, NBT); -GFRB = ones(1, NBT); -GFRB=GFRB.*GFR; -DEQB = ones(1, NBT); -DEQB=DEQB.*DEQ; -ENR =(YNGB.*(LI.^2)).*ALFA; -aux=(2.0*DELTA*(4.0/3.0))/sqrt(3.0); -EDG = ENR*aux; -LCRB = ones(1, NBT); -LCR = DEQ * 2.0 * CAF / ALFA; -LCRB= LCRB.*LCR; -EPRB =sqrt(GFRB./(YNGB.*DEQB)); -LMIN= min(LI) -dt_cmin = LMIN/(sqrt(min(YNGB)/ROH)); - -if dt_cmin < DT - fprintf('dt_cmin = %g, dt = %g\n', dt_cmin, DT); - error('NAYFES0: dt_cmin < DT . Execution stopped.'); -end - ini=1; - end diff --git a/src/ldem/NODMASS.m b/src/ldem/NODMASS.m deleted file mode 100644 index 9dc9b32..0000000 --- a/src/ldem/NODMASS.m +++ /dev/null @@ -1,68 +0,0 @@ - -function ini=NODMASS() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - -%! Esta subrotina determina as condições de contorno da estrutura. -% -% ! Esta subrotina calcula a massa nodal, baseada no volume de influência -% ! de cada nó. -MSS=ones(NNT,1); -MSS=MSS.*(LCO*LCO*LCO*ROH/2.0D00); -%! -% DO I=1,NNT -% MSS(I)=LCO*LCO*LCO*ROH/2.0D00 -% END DO -% ! - -% !-------------------------------------------------------------------------- -% DO 10 K=1,L -% DO 10 J=1,N -% DO 10 I=1,M -% RED=1.0D00 -% IF ((K.EQ.1).OR.(K.EQ.L)) RED=RED/2.0D00 -% IF ((J.EQ.1).OR.(J.EQ.N)) RED=RED/2.0D00 -% IF ((I.EQ.1).OR.(I.EQ.M)) RED=RED/2.0D00 -% NO=(K-1)*M*N+(J-1)*M+I -% MAS(NO)=RED*MSS(NO) -% 10 CONTINUE -% ! -% DO 20 K=1,L1 -% DO 20 J=1,N1 -% DO 20 I=1,M1 -% NO=MNL+(K-1)*M1*N1+(J-1)*M1+I -% MAS(NO)=MSS(NO) -% 20 CONTINUE -% ! - -% Create 3D grids of indices -[I, J, K] = ndgrid(1:M, 1:N, 1:L); % I varies fastest (first dimension) - -% Count how many boundaries the point lies on -boundaryCount = (K == 1 | K == L) + (J == 1 | J == N) + (I == 1 | I == M); -RED = 2 .^ (-boundaryCount); % RED = 1/2^count - -% Linear index in column-major order (same formula) -NO = (K-1)*M*N + (J-1)*M + I; - -% Assign scaled values -MAS(NO) = RED .* MSS(NO); - -% Generate indices for the second region -[I, J, K] = ndgrid(1:M1, 1:N1, 1:L1); -NO = MNL + (K-1)*M1*N1 + (J-1)*M1 + I; -MAS(NO) = MSS(NO); -% RETURN -% END -%! - - ini=1; - end diff --git a/src/ldem/RMEC.m b/src/ldem/RMEC.m deleted file mode 100644 index 2c86a17..0000000 --- a/src/ldem/RMEC.m +++ /dev/null @@ -1,93 +0,0 @@ -function ini=RMEC() -% RMEC Calcula as propriedades mecânicas das barras (exteriores, interiores e diagonais). -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - - NBA=0 - NBS=0 - NBT=0 -%! -M2 = M - 2; -N2 = N - 2; -L2 = L - 2; -MN = M * N; -MN1 = M1 * N1; -%-------------------------------------------------------------------------- -% Calls to exterior / interior / diagonal routines -%-------------------------------------------------------------------------- -RMECEX(M1, N, L, 0, 1, 1, 1); -RMECEX(M, N1, L, 1, 0, 1, M); -RMECEX(M, N, L1, 1, 1, 0, MN); -% -RMECIN(M2, N1, L1, 1); -RMECIN(M1, N2, L1, M1); -RMECIN(M1, N1, L2, MN1); -% -RMECDI(); -% -NBS = NBA; -NI = NNO; -NBT = NBS; -% -% ! -% SUBROUTINE RMEC -% ! =============== -% ! -% ! -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER M2,N2,L2,MN,MN1 -% !-------------------------------------------------------------------------- -% NBA=0 -% NBS=0 -% NBT=0 -% ! -% M2=M-2 -% N2=N-2 -% L2=L-2 -% MN=M*N -% MN1=M1*N1 -% ! -% -% CALL RMECEX (M1,N,L,0,1,1,1) -% CALL RMECEX (M,N1,L,1,0,1,M) -% CALL RMECEX (M,N,L1,1,1,0,MN) -% ! -% -% CALL RMECIN (M2,N1,L1,1) -% CALL RMECIN (M1,N2,L1,M1) -% CALL RMECIN (M1,N1,L2,MN1) -% -% CALL RMECDI -% ! -% NBS=NBA -% NI=NNO -% NBT=NBS -% ! -% RETURN -% END - -% MODIFICAÇÃO RODRIGO -% ======================================================== - % VETORIZAÇÃO GLOBAL: Substitui milhões de chamadas ao DEFEP - % Aplica as propriedades comuns a todas as barras instantaneamente - % ======================================================== - EP(1:NBT) = EPRB(1:NBT); - KR(1:NBT) = LCRB(1:NBT) ./ LI(1:NBT); - E2(1:NBT) = E1(1:NBT); - - ini = 1; -end \ No newline at end of file diff --git a/src/ldem/RMEC2.m b/src/ldem/RMEC2.m deleted file mode 100644 index 56f5976..0000000 --- a/src/ldem/RMEC2.m +++ /dev/null @@ -1,114 +0,0 @@ -function ini=RMEC2() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - - NBA=0 - NBS=0 - NBT=0 -%! -M2 = M - 2; -N2 = N - 2; -L2 = L - 2; -MN = M * N; -MN1 = M1 * N1; -%-------------------------------------------------------------------------- -% Calls to exterior / interior / diagonal routines -%-------------------------------------------------------------------------- - -for K = 1:LX - for J = 1:NX - for I = 1:MX - TYPES = 0; - if (I == 1) || (I == M) - TYPES = TYPES + C1; - end - if (J == 1) || (J == N) - TYPES = TYPES + C2; - end - if (K == 1) || (K == L) - TYPES = TYPES + C3; - end - - NO = (K - 1) * M * N + (J - 1) * M + I; - B = NBA + (K - 1) * MX * NX + (J - 1) * MX + I; - NOI = NO; - NOF = NO + ST; - - DEFEP(B, TYPES); - - end - end -end - -%-------------------------------------------------------------------------- -% Update global counter -%-------------------------------------------------------------------------- -NBA = NBA + MX * NX * LX; -RMECEX(M1, N, L, 0, 1, 1, 1); -RMECEX(M, N1, L, 1, 0, 1, M); -RMECEX(M, N, L1, 1, 1, 0, MN); -% -RMECIN(M2, N1, L1, 1); -RMECIN(M1, N2, L1, M1); -RMECIN(M1, N1, L2, MN1); -% -RMECDI(); -% -NBS = NBA; -NI = NNO; -NBT = NBS; -% -% ! -% SUBROUTINE RMEC -% ! =============== -% ! -% ! -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER M2,N2,L2,MN,MN1 -% !-------------------------------------------------------------------------- -% NBA=0 -% NBS=0 -% NBT=0 -% ! -% M2=M-2 -% N2=N-2 -% L2=L-2 -% MN=M*N -% MN1=M1*N1 -% ! -% -% CALL RMECEX (M1,N,L,0,1,1,1) -% CALL RMECEX (M,N1,L,1,0,1,M) -% CALL RMECEX (M,N,L1,1,1,0,MN) -% ! -% -% CALL RMECIN (M2,N1,L1,1) -% CALL RMECIN (M1,N2,L1,M1) -% CALL RMECIN (M1,N1,L2,MN1) -% -% CALL RMECDI -% ! -% NBS=NBA -% NI=NNO -% NBT=NBS -% ! -% RETURN -% END - - - ini=1; - end diff --git a/src/ldem/RMECDI.m b/src/ldem/RMECDI.m deleted file mode 100644 index ec581eb..0000000 --- a/src/ldem/RMECDI.m +++ /dev/null @@ -1,88 +0,0 @@ - -function ini=RMECDI() -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% SUBROUTINE RMECDI -% ! ================= -% ! -% ! Esta subrotina é chamada pela subrotina rmec para definir as -% ! propriedades mecânicas das barras diagonais dos módulos cúbicos. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER G,I,J,K,NOI,NOF,B,ST(8),REF,NOFF -% !-------------------------------------------------------------------------- -% REF=NBA -% ST(1)=0 -% ST(2)=1 -% ST(3)=M -% ST(4)=M+1 -% ST(5)=N*M -% ST(6)=N*M+1 -% ST(7)=N*M+M -% ST(8)=N*M+M+1 -% ! -% DO 20 K=1,L1 -% DO 20 J=1,N1 -% DO 20 I=1,M1 -% NOI=(K-1)*M1*N1+(J-1)*M1+I -% NOF=(K-1)*M*N+(J-1)*M+I -% B=REF+(NOI-1)*8 -% NOI=NOI+MNL -% DO 10 G=1,8 -% B=B+1 -% NOFF=NOF+ST(G) -% ! -% CALL DEFEP(B,3) -% ! -% 10 CONTINUE -% ! -% NBA=NBA+8 -% ! -% 20 CONTINUE -% ! -% RETURN -% END -% ! -% Local variables -%-------------------------------------------------------------------------- -%ST = zeros(1, 8); % 1-based indexing matches Fortran's ST(1..8) -%-------------------------------------------------------------------------- -% Reference offset and ST table -%-------------------------------------------------------------------------- - -% MODIFICAÇÕES RODRIGO -REF = NBA; -ST = [0, 1, M, M+1, N*M, N*M+1, N*M+M, N*M+M+1]; - -%-------------------------------------------------------------------------- -% Outer nest: K (outer), J (middle), I (inner) -- all share label 20 -%-------------------------------------------------------------------------- -for K = 1:L1 - for J = 1:N1 - for I = 1:M1 - NOI = (K - 1) * M1 * N1 + (J - 1) * M1 + I; - B = REF + (NOI - 1) * 8; - - for G = 1:8 - B = B + 1; - E1(B) = EDG(B); % Lógica embutida do DEFEP - end - NBA = NBA + 8; - end - end - end - ini = 1; -end diff --git a/src/ldem/RMECEX.m b/src/ldem/RMECEX.m deleted file mode 100644 index b3718e4..0000000 --- a/src/ldem/RMECEX.m +++ /dev/null @@ -1,84 +0,0 @@ - -function ini=RMECEX (MX,NX,LX,C1,C2,C3,ST) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% SUBROUTINE RMECEX (MX,NX,LX,C1,C2,C3,ST) -% ! ================= -% ! -% ! Esta subrotina é chamada pela subrotina rmec para definir as -% ! propriedades mecânicas das barras externas dos módulos cúbicos. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER I,J,K,NO,B,MX,NX,LX -% INTEGER NOI,NOF,ST -% INTEGER TYPES,C1,C2,C3 -% !-------------------------------------------------------------------------- -% DO 10 K=1,LX -% DO 10 J=1,NX -% DO 10 I=1,MX -% ! -% TYPES=0 -% IF ((I.EQ.1).OR.(I.EQ.M)) TYPES=TYPES+C1 -% IF ((J.EQ.1).OR.(J.EQ.N)) TYPES=TYPES+C2 -% IF ((K.EQ.1).OR.(K.EQ.L)) TYPES=TYPES+C3 -% ! -% NO=(K-1)*M*N+(J-1)*M+I -% B=NBA+(K-1)*MX*NX+(J-1)*MX+I -% NOI=NO -% NOF=NO+ST -% ! -% -% CALL DEFEP(B,TYPES) -% -% ! -% 10 CONTINUE -% ! -% NBA=NBA+MX*NX*LX -% ! -% RETURN -% END -% ! - -% MODIFICAÇÃO RODRIGO -for K = 1:LX - for J = 1:NX - for I = 1:MX - TYPES = 0; - if (I == 1) || (I == M), TYPES = TYPES + C1; end - if (J == 1) || (J == N), TYPES = TYPES + C2; end - if (K == 1) || (K == L), TYPES = TYPES + C3; end - - B = NBA + (K - 1) * MX * NX + (J - 1) * MX + I; - - % Lógica embutida do DEFEP - if TYPES == 0 - RED = 1.00; - elseif TYPES == 1 - RED = 0.50; - else - RED = 0.25; - end - - E1(B) = ENR(B) * RED; - end - end -end -%-------------------------------------------------------------------------- -% Update global counter -%-------------------------------------------------------------------------- - NBA = NBA + MX * NX * LX; - ini = 1; -end \ No newline at end of file diff --git a/src/ldem/RMECIN.m b/src/ldem/RMECIN.m deleted file mode 100644 index 7ddf2b8..0000000 --- a/src/ldem/RMECIN.m +++ /dev/null @@ -1,59 +0,0 @@ - -function ini=RMECIN (MX,NX,LX,ST) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% -% SUBROUTINE RMECIN (MX,NX,LX,ST) -% ! ================= -% ! -% ! Esta subrotina é chamada pela subrotina rmec para definir as -% ! propriedades mecânicas das barras internas dos módulos cúbicos. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% INTEGER I,J,K,NO,B,MX,NX,LX -% INTEGER NOI,NOF,ST -% !-------------------------------------------------------------------------- -% DO 10 K=1,LX -% DO 10 J=1,NX -% DO 10 I=1,MX -% ! -% NO=MNL+(K-1)*M1*N1+(J-1)*M1+I -% NOI=NO -% NOF=NO+ST -% B=NBA+(K-1)*MX*NX+(J-1)*MX+I -% ! -% CALL DEFEP(B,0) -% -% ! -% 10 CONTINUE -% ! -% NBA=NBA+MX*NX*LX -% ! -% RETURN -% END - -% MODIFICAÇÕES RODRIGO -for K = 1:LX - for J = 1:NX - for I = 1:MX - B = NBA + (K - 1) * MX * NX + (J - 1) * MX + I; - E1(B) = ENR(B); % Lógica embutida do DEFEP - end - end - end - NBA = NBA + MX * NX * LX; - ini = 1; -end \ No newline at end of file diff --git a/src/ldem/SIM01.DAT b/src/ldem/SIM01.DAT deleted file mode 100644 index 9dcf4ae..0000000 --- a/src/ldem/SIM01.DAT +++ /dev/null @@ -1 +0,0 @@ - 2.000000000000e-07 -3.999995648852e+01 0.000000000000e+00 0.000000000000e+00 diff --git a/src/ldem/Teste_combinado - Copia.m b/src/ldem/Teste_combinado - Copia.m deleted file mode 100644 index c32b46f..0000000 --- a/src/ldem/Teste_combinado - Copia.m +++ /dev/null @@ -1,239 +0,0 @@ -clear all -clc - -% Configurações - n_total = 5000; % Número total de elementos - velocidade1 = 5; % Velocidade de transição entrada potencial(1-10) - velocidade2 = 5; % Velocidade de transição saida potencial (1-10) - expoente = 1; % Expoente da lei de potência - - dados =gerar_transicao_dupla2(n_total, velocidade1, velocidade2, expoente); - %dados = gerar_transicao_uniforme_potencial(n_total, velocidade, expoente); - %unif = rand(n_total /2,1); - %dados=[dados';unif]'; n_total=size(dados,2); - % Criar janela com subplots para visualização - figure('Position', [100, 100, 1200, 800]); - - % Subplot 1: Histograma completo - %subplot(2, 3, [1, 4]); - subplot(2,1,1); - histogram(dados, 100, 'Normalization', 'pdf', 'FaceColor', [0.3, 0.6, 0.9]); - xlabel('Value'); - ylabel('Density'); - title(sprintf('Uniform + Power law distribution + Uniform (N =%d)', n_total)); - grid on; - - % Subplot 4: Evolução temporal dos valores - %subplot(2, 3, [5, 6]); - subplot(2,1,2); - plot(1:n_total, dados', '.', 'MarkerSize', 2); - xlabel('N'); - ylabel('Value'); - title('Evolução Temporal dos Valores'); - grid on; - - % Adicionar linha de tendência móvel - window_size = 500; - media_movel = movmean(dados', window_size); - hold on; - plot(1:n_total, media_movel, 'r-', 'LineWidth', 2); - legend('Data', sprintf('Moving average (W=%d)', window_size), 'Location', 'best'); - hold off; - - % Estatísticas descritivas - fprintf('\n--- Estatísticas ---\n'); - fprintf('Média: %.4f\n', mean(dados)); - fprintf('Mediana: %.4f\n', median(dados)); - fprintf('Desvio padrão: %.4f\n', std(dados)); - fprintf('Mínimo: %.4f\n', min(dados)); - fprintf('Máximo: %.4f\n', max(dados)); - - % Análise da transição - % fprintf('\n--- Análise da Transição ---\n'); - - % % Dividir em 5 segmentos - % segmentos = 5; - % for k = 1:segmentos - % idx_inicio = round((k-1)*n_total/segmentos) + 1; - % idx_fim = round(k*n_total/segmentos); - % segmento = dados(idx_inicio:idx_fim); - % - % % Calcular média e mediana - % fprintf('Segmento %d (%.0f%%-%.0f%%): Média=%.4f, Mediana=%.4f, Coef.Variação=%.4f\n', ... - % k, (k-1)*100/segmentos, k*100/segmentos, ... - % mean(segmento), median(segmento), std(segmento)/mean(segmento)); - % end -%end -%%%%%%%%%%%%%%%% NATURAL TIME -Q=dados'; -% 1. Configuração Inicial e Medida de Energia -% O artigo sugere que a medida adequada é Qk = A^1.5, onde A é a amplitude [4, 5]. -%Q = Amp.^1.5; -Lin = length(Q); - -% Definição de PI_c (ruído uniforme) - calculada uma única vez -fi = 0:0.025:0.5; -ww = 2 * pi * fi; -pi_c = 18./(5*ww.^2) - 6*cos(ww)./(5*ww.^2) - 12*sin(ww)./(5*ww.^3); -pi_c(1) = 1; % Limite quando w -> 0 - -% Pré-alocação de variáveis para velocidade -kapa1 = zeros(Lin, 1); -Snt = zeros(Lin, 1); -Srev = zeros(Lin, 1); -D = zeros(Lin, 1); - -% Loop principal (Evolução dos eventos) -% Nota: Calculamos os parâmetros para cada janela de tamanho k -for k = 1:Lin - % 1. Recorte e Normalização da janela atual - Q_k = Q(1:k); - An = sum(Q_k); - pk = Q_k / An; % Energias normalizadas P_k [4] - - % 2. Vetor de Tempo Natural chi_k [4] - xk = (1:k)' / k; - - % 3. Cálculo Vetorizado de Kappa1 (Variância) - k1 = sum(pk .* (xk.^2)); - k2 = sum(pk .* xk); - kapa1(k) = k1 - k2^2; - - % 4. Cálculo Vetorizado das Entropias (S e S_inv) [1, 3] - % Usando logaritmo natural 'log' conforme recomendado [2] - Snt(k) = sum(pk .* xk .* log(xk)) - k2 * log(k2); - - % Para S_inv, invertemos a ordem das energias P_k -> P_{N-k+1} - pk_rev = flipud(pk); - k2_rev = sum(pk_rev .* xk); - Srev(k) = sum(pk_rev .* xk .* log(xk)) - k2_rev * log(k2_rev); - - % 5. Cálculo Vetorizado de PI(phi) e Distância D - % Criamos uma matriz para evitar o loop 'b' - % xk: (k x 1), ww: (1 x n_fi) -> exp_arg: (k x n_fi) - exp_arg = complex(0, 1) * (xk * ww); - Pi_phi = abs(pk' * exp(exp_arg)).^2; % Produto matricial calcula todos os fi de uma vez - - D(k) = mean(abs(Pi_phi - pi_c)); - - % Convertional time - %ct(k)=tpico(k); - % Natural time - nt(k)=k; - - % Feedback de progresso (opcional) - % if mod(k, 1000) == 0, disp(['Progresso: ', num26(k/Lin*100), '%']); end -end -% -figure() -% nt=ct; -plot(nt,kapa1,'r') -hold on -plot(nt,Snt,'b') -plot(nt,Srev,'m') -plot(nt,D,'g') -grid on - -plot([0 k],[0.07 0.07],'r--') -plot([0 k],[0.096 0.096],'b--') -plot([0 k],[0.02 0.02],'g--') -% ylim([0 0.3]) -legend('\kappa_1','S','S_r_e_v','D','0.07','0.096','0.02') -xlabel('N','FontName','Times New Roman','FontSize',18,'Rotation',0) -ylabel('\kappa_1, S, S_r_e_v, D','FontName','Times New Roman','FontSize',18,'Rotation',90) - -%% ENTROPIAS SHENNON AND HKL - -%Q=dados'; -Lin = length(Q); - -% 2. Pré-alocação de variáveis para desempenho -Hs = zeros(Lin, 1); -Hkl = zeros(Lin, 1); - -% 3. Cálculo Evolutivo (Abordagem de Janela Crescente) -% Conforme o artigo, a janela de detecção inicia no primeiro evento e -% cresce a cada novo hit para capturar o comportamento histórico [3, 6]. -for K = 2:Lin - % Energias da janela atual (do evento 1 até K) - current_Q = Q(1:K); - An = sum(current_Q); % Soma total da área/energia da janela [6, 7] - - % Vetor de probabilidade pK (distribuição de massa de ocorrência) [2] - % pK(k) é o k-ésimo elemento do vetor de probabilidade [2] - pk = current_Q / An; - - % --- Entropia de Shannon (Hs) --- - % Calculada para o hit K usando o logaritmo natural (ln) conforme orientação [2, 5] - % Hs(K) = -sum( pK * ln(pK) ) [2, 6] - Hs(K) = -sum(pk .* log(pk + eps)); - - % --- Entropia de Kullback-Leibler (Hkl) --- - % Expressa a probabilidade do evento atual condicionada pelo anterior [8] - % HKL(K) = -sum_{k=2}^{K} pK(k) * ln( pK(k) / pK(k-1) ) [6] - pk_atual = pk(2:end); - pk_anterior = pk(1:end-1); - Hkl(K) = -sum(pk_atual .* log((pk_atual + eps) ./ (pk_anterior + eps))); -end - -% 4. Valores Cumulativos (Sigma Hs e Sigma Hkl) -% O artigo também avalia a sensibilidade dos valores acumulados ao dano [1, 8]. -sum_Hs = cumsum(Hs); -sum_Hkl = cumsum(Hkl); - -% 5. Visualização dos Resultados -figure; -%subplot(2,1,1); -plot(Hs); -ylabel('\itH_s','FontName','Times New Roman','FontSize',18,'Rotation',90) -%set(gca, 'XTickLabel', []); % Remove os rótulos do eixo x grid on; -grid on -yyaxis right -ax = gca; -ax.YColor = 'k'; % define a cor do eixo Y direito como preto -hold on -%subplot(2,1,2); -plot(Hkl); grid on; -ylabel('\itH_{KL}','FontName','Times New Roman','FontSize',18,'Rotation',90) -legend('\itH_s','itH_{KL}') - -%% TSALLIS ENTROPY -win=50; %initial data size -k=1; -Amp=dados'; -tpico=1:1:size(dados,2) ; tpico=tpico'; -for jj=win+1:1:size(dados,2) -%Interval=[tpico(jj-win) tpico(jj)]; % SLIDING WINDOWN -Interval=[1 jj]; % -Mi=0.05; % division on the Amplitude distribution -[Datavalue, A_fit, lmbda_fit, q_fit, resultados_fit,p2]=EA_Calc_q(Amp,tpico,Interval,Mi,'NHist'); -A(k)=A_fit; -lmbda(k)=lmbda_fit; -q(k)=q_fit; -R(k)=resultados_fit.R_squared; -TPico(k)=jj; -p22(k)=p2; -k=k+1; -end -%% -figure; -plot(TPico,q,'r') -ylabel('q','FontName','Times New Roman','FontSize',20,'Rotation',90) -yyaxis right -hold on -plot(TPico,1./lmbda,'b') -legend('q','lambda') -xlabel('N','FontName','Times New Roman','FontSize',20,'Rotation',0) -ylabel('lambda','FontName','Times New Roman','FontSize',20,'Rotation',90) - -% -figure; -scatter(1./lmbda, q, 8, TPico, 'o'); % 50 = tamanho dos marcadores -colorbar; -xlabel('1/\it\lambda', 'FontSize', 12); -ylabel('\itq', 'FontSize', 12); -grid on -box on -ylabel(colorbar, 'Time [s]'); - - diff --git a/src/ldem/Teste_combinado.m b/src/ldem/Teste_combinado.m deleted file mode 100644 index c32b46f..0000000 --- a/src/ldem/Teste_combinado.m +++ /dev/null @@ -1,239 +0,0 @@ -clear all -clc - -% Configurações - n_total = 5000; % Número total de elementos - velocidade1 = 5; % Velocidade de transição entrada potencial(1-10) - velocidade2 = 5; % Velocidade de transição saida potencial (1-10) - expoente = 1; % Expoente da lei de potência - - dados =gerar_transicao_dupla2(n_total, velocidade1, velocidade2, expoente); - %dados = gerar_transicao_uniforme_potencial(n_total, velocidade, expoente); - %unif = rand(n_total /2,1); - %dados=[dados';unif]'; n_total=size(dados,2); - % Criar janela com subplots para visualização - figure('Position', [100, 100, 1200, 800]); - - % Subplot 1: Histograma completo - %subplot(2, 3, [1, 4]); - subplot(2,1,1); - histogram(dados, 100, 'Normalization', 'pdf', 'FaceColor', [0.3, 0.6, 0.9]); - xlabel('Value'); - ylabel('Density'); - title(sprintf('Uniform + Power law distribution + Uniform (N =%d)', n_total)); - grid on; - - % Subplot 4: Evolução temporal dos valores - %subplot(2, 3, [5, 6]); - subplot(2,1,2); - plot(1:n_total, dados', '.', 'MarkerSize', 2); - xlabel('N'); - ylabel('Value'); - title('Evolução Temporal dos Valores'); - grid on; - - % Adicionar linha de tendência móvel - window_size = 500; - media_movel = movmean(dados', window_size); - hold on; - plot(1:n_total, media_movel, 'r-', 'LineWidth', 2); - legend('Data', sprintf('Moving average (W=%d)', window_size), 'Location', 'best'); - hold off; - - % Estatísticas descritivas - fprintf('\n--- Estatísticas ---\n'); - fprintf('Média: %.4f\n', mean(dados)); - fprintf('Mediana: %.4f\n', median(dados)); - fprintf('Desvio padrão: %.4f\n', std(dados)); - fprintf('Mínimo: %.4f\n', min(dados)); - fprintf('Máximo: %.4f\n', max(dados)); - - % Análise da transição - % fprintf('\n--- Análise da Transição ---\n'); - - % % Dividir em 5 segmentos - % segmentos = 5; - % for k = 1:segmentos - % idx_inicio = round((k-1)*n_total/segmentos) + 1; - % idx_fim = round(k*n_total/segmentos); - % segmento = dados(idx_inicio:idx_fim); - % - % % Calcular média e mediana - % fprintf('Segmento %d (%.0f%%-%.0f%%): Média=%.4f, Mediana=%.4f, Coef.Variação=%.4f\n', ... - % k, (k-1)*100/segmentos, k*100/segmentos, ... - % mean(segmento), median(segmento), std(segmento)/mean(segmento)); - % end -%end -%%%%%%%%%%%%%%%% NATURAL TIME -Q=dados'; -% 1. Configuração Inicial e Medida de Energia -% O artigo sugere que a medida adequada é Qk = A^1.5, onde A é a amplitude [4, 5]. -%Q = Amp.^1.5; -Lin = length(Q); - -% Definição de PI_c (ruído uniforme) - calculada uma única vez -fi = 0:0.025:0.5; -ww = 2 * pi * fi; -pi_c = 18./(5*ww.^2) - 6*cos(ww)./(5*ww.^2) - 12*sin(ww)./(5*ww.^3); -pi_c(1) = 1; % Limite quando w -> 0 - -% Pré-alocação de variáveis para velocidade -kapa1 = zeros(Lin, 1); -Snt = zeros(Lin, 1); -Srev = zeros(Lin, 1); -D = zeros(Lin, 1); - -% Loop principal (Evolução dos eventos) -% Nota: Calculamos os parâmetros para cada janela de tamanho k -for k = 1:Lin - % 1. Recorte e Normalização da janela atual - Q_k = Q(1:k); - An = sum(Q_k); - pk = Q_k / An; % Energias normalizadas P_k [4] - - % 2. Vetor de Tempo Natural chi_k [4] - xk = (1:k)' / k; - - % 3. Cálculo Vetorizado de Kappa1 (Variância) - k1 = sum(pk .* (xk.^2)); - k2 = sum(pk .* xk); - kapa1(k) = k1 - k2^2; - - % 4. Cálculo Vetorizado das Entropias (S e S_inv) [1, 3] - % Usando logaritmo natural 'log' conforme recomendado [2] - Snt(k) = sum(pk .* xk .* log(xk)) - k2 * log(k2); - - % Para S_inv, invertemos a ordem das energias P_k -> P_{N-k+1} - pk_rev = flipud(pk); - k2_rev = sum(pk_rev .* xk); - Srev(k) = sum(pk_rev .* xk .* log(xk)) - k2_rev * log(k2_rev); - - % 5. Cálculo Vetorizado de PI(phi) e Distância D - % Criamos uma matriz para evitar o loop 'b' - % xk: (k x 1), ww: (1 x n_fi) -> exp_arg: (k x n_fi) - exp_arg = complex(0, 1) * (xk * ww); - Pi_phi = abs(pk' * exp(exp_arg)).^2; % Produto matricial calcula todos os fi de uma vez - - D(k) = mean(abs(Pi_phi - pi_c)); - - % Convertional time - %ct(k)=tpico(k); - % Natural time - nt(k)=k; - - % Feedback de progresso (opcional) - % if mod(k, 1000) == 0, disp(['Progresso: ', num26(k/Lin*100), '%']); end -end -% -figure() -% nt=ct; -plot(nt,kapa1,'r') -hold on -plot(nt,Snt,'b') -plot(nt,Srev,'m') -plot(nt,D,'g') -grid on - -plot([0 k],[0.07 0.07],'r--') -plot([0 k],[0.096 0.096],'b--') -plot([0 k],[0.02 0.02],'g--') -% ylim([0 0.3]) -legend('\kappa_1','S','S_r_e_v','D','0.07','0.096','0.02') -xlabel('N','FontName','Times New Roman','FontSize',18,'Rotation',0) -ylabel('\kappa_1, S, S_r_e_v, D','FontName','Times New Roman','FontSize',18,'Rotation',90) - -%% ENTROPIAS SHENNON AND HKL - -%Q=dados'; -Lin = length(Q); - -% 2. Pré-alocação de variáveis para desempenho -Hs = zeros(Lin, 1); -Hkl = zeros(Lin, 1); - -% 3. Cálculo Evolutivo (Abordagem de Janela Crescente) -% Conforme o artigo, a janela de detecção inicia no primeiro evento e -% cresce a cada novo hit para capturar o comportamento histórico [3, 6]. -for K = 2:Lin - % Energias da janela atual (do evento 1 até K) - current_Q = Q(1:K); - An = sum(current_Q); % Soma total da área/energia da janela [6, 7] - - % Vetor de probabilidade pK (distribuição de massa de ocorrência) [2] - % pK(k) é o k-ésimo elemento do vetor de probabilidade [2] - pk = current_Q / An; - - % --- Entropia de Shannon (Hs) --- - % Calculada para o hit K usando o logaritmo natural (ln) conforme orientação [2, 5] - % Hs(K) = -sum( pK * ln(pK) ) [2, 6] - Hs(K) = -sum(pk .* log(pk + eps)); - - % --- Entropia de Kullback-Leibler (Hkl) --- - % Expressa a probabilidade do evento atual condicionada pelo anterior [8] - % HKL(K) = -sum_{k=2}^{K} pK(k) * ln( pK(k) / pK(k-1) ) [6] - pk_atual = pk(2:end); - pk_anterior = pk(1:end-1); - Hkl(K) = -sum(pk_atual .* log((pk_atual + eps) ./ (pk_anterior + eps))); -end - -% 4. Valores Cumulativos (Sigma Hs e Sigma Hkl) -% O artigo também avalia a sensibilidade dos valores acumulados ao dano [1, 8]. -sum_Hs = cumsum(Hs); -sum_Hkl = cumsum(Hkl); - -% 5. Visualização dos Resultados -figure; -%subplot(2,1,1); -plot(Hs); -ylabel('\itH_s','FontName','Times New Roman','FontSize',18,'Rotation',90) -%set(gca, 'XTickLabel', []); % Remove os rótulos do eixo x grid on; -grid on -yyaxis right -ax = gca; -ax.YColor = 'k'; % define a cor do eixo Y direito como preto -hold on -%subplot(2,1,2); -plot(Hkl); grid on; -ylabel('\itH_{KL}','FontName','Times New Roman','FontSize',18,'Rotation',90) -legend('\itH_s','itH_{KL}') - -%% TSALLIS ENTROPY -win=50; %initial data size -k=1; -Amp=dados'; -tpico=1:1:size(dados,2) ; tpico=tpico'; -for jj=win+1:1:size(dados,2) -%Interval=[tpico(jj-win) tpico(jj)]; % SLIDING WINDOWN -Interval=[1 jj]; % -Mi=0.05; % division on the Amplitude distribution -[Datavalue, A_fit, lmbda_fit, q_fit, resultados_fit,p2]=EA_Calc_q(Amp,tpico,Interval,Mi,'NHist'); -A(k)=A_fit; -lmbda(k)=lmbda_fit; -q(k)=q_fit; -R(k)=resultados_fit.R_squared; -TPico(k)=jj; -p22(k)=p2; -k=k+1; -end -%% -figure; -plot(TPico,q,'r') -ylabel('q','FontName','Times New Roman','FontSize',20,'Rotation',90) -yyaxis right -hold on -plot(TPico,1./lmbda,'b') -legend('q','lambda') -xlabel('N','FontName','Times New Roman','FontSize',20,'Rotation',0) -ylabel('lambda','FontName','Times New Roman','FontSize',20,'Rotation',90) - -% -figure; -scatter(1./lmbda, q, 8, TPico, 'o'); % 50 = tamanho dos marcadores -colorbar; -xlabel('1/\it\lambda', 'FontSize', 12); -ylabel('\itq', 'FontSize', 12); -grid on -box on -ylabel(colorbar, 'Time [s]'); - - diff --git a/src/ldem/Teste_pot - Copia.m b/src/ldem/Teste_pot - Copia.m deleted file mode 100644 index 9344930..0000000 --- a/src/ldem/Teste_pot - Copia.m +++ /dev/null @@ -1,239 +0,0 @@ -clear all -clc - -% Configurações - n_total = 5000; % Número total de elementos - velocidade1 = 10; % Velocidade de transição entrada potencial(1-10) - velocidade2 = 10; % Velocidade de transição saida potencial (1-10) - expoente = 1; % Expoente da lei de potência - - dados =gerar_transicao_dupla2(n_total, velocidade1, velocidade2, expoente); - %dados = gerar_transicao_uniforme_potencial(n_total, velocidade, expoente); - %unif = rand(n_total /2,1); - %dados=[dados';unif]'; n_total=size(dados,2); - % Criar janela com subplots para visualização - figure('Position', [100, 100, 1200, 800]); - - % Subplot 1: Histograma completo - %subplot(2, 3, [1, 4]); - subplot(2,1,1); - histogram(dados, 100, 'Normalization', 'pdf', 'FaceColor', [0.3, 0.6, 0.9]); - xlabel('Value'); - ylabel('Density'); - title(sprintf('Uniform + Power law distribution + Uniform (N =%d)', n_total)); - grid on; - - % Subplot 4: Evolução temporal dos valores - %subplot(2, 3, [5, 6]); - subplot(2,1,2); - plot(1:n_total, dados', '.', 'MarkerSize', 2); - xlabel('N'); - ylabel('Value'); - title('Evolução Temporal dos Valores'); - grid on; - - % Adicionar linha de tendência móvel - window_size = 500; - media_movel = movmean(dados', window_size); - hold on; - plot(1:n_total, media_movel, 'r-', 'LineWidth', 2); - legend('Data', sprintf('Moving average (W=%d)', window_size), 'Location', 'best'); - hold off; - - % Estatísticas descritivas - fprintf('\n--- Estatísticas ---\n'); - fprintf('Média: %.4f\n', mean(dados)); - fprintf('Mediana: %.4f\n', median(dados)); - fprintf('Desvio padrão: %.4f\n', std(dados)); - fprintf('Mínimo: %.4f\n', min(dados)); - fprintf('Máximo: %.4f\n', max(dados)); - - % Análise da transição - % fprintf('\n--- Análise da Transição ---\n'); - - % % Dividir em 5 segmentos - % segmentos = 5; - % for k = 1:segmentos - % idx_inicio = round((k-1)*n_total/segmentos) + 1; - % idx_fim = round(k*n_total/segmentos); - % segmento = dados(idx_inicio:idx_fim); - % - % % Calcular média e mediana - % fprintf('Segmento %d (%.0f%%-%.0f%%): Média=%.4f, Mediana=%.4f, Coef.Variação=%.4f\n', ... - % k, (k-1)*100/segmentos, k*100/segmentos, ... - % mean(segmento), median(segmento), std(segmento)/mean(segmento)); - % end -%end -%%%%%%%%%%%%%%%% NATURAL TIME -Q=dados'; -% 1. Configuração Inicial e Medida de Energia -% O artigo sugere que a medida adequada é Qk = A^1.5, onde A é a amplitude [4, 5]. -%Q = Amp.^1.5; -Lin = length(Q); - -% Definição de PI_c (ruído uniforme) - calculada uma única vez -fi = 0:0.025:0.5; -ww = 2 * pi * fi; -pi_c = 18./(5*ww.^2) - 6*cos(ww)./(5*ww.^2) - 12*sin(ww)./(5*ww.^3); -pi_c(1) = 1; % Limite quando w -> 0 - -% Pré-alocação de variáveis para velocidade -kapa1 = zeros(Lin, 1); -Snt = zeros(Lin, 1); -Srev = zeros(Lin, 1); -D = zeros(Lin, 1); - -% Loop principal (Evolução dos eventos) -% Nota: Calculamos os parâmetros para cada janela de tamanho k -for k = 1:Lin - % 1. Recorte e Normalização da janela atual - Q_k = Q(1:k); - An = sum(Q_k); - pk = Q_k / An; % Energias normalizadas P_k [4] - - % 2. Vetor de Tempo Natural chi_k [4] - xk = (1:k)' / k; - - % 3. Cálculo Vetorizado de Kappa1 (Variância) - k1 = sum(pk .* (xk.^2)); - k2 = sum(pk .* xk); - kapa1(k) = k1 - k2^2; - - % 4. Cálculo Vetorizado das Entropias (S e S_inv) [1, 3] - % Usando logaritmo natural 'log' conforme recomendado [2] - Snt(k) = sum(pk .* xk .* log(xk)) - k2 * log(k2); - - % Para S_inv, invertemos a ordem das energias P_k -> P_{N-k+1} - pk_rev = flipud(pk); - k2_rev = sum(pk_rev .* xk); - Srev(k) = sum(pk_rev .* xk .* log(xk)) - k2_rev * log(k2_rev); - - % 5. Cálculo Vetorizado de PI(phi) e Distância D - % Criamos uma matriz para evitar o loop 'b' - % xk: (k x 1), ww: (1 x n_fi) -> exp_arg: (k x n_fi) - exp_arg = complex(0, 1) * (xk * ww); - Pi_phi = abs(pk' * exp(exp_arg)).^2; % Produto matricial calcula todos os fi de uma vez - - D(k) = mean(abs(Pi_phi - pi_c)); - - % Convertional time - %ct(k)=tpico(k); - % Natural time - nt(k)=k; - - % Feedback de progresso (opcional) - % if mod(k, 1000) == 0, disp(['Progresso: ', num26(k/Lin*100), '%']); end -end -% -figure() -% nt=ct; -plot(nt,kapa1,'r') -hold on -plot(nt,Snt,'b') -plot(nt,Srev,'m') -plot(nt,D,'g') -grid on - -plot([0 k],[0.07 0.07],'r--') -plot([0 k],[0.096 0.096],'b--') -plot([0 k],[0.02 0.02],'g--') -% ylim([0 0.3]) -legend('\kappa_1','S','S_r_e_v','D','0.07','0.096','0.02') -xlabel('N','FontName','Times New Roman','FontSize',18,'Rotation',0) -ylabel('\kappa_1, S, S_r_e_v, D','FontName','Times New Roman','FontSize',18,'Rotation',90) - -%% ENTROPIAS SHENNON AND HKL - -%Q=dados'; -Lin = length(Q); - -% 2. Pré-alocação de variáveis para desempenho -Hs = zeros(Lin, 1); -Hkl = zeros(Lin, 1); - -% 3. Cálculo Evolutivo (Abordagem de Janela Crescente) -% Conforme o artigo, a janela de detecção inicia no primeiro evento e -% cresce a cada novo hit para capturar o comportamento histórico [3, 6]. -for K = 2:Lin - % Energias da janela atual (do evento 1 até K) - current_Q = Q(1:K); - An = sum(current_Q); % Soma total da área/energia da janela [6, 7] - - % Vetor de probabilidade pK (distribuição de massa de ocorrência) [2] - % pK(k) é o k-ésimo elemento do vetor de probabilidade [2] - pk = current_Q / An; - - % --- Entropia de Shannon (Hs) --- - % Calculada para o hit K usando o logaritmo natural (ln) conforme orientação [2, 5] - % Hs(K) = -sum( pK * ln(pK) ) [2, 6] - Hs(K) = -sum(pk .* log(pk + eps)); - - % --- Entropia de Kullback-Leibler (Hkl) --- - % Expressa a probabilidade do evento atual condicionada pelo anterior [8] - % HKL(K) = -sum_{k=2}^{K} pK(k) * ln( pK(k) / pK(k-1) ) [6] - pk_atual = pk(2:end); - pk_anterior = pk(1:end-1); - Hkl(K) = -sum(pk_atual .* log((pk_atual + eps) ./ (pk_anterior + eps))); -end - -% 4. Valores Cumulativos (Sigma Hs e Sigma Hkl) -% O artigo também avalia a sensibilidade dos valores acumulados ao dano [1, 8]. -sum_Hs = cumsum(Hs); -sum_Hkl = cumsum(Hkl); - -% 5. Visualização dos Resultados -figure; -%subplot(2,1,1); -plot(Hs); -ylabel('\itH_s','FontName','Times New Roman','FontSize',18,'Rotation',90) -%set(gca, 'XTickLabel', []); % Remove os rótulos do eixo x grid on; -grid on -yyaxis right -ax = gca; -ax.YColor = 'k'; % define a cor do eixo Y direito como preto -hold on -%subplot(2,1,2); -plot(Hkl); grid on; -ylabel('\itH_{KL}','FontName','Times New Roman','FontSize',18,'Rotation',90) -legend('\itH_s','itH_{KL}') - -%% TSALLIS ENTROPY -win=50; %initial data size -k=1; -Amp=dados'; -tpico=1:1:size(dados,2) ; tpico=tpico'; -for jj=win+1:1:size(dados,2) -%Interval=[tpico(jj-win) tpico(jj)]; % SLIDING WINDOWN -Interval=[1 jj]; % -Mi=0.05; % division on the Amplitude distribution -[Datavalue, A_fit, lmbda_fit, q_fit, resultados_fit,p2]=EA_Calc_q(Amp,tpico,Interval,Mi,'NHist'); -A(k)=A_fit; -lmbda(k)=lmbda_fit; -q(k)=q_fit; -R(k)=resultados_fit.R_squared; -TPico(k)=jj; -p22(k)=p2; -k=k+1; -end -%% -figure; -plot(TPico,q,'r') -ylabel('q','FontName','Times New Roman','FontSize',20,'Rotation',90) -yyaxis right -hold on -plot(TPico,1./lmbda,'b') -legend('q','lambda') -xlabel('N','FontName','Times New Roman','FontSize',20,'Rotation',0) -ylabel('lambda','FontName','Times New Roman','FontSize',20,'Rotation',90) - -% -figure; -scatter(1./lmbda, q, 8, TPico, 'o'); % 50 = tamanho dos marcadores -colorbar; -xlabel('1/\it\lambda', 'FontSize', 12); -ylabel('\itq', 'FontSize', 12); -grid on -box on -ylabel(colorbar, 'Time [s]'); - - diff --git a/src/ldem/Teste_pot.m b/src/ldem/Teste_pot.m deleted file mode 100644 index 9344930..0000000 --- a/src/ldem/Teste_pot.m +++ /dev/null @@ -1,239 +0,0 @@ -clear all -clc - -% Configurações - n_total = 5000; % Número total de elementos - velocidade1 = 10; % Velocidade de transição entrada potencial(1-10) - velocidade2 = 10; % Velocidade de transição saida potencial (1-10) - expoente = 1; % Expoente da lei de potência - - dados =gerar_transicao_dupla2(n_total, velocidade1, velocidade2, expoente); - %dados = gerar_transicao_uniforme_potencial(n_total, velocidade, expoente); - %unif = rand(n_total /2,1); - %dados=[dados';unif]'; n_total=size(dados,2); - % Criar janela com subplots para visualização - figure('Position', [100, 100, 1200, 800]); - - % Subplot 1: Histograma completo - %subplot(2, 3, [1, 4]); - subplot(2,1,1); - histogram(dados, 100, 'Normalization', 'pdf', 'FaceColor', [0.3, 0.6, 0.9]); - xlabel('Value'); - ylabel('Density'); - title(sprintf('Uniform + Power law distribution + Uniform (N =%d)', n_total)); - grid on; - - % Subplot 4: Evolução temporal dos valores - %subplot(2, 3, [5, 6]); - subplot(2,1,2); - plot(1:n_total, dados', '.', 'MarkerSize', 2); - xlabel('N'); - ylabel('Value'); - title('Evolução Temporal dos Valores'); - grid on; - - % Adicionar linha de tendência móvel - window_size = 500; - media_movel = movmean(dados', window_size); - hold on; - plot(1:n_total, media_movel, 'r-', 'LineWidth', 2); - legend('Data', sprintf('Moving average (W=%d)', window_size), 'Location', 'best'); - hold off; - - % Estatísticas descritivas - fprintf('\n--- Estatísticas ---\n'); - fprintf('Média: %.4f\n', mean(dados)); - fprintf('Mediana: %.4f\n', median(dados)); - fprintf('Desvio padrão: %.4f\n', std(dados)); - fprintf('Mínimo: %.4f\n', min(dados)); - fprintf('Máximo: %.4f\n', max(dados)); - - % Análise da transição - % fprintf('\n--- Análise da Transição ---\n'); - - % % Dividir em 5 segmentos - % segmentos = 5; - % for k = 1:segmentos - % idx_inicio = round((k-1)*n_total/segmentos) + 1; - % idx_fim = round(k*n_total/segmentos); - % segmento = dados(idx_inicio:idx_fim); - % - % % Calcular média e mediana - % fprintf('Segmento %d (%.0f%%-%.0f%%): Média=%.4f, Mediana=%.4f, Coef.Variação=%.4f\n', ... - % k, (k-1)*100/segmentos, k*100/segmentos, ... - % mean(segmento), median(segmento), std(segmento)/mean(segmento)); - % end -%end -%%%%%%%%%%%%%%%% NATURAL TIME -Q=dados'; -% 1. Configuração Inicial e Medida de Energia -% O artigo sugere que a medida adequada é Qk = A^1.5, onde A é a amplitude [4, 5]. -%Q = Amp.^1.5; -Lin = length(Q); - -% Definição de PI_c (ruído uniforme) - calculada uma única vez -fi = 0:0.025:0.5; -ww = 2 * pi * fi; -pi_c = 18./(5*ww.^2) - 6*cos(ww)./(5*ww.^2) - 12*sin(ww)./(5*ww.^3); -pi_c(1) = 1; % Limite quando w -> 0 - -% Pré-alocação de variáveis para velocidade -kapa1 = zeros(Lin, 1); -Snt = zeros(Lin, 1); -Srev = zeros(Lin, 1); -D = zeros(Lin, 1); - -% Loop principal (Evolução dos eventos) -% Nota: Calculamos os parâmetros para cada janela de tamanho k -for k = 1:Lin - % 1. Recorte e Normalização da janela atual - Q_k = Q(1:k); - An = sum(Q_k); - pk = Q_k / An; % Energias normalizadas P_k [4] - - % 2. Vetor de Tempo Natural chi_k [4] - xk = (1:k)' / k; - - % 3. Cálculo Vetorizado de Kappa1 (Variância) - k1 = sum(pk .* (xk.^2)); - k2 = sum(pk .* xk); - kapa1(k) = k1 - k2^2; - - % 4. Cálculo Vetorizado das Entropias (S e S_inv) [1, 3] - % Usando logaritmo natural 'log' conforme recomendado [2] - Snt(k) = sum(pk .* xk .* log(xk)) - k2 * log(k2); - - % Para S_inv, invertemos a ordem das energias P_k -> P_{N-k+1} - pk_rev = flipud(pk); - k2_rev = sum(pk_rev .* xk); - Srev(k) = sum(pk_rev .* xk .* log(xk)) - k2_rev * log(k2_rev); - - % 5. Cálculo Vetorizado de PI(phi) e Distância D - % Criamos uma matriz para evitar o loop 'b' - % xk: (k x 1), ww: (1 x n_fi) -> exp_arg: (k x n_fi) - exp_arg = complex(0, 1) * (xk * ww); - Pi_phi = abs(pk' * exp(exp_arg)).^2; % Produto matricial calcula todos os fi de uma vez - - D(k) = mean(abs(Pi_phi - pi_c)); - - % Convertional time - %ct(k)=tpico(k); - % Natural time - nt(k)=k; - - % Feedback de progresso (opcional) - % if mod(k, 1000) == 0, disp(['Progresso: ', num26(k/Lin*100), '%']); end -end -% -figure() -% nt=ct; -plot(nt,kapa1,'r') -hold on -plot(nt,Snt,'b') -plot(nt,Srev,'m') -plot(nt,D,'g') -grid on - -plot([0 k],[0.07 0.07],'r--') -plot([0 k],[0.096 0.096],'b--') -plot([0 k],[0.02 0.02],'g--') -% ylim([0 0.3]) -legend('\kappa_1','S','S_r_e_v','D','0.07','0.096','0.02') -xlabel('N','FontName','Times New Roman','FontSize',18,'Rotation',0) -ylabel('\kappa_1, S, S_r_e_v, D','FontName','Times New Roman','FontSize',18,'Rotation',90) - -%% ENTROPIAS SHENNON AND HKL - -%Q=dados'; -Lin = length(Q); - -% 2. Pré-alocação de variáveis para desempenho -Hs = zeros(Lin, 1); -Hkl = zeros(Lin, 1); - -% 3. Cálculo Evolutivo (Abordagem de Janela Crescente) -% Conforme o artigo, a janela de detecção inicia no primeiro evento e -% cresce a cada novo hit para capturar o comportamento histórico [3, 6]. -for K = 2:Lin - % Energias da janela atual (do evento 1 até K) - current_Q = Q(1:K); - An = sum(current_Q); % Soma total da área/energia da janela [6, 7] - - % Vetor de probabilidade pK (distribuição de massa de ocorrência) [2] - % pK(k) é o k-ésimo elemento do vetor de probabilidade [2] - pk = current_Q / An; - - % --- Entropia de Shannon (Hs) --- - % Calculada para o hit K usando o logaritmo natural (ln) conforme orientação [2, 5] - % Hs(K) = -sum( pK * ln(pK) ) [2, 6] - Hs(K) = -sum(pk .* log(pk + eps)); - - % --- Entropia de Kullback-Leibler (Hkl) --- - % Expressa a probabilidade do evento atual condicionada pelo anterior [8] - % HKL(K) = -sum_{k=2}^{K} pK(k) * ln( pK(k) / pK(k-1) ) [6] - pk_atual = pk(2:end); - pk_anterior = pk(1:end-1); - Hkl(K) = -sum(pk_atual .* log((pk_atual + eps) ./ (pk_anterior + eps))); -end - -% 4. Valores Cumulativos (Sigma Hs e Sigma Hkl) -% O artigo também avalia a sensibilidade dos valores acumulados ao dano [1, 8]. -sum_Hs = cumsum(Hs); -sum_Hkl = cumsum(Hkl); - -% 5. Visualização dos Resultados -figure; -%subplot(2,1,1); -plot(Hs); -ylabel('\itH_s','FontName','Times New Roman','FontSize',18,'Rotation',90) -%set(gca, 'XTickLabel', []); % Remove os rótulos do eixo x grid on; -grid on -yyaxis right -ax = gca; -ax.YColor = 'k'; % define a cor do eixo Y direito como preto -hold on -%subplot(2,1,2); -plot(Hkl); grid on; -ylabel('\itH_{KL}','FontName','Times New Roman','FontSize',18,'Rotation',90) -legend('\itH_s','itH_{KL}') - -%% TSALLIS ENTROPY -win=50; %initial data size -k=1; -Amp=dados'; -tpico=1:1:size(dados,2) ; tpico=tpico'; -for jj=win+1:1:size(dados,2) -%Interval=[tpico(jj-win) tpico(jj)]; % SLIDING WINDOWN -Interval=[1 jj]; % -Mi=0.05; % division on the Amplitude distribution -[Datavalue, A_fit, lmbda_fit, q_fit, resultados_fit,p2]=EA_Calc_q(Amp,tpico,Interval,Mi,'NHist'); -A(k)=A_fit; -lmbda(k)=lmbda_fit; -q(k)=q_fit; -R(k)=resultados_fit.R_squared; -TPico(k)=jj; -p22(k)=p2; -k=k+1; -end -%% -figure; -plot(TPico,q,'r') -ylabel('q','FontName','Times New Roman','FontSize',20,'Rotation',90) -yyaxis right -hold on -plot(TPico,1./lmbda,'b') -legend('q','lambda') -xlabel('N','FontName','Times New Roman','FontSize',20,'Rotation',0) -ylabel('lambda','FontName','Times New Roman','FontSize',20,'Rotation',90) - -% -figure; -scatter(1./lmbda, q, 8, TPico, 'o'); % 50 = tamanho dos marcadores -colorbar; -xlabel('1/\it\lambda', 'FontSize', 12); -ylabel('\itq', 'FontSize', 12); -grid on -box on -ylabel(colorbar, 'Time [s]'); - - diff --git a/src/ldem/WRICON.m b/src/ldem/WRICON.m deleted file mode 100644 index 392d837..0000000 --- a/src/ldem/WRICON.m +++ /dev/null @@ -1,117 +0,0 @@ - -function ini=WRICON(fid) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%!-------------------------------------------------------------------------- -%function WRICON(fid) -% WRICON -% ================= -% -% DATA: 22/03/1993 -% AUTOR: IGNACIO ITURRIOZ -% -% Esta subrotina grava dados no arquivo CONNAME. -% - -fprintf(1, 'entro na wricon\n'); - -fprintf(fid, '\n'); -fprintf(fid, ' ********************* DEM ********************* \n'); -fprintf(fid, '\n'); -fprintf(fid, ' Discrete Element Method \n'); -fprintf(fid, '\n'); -fprintf(fid, ' All Rights Reserved - PPGEC / UFRGS \n'); -fprintf(fid, '\n'); -fprintf(fid, ' DATA CONTROL OUTPUT \n'); -fprintf(fid, ' ******************* \n'); -fprintf(fid, '\n'); -fprintf(fid, ' Simulation =======================>%12d\n', RUN); -fprintf(fid, '\n'); - -% Fortran FORMAT (A40,I12) --> left-justified 40-char label + %12d -fprintf(fid, '%-40s%12d\n', ' Test simulated...................... ', TEST); -fprintf(fid, '%-40s%12d\n', ' Truss modules in X-direction........ ', M1); -fprintf(fid, '%-40s%12d\n', ' Truss modules in Y-direction........ ', N1); -fprintf(fid, '%-40s%12d\n', ' Truss modules in Z-direction........ ', L1); -fprintf(fid, '\n'); - -fprintf(fid, '%-40s%12d\n', ' Principal nodes number.............. ', NNO); -fprintf(fid, '%-40s%12d\n', ' Symmetry nodes number............... ', NNS); -fprintf(fid, '%-40s%12d\n', ' Total nodes number.................. ', NNT); -fprintf(fid, '%-40s%12d\n', ' Principal bars number............... ', NBA); -fprintf(fid, '%-40s%12d\n', ' Symmetry bars number................ ', NBS); -fprintf(fid, '%-40s%12d\n', ' Total bars number................... ', NBT); -fprintf(fid, '\n'); - -%-------------------------------------------------------------------------- -% Control node numbers (Fortran DO 10 I=1,INCO) -%-------------------------------------------------------------------------- -for I = 1:INCO - fprintf(fid, '%-40s%12d\n', ' Control node number................. ', NCON(I)); -end - -fprintf(fid, '\n'); -fprintf(fid, '\n'); - -%-------------------------------------------------------------------------- -% FORMAT (A40,E12.6) --> left-justified 40-char label + %12.6E -%-------------------------------------------------------------------------- -fprintf(fid, '%-40s%12.6E\n', ' Initial damping factor.............. ', DF1); -fprintf(fid, '%-40s%12.6E\n', ' Final damping factor................ ', DF2); -fprintf(fid, '%-40s%12.6E\n', ' Time of damping change.............. ', TDAF); -fprintf(fid, '%-40s%12.6E\n', ' Stiffness proportional damping...... ', CON); -fprintf(fid, '\n'); -fprintf(fid, '%-40s%12.6E\n', ' Truss module length................. ', LCO); -fprintf(fid, '%-40s%12.6E\n', ' Time increment...................... ', DT); -fprintf(fid, '%-40s%12.6E\n', ' Total time of integration........... ', TTOT); - -%-------------------------------------------------------------------------- -% Derived quantities -%-------------------------------------------------------------------------- -KRN = LCR / LCO; -DELTA = 9.0 * PSN / (4.0 - 8.0 * PSN); -ALFA = (9.0 + 8.0 * DELTA) / (18.0 + 24.0 * DELTA); -MASTOT = (M1 * LCO * N1 * LCO * L1 * LCO) * ROH; - -fprintf(fid, '\n'); -fprintf(fid, '%-40s%12.6E\n', ' Poissons ratio...................... ', PSN); -fprintf(fid, '%-40s%12.6E\n', ' Mass density........................ ', ROH); -fprintf(fid, '%-40s%12.6E\n', ' Total mass.......................... ', MASTOT); -fprintf(fid, '%-40s%12.6E\n', ' Youngs modulus...................... ', YNG); -fprintf(fid, '%-40s%12.6E\n', ' Element normal stiffness............ ', ENR(1)); -fprintf(fid, '%-40s%12.6E\n', ' Element diagonal stiffness.......... ', EDG(1)); -fprintf(fid, '%-40s%12.6E\n', ' Specific fracture energy............ ', GFR); -fprintf(fid, '%-40s%12.6E\n', ' equivalent d ........ ', DEQ); -fprintf(fid, '%-40s%12.6E\n', ' Proportionality mean strain......... ', EP(1)); -fprintf(fid, '%-40s%12.6E\n', ' Critical value for Lc............... ', LCR); -fprintf(fid, '%-40s%12.6E\n', ' Kr value for normal bars............ ', KRN); -fprintf(fid, '%-40s%12.6E\n', ' Delta coefficient................... ', DELTA); -fprintf(fid, '%-40s%12.6E\n', ' Alfa coefficient.................... ', ALFA); -fprintf(fid, '\n'); -fprintf(fid, '%-40s%12.6E\n', ' Maximum value for ep................ ', EPMAX); -fprintf(fid, '%-40s%12.6E\n', ' Minimum value for ep................ ', EPMIN); -fprintf(fid, '\n'); - -%-------------------------------------------------------------------------- -% General remarks section -%-------------------------------------------------------------------------- -fprintf(fid, '\n'); -fprintf(fid, ' GENERAL REMARKS \n'); -fprintf(fid, ' *************** \n'); -fprintf(fid, '\n'); -fprintf(fid, '%-40s%12.6E\n', ' Mean ep............................. ', MEAN); -fprintf(fid, '%-40s%12.6E\n', ' Coefficient of variation for ep..... ', COEV); -fprintf(fid, '\n'); - -fprintf(fid, '\n'); - -ini=1; - end diff --git a/src/ldem/WRIDIPO.m b/src/ldem/WRIDIPO.m deleted file mode 100644 index 13e3acf..0000000 --- a/src/ldem/WRIDIPO.m +++ /dev/null @@ -1,84 +0,0 @@ - -function ini=WRIDIPO(fid16, fid17) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% ! -% !-------------------------------------------------------------------------- -% !-------------------------------------------------------------------------- -% ! -% SUBROUTINE WRIDIPO -% ! ================== -% ! -% ! DATA: 22/03/1993 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina grava os resultados nos arquivos DISNAME e POSNAME. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% ! ADAPTAR PARA CADA EXEMPLO TESTADO -% !-------------------------------------------------------------------------- -% -% IF (TEST.EQ.102) THEN -% ! -% WRITE (17,'(3(E25.12,3X))') TIME, -% &ACX(NCON(1)),ACX(NCON(2)) -% ! -% END IF -% -% -% -% RETURN -% END -% ! -% !-------------------------------------------------------------------------- - - -% WRIDIPO -% ======= -% -% DATA: 22/03/1993 -% AUTOR: IGNACIO ITURRIOZ -% -% Esta subrotina grava os resultados nos arquivos DISNAME e POSNAME. -% -% MATLAB translation using GLOBAL variables instead of COMMON. -% -% Inputs: -% fid16 -> file identifier for LET.DIS (DISNAME) -% fid17 -> file identifier for LET.POS (POSNAME) - -% ------------------------------------------------------------------------- -% Global variables (equivalent to the COMMON block) -% ------------------------------------------------------------------------- - - -% ------------------------------------------------------------------------- -% ADAPT FOR EACH TEST EXAMPLE -% ------------------------------------------------------------------------- -if TEST == 102 - - % Write to LET.POS (unit 17 in Fortran -> fid17) - fprintf(fid17, '%25.12e %25.12e %25.12e\n', ... - TIME, ACX(NCON(1)), ACX(NCON(2))); - -end - - - - - -ini=1; - end diff --git a/src/ldem/WRIENE.m b/src/ldem/WRIENE.m deleted file mode 100644 index 46348dd..0000000 --- a/src/ldem/WRIENE.m +++ /dev/null @@ -1,38 +0,0 @@ - -function ini=WRIENE(fid18) -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED - -% SUBROUTINE WRIENE -% ! ================= -% ! -% ! DATA: 22/03/1993 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina grava os resultados em ENENAME. -% ! -% !-------------------------------------------------------------------------- -% PARAMETER (INN=1.2E6,INB=6E6,IRU=6,INCON=10) -% !-------------------------------------------------------------------------- -% ! DEFINIÇÃO DE VARIÁVEIS E GRUPOS COMUNS -% INCLUDE 'COMMON.FOR' -% !-------------------------------------------------------------------------- -% ! ENIN = ENCN + ENEL + ENGD + ENDP -% ! DEN = (ENEX - ENIN) -% ! -% WRITE (18,'(7(E25.12,3X))') TIME,ENEX,ENCN,ENEL,ENGD,ENDP,DEN -% ! -% RETURN -% END - fprintf(fid18, '%25.12e %25.12e %25.12e %25.12e %25.12 %25.12e %25.12e\n', ... - TIME, ENEX,ENCN,ENEL,ENGD,ENDP,DEN); -ini=1; - end diff --git a/src/ldem/gerar_transicao_dupla2 - Copia.m b/src/ldem/gerar_transicao_dupla2 - Copia.m deleted file mode 100644 index a794295..0000000 --- a/src/ldem/gerar_transicao_dupla2 - Copia.m +++ /dev/null @@ -1,74 +0,0 @@ -function dados = gerar_transicao_dupla(n_total, velocidade1, velocidade2, expoente) - % GERAR_TRANSICAO_DUPLA - Gera números com transição uniforme → potencial → uniforme - % - % Entradas: - % n_total - número total de elementos - % velocidade1 - velocidade da primeira transição (uniforme → potencial) - % valores típicos: 1 a 10 (maior = mais abrupta) - % velocidade2 - velocidade da segunda transição (potencial → uniforme) - % expoente - expoente da distribuição potencial (alfa > 0) - % - % Saída: - % dados - vetor (1 x n_total) com os números gerados - - % Validações - if nargin < 4 - error('São necessários 4 argumentos: n_total, velocidade1, velocidade2, expoente'); - end - if velocidade1 <= 0 || velocidade2 <= 0 - error('As velocidades devem ser positivas'); - end - if expoente <= 0 - error('Expoente deve ser positivo'); - end - - % Pontos de transição fixos (frações normalizadas de 0 a 1) - p1 = 0.01; % fim da primeira zona uniforme - p2 = 0.01; % fim da transição uniforme → potencial - p3 = 1.0; % fim da zona potencial pura - p4 = 1.0; % fim da transição potencial → uniforme - - % Pré‑calcular a distribuição potencial (intervalo [0.01, 1]) - x_min = 0.01; - x_max = 1.0; - if abs(expoente - 1) < 1e-6 - % Expoente = 1 → distribuição logarítmica - log_ratio = log(x_max / x_min); - gerar_potencial = @() x_min * exp(rand() * log_ratio); - else - c1 = x_min^(1 - expoente); - c2 = x_max^(1 - expoente); - gerar_potencial = @() (rand() * (c2 - c1) + c1)^(1/(1 - expoente)); - end - - % Gerar cada elemento - dados = zeros(1, n_total); - for i = 1:n_total - t = (i - 1) / (n_total - 1); % posição normalizada (0 → 1) - - % Determinar o peso da componente potencial (0 = uniforme, 1 = potencial) - if t <= p1 - peso_pot = 0; - elseif t <= p2 - % Transição uniforme → potencial (sigmóide crescente) - t_norm = (t - p1) / (p2 - p1); % mapeia [p1, p2] → [0, 1] - peso_pot = 1 / (1 + exp(-velocidade1 * (t_norm - 0.5) * 8)); - elseif t <= p3 - % Zona potencial pura - peso_pot = 1; - elseif t <= p4 - % Transição potencial → uniforme (sigmóide decrescente) - t_norm = (t - p3) / (p4 - p3); % mapeia [p3, p4] → [0, 1] - peso_pot = 1 / (1 + exp(velocidade2 * (t_norm - 0.5) * 8)); - else - peso_pot = 0; - end - - % Amostrar conforme o peso - if rand() < peso_pot - dados(i) = gerar_potencial(); - else - dados(i) = rand(); % uniforme em [0,1] - end - end -end \ No newline at end of file diff --git a/src/ldem/gerar_transicao_dupla2.m b/src/ldem/gerar_transicao_dupla2.m deleted file mode 100644 index a794295..0000000 --- a/src/ldem/gerar_transicao_dupla2.m +++ /dev/null @@ -1,74 +0,0 @@ -function dados = gerar_transicao_dupla(n_total, velocidade1, velocidade2, expoente) - % GERAR_TRANSICAO_DUPLA - Gera números com transição uniforme → potencial → uniforme - % - % Entradas: - % n_total - número total de elementos - % velocidade1 - velocidade da primeira transição (uniforme → potencial) - % valores típicos: 1 a 10 (maior = mais abrupta) - % velocidade2 - velocidade da segunda transição (potencial → uniforme) - % expoente - expoente da distribuição potencial (alfa > 0) - % - % Saída: - % dados - vetor (1 x n_total) com os números gerados - - % Validações - if nargin < 4 - error('São necessários 4 argumentos: n_total, velocidade1, velocidade2, expoente'); - end - if velocidade1 <= 0 || velocidade2 <= 0 - error('As velocidades devem ser positivas'); - end - if expoente <= 0 - error('Expoente deve ser positivo'); - end - - % Pontos de transição fixos (frações normalizadas de 0 a 1) - p1 = 0.01; % fim da primeira zona uniforme - p2 = 0.01; % fim da transição uniforme → potencial - p3 = 1.0; % fim da zona potencial pura - p4 = 1.0; % fim da transição potencial → uniforme - - % Pré‑calcular a distribuição potencial (intervalo [0.01, 1]) - x_min = 0.01; - x_max = 1.0; - if abs(expoente - 1) < 1e-6 - % Expoente = 1 → distribuição logarítmica - log_ratio = log(x_max / x_min); - gerar_potencial = @() x_min * exp(rand() * log_ratio); - else - c1 = x_min^(1 - expoente); - c2 = x_max^(1 - expoente); - gerar_potencial = @() (rand() * (c2 - c1) + c1)^(1/(1 - expoente)); - end - - % Gerar cada elemento - dados = zeros(1, n_total); - for i = 1:n_total - t = (i - 1) / (n_total - 1); % posição normalizada (0 → 1) - - % Determinar o peso da componente potencial (0 = uniforme, 1 = potencial) - if t <= p1 - peso_pot = 0; - elseif t <= p2 - % Transição uniforme → potencial (sigmóide crescente) - t_norm = (t - p1) / (p2 - p1); % mapeia [p1, p2] → [0, 1] - peso_pot = 1 / (1 + exp(-velocidade1 * (t_norm - 0.5) * 8)); - elseif t <= p3 - % Zona potencial pura - peso_pot = 1; - elseif t <= p4 - % Transição potencial → uniforme (sigmóide decrescente) - t_norm = (t - p3) / (p4 - p3); % mapeia [p3, p4] → [0, 1] - peso_pot = 1 / (1 + exp(velocidade2 * (t_norm - 0.5) * 8)); - else - peso_pot = 0; - end - - % Amostrar conforme o peso - if rand() < peso_pot - dados(i) = gerar_potencial(); - else - dados(i) = rand(); % uniforme em [0,1] - end - end -end \ No newline at end of file diff --git a/src/ldem/ini_DEM3 - Copia.m b/src/ldem/ini_DEM3 - Copia.m deleted file mode 100644 index 70c1188..0000000 --- a/src/ldem/ini_DEM3 - Copia.m +++ /dev/null @@ -1,218 +0,0 @@ -function ini=ini_DEM3() -%H1 this function put initial values in the global variables -% -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS - -% Variables setting -INT=10000; % total nodes -IBT=100000;% total elements -U(3,INT)=0.0; % nodal displacement, U=x,V=y,W=z, i-1,i,i+1 time_ step -V(3,INT)=0.0; -W(3,INT)=0.0; -U0(INT)=0.0;% nodal displacements in the initial configuration -V0(INT)=0.0;% -W0(INT)=0.0;% -BDX(INT)=0;% boundary conditions 1=fix, 0=fix -BDY(INT)=0; -BDZ(INT)=0; -VLX(INT)=0.0;% nodal velocities -VLY(INT)=0.0; -VLZ(INT)=0.0; -ACX(INT)=0.0;%nodal acelerations -ACY(INT)=0.0; -ACZ(INT)=0.0; -FRX(INT)=0.0; %Nodal forces in each step -FRY(INT)=0.0; -FRZ(INT)=0.0; -FX(INT)=0.0; %acumulated nodal forces -FY(INT)=0.0; -FZ(INT)=0.0; -MAS(INT)=0.0; % nodal masses with corrections taken into account -MSS(INT)=0.0; -%,ROMP,ROMP_OLD -%! - -CN(2,INB)=0; %conectivity i, and j of each element -ENR(INB)=0.0;% normal specific stifness ENR(i)=YNGB(i)*ALPHA*(LI(i))^2 -EDG(INB)=0.0;% diagonal stifness bar EDG(B)=2.0D00*DELTA*(4.0D00/3.0D00)*ENR(B)/DSQRT(3.0D00) -E1(INB)=0.0;% Normal stifness in compression taking into account if the bar is in the border or is a internal bar -E2(INB)=0.0;% Normal stifness in tension -LI(INB)=0.0; % cubic module length -% -DEQB(INB)=0.0;%equivalent distance for each element -F(INB)=0.0;%element force -YNGB(INB)=0.0; %Young modules in each bar -GFRB(INB)=0.0; %toughness in each bar -LCRB(INB)=0.0; %LCR=DEQ*2.0D00*CAF/ALFA -EPRB(INB)=0.0;% EPRB(i)=DSQRT(GFRB(i)/(YNGB(i)*DEQB(i))) -EP(INB)=0.0;%the same of EPRB ??? %%%%%%%% -SS(INB)=0.0; %the strain in the bar the last step -EM(INB)=0.0;% te same that SS ?????? %%%%%%%% -EN(2,INB)=0.0; %elastic energy in each bar computed in each step, 1 undamage, 2 damage. this information it isnt used -KR(INB)=0.0; %er(i)= kr(i)* ep(i) -KR1(INB)=0.0;%%%% it is not used -DSS(INB)=0.0; %the derivative of the strain STRRT in each step -DM(INB)=true; % damage index if DM=true bar is undamage -FS(INB)=true; %failure index if DM= true bar is unfail, with partial damage or not. -%DM1(INB)=true; -%FS1(INB)=true; -%TR(INB)=0.0; -%ansysColor=0 -% -CAF=0.1385; %failure area of each normal bars An(i)=CAF*LI(i) -%CUT=0.0; -DT=0.0; % time increment -GFR=0.0; %tougnhess , mean value -DEQ=0.0;% critical distance mean value -LCR=0.0; % critical length -%SEED=0.0; -TEST=0; %number of test to stablish characteristic of each specific problem -EST=0; % establish differetn type of damping |EstEST=0 ==> Amortecimento padrão (C=DF*M) -%! EST=1 ==> EST=0 + um amortecimento introduzido -%! na equação constitutiva com CON -%! EST=2 ==> EST=0, mas o coefic. de amortecimento -%! DF é multiplicado pelo índice de dano -DF1=0.0; %input damping value -DF2=0.0; -DMP1=0.0; %%% % DMP1=(1.0D00-DF11*DT/2.0D00)%%%%must be global??? -DMP2=0.0; %%%%must be global??? -TDAF=0.0; %time in which the damping 1 change to damping 2 -CON=0.0; % values that introduce damping proportional to the stifness -%Label=0; -M=0; %number of modules Mx, N(y), L(z) , -N=0; -L=0; -M1=0; -N1=0; -L1=0; -%MNL=0;% M*N*L -NNO=0;% NNO=MNL+M1*N1*L1 %%%%%%%%%% -NNS=0;% %%%%%%%%% -NNT=0;% total number of nodes -NBA=0;%partial values %%%%%%% -NBS=0;%partial values %%%%%%%% -NBT=0; % total number of elements -INCO(10)=0;%the specific number of node indicated as input %%%%%%% -NCON(10)=0;%Number of nodes that could be identified -% OU2=0; % the number of output for print the results %%%%%% -% OU3=0; -% OU4=0; -% OU5=0; -% OU6=0; -% OU7=0; -% OU8=0; -% OU9=0; -% PR3=0; % numer os step to skip when th result are save -% PR4=0; -% PR5=0; -% PR67=0; -% PR8=0; -% PR9=0; -STEP=0;% current number of step -NSTEP=0;% tital number of steps -NDAMF=0;% step number correlated with TDAF -RUN=0; %current number of simulation -NRUN=0; % total number of simulations -LCO=0.0; %lenth of the cubic module -TIME=0.0; % current time -TTOT=0.0; % total time of the simulation -PSN=0.0;% poisson coeficient -ROH=0.0; % density -YNG=0.0; %mean young modulus -EPR=0.0; % -EPMAX=0.0; % maximum value of the critical strain -EPMIN=0.0; %minimum value of the critical strain -MEAN=0.0 ; %mean value of critical strain -COEV=0.0 ; % variation coeficient of critical strain -ENEX=0.0 ;% External energy -ENCN=0.0;% kinetic energy -ENEL=0.0;% Elastic energy -ENGD=0.0;% damage energy -ENDP=0.0;% damping energy -ENIN=0.0;% internal energy -DEN=0.0;% ENEX-ENIN -DERIV=0.0;% derivative of the ENGD -XB(INB)=0.0; %baricentric coordinates fo the elements -YB(INB)=0.0; -ZB(INB)=0.0; -UBAR(INB)=0.0;%displacement in the baricentric of each bar -VBAR(INB)=0.0; -WBAR(INB)=0.0; - -REACAOX=0.0;% summation of the reaction in x diretion -REACAOY=0.0; -REACAOZ=0.0; -STRAIN=0.0; -STRESS=0.0; -%X -%Y -%Z -% ,aaa -% ,ReaV -% ,vmax -% ,tt1 -% ,vmax2 -% ,tt2 -% VF1 -% ,VF2 -% ,VF3 -% ,vmax3 -% ,tt3 -% ,VF4 -% ,vmax4 -% ,vmax5 -% ,tt5 -% ,VF6 -% ,vmax6 -% ,tt6 -% ,dmax -% ,dmax2 - - % NK1 - % ,NK2 - % ,NK3 -% D2,PI,K1,K2,K3,DK1,DK2,DK3 -% PHI1,PHI2,PHI3,PHI4,AN - % CVROH,CVYNG,CVGFR,CORRCAF - %TENNORMZ,TENTANGX - % RKX,RKZ,VF -%FOR1 -%STR1 -%FOR2 -%STR2 -%FOR3 -%STR3 -%FOR4 -%STR4 -%ROHN - % BTA,GMA,IBT - % LCORX,LCORY,LCORZ,NPTX,NPTY,NPTZ,NPTOTAL - - % ,IPT - % MPJ,NPJ,LPJ,MPI,NPI,LPI - % IPT1,IPT2,IPT3,IPT4,IPT5,IPT6,IPT7,IPT8,IPT9 - % MP2,NP2,LP2,PHI - % PMI,PNI,PLI,PHIV - %xc,yc,vfarea,vfareal,time1 - %neib,iicont - % krs,epp,constB - % krsc,E2C,EMC - %g51589,gg51589,g89116,gg89116,ggg89116,giv89116 - % DESELX,DESELXMEDIO,SOMADESX,DESELY,DESELYMEDIO, & - %SOMADESY - -ini=1 -return - - - - diff --git a/src/ldem/ini_DEM3.m b/src/ldem/ini_DEM3.m deleted file mode 100644 index b0de085..0000000 --- a/src/ldem/ini_DEM3.m +++ /dev/null @@ -1,221 +0,0 @@ -function ini=ini_DEM3() -%H1 this function put initial values in the global variables -% -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -% -% Variables setting -INT=168000 -INB=2300000 -U(3,INT)=0.0; % nodal displacement, U=x,V=y,W=z, i-1,i,i+1 time_ step -V(3,INT)=0.0; -W(3,INT)=0.0; -U0(INT)=0.0;% nodal displacements in the initial configuration -V0(INT)=0.0;% -W0(INT)=0.0;% -BDX(INT)=0;% boundary conditions 1=fix, 0=fix -BDY(INT)=0; -BDZ(INT)=0; -VLX(INT)=0.0;% nodal velocities -VLY(INT)=0.0; -VLZ(INT)=0.0; -ACX(INT)=0.0;%nodal acelerations -ACY(INT)=0.0; -ACZ(INT)=0.0; -FRX(INT)=0.0; %Nodal forces in each step -FRY(INT)=0.0; -FRZ(INT)=0.0; -FX(INT)=0.0; %acumulated nodal forces -FY(INT)=0.0; -FZ(INT)=0.0; -MAS(INT)=0.0; % nodal masses with corrections taken into account -MSS(INT)=0.0; -CN(2*INB)=0; -%,ROMP,ROMP_OLD -%! - -%CN(2,INB)=0; %conectivity i, and j of each element -%ENR(INB)=0.0;% normal specific stifness ENR(i)=YNGB(i)*ALPHA*(LI(i))^2 -%EDG(INB)=0.0;% diagonal stifness bar EDG(B)=2.0D00*DELTA*(4.0D00/3.0D00)*ENR(B)/DSQRT(3.0D00) -%E1(INB)=0.0;% Normal stifness in compression taking into account if the bar is in the border or is a internal bar -%E2(INB)=0.0;% Normal stifness in tension -%LI(INB)=0.0; % cubic module length -% -%DEQB(INB)=0.0;%equivalent distance for each element -%F(INB)=0.0;%element force -%YNGB(INB)=0.0; %Young modules in each bar -%GFRB(INB)=0.0; %toughness in each bar -%LCRB(INB)=0.0; %LCR=DEQ*2.0D00*CAF/ALFA -%EPRB(INB)=0.0;% EPRB(i)=DSQRT(GFRB(i)/(YNGB(i)*DEQB(i))) -%EP(INB)=0.0;%the same of EPRB ??? %%%%%%%% -%SS(INB)=0.0; %the strain in the bar the last step -%EM(INB)=0.0;% te same that SS ?????? %%%%%%%% -%EN(2,INB)=0.0; %elastic energy in each bar computed in each step, 1 undamage, 2 damage. this information it isnt used -%KR(INB)=0.0; %er(i)= kr(i)* ep(i) -%KR1(INB)=0.0;%%%% it is not used -%DSS(INB)=0.0; %the derivative of the strain STRRT in each step -%DM(INB)=true; % damage index if DM=true bar is undamage -%FS(INB)=true; %failure index if DM= true bar is unfail, with partial damage or not. -%DM1(INB)=true; -%FS1(INB)=true; -%TR(INB)=0.0; -%ansysColor=0 -% -CAF=0.1385; %failure area of each normal bars An(i)=CAF*LI(i) -%CUT=0.0; -DT=0.0; % time increment -GFR=0.0; %tougnhess , mean value -DEQ=0.0;% critical distance mean value -LCR=0.0; % critical length -%SEED=0.0; -TEST=0; %number of test to stablish characteristic of each specific problem -EST=0; % establish differetn type of damping |EstEST=0 ==> Amortecimento padrão (C=DF*M) -%! EST=1 ==> EST=0 + um amortecimento introduzido -%! na equação constitutiva com CON -%! EST=2 ==> EST=0, mas o coefic. de amortecimento -%! DF é multiplicado pelo índice de dano -DF=0.0; -DF1=0.0; %input damping value -DF2=0.0; -DMP1=0.0; %%% % DMP1=(1.0D00-DF11*DT/2.0D00)%%%%must be global??? -DMP2=0.0; %%%%must be global??? -TDAF=0.0; %time in which the damping 1 change to damping 2 -CON=0.0; % values that introduce damping proportional to the stifness -%Label=0; -M=0; %number of modules Mx, N(y), L(z) , -N=0; -L=0; -M1=0; -N1=0; -L1=0; -MNL=0;% M*N*L -NNO=0;% NNO=MNL+M1*N1*L1 %%%%%%%%%% -NNS=0;% %%%%%%%%% -NNT=0;% total number of nodes -NBA=0;%partial values %%%%%%% -NBS=0;%partial values %%%%%%%% -NBT=0; % total number of elements -INCO(10)=0;%the specific number of node indicated as input %%%%%%% -NCON(10)=0;%Number of nodes that could be identified -% OU2=0; % the number of output for print the results %%%%%% -% OU3=0; -% OU4=0; -% OU5=0; -% OU6=0; -% OU7=0; -% OU8=0; -% OU9=0; -% PR3=0; % numer os step to skip when th result are save -% PR4=0; -% PR5=0; -% PR67=0; -% PR8=0; -% PR9=0; -STEP=0;% current number of step -NSTEP=0;% tital number of steps -NDAMF=0;% step number correlated with TDAF -RUN=0; %current number of simulation -NRUN=0; % total number of simulations -LCO=0.0; %lenth of the cubic module -TIME=0.0; % current time -TTOT=0.0; % total time of the simulation -PSN=0.0;% poisson coeficient -ROH=0.0; % density -YNG=0.0; %mean young modulus -EPR=0.0; % -EPMAX=0.0; % maximum value of the critical strain -EPMIN=0.0; %minimum value of the critical strain -MEAN=0.0 ; %mean value of critical strain -COEV=0.0 ; % variation coeficient of critical strain -ENEX=0.0 ;% External energy -ENCN=0.0;% kinetic energy -ENEL=0.0;% Elastic energy -ENGD=0.0;% damage energy -ENDP=0.0;% damping energy -ENIN=0.0;% internal energy -DEN=0.0;% ENEX-ENIN -DERIV=0.0;% derivative of the ENGD -XB(INB)=0.0; %baricentric coordinates fo the elements -YB(INB)=0.0; -ZB(INB)=0.0; -UBAR(INB)=0.0;%displacement in the baricentric of each bar -VBAR(INB)=0.0; -WBAR(INB)=0.0; - -REACAOX=0.0;% summation of the reaction in x diretion -REACAOY=0.0; -REACAOZ=0.0; -STRAIN=0.0; -STRESS=0.0; -SEED=0; %seed number to generate a perturbed mesh -%X -%Y -%Z -% ,aaa -% ,ReaV -% ,vmax -% ,tt1 -% ,vmax2 -% ,tt2 -% VF1 -% ,VF2 -% ,VF3 -% ,vmax3 -% ,tt3 -% ,VF4 -% ,vmax4 -% ,vmax5 -% ,tt5 -% ,VF6 -% ,vmax6 -% ,tt6 -% ,dmax -% ,dmax2 - - % NK1 - % ,NK2 - % ,NK3 -% D2,PI,K1,K2,K3,DK1,DK2,DK3 -% PHI1,PHI2,PHI3,PHI4,AN - % CVROH,CVYNG,CVGFR,CORRCAF - %TENNORMZ,TENTANGX - % RKX,RKZ,VF -%FOR1 -%STR1 -%FOR2 -%STR2 -%FOR3 -%STR3 -%FOR4 -%STR4 -%ROHN - % BTA,GMA,IBT - % LCORX,LCORY,LCORZ,NPTX,NPTY,NPTZ,NPTOTAL - - % ,IPT - % MPJ,NPJ,LPJ,MPI,NPI,LPI - % IPT1,IPT2,IPT3,IPT4,IPT5,IPT6,IPT7,IPT8,IPT9 - % MP2,NP2,LP2,PHI - % PMI,PNI,PLI,PHIV - %xc,yc,vfarea,vfareal,time1 - %neib,iicont - % krs,epp,constB - % krsc,E2C,EMC - %g51589,gg51589,g89116,gg89116,ggg89116,giv89116 - % DESELX,DESELXMEDIO,SOMADESX,DESELY,DESELYMEDIO, & - %SOMADESY - -ini=1; -end - - - - diff --git a/src/ldem/initialization_DEM - Copia.m b/src/ldem/initialization_DEM - Copia.m deleted file mode 100644 index 372d17f..0000000 --- a/src/ldem/initialization_DEM - Copia.m +++ /dev/null @@ -1,15 +0,0 @@ - -function ini= ini_DEM - -global INT U V W - - - - % Variables setting - INT=10000; % total nodes - - U(3,INT)=0.0; % nodal displacement, U=x,V=y,W=z, i-1,i,i+1 time_ step - V(3,INT)=0.0; - W(3,INT)=0.0; - ini=1; - end diff --git a/src/ldem/initialization_DEM.m b/src/ldem/initialization_DEM.m deleted file mode 100644 index 372d17f..0000000 --- a/src/ldem/initialization_DEM.m +++ /dev/null @@ -1,15 +0,0 @@ - -function ini= ini_DEM - -global INT U V W - - - - % Variables setting - INT=10000; % total nodes - - U(3,INT)=0.0; % nodal displacement, U=x,V=y,W=z, i-1,i,i+1 time_ step - V(3,INT)=0.0; - W(3,INT)=0.0; - ini=1; - end diff --git a/src/ldem/main - Copia.m b/src/ldem/main - Copia.m deleted file mode 100644 index dc5f223..0000000 --- a/src/ldem/main - Copia.m +++ /dev/null @@ -1,15 +0,0 @@ -clear all -clc -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS - -ini=ini_DEM3() -CAF \ No newline at end of file diff --git a/src/ldem/main.m b/src/ldem/main.m deleted file mode 100644 index 082baf9..0000000 --- a/src/ldem/main.m +++ /dev/null @@ -1,14 +0,0 @@ -clear all -clc -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS - -ini=ini_DEM3() diff --git a/src/ldem/main1.m b/src/ldem/main1.m deleted file mode 100644 index 9c40583..0000000 --- a/src/ldem/main1.m +++ /dev/null @@ -1,536 +0,0 @@ -% boris -a= 1 -b = 2 -c= 3 - - -clear all -clc -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -global OU2 OU3 OU4 OU5 OU6 OU7 OU8 OU9 - -% -ini=ini_DEM3() %an initialization of the main variables was done -% -DATNAME=' '; -CONNAME=' '; -ANSNAME=' '; -RESNAME=' '; -DISNAME=' '; -POSNAME=' '; -ENENAME=' '; -%ARMANS(1000)=' '; -cont1=0; -cont2=0; -cont3=0; -cont4=0; -cont5=0; -cont6=0; -%counter of the linked the file writing -PR3=1; %Ansys File -PR67=1; %DIS and POS files -PR8=1; %ENE file -PR9=1; % SIM01 file inside CALRES -% - % CHARACTER*14 DATNAME,CONNAME - % CHARACTER*14 ANSNAME,RESNAME,DISNAME - % CHARACTER*14 POSNAME,ENENAME - % CHARACTER*14 ARMANS(10000000) - % integer cont1,cont2,cont3,cont4,cont5,cont6,B,bb -% -% -% ! -% OPEN (UNIT=10,ACCESS='SEQUENTIAL',FILE='DATA0.DAT',& -% & STATUS='OLD') -% -% ! -% ! READAT -----> L os dados que esto no arquivo DATA0.DAT - % CALL READAT0 - ini=read_dat0() % read the input data saved in DATA0.DAT - 'ini=read_dat0()' - % - % ! -% Close (10) -% ! -% !-------------------------------------------------------------------------- -% ! PREPARAO DAS VARIVEIS E CHAMAMENTO DAS SUBROTINAS PRELIMINARES -% !-------------------------------------------------------------------------- -% ! -% -% ! PREPVAR ----> setting of initial parameters -% CALL PREPVAR - ini=prepvar() %setting of initial parameters -'ini=prepvar()' - - % ! -% ! COORD ------> Gera coordenadas de um prisma -% CALL COORD -ini=COORD() % Build the nodes coordinate of prism with MxNxL modules -'ini=COORD()' - -% ! -% -% -% ! IMPERF -----> Impe uma aleatoriedade (imperfeio) s coordenadas -% CALL IMPERF -ini=IMPERF()% ! -'ini=IMPERF()' -% ! BOUND ------> Determina as condies de contorno da estrutura -% CALL BOUND -ini=BOUND()% ! -'ini=BOUND()' -% ! -% ! NODMASS ----> Atribui um valor de massa a cada n da estrutura -% CALL NODMASS -ini=NODMASS()% ! -'ini=NODMASS()' -% ! -% ! CONECTI ----> Gera conectividades das barras -% CALL CONECTI -ini=CONECTI()% ! -'ini=CONECTI()' -% ! -% ! CALAUX -----> Clculos auxiliares e determinao compr. cada barra -% CALL CALAUX -ini=CALAUX()% ! - -'ini=CALAUX()' -% -% -% OPEN (UNIT=70,ACCESS='SEQUENTIAL',FILE='BARI.txt',& -% & STATUS='UNKNOWN') -% -% DO I=1, NBT -% WRITE(70,'(I7,3X,3(E25.12,3X))') I,XB(I),YB(I),ZB(I) -% -% ENDDO -% -% CLOSE(70) -% Open the file for writing ('w' creates/overwrites, equivalent to STATUS='UNKNOWN') -fid = fopen('BARI.txt', 'w'); - -% Loop equivalent to DO I=1, NBT -for I = 1:NBT - % fprintf replaces WRITE with formatted output - % Format spec: %7d (I7), 3 spaces (3X), 3 floating-point values in scientific notation (E25.12) - fprintf(fid, '%7d %25.12E %25.12E %25.12E\n', I, XB(I), YB(I), ZB(I)); -end - -% Close the file -fclose(fid); -'The file BARI.txt was made' - - - -% ! -% ! NAYFES0 ---->BAR STIFNESS DETERMINATION -% CALL NAYFES0 -ini=NAYFES0() -'ini=NAYFES0()' -% ! RMEC ------->BAR STIFNESS DETERMINATION -% CALL RMEC -ini=RMEC() -'ini=RMEC()' - - -% --- Introduce random field into EP(B) ---------------------------------- -fid = fopen('arquivo_3lc_rnao_cv05', 'r'); -if fid == -1 - error('Console1: cannot open arquivo_3lc_rnao_cv05'); -% !arquivo_lc3l_rnao_cv100.txt -% !arquivo_3lc_rnao_cv05.txt -end -for I = 1:NBT - Phitemp = fscanf(fid, '%f', 1); - EP(I) = Phitemp * EP(I); - EM(I) = EP(I); % very important!!! -end -fprintf('%g\n', EP(1)); -fclose(fid); - -ini=CALCOEV() % computation of Mean value and variation -% coeficient of EP -'ini=CALCOEV()' -% ini= NEIBOUR() !WE NEED THIS SBROUTINE TO COMPUTE BARS -% THAT ARRIVING IN THE NODS i AND J OF THE b BAR -% 'ini=CALCOEV()' ( We need to implement) -% -% !-------------------------------------------------------------------------- -% ! ABRINDO OS ARQUIVOS DE SADA -% !-------------------------------------------------------------------------- -fid_CON = -1; fid_AN1 = -1; fid_RES = -1; -fid_DIS = -1; fid_POS = -1; fid_ENE = -1; -fid_Lei = -1; fid_EnB = -1; - -if OU2 > 0, fid_CON = fopen('LET.CON', 'w'); end -if OU3 > 0, fid_AN1 = fopen('LET.AN1', 'r'); end -if OU5 > 0, fid_RES = fopen('LET.RES', 'w'); end -if OU6 > 0, fid_DIS = fopen('LET.DIS', 'w'); end -if OU7 > 0, fid_POS = fopen('LET.POS', 'w'); end -if OU8 > 0, fid_ENE = fopen('LET.ENE', 'w'); end -if OU9 > 0, fid_Lei = fopen('Lei_Barra.TXT', 'w'); end -if OU9 > 0, fid_EnB = fopen('Energia_Barra.TXT','w'); end -% ! -% IF (OU2.GT.0)& -% & OPEN (UNIT=12,ACCESS='SEQUENTIAL',FILE='LET.CON',& -% & STATUS='UNKNOWN') -% ! -% IF (OU3.GT.0)& -% & OPEN (UNIT=13,ACCESS='SEQUENTIAL',FILE='LET.AN1',& -% & STATUS='UNKNOWN') -% -% IF (OU5.GT.0)& -% & OPEN (UNIT=15,ACCESS='SEQUENTIAL',FILE='LET.RES',& -% & STATUS='UNKNOWN') -% ! -% IF (OU6.GT.0)& -% & OPEN (UNIT=16,ACCESS='SEQUENTIAL',FILE='LET.DIS',& -% & STATUS='UNKNOWN') -% ! -% IF (OU7.GT.0)& -% & OPEN (UNIT=17,ACCESS='SEQUENTIAL',FILE='LET.POS',& -% & STATUS='UNKNOWN') -% ! -% IF (OU8.GT.0)& -% & OPEN (UNIT=18,ACCESS='SEQUENTIAL',FILE='LET.ENE',& -% & STATUS='UNKNOWN') -% -% ! -% IF (OU9.GT.0)& -% & OPEN (UNIT=19,ACCESS='SEQUENTIAL',FILE='Lei_Barra.TXT',& -% & STATUS='UNKNOWN') -% -% ! -% IF (OU9.GT.0)& -% & OPEN (UNIT=20,ACCESS='SEQUENTIAL',FILE='Energia_Barra.TXT',& -% & STATUS='UNKNOWN') -% !-------------------------------------------------------------------------- -% IF (OU2.GT.0) THEN -% ! WRICON -----> Gravao de informao de entrada no arquivo CONNAME -% CALL WRICON -% ! We close(2) in the end of the Main program -% END IF -% !-------------------------------------------------------------------------- -% ! LEITURA NOMES DE ARQUIVOS DO ANSYS -% !-------------------------------------------------------------------------- -% -% ! -% IF (OU3.GT.0) THEN -% DO 30 III=1,(NSTEP/OU3)+1 -% READ (13,*) ARMANS(III) -% 30 CONTINUE -% CLOSE (13) -% ! -% -% !-------------------------------------------------------------------------- -% ! GRAVAO DO PRIMEIRO ARQUIVO DO ANSYS -% !-------------------------------------------------------------------------- -% I3=1 -% OPEN (UNIT=13,ACCESS='SEQUENTIAL',FILE=ARMANS(I3),& -% & STATUS='UNKNOWN') -% WRITE (13,*) '!ARQUIVO NO TEMPO =',TIME -% CALL ANSYS (13,CONT1,CONT2,CONT3,CONT4,CONT5,CONT6) -% CLOSE (13) -% END IF - - -% ------------------------------------------------------------------------- -if OU2 > 0 - % WRICON -----> writes input info to CONNAME - ini=WRICON(fid_CON); % stream passed in (or use global fid) -'ini=WRICON' -end - -% ------------------------------------------------------------------------- -% READ FILENAMES OF ANSYS FILES -% ------------------------------------------------------------------------- -I3 = 1; -if OU3 > 0 -ARMANS = cell(floor(NSTEP/OU3) + 1, 1); -for III = 1:floor(NSTEP/OU3) + 1 -ARMANS{III} = strtrim(fgetl(fid_AN1)); % l uma linha e remove espaos - end - fclose(fid_AN1); - - - - % --- Write first ANSYS file ----------------------------------------- - fid_AN1 = fopen(ARMANS{I3}, 'w'); - fprintf(fid_AN1, '!ARQUIVO NO TEMPO = %g\n', TIME); - - - - ini= ANSYS(fid_AN1, cont1, cont2, cont3, cont4, cont5, cont6); - 'ini=ANSYS' - fclose(fid_AN1); -end - -% -% !-------------------------------------------------------------------------- -% ! CONCLUIU-SE A MONTAGEM DO MODELO. INICIA-SE A INTEGRAO PASSO A PASSO -% !-------------------------------------------------------------------------- -% ! LOOP PRINCIPAL DE INTEGRAO -% !-------------------------------------------------------------------------- -% -% -% -% WRITE (*,*) -% WRITE (*,*) ' *** PERFORMING THE INTEGRATION STEP BY STEP ** ' -% WRITE (*,*) -% ! -% STEPP=1 -% ! -% DO 60 STEP = STEPP,NSTEP -% ! -% !-------------------------------------------------------------------------- -% ! Escreve uma informao de controle na tela em cada passo de integrao -% !-------------------------------------------------------------------------- -% WRITE (*,40) STEP -% 40 FORMAT (' STEP ======================> ',I7,' / ',I2) -% -% ! -% !-------------------------------------------------------------------------- -% ! Controle de mudana de amortecimento -% !-------------------------------------------------------------------------- -% IF (STEP.EQ.NDAMF) THEN -% DF1=DF2 -% DMP1=1.0D00-DF2*DT/2.0D00 -% DMP2=1.0D00+DF2*DT/2.0D00 -% END IF -% ! -% !-------------------------------------------------------------------------- -% ! Incremento do tempo -% !-------------------------------------------------------------------------- -% TIME=TIME+DT -% WRITE (*,50) TIME -% 50 FORMAT (' TIME ======================> ',F12.8) -%------------------------------------------------------------------------- -% ! Avaliao das foras e determinao da nova configurao -% !-------------------------------------------------------------------------- -% ! CALOAD -----> Clculo das cargas sobre os ns -% CALL CALOAD -% write(*,*) 'caload' -% ! -% ! Especifica-se a carga em cada tempo e calcula-se a energia externa -% ! fornecida ao sistema. Em funo do exemplo tem-se que modificar esta -% ! subrotina. -% ! -% !-------------------------------------------------------------------------- -% ! CABAR ------> compute de nodal forces in the structure, in CABAR we have a loop over all the bars and -% ! we call the constit subroutine to compute the forces in each bars -% CALL CABAR -% write(*,*) 'cabar' -% ! -% !-------------------------------------------------------------------------- -% ! IGN012 -----> Clculo das coordenadas no tempo TIME aplicando -% ! diferenas finitas centrais na equao do movimento -% CALL IGN012 -% ! Nesta subrotina realiza-se a integrao via mtodo das diferenas -% ! finitas centrais. Tem-se um loop sobre os ns. Entra-se com as foras -% ! calculadas em CABAR e com a configurao do sistema nos dois tempos -% ! anteriores e determina-se a configurao no tempo novo. -% ! -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% ------------------------------------------------------------------------- -% MODEL ASSEMBLY COMPLETE. START STEP-BY-STEP INTEGRATION -% ------------------------------------------------------------------------- -fprintf('\n *** PERFORMING THE INTEGRATION STEP BY STEP ** \n\n'); - -STEPP = 1; - -for STEP = STEPP:NSTEP - - fprintf(' STEP ======================> %7d / %2d\n', STEP, 0); - - % --------------------------------------------------------------------- - % Damping change control - % --------------------------------------------------------------------- - if STEP == NDAMF - DF1 = DF2; - DMP1 = 1.0 - DF2 * DT / 2.0; - DMP2 = 1.0 + DF2 * DT / 2.0; - end - - % --------------------------------------------------------------------- - % Time increment - % --------------------------------------------------------------------- - TIME = TIME + DT; - fprintf(' TIME ======================> %12.8f\n', TIME); - fprintf('\n'); - % --------------------------------------------------------------------- - % Evaluate forces and determine new configuration - % --------------------------------------------------------------------- - ini=CALOAD(); - 'ini=CALOAD()' - - ini=CABAR(fid_Lei); - 'ini=CABAR()' - - ini=IGN012(); % central finite differences integration - 'ini=IGN012()' -% !-------------------------------------------------------------------------- -% ! Gerao dos arquivos de sada -% !-------------------------------------------------------------------------- -% ! SADA - VISUALIZAO NO ANSYS -% !-------------------------------------------------------------------------- -% IF (PR3.EQ.OU3) THEN -% I3=I3+1 -% PR3=1 -% OPEN (UNIT=11,ACCESS='SEQUENTIAL',FILE=ARMANS(I3), & -% & STATUS='UNKNOWN') -% WRITE (11,*) '!ARQUIVO NO TEMPO =',TIME -% CALL ANSYS (11,CONT1,CONT2,CONT3,CONT4,CONT5,CONT6) -% CLOSE (11) -% ELSE -% PR3=PR3+1 -% END IF -% ! -% !-------------------------------------------------------------------------- -% ! SADA - REAES NODAIS -% !-------------------------------------------------------------------------- -% ! write(*,*) 'antes de calres' -% ! CALRES -----> Clculo de resultados que sero gravados em RESNAME -% CALL CALRES -% ! write(*,*) 'calres' -% ! -% !-------------------------------------------------------------------------- -% ! SADA - CONTROLE DE DESLOCAMENTOS, VELOCIDADES E ACELERAES -% !-------------------------------------------------------------------------- -% ! -% IF (PR67.EQ.OU6) THEN -% CALL WRIDIPO -% !! Esta subrotina grava os arquivos *.dis e *.pos que tem os valores dos -% ! deslocamentos, velocidades e aceleraes nos ns de controle. -% ! -% PR67=1 -% ELSE -% PR67=PR67+1 -% END IF -% !-------------------------------------------------------------------------- -% ! SADA - AVALIAO DA ENERGIA -% !-------------------------------------------------------------------------- -% ! -% ! ENERG2 -----> Clculo das energias que sero gravadas em ENENAME -% CALL ENERG2 -% ! Esta subrotina calcula em cada tempo as energias que esto se -% ! transformando no processo. -% ! -% IF (PR8.EQ.OU8) THEN -% CALL WRIENE -% ! Esta subrotina grava o arquivo *.ene que tem os valores das energias. -% ! -% PR8=1 -% ELSE -% PR8=PR8+1 -% END IF -% -% ! -% !-------------------------------------------------------------------------- -% 60 CONTINUE -% !-------------------------------------------------------------------------- -% ! -% IF (RUN.EQ.NRUN) GO TO 70 -% ! -% IF (OU5.GT.0) CLOSE (5) -% IF (OU6.GT.0) CLOSE (6) -% IF (OU7.GT.0) CLOSE (7) -% IF (OU8.GT.0) CLOSE (8) -% ! -% ! -% 70 CONTINUE -% ! -% -% WRITE (*,*) -% WRITE (*,*) ' ****************** THE END ******************* ' -% WRITE (*,*) -% -% close(22) -% close(2) -% end program Console1 - % --------------------------------------------------------------------- - % Generate output files - % --------------------------------------------------------------------- - - % Output - ANSYS visualisation - if PR3 == OU3 - I3 = I3 + 1; - PR3 = 1; - fid11 = fopen(ARMANS(I3), 'w'); - fprintf(fid11, '!ARQUIVO NO TEMPO = %g\n', TIME); - [CONT1, CONT2, CONT3, CONT4, CONT5, CONT6] = ... - ini==ANSYS(fid11, CONT1, CONT2, CONT3, CONT4, CONT5, CONT6); - 'ini=ANSYS()' - fclose(fid11); - else - PR3 = PR3 + 1; - end - - - % --------------------------------------------------------------------- - % Output - control of displacements, velocities and accelerations - % --------------------------------------------------------------------- - if PR67 == OU6 - % Output - nodal reactions - % CALRES -----> Compute results to be written to RESNAME - ini=CALRES(); - 'ini=CALRES()' - - ini=WRIDIPO(fid_DIS, fid_POS); - 'ini=WRIDIPO' - PR67 = 1; - else - PR67 = PR67 + 1; - end - - % --------------------------------------------------------------------- - % Output - energy evaluation - % --------------------------------------------------------------------- - % ENERG2 -----> Compute energies to be written to ENENAME - ini=ENERG2(fid_EnB); - 'ini=ENERG2()' - if PR8 == OU8 - ini=WRIENE(fid_ENE); - 'ini=WRIENE' - - PR8 = 1; - else - PR8 = PR8 + 1; - end - -end -% ------------------------------------------------------------------------- - -if RUN == NRUN - % GO TO 70 -else - if OU5 > 0 && fid15 >= 0, fclose(fid15); end - if OU6 > 0 && fid_DIS>= 0, fclose(fid_DIS); end - if OU7 > 0 && fid_POS >= 0, fclose(fid_POS); end - if OU8 > 0 && fid_ENE >= 0, fclose(fid_ENE); end -end - -% 70 CONTINUE - -fprintf('\n'); -fprintf(' ****************** THE END ******************* \n'); -fprintf('\n'); - -% Close remaining open files -if fid19 >= 0, fclose(fid19); end -if fid20 >= 0, fclose(fid20); end -if fid12 >= 0, fclose(fid12); end - -% End of program Console1 - - - diff --git a/src/ldem/mainDEM.m b/src/ldem/mainDEM.m deleted file mode 100644 index f5fd5bd..0000000 --- a/src/ldem/mainDEM.m +++ /dev/null @@ -1,404 +0,0 @@ -clear all -clc - -% Configurações -INT = 10000; % total number of nodes -IBT = 100000; % total number of bars/elements -U(3, INT) = 0.0; % nodal displacements in the x direction, at (i-1), (i), (i+1) -V(3, INT) = 0.0; % y direction -W(3, INT) = 0.0; % z direction -U0(INT) = 0.0; % initial displacements -V0(INT)=0.0; -W0(INT)=0.0; -BDX(INT)=0.0;% Boundary conditions (1=fix, 0=free) -BDY(INT)=0.0;% nodal velocities -BDZ(INT)=0.0; -VLX(INT)=0.0;% nodal velocities -VLY(INT)=0.0; -VLZ(INT)=0.0; -ACX(INT)=0.0;% nodal acelerations -ACY(INT)=0.0; -ACZ(INT)=0.0; -FRX(INT)=0.0;% nodal force computed in each step -FRY(INT)=0.0; -FRZ(INT)=0.0; -FX(INT)=0.0;% nodal forces acumulated -FY(INT)=0.0; -FZ(INT)=0.0; -MAS(INT)=0.0; % nodal mass with correction by border effect -MSS(INT)=0.0;% nodal mass with correction without border effect -% -CN(2,INB)=0; %C(1,INB)=conect(i), C(2,INB)=conect(j) -ENR(INB)=0.0; -EDG(INB)=0.0; -LI(INB)=0.0; -EP(INB)=0.0; -EM(INB)=0.0; -SS(INB)=0.0; -DSS(INB)=0.0; -EPRB(INB)=0.0; -EPRB(INB)=0.0; -E1(INB)=0.0; -E2(INB)=0.0; -KR(INB)=0.0; -KR1(INB)=0.0; -DM(INB)=true; -FS(INB)=true; -DM1(INB)=true; -FS1(INB)=true; -EN(INB)=0.0 -ansysColor(INB)=0 -DEQB(INB)=0.0; -YNGB(INB)=0.0; -GFRB(INB)=0.0; -F(INB)=0.0; -LCRB(INB)=0.0; -TR(INB)=0.0; - - - COMMON /SIM/ CAF,CUT,DT,GFR,DEQ,LCR,SEED - COMMON /COM0/ TEST,EST,Label - COMMON /COM1/ M,N,L,M1,N1,L1,MNL - COMMON /COM2/ NNO,NNS,NNT,NBA,NBS,NBT - COMMON /COM3/ INCO,NCON - COMMON /COM4/ OU2,OU3,OU4,OU5,OU6,OU7,OU8,OU9 - COMMON /COM5/ PR3,PR4,PR5,PR67,PR8,PR9 - COMMON /COM6/ STEP,NSTEP,NDAMF,RUN,NRUN - COMMON /COM7/ LCO,DF1,DF2,DMP1,DMP2,TDAF,CON - COMMON /COM8/ TIME,TTOT - COMMON /COM9/ PSN,ROH,YNG,EPR - COMMON /CO10/ EPMAX,EPMIN,MEAN,COEV - COMMON /CO11/ ENEX,ENCN,ENEL,ENGD,ENDP,ENIN,DEN,DERIV - COMMON /CO12/ REACAOX,REACAOY,REACAOZ,aaa,ReaV,vmax,tt1,vmax2,tt2, & - &VF1,VF2,VF3,vmax3,tt3,VF4,vmax4,vmax5,tt5,VF6,vmax6,tt6,dmax,dmax2 - - COMMON /CO13/ XB,YB,ZB - COMMON /CO14/ NK1,NK2,NK3 - COMMON /CO15/ D2,PI,K1,K2,K3,DK1,DK2,DK3 - COMMON /CO16/ PHI1,PHI2,PHI3,PHI4,AN - COMMON /CO17/ CVROH,CVYNG,CVGFR,CORRCAF - COMMON /CO18/ TENNORMZ,TENTANGX - COMMON /CO19/ RKX,RKZ,VF - COMMON /CO20/ STRAIN,STRESS - COMMON /CO21/ FOR1,STR1,FOR2,STR2,FOR3,STR3,FOR4,STR4 - COMMON /CO22/ ROHN - COMMON /CO23/ BTA,GMA,IBT - COMMON /CO24/ LCORX,LCORY,LCORZ,NPTX,NPTY,NPTZ,NPTOTAL - COMMON /CO25/ UBAR,VBAR,WBAR,IPT - COMMON /CO26/ MPJ,NPJ,LPJ,MPI,NPI,LPI - COMMON /CO27/ IPT1,IPT2,IPT3,IPT4,IPT5,IPT6,IPT7,IPT8,IPT9 - COMMON /CO28/ X,Y,Z - COMMON /CO29/ MP2,NP2,LP2,PHI - COMMON /CO30/ PMI,PNI,PLI,PHIV - COMMON /CO31/ xc,yc,vfarea,vfareal,time1 - COMMON /CO34/ neib,iicont - COMMON /CO35/ krs,epp,constB - COMMON/C036/krsc,E2C,EMC - common /g/g51589,gg51589,g89116,gg89116,ggg89116,giv89116 - COMMON/str/DESELX,DESELXMEDIO,SOMADESX,DESELY,DESELYMEDIO, & - & SOMADESY - -DOUBLE PRECISION DESELX,DESELXMEDIO,SOMADESX - DOUBLE PRECISION DESELY,DESELYMEDIO,SOMADESY - integer neib(420000,30),iicont - double precision krs,epp,g51589,gg51589,g89116,gg89116,ggg8911, & - & constB - double precision giv89116 - double precision krsc,e2c(inb),emc(inb) - - DOUBLE PRECISION U(3,INN),V(3,INN),W(3,INN),U0(INN),V0(INN), & - &W0(INN),VLX(INN),VLY(INN),VLZ(INN),ACX(INN), & - &ACY(INN),ACZ(INN),FRX(INN),FRY(INN),FRZ(INN), & - &FX(INN),FY(INN),FZ(INN),MAS(INN),MSS(INN), ROMP(INB,1), & - &ROMP_OLD(INB,1) -! - DOUBLE PRECISION UBAR,VBAR,WBAR,MPJ,MP2,NP2,LP2,NPJ,LPJ, & - &MPI,NPI,LPI,PHI(INN),PMI,PNI,PLI,IPT1,IPT7,IPT8,IPT2,IPT3, & - &IPT4,IPT5,IPT6 -! - INTEGER BDX(INN),BDY(INN),BDZ(INN),NPTOTAL -! - INTEGER CN(2*INB) -! - DOUBLE PRECISION ENR(INB),EDG(INB),LI(INB),EP(INB),E1(INB), & - &E2(INB),SS(INB),EM(INB),KR(INB),DSS(INB),EPRB(INB),EN(2,INB), & - &ansysColor (INB), DEQB(INB), F(INB), YNGB(INB),GFRB(INB), & - &LCRB(INB),KR1(INB) -! - DOUBLE PRECISION LCORX,LCORY,LCORZ -! - LOGICAL DM(INB),FS(INB),DM1(INB),FS1(INB),TR(INB) -! - INTEGER SEED - INTEGER TEST,EST,Label - INTEGER M,N,L,M1,N1,L1,MNL - INTEGER NNO,NNS,NNT,NBA,NBS,NBT - INTEGER NCON(INCON),INCO - INTEGER OU2,OU3,OU4,OU5,OU6,OU7,OU8,OU9 - INTEGER PR3,PR4,PR5,PR67,PR8,PR9 - INTEGER STEP,NSTEP,NDAMF,RUN,NRUN - INTEGER NK1,NK2,NK3 - INTEGER NBTX,NBTY,NBTZ,IBT - INTEGER IBTX,IBTY,IBTZ -! - DOUBLE PRECISION CAF,DT,GFR,RFC,LCR,CUT - DOUBLE PRECISION LCO,DF1,DF2,DMP1,DMP2,TDAF,CON - DOUBLE PRECISION TIME,TTOT - DOUBLE PRECISION PSN,ROH,YNG,EPR - DOUBLE PRECISION EPMAX,EPMIN,MEAN,COEV - DOUBLE PRECISION ENEX,ENCN,ENEL,ENGD,ENDP,ENIN,DEN,DERIV - DOUBLE PRECISION REACAOX,REACAOY,REACAOZ,aaa,ReaV,vmax,tt1,vmax2, & - & tt2,VF1,VF2,VF3,vmax3,tt3,VF4,vmax4,tt4,VF5,vmax5,tt5,VF6,vmax6, & - & tt6,dmax,dmax2 - DOUBLE PRECISION XB(INB),YB(INB),ZB(INB) - DOUBLE PRECISION D2,PI,K1,K2,K3,DK1,DK2,DK3 - DOUBLE PRECISION PHI1(16,16,16),PHI2(16,16,16) - DOUBLE PRECISION PHI3(16,16,16),PHI4(16,16,16) - DOUBLE PRECISION AN(16,16,16) - DOUBLE PRECISION CVROH,CVYNG,CVGFR,CORRCAF - DOUBLE PRECISION TENNORMZ,TENTANGX - DOUBLE PRECISION RKX,RKZ,VF -! - DOUBLE PRECISION FOR1,STR1,FOR2,STR2,FOR3,STR3,FOR4,STR4 -! - DOUBLE PRECISION STRESS,STRAIN - DOUBLE PRECISION ROHN(INN) - DOUBLE PRECISION GMA,BTA - DOUBLE PRECISION xc,yc,vfarea,vfareal,time1 - - - n_total = 5000; % Número total de elementos - velocidade1 = 5; % Velocidade de transição entrada potencial(1-10) - velocidade2 = 5; % Velocidade de transição saida potencial (1-10) - expoente = 1; % Expoente da lei de potência - - dados =gerar_transicao_dupla2(n_total, velocidade1, velocidade2, expoente); - %dados = gerar_transicao_uniforme_potencial(n_total, velocidade, expoente); - %unif = rand(n_total /2,1); - %dados=[dados';unif]'; n_total=size(dados,2); - % Criar janela com subplots para visualização - figure('Position', [100, 100, 1200, 800]); - - % Subplot 1: Histograma completo - %subplot(2, 3, [1, 4]); - subplot(2,1,1); - histogram(dados, 100, 'Normalization', 'pdf', 'FaceColor', [0.3, 0.6, 0.9]); - xlabel('Value'); - ylabel('Density'); - title(sprintf('Uniform + Power law distribution + Uniform (N =%d)', n_total)); - grid on; - - % Subplot 4: Evolução temporal dos valores - %subplot(2, 3, [5, 6]); - subplot(2,1,2); - plot(1:n_total, dados', '.', 'MarkerSize', 2); - xlabel('N'); - ylabel('Value'); - title('Evolução Temporal dos Valores'); - grid on; - - % Adicionar linha de tendência móvel - window_size = 500; - media_movel = movmean(dados', window_size); - hold on; - plot(1:n_total, media_movel, 'r-', 'LineWidth', 2); - legend('Data', sprintf('Moving average (W=%d)', window_size), 'Location', 'best'); - hold off; - - % Estatísticas descritivas - fprintf('\n--- Estatísticas ---\n'); - fprintf('Média: %.4f\n', mean(dados)); - fprintf('Mediana: %.4f\n', median(dados)); - fprintf('Desvio padrão: %.4f\n', std(dados)); - fprintf('Mínimo: %.4f\n', min(dados)); - fprintf('Máximo: %.4f\n', max(dados)); - - % Análise da transição - % fprintf('\n--- Análise da Transição ---\n'); - - % % Dividir em 5 segmentos - % segmentos = 5; - % for k = 1:segmentos - % idx_inicio = round((k-1)*n_total/segmentos) + 1; - % idx_fim = round(k*n_total/segmentos); - % segmento = dados(idx_inicio:idx_fim); - % - % % Calcular média e mediana - % fprintf('Segmento %d (%.0f%%-%.0f%%): Média=%.4f, Mediana=%.4f, Coef.Variação=%.4f\n', ... - % k, (k-1)*100/segmentos, k*100/segmentos, ... - % mean(segmento), median(segmento), std(segmento)/mean(segmento)); - % end -%end -%%%%%%%%%%%%%%%% NATURAL TIME -Q=dados'; -% 1. Configuração Inicial e Medida de Energia -% O artigo sugere que a medida adequada é Qk = A^1.5, onde A é a amplitude [4, 5]. -%Q = Amp.^1.5; -Lin = length(Q); - -% Definição de PI_c (ruído uniforme) - calculada uma única vez -fi = 0:0.025:0.5; -ww = 2 * pi * fi; -pi_c = 18./(5*ww.^2) - 6*cos(ww)./(5*ww.^2) - 12*sin(ww)./(5*ww.^3); -pi_c(1) = 1; % Limite quando w -> 0 - -% Pré-alocação de variáveis para velocidade -kapa1 = zeros(Lin, 1); -Snt = zeros(Lin, 1); -Srev = zeros(Lin, 1); -D = zeros(Lin, 1); - -% Loop principal (Evolução dos eventos) -% Nota: Calculamos os parâmetros para cada janela de tamanho k -for k = 1:Lin - % 1. Recorte e Normalização da janela atual - Q_k = Q(1:k); - An = sum(Q_k); - pk = Q_k / An; % Energias normalizadas P_k [4] - - % 2. Vetor de Tempo Natural chi_k [4] - xk = (1:k)' / k; - - % 3. Cálculo Vetorizado de Kappa1 (Variância) - k1 = sum(pk .* (xk.^2)); - k2 = sum(pk .* xk); - kapa1(k) = k1 - k2^2; - - % 4. Cálculo Vetorizado das Entropias (S e S_inv) [1, 3] - % Usando logaritmo natural 'log' conforme recomendado [2] - Snt(k) = sum(pk .* xk .* log(xk)) - k2 * log(k2); - - % Para S_inv, invertemos a ordem das energias P_k -> P_{N-k+1} - pk_rev = flipud(pk); - k2_rev = sum(pk_rev .* xk); - Srev(k) = sum(pk_rev .* xk .* log(xk)) - k2_rev * log(k2_rev); - - % 5. Cálculo Vetorizado de PI(phi) e Distância D - % Criamos uma matriz para evitar o loop 'b' - % xk: (k x 1), ww: (1 x n_fi) -> exp_arg: (k x n_fi) - exp_arg = complex(0, 1) * (xk * ww); - Pi_phi = abs(pk' * exp(exp_arg)).^2; % Produto matricial calcula todos os fi de uma vez - - D(k) = mean(abs(Pi_phi - pi_c)); - - % Convertional time - %ct(k)=tpico(k); - % Natural time - nt(k)=k; - - % Feedback de progresso (opcional) - % if mod(k, 1000) == 0, disp(['Progresso: ', num26(k/Lin*100), '%']); end -end -% -figure() -% nt=ct; -plot(nt,kapa1,'r') -hold on -plot(nt,Snt,'b') -plot(nt,Srev,'m') -plot(nt,D,'g') -grid on - -plot([0 k],[0.07 0.07],'r--') -plot([0 k],[0.096 0.096],'b--') -plot([0 k],[0.02 0.02],'g--') -% ylim([0 0.3]) -legend('\kappa_1','S','S_r_e_v','D','0.07','0.096','0.02') -xlabel('N','FontName','Times New Roman','FontSize',18,'Rotation',0) -ylabel('\kappa_1, S, S_r_e_v, D','FontName','Times New Roman','FontSize',18,'Rotation',90) - -%% ENTROPIAS SHENNON AND HKL - -%Q=dados'; -Lin = length(Q); - -% 2. Pré-alocação de variáveis para desempenho -Hs = zeros(Lin, 1); -Hkl = zeros(Lin, 1); - -% 3. Cálculo Evolutivo (Abordagem de Janela Crescente) -% Conforme o artigo, a janela de detecção inicia no primeiro evento e -% cresce a cada novo hit para capturar o comportamento histórico [3, 6]. -for K = 2:Lin - % Energias da janela atual (do evento 1 até K) - current_Q = Q(1:K); - An = sum(current_Q); % Soma total da área/energia da janela [6, 7] - - % Vetor de probabilidade pK (distribuição de massa de ocorrência) [2] - % pK(k) é o k-ésimo elemento do vetor de probabilidade [2] - pk = current_Q / An; - - % --- Entropia de Shannon (Hs) --- - % Calculada para o hit K usando o logaritmo natural (ln) conforme orientação [2, 5] - % Hs(K) = -sum( pK * ln(pK) ) [2, 6] - Hs(K) = -sum(pk .* log(pk + eps)); - - % --- Entropia de Kullback-Leibler (Hkl) --- - % Expressa a probabilidade do evento atual condicionada pelo anterior [8] - % HKL(K) = -sum_{k=2}^{K} pK(k) * ln( pK(k) / pK(k-1) ) [6] - pk_atual = pk(2:end); - pk_anterior = pk(1:end-1); - Hkl(K) = -sum(pk_atual .* log((pk_atual + eps) ./ (pk_anterior + eps))); -end - -% 4. Valores Cumulativos (Sigma Hs e Sigma Hkl) -% O artigo também avalia a sensibilidade dos valores acumulados ao dano [1, 8]. -sum_Hs = cumsum(Hs); -sum_Hkl = cumsum(Hkl); - -% 5. Visualização dos Resultados -figure; -%subplot(2,1,1); -plot(Hs); -ylabel('\itH_s','FontName','Times New Roman','FontSize',18,'Rotation',90) -%set(gca, 'XTickLabel', []); % Remove os rótulos do eixo x grid on; -grid on -yyaxis right -ax = gca; -ax.YColor = 'k'; % define a cor do eixo Y direito como preto -hold on -%subplot(2,1,2); -plot(Hkl); grid on; -ylabel('\itH_{KL}','FontName','Times New Roman','FontSize',18,'Rotation',90) -legend('\itH_s','itH_{KL}') - -%% TSALLIS ENTROPY -win=50; %initial data size -k=1; -Amp=dados'; -tpico=1:1:size(dados,2) ; tpico=tpico'; -for jj=win+1:1:size(dados,2) -%Interval=[tpico(jj-win) tpico(jj)]; % SLIDING WINDOWN -Interval=[1 jj]; % -Mi=0.05; % division on the Amplitude distribution -[Datavalue, A_fit, lmbda_fit, q_fit, resultados_fit,p2]=EA_Calc_q(Amp,tpico,Interval,Mi,'NHist'); -A(k)=A_fit; -lmbda(k)=lmbda_fit; -q(k)=q_fit; -R(k)=resultados_fit.R_squared; -TPico(k)=jj; -p22(k)=p2; -k=k+1; -end -%% -figure; -plot(TPico,q,'r') -ylabel('q','FontName','Times New Roman','FontSize',20,'Rotation',90) -yyaxis right -hold on -plot(TPico,1./lmbda,'b') -legend('q','lambda') -xlabel('N','FontName','Times New Roman','FontSize',20,'Rotation',0) -ylabel('lambda','FontName','Times New Roman','FontSize',20,'Rotation',90) - -% -figure; -scatter(1./lmbda, q, 8, TPico, 'o'); % 50 = tamanho dos marcadores -colorbar; -xlabel('1/\it\lambda', 'FontSize', 12); -ylabel('\itq', 'FontSize', 12); -grid on -box on -ylabel(colorbar, 'Time [s]'); - - diff --git a/src/ldem/prepvar.m b/src/ldem/prepvar.m deleted file mode 100644 index 799c967..0000000 --- a/src/ldem/prepvar.m +++ /dev/null @@ -1,38 +0,0 @@ - -function ini=prepvar() -% PREPVAR Inicializa variáveis de tempo, energia e dimensões derivadas do modelo. -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED -%--------------------------------------------------- - TIME=0.0D00; - ENEX=0.0D00; - ENIN=0.0D00; - ENCN=0.0D00; - ENDP=0.0D00; - ENGD=0.0D00; - DERIV=0.0D00; - EPMAX=0.0D00; - EPMIN=9.9D99; -% - M1=M-1; - N1=N-1; - L1=L-1; - MNL=M*N*L; -% - DMP1=1.0D00-DF1*DT/2.0D00; - DMP2=1.0D00+DF1*DT/2.0D00; - NSTEP=int32(TTOT/DT); - NDAMF=int32(TDAF/DT); - CAF=0.1385D00; - - % - ini=1; - end diff --git a/src/ldem/read_dat0.m b/src/ldem/read_dat0.m deleted file mode 100644 index 9a89703..0000000 --- a/src/ldem/read_dat0.m +++ /dev/null @@ -1,132 +0,0 @@ - -function ini= read_dat0() -% READ_DAT0 Lê os dados de entrada dos arquivos DATNAME(I). -global INT INB U V W U0 V0 W0 BDX BDY BDZ VLX VLY VLZ -global ACX ACY ACZ FRX FRY FRZ FX FY FZ MAS MSS CN ENR -global EDG E1 E2 LI DEQB F YNGB GFRB LCRB EPRB EP SS EM -global EN KR KR1 DSS DM FS CAF DT GFR DEQ LCR TEST EST -global DF DF1 DF2 DMP1 DMP2 TDAF CON M N L M1 N1 L1 MNL -global NNO NNS NNT NBA NBS NBT INCO NCON STEP NSTEP NDAMF -global RUN NRUN LCO TIME TTOT PSN ROH YNG EPR EPMAX EPMIN -global MEAN COEV ENEX ENCN ENEL ENGD ENDP ENIN DEN DERIV -global XB YB ZB UBAR VBAR WBAR REACAOX REACAOY REACAOZ -global STRAIN STRESS SEED C -global OU2 OU3 OU4 OU5 OU6 OU7 OU8 OU9 - -% ! DATA: 27/04/2024 -% ! AUTOR: IGNACIO ITURRIOZ -% ! -% ! Esta subrotina lê os dados de entrada dos arquivos DATNAME(I). -% ! -% !-------------------------------------------------------------------------- -% ! VARIÁVEIS LIDAS DO ARQUIVO DE ENTRADA DATNAME(I) -% !-------------------------------------------------------------------------- -% ! -% ! TEST = (INTEGER) NÚMERO DO TESTE A SER REALIZADO -% ! SEED= (INT) SEMENTE DE GERACAO DE NUMEROS ALEATORIOS -% ! -% ! LCo = (REAL) COMPRIMENTO DA ARESTA DO MÓDULO CÚBICO SEM DEFORMAR -% ! -% ! M, N, L = (INTEGER) DIMENSÕES MODULARES DAS ARESTAS DO PRISMA. -% ! REPRESENTAM O NÚMERO DE NÓS PRESENTES NAS ARESTAS DO PRISMA -% ! PARALELAS AOS EIXOS CARTESIANOS X,Y,Z, RESPECTIVAMENTE. -% ! -% ! DF1, DF2 = (REAL) COEFICIENTES DE AMORTECIMENTO PROPORCIONAL À MASSA -% ! INICIAL E FINAL M(X)''+DF(X)'=FX -% ! -% ! TDAF = (REAL) TEMPO DE TROCA DO AMORTECIMENTO DF1 PARA DF2 -% ! -% ! CON = (REAL) AMORTECIMENTO CONSIDERADO DENTRO DA EQUAÇÃO CONSTITUTIVA -% ! (EST=1) -% ! -% ! DT = (REAL) INTERVALO DE INTEGRAÇÃO. DT<=0.6*LCO/C0, SENDO C0=(E/RO)**.5 -% ! -% ! TTOT = (REAL) TEMPO TOTAL DE INTEGRAÇÃO -% ! -% ! INCO = (INTEGER) NÚMERO DE PONTOS DE CONTROLE A CONSIDERAR (INCO<=INCON) -% ! -% ! NCON(I) = (INTEGER) I-ÉSIMO PONTO DE CONTROLE A CONSIDERAR (I=1,INCO) -% ! -% ! OU2, OU3, OU4, OU5, OU6, OU7, OU8, OU9 = (INTEGER) CONTROLE DA EDIÇÃO DE -% ! ARQUIVOS DE SAÍDA -% ! OU2,OU3,OU4,OU5,OU6,OU7,OU8,OU9 = 0, ARQUIVO NÃO SE IMPRIME -% ! OU2 = n, ARQUIVO SE IMPRIME -% ! OU3 = n, SE IMPRIME 1 ARQUIVO NO TEMPO ZERO E ARQUIVOS A CADA n -% ! PASSOS DE INTEGRAÇÃO -% ! OU4 = n, SE IMPRIMEM ARQUIVOS A CADA n PASSOS DE INTEGRAÇÃO -% ! OU5,OU6,OU7,OU8,OU9 = n, SE IMPRIMEM VALORES A CADA n PASSOS DE -% ! INTEGRAÇÃO -% ! -% ! PSN = (REAL) COEFICIENTE DE POISSON -% ! -% ! ROH = (REAL) MASSA ESPECÍFICA -% ! -% ! YNG = (REAL) MÓDULO DE YOUNG -% ! -% ! GFR = (REAL) ENERGIA ESPECÍFICA DE FRATURA -% ! -% ! DEQ= (REAL) Equivalence Distance -% ! -% !-------------------------------------------------------------------------- -% ! FORMATO DO ARQUIVO DE ENTRADA DATNAME(I) -% !-------------------------------------------------------------------------- -% ! TEST,LCO,M,N,L, -% ! DF1,DF2,TDAF,CON, -% ! DT,TTOT, -% ! INCO,NCON(1),NCON(2),...,NCON(INCO), -% ! OU2,OU3,OU4,OU5,OU6,OU7,OU8,OU9, -% ! PSN,ROH,YNG,GFR,DEQ -% ! -%C = textscan(fileID,formatSpec) -[C]=textread('DATA0.DAT','%s %*[^\n]') -% we enter de data in char format -TEST=str2double(C(1)) -SEED=str2double(C(2))% SEED to create a pertubed mesh ' -LCO=str2double(C(3)) %cubic module length -M= str2double(C(4)) -N= str2double(C(5)) -L= str2double(C(6)) -DF1 =str2double(C(7)) -DF2 =str2double(C(8)) - TDAF=str2double(C(9)) - CON =str2double(C(10)) - DT =str2double(C(11)) - TTOT =str2double(C(12)) -INCO= str2double(C(13)) -for i=1:INCO -NCON(i)= str2double(C(13+i)) -end -OU2 =str2double(C(14+INCO));% OU2 -OU3 =str2double(C(15+INCO));% OU3 -OU4 =str2double(C(16+INCO));% OU4 -OU5 =str2double(C(17+INCO));% OU5 -OU6 =str2double(C(18+INCO));% OU6 -OU7 =str2double(C(19+INCO));% OU7 -OU8 =str2double(C(20+INCO));% OU8 -OU9 =str2double(C(21+INCO));% OU9 -PSN =str2double(C(22+INCO)) -ROH =str2double(C(23+INCO)) -YNG =str2double(C(24+INCO)) -GFR=str2double(C(25+INCO)) -DEQ =str2double(C(26+INCO)) - - % fid = fopen('dados.txt', 'r'); -% A = fscanf(fid, '%f'); % Lê todos os números -% fclose(fid); -% READ (10,*)TEST,TEXTO,SEED,TEXTO,LCO,TEXTO,M,TEXTO,N,TEXTO,L,TEXTO -% READ (10,*) DF1,TEXTO,DF2,TEXTO,TDAF,TEXTO,CON,TEXTO -% READ (10,*) DT,TEXTO,TTOT,TEXTO,INCO,TEXTO -% ! -% DO 10 I=1,INCO -% READ (10,*) NCON(I),TEXTO -% 10 CONTINUE -% ! -% READ (10,*) OU2,TEXTO,OU3,TEXTO,OU4,TEXTO,OU5,TEXTO -% READ (10,*) OU6,TEXTO,OU7,TEXTO,OU8,TEXTO,OU9,TEXTO -% READ (10,*) PSN,TEXTO,ROH,TEXTO,YNG,TEXTO -% READ (10,*) GFR,TEXTO,DEQ,TEXTO -% RETURN -% END -% ! - ini=1; - end diff --git a/tests/LdemTestCase.m b/tests/LdemTestCase.m new file mode 100644 index 0000000..b40ed01 --- /dev/null +++ b/tests/LdemTestCase.m @@ -0,0 +1,27 @@ +classdef (Abstract) LdemTestCase < matlab.unittest.TestCase + %LDEMTESTCASE Base class of the tests of the refactored ldem package. + % + % Adds src/ (the ldem package) to the MATLAB path for the duration of + % the test class and exposes the repository folders. Derive a test + % from it with: + % + % classdef TestSomething < LdemTestCase + % + % The tests/ folder must be on the path (run_tests does it). + + properties (Access = protected) + % Absolute path of the repository root. + RepoRoot (1,1) string + end + + methods (TestClassSetup) + function addSourceToPath(testCase) + here = fileparts(mfilename('fullpath')); + testCase.RepoRoot = string(fileparts(here)); + testCase.applyFixture(matlab.unittest.fixtures.PathFixture( ... + fullfile(testCase.RepoRoot, 'src'))); + testCase.applyFixture(matlab.unittest.fixtures.PathFixture( ... + fullfile(testCase.RepoRoot, 'tests', 'tools'))); + end + end +end diff --git a/tests/TestLdemPath.m b/tests/TestLdemPath.m deleted file mode 100644 index fd7abf4..0000000 --- a/tests/TestLdemPath.m +++ /dev/null @@ -1,22 +0,0 @@ -classdef TestLdemPath < matlab.unittest.TestCase - %TESTLDEMPATH Verifica que as rotinas principais estão no path e documentadas. - properties (TestParameter) - routine = {'ini_DEM3','CALOAD','CALRES','BOUND','CONECTI', ... - 'INTCO1','RMEC','ENERG2','read_dat0','prepvar'} - end - methods (TestClassSetup) - function addSource(testCase) - root = fileparts(fileparts(mfilename('fullpath'))); - testCase.applyFixture(matlab.unittest.fixtures.PathFixture( ... - fullfile(root, 'src', 'ldem'))); - end - end - methods (Test) - function routineExists(testCase, routine) - testCase.verifyEqual(exist(routine, 'file'), 2); - end - function routineHasHelp(testCase, routine) - testCase.verifyNotEmpty(help(routine)); - end - end -end diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md new file mode 100644 index 0000000..1977242 --- /dev/null +++ b/tests/fixtures/README.md @@ -0,0 +1,19 @@ +# Golden-master fixtures + +`tension101_elastic.mat`, `tension101_damage.mat` and `bending102.mat` hold the +results of three small simulations run with the original MATLAB code (the +`legacy/` folder, translated from Fortran), after correcting its obvious bugs +(see `docs/known-issues/KNOWN_ISSUES.md`). The case definitions are in +`tests/tools/referenceCases.m`. + +`clamped103.mat` is the bi-clamped beam of Rodrigo (branch `dev_rodrigo`, +commit 3249300): it was produced with the same original code but with the +`BOUND` and `CALOAD` routines of that branch (they modify `TEST 102`; the new +code registers the model as test 103). It is a reduced version of the model +(5x5x21 nodes, 1600 steps, fracture energy 0.02 N/m so that bars soften). + +The regression tests in `tests/regression` compare the `ldem` package with +these files (relative tolerance 1e-9). The original code is not in the working +tree; it is in the git history under the tag `legacy-reference`, together with +the tools that generated the fixtures (`tests/tools/generateReference.m`). +Change a fixture only on purpose, and say why in the pull request. diff --git a/tests/fixtures/bending102.mat b/tests/fixtures/bending102.mat new file mode 100644 index 0000000..5b95297 Binary files /dev/null and b/tests/fixtures/bending102.mat differ diff --git a/tests/fixtures/clamped103.mat b/tests/fixtures/clamped103.mat new file mode 100644 index 0000000..7daaa14 Binary files /dev/null and b/tests/fixtures/clamped103.mat differ diff --git a/tests/fixtures/tension101_damage.mat b/tests/fixtures/tension101_damage.mat new file mode 100644 index 0000000..0b2ba91 Binary files /dev/null and b/tests/fixtures/tension101_damage.mat differ diff --git a/tests/fixtures/tension101_elastic.mat b/tests/fixtures/tension101_elastic.mat new file mode 100644 index 0000000..2c98927 Binary files /dev/null and b/tests/fixtures/tension101_elastic.mat differ diff --git a/tests/regression/TestAnsysAgainstLegacy.m b/tests/regression/TestAnsysAgainstLegacy.m new file mode 100644 index 0000000..89c9065 --- /dev/null +++ b/tests/regression/TestAnsysAgainstLegacy.m @@ -0,0 +1,79 @@ +classdef TestAnsysAgainstLegacy < LdemTestCase + %TESTANSYSAGAINSTLEGACY The new ANSYS files equal the ones of the legacy code. + % + % Runs ldem.runSimulation on the reference cases, writing ANSYS files at + % the same steps as the legacy run, and compares them line by line with + % the files stored in the golden-master fixtures (time zero and the + % later snapshots). + % + % Intentional differences, removed before comparing (see + % ldem.io.exportAnsys): + % * the legacy line "ET,IFILE,4" is an invalid command and the new + % file writes "ET,3,4"; + % * for TEST 101 the legacy file has no constraint lines ("D,..."), + % the new one lists the fixed degrees of freedom; + % * the new applied-loads section lists the imposed displacements + % ("D,node,direction,value"), the legacy one is empty. + % + % See also TestSolverAgainstLegacy, ldem.io.exportAnsys. + + properties (TestParameter) + caseName = {'tension101_elastic', 'tension101_damage', 'bending102'} + end + + methods (Test, TestTags = {'Regression'}) + function ansysFilesMatchLegacy(testCase, caseName) + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', caseName + ".mat")); + c = fixture.caseDef; + folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + + params = testCase.parametersOf(c); + ldem.runSimulation(params, OutputFolder=folder, Formats="ansys"); + + nFiles = floor(c.nSteps / c.ansysEvery) + 1; + for k = 0:nFiles - 1 + legacyName = sprintf('ANSYS%02d_MAC', k); + testCase.assertTrue(isfield(fixture.files, legacyName), "Fixture lacks " + legacyName); + legacyText = testCase.normalize(fixture.files.(legacyName), c.test); + newText = testCase.normalize( ... + fileread(fullfile(folder, sprintf('snapshot_%04d.mac', k))), c.test); + testCase.verifyEqual(newText, legacyText, ... + sprintf('Snapshot %d of %s differs from the legacy ANSYS file.', k, caseName)); + end + end + end + + methods (Access = private) + function lines = normalize(~, text, testId) + lines = splitlines(string(text)); + lines = strip(lines, 'right', char(13)); + lines(lines == "ET,IFILE,4") = "ET,3,4"; + if testId == 101 + lines(startsWith(lines, "D,")) = []; + end + % The new applied-loads section lists the imposed displacements + % ("D,node,dir,value"); the legacy section is empty. + lines(startsWith(lines, "D,") & count(lines, ",") == 3) = []; + lines(startsWith(lines, "!CARGAS APLICADAS")) = "!CARGAS APLICADAS"; + % Trailing empty lines are not significant. + while ~isempty(lines) && lines(end) == "" + lines(end) = []; + end + end + + function params = parametersOf(testCase, c) + fieldFile = fullfile(testCase.RepoRoot, 'examples', 'beam_102', 'arquivo_3lc_rnao_cv05'); + params = ldem.Parameters( ... + testId = c.test, seed = c.seed, moduleLength = c.moduleLength, ... + nModules = c.modules, dampingInitial = c.damping1, dampingFinal = c.damping2, ... + dampingSwitchTime = c.dampingSwitchTime, constitutiveDamping = c.con, ... + dt = c.dt, totalTime = c.nSteps * c.dt, controlNodes = c.controlNodes, ... + youngModulus = c.youngModulus, density = c.density, poissonRatio = c.poisson, ... + fractureEnergy = c.fractureEnergy, criticalDistance = c.criticalDistance, ... + randomFieldFile = fieldFile, ... + output = struct('snapshotEvery', c.ansysEvery, 'controlNodesEvery', 0, ... + 'energyEvery', 0, 'trackedBarEvery', 0)); + end + end +end diff --git a/tests/regression/TestClampedBeamAgainstLegacy.m b/tests/regression/TestClampedBeamAgainstLegacy.m new file mode 100644 index 0000000..55c2a3c --- /dev/null +++ b/tests/regression/TestClampedBeamAgainstLegacy.m @@ -0,0 +1,127 @@ +classdef TestClampedBeamAgainstLegacy < LdemTestCase + %TESTCLAMPEDBEAMAGAINSTLEGACY The clamped beam (test 103) reproduces the original code. + % + % The fixture tests/fixtures/clamped103.mat was produced by running the + % original program with the BOUND and CALOAD routines of the bi-clamped + % beam model of Rodrigo (branch dev_rodrigo, commit 3249300), which + % modify TEST 102. The legacy input file therefore says TEST 102, while + % the new code registers the same model as test 103 + % (ldem.scenarios.ClampedBeam). + % + % The fixture is a reduced version of the model (5x5x21 nodes, 1600 + % steps, fracture energy 0.02 N/m so that bars soften and break). The + % comparison covers the final state, the bar state and the energies. + % In the original code the force applied at mid-span is added to the + % nodal force array (FRY), so the new nodal force is compared after + % adding state.appliedForce. + % + % Not compared: the external energy and the balance, which the original + % code never computed (see docs/known-issues/KNOWN_ISSUES.md). + % + % See also TestSolverAgainstLegacy, ldem.scenarios.ClampedBeam. + + properties (Constant) + RelTol = 1e-9 + end + + methods (Test, TestTags = {'Regression'}) + function fixtureExercisesDamageAndTheLoadRamp(testCase) + fixture = testCase.loadFixture(); + c = fixture.caseDef; + testCase.verifyGreaterThan(nnz(~fixture.state.DM), 0, 'The fixture needs damaged bars.'); + % The 0.35 ms ramp ends inside the simulated time. + testCase.verifyGreaterThan(c.nSteps * c.dt, 3.5e-4); + end + + function finalStateMatchesLegacy(testCase) + [fixture, state, ~] = testCase.runCase(); + s = fixture.state; + nodal = @(x, y, z) [x(:), y(:), z(:)]; + + testCase.compare(state.time, s.TIME, 'time'); + testCase.compare(state.displacement, nodal(s.U(2, :), s.V(2, :), s.W(2, :)), 'displacement'); + testCase.compare(state.previousDisplacement, nodal(s.U(1, :), s.V(1, :), s.W(1, :)), 'previous displacement'); + testCase.compare(state.velocity, nodal(s.VLX, s.VLY, s.VLZ), 'velocity'); + testCase.compare(state.acceleration, nodal(s.ACX, s.ACY, s.ACZ), 'acceleration'); + testCase.compare(state.force + state.appliedForce, nodal(s.FRX, s.FRY, s.FRZ), 'nodal force'); + end + + function barStateMatchesLegacy(testCase) + [fixture, state, ~] = testCase.runCase(); + s = fixture.state; + + testCase.compare(state.strain, s.SS(:), 'strain'); + testCase.compare(state.strainRate, s.DSS(:), 'strain rate'); + testCase.compare(state.axialForce, s.F(:), 'axial force'); + testCase.compare(state.history.tensionStiffness, s.E2(:), 'tension stiffness'); + testCase.compare(state.history.maxStrain, s.EM(:), 'largest strain'); + testCase.verifyEqual(state.history.isUndamaged, logical(s.DM(:)), 'Damage flags differ.'); + testCase.verifyEqual(state.history.isUnbroken, logical(s.FS(:)), 'Rupture flags differ.'); + end + + function energiesMatchLegacy(testCase) + [fixture, ~, record] = testCase.runCase(); + s = fixture.state; + last = numel(record.energy.time); + + testCase.compare(record.energy.time(last), s.TIME, 'energy time'); + testCase.compare(record.energy.kinetic(last), sum(s.ENCN), 'kinetic energy'); + testCase.compare(record.energy.elastic(last), s.ENEL, 'elastic energy'); + testCase.compare(record.energy.damage(last), s.ENGD, 'damage energy'); + testCase.compare(record.energy.brokenBars(last), s.DEN, 'energy of broken bars'); + testCase.compare(record.energy.damageRate(last), s.DERIV, 'damage rate'); + testCase.compare(record.energy.damping(last), sum(s.ENDP), 'damping energy'); + end + + function energyBalanceClosesWithTheAppliedForce(testCase) + [~, ~, record] = testCase.runCase(); + testCase.verifyGreaterThan(record.energy.external(end), 0); + testCase.verifyLessThan(max(abs(record.energy.balance)) / record.energy.external(end), 1e-2); + end + end + + methods (Access = private) + function fixture = loadFixture(testCase) + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', 'clamped103.mat')); + end + + function [fixture, state, record] = runCase(testCase) + fixture = testCase.loadFixture(); + c = fixture.caseDef; + fieldFile = fullfile(testCase.RepoRoot, 'examples', 'beam_102', 'arquivo_3lc_rnao_cv05'); + params = ldem.Parameters( ... + testId = 103, ... % the legacy file says 102, see the class help + seed = c.seed, ... + moduleLength = c.moduleLength, ... + nModules = c.modules, ... + dampingInitial = c.damping1, ... + dampingFinal = c.damping2, ... + dampingSwitchTime = c.dampingSwitchTime, ... + constitutiveDamping = c.con, ... + dt = c.dt, ... + totalTime = c.nSteps * c.dt, ... + controlNodes = c.controlNodes, ... + youngModulus = c.youngModulus, ... + density = c.density, ... + poissonRatio = c.poisson, ... + fractureEnergy = c.fractureEnergy, ... + criticalDistance = c.criticalDistance, ... + randomFieldFile = fieldFile, ... + output = struct('snapshotEvery', 0, 'controlNodesEvery', c.everyN, ... + 'energyEvery', c.everyN, 'trackedBarEvery', 0)); + + mesh = ldem.mesh.buildMesh(params); + [barProps, history] = ldem.material.buildBarProperties(mesh, params); + scenario = ldem.scenarios.fromTestId(params.testId); + [state, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario); + end + + function compare(testCase, actual, expected, name) + % Relative comparison with an absolute floor tied to the data scale. + scale = max(abs(expected(:))); + floor = 1e-12 * scale + realmin; + testCase.verifyEqual(actual, expected, 'RelTol', testCase.RelTol, 'AbsTol', floor, ... + sprintf('%s differs from the original result.', name)); + end + end +end diff --git a/tests/regression/TestFixtures.m b/tests/regression/TestFixtures.m new file mode 100644 index 0000000..35a7bd5 --- /dev/null +++ b/tests/regression/TestFixtures.m @@ -0,0 +1,76 @@ +classdef TestFixtures < matlab.unittest.TestCase + %TESTFIXTURES Fast sanity checks of the golden-master fixtures. + % + % Verifies that the fixtures exist, are consistent with their case + % definitions and exercise the interesting branches (damage), so they + % are useful as references. Does not run any simulation. + % + % The fixtures were generated with the corrected original code (git tag + % legacy-reference); see docs/known-issues/KNOWN_ISSUES.md. + % + % See also referenceCases. + + properties (TestParameter) + caseName = {'tension101_elastic', 'tension101_damage', 'bending102'} + end + + properties + FixtureDir + end + + methods (TestClassSetup) + function addTools(testCase) + testsDir = fileparts(fileparts(mfilename('fullpath'))); + testCase.applyFixture(matlab.unittest.fixtures.PathFixture( ... + fullfile(testsDir, 'tools'))); + testCase.FixtureDir = fullfile(testsDir, 'fixtures'); + end + end + + methods (Test, TestTags = {'Regression'}) + function caseListIsCurrent(testCase) + % Keeps the hardcoded lists of the regression tests in sync. + expected = sort(string({referenceCases().name})); + listed = sort(string(TestFixtures.caseName_)); + testCase.verifyEqual(listed, expected, ... + 'Update the caseName lists in the regression tests.'); + end + + function fixtureIsConsistent(testCase, caseName) + fixture = load(fullfile(testCase.FixtureDir, caseName + ".mat")); + c = fixture.caseDef; + s = fixture.state; + + testCase.verifyEqual(c.name, char(caseName)); + testCase.verifyEqual(s.M, c.modules(1)); + testCase.verifyEqual(double(s.NSTEP), c.nSteps); + testCase.verifyEqual(size(s.U, 2), s.NNT, 'Node arrays must be trimmed.'); + testCase.verifyEqual(numel(s.CN), 2 * s.NBT, 'CN must be trimmed.'); + testCase.verifyTrue(all(isfinite(s.U), 'all')); + end + + function fixturesIncludeTheTimeIntegration(testCase, caseName) + % The legacy driver once skipped the integration (nodes stayed + % at rest). Free nodes must have moved in every reference case. + fixture = load(fullfile(testCase.FixtureDir, caseName + ".mat")); + s = fixture.state; + speed = max(abs([s.VLX(:); s.VLY(:); s.VLZ(:)])); + testCase.verifyGreaterThan(speed, 0, ... + 'Velocities are zero: the equations of motion were not integrated.'); + end + + function damageCaseActuallyDamages(testCase) + elastic = load(fullfile(testCase.FixtureDir, 'tension101_elastic.mat')); + damaged = load(fullfile(testCase.FixtureDir, 'tension101_damage.mat')); + testCase.verifyEqual(nnz(~elastic.state.DM), 0); + testCase.verifyGreaterThan(nnz(~damaged.state.DM), 0, 'No bar softened.'); + testCase.verifyGreaterThan(nnz(~damaged.state.FS), 0, 'No bar broke.'); + end + end + + methods (Static, Access = private) + function names = caseName_() + names = {'tension101_elastic', 'tension101_damage', 'bending102'}; + end + end +end diff --git a/tests/regression/TestMaterialAgainstLegacy.m b/tests/regression/TestMaterialAgainstLegacy.m new file mode 100644 index 0000000..42dd7bc --- /dev/null +++ b/tests/regression/TestMaterialAgainstLegacy.m @@ -0,0 +1,73 @@ +classdef TestMaterialAgainstLegacy < LdemTestCase + %TESTMATERIALAGAINSTLEGACY The new bar properties equal the legacy ones. + % + % Compares ldem.material.buildBarProperties with the stiffness, + % critical strain, rupture ratio and statistics stored in the + % golden-master fixtures. The legacy random field file is used, so + % the comparison also covers the scatter of the critical strain. + % + % For the elastic case no bar ever softens, so the damage state at the + % end of the legacy run is still the initial one and it is compared + % too. + % + % See also TestMeshAgainstLegacy. + + properties (TestParameter) + caseName = {'tension101_elastic', 'tension101_damage', 'bending102'} + end + + methods (Test, TestTags = {'Regression'}) + function barPropertiesMatchLegacy(testCase, caseName) + [fixture, params] = testCase.loadCase(caseName); + s = fixture.state; + mesh = ldem.mesh.buildMesh(params); + + [props, ~] = ldem.material.buildBarProperties(mesh, params); + + tight = {'RelTol', 1e-14, 'AbsTol', 1e-30}; + testCase.verifyEqual(props.stiffness, s.E1(:), tight{:}); + testCase.verifyEqual(props.criticalStrain, s.EP(:), tight{:}); + testCase.verifyEqual(props.ruptureRatio, s.KR(:), tight{:}); + testCase.verifyEqual(props.criticalStrainMean, s.MEAN, tight{:}); + end + + function initialStateMatchesLegacyWhenNothingDamaged(testCase) + [fixture, params] = testCase.loadCase('tension101_elastic'); + s = fixture.state; + mesh = ldem.mesh.buildMesh(params); + [~, history] = ldem.material.buildBarProperties(mesh, params); + + tight = {'RelTol', 1e-14, 'AbsTol', 1e-30}; + testCase.verifyEqual(history.tensionStiffness, s.E2(:), tight{:}); + testCase.verifyEqual(history.maxStrain, s.EM(:), tight{:}); + testCase.verifyEqual(history.isUndamaged, logical(s.DM(:))); + testCase.verifyEqual(history.isUnbroken, logical(s.FS(:))); + end + end + + methods (Access = private) + function [fixture, params] = loadCase(testCase, caseName) + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', caseName + ".mat")); + c = fixture.caseDef; + fieldFile = fullfile(testCase.RepoRoot, 'examples', 'beam_102', 'arquivo_3lc_rnao_cv05'); + params = ldem.Parameters( ... + testId = c.test, ... + seed = c.seed, ... + moduleLength = c.moduleLength, ... + nModules = c.modules, ... + dampingInitial = c.damping1, ... + dampingFinal = c.damping2, ... + dampingSwitchTime = c.dampingSwitchTime, ... + constitutiveDamping = c.con, ... + dt = c.dt, ... + totalTime = c.nSteps * c.dt, ... + controlNodes = c.controlNodes, ... + youngModulus = c.youngModulus, ... + density = c.density, ... + poissonRatio = c.poisson, ... + fractureEnergy = c.fractureEnergy, ... + criticalDistance = c.criticalDistance, ... + randomFieldFile = fieldFile); + end + end +end diff --git a/tests/regression/TestMeshAgainstLegacy.m b/tests/regression/TestMeshAgainstLegacy.m new file mode 100644 index 0000000..e6245ca --- /dev/null +++ b/tests/regression/TestMeshAgainstLegacy.m @@ -0,0 +1,86 @@ +classdef TestMeshAgainstLegacy < LdemTestCase + %TESTMESHAGAINSTLEGACY The new mesh equals the one built by the legacy code. + % + % Compares ldem.mesh.buildMesh with the node coordinates, supports, + % masses, connectivity and bar geometry stored in the golden-master + % fixtures (generated by the original main1.m). No simulation is run, so the + % test is fast. + % + % See also TestFixtures. + + properties (TestParameter) + caseName = {'tension101_elastic', 'tension101_damage', 'bending102'} + end + + methods (Test, TestTags = {'Regression'}) + function meshMatchesLegacy(testCase, caseName) + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', caseName + ".mat")); + s = fixture.state; + params = TestMeshAgainstLegacy.parametersOf(fixture.caseDef); + + mesh = ldem.mesh.buildMesh(params); + + tight = {'RelTol', 1e-14, 'AbsTol', 1e-18}; + + testCase.verifyEqual(params.nNodes, s.NNT, 'Node count differs.'); + testCase.verifyEqual(size(mesh.bars, 1), s.NBT, 'Bar count differs.'); + + % Initial coordinates (legacy U0, V0, W0). + testCase.verifyEqual(mesh.nodes0, [s.U0(:), s.V0(:), s.W0(:)], tight{:}); + + % Supports (legacy BDX, BDY, BDZ). + legacyFixed = [s.BDX(:), s.BDY(:), s.BDZ(:)] ~= 0; + testCase.verifyEqual(mesh.fixed, legacyFixed, 'Supports differ.'); + + % Lumped masses (legacy MAS). + testCase.verifyEqual(mesh.mass, s.MAS(:), tight{:}); + + % Connectivity (legacy CN is [start1 end1 start2 end2 ...]). + testCase.verifyEqual(mesh.bars, reshape(s.CN, 2, []).', 'Connectivity differs.'); + + % Bar geometry (legacy LI, XB, YB, ZB). + testCase.verifyEqual(mesh.barLength, s.LI(:), tight{:}); + testCase.verifyEqual(mesh.barCentres, [s.XB(:), s.YB(:), s.ZB(:)], tight{:}); + end + + function timeIntegrationSettingsMatchLegacy(testCase, caseName) + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', caseName + ".mat")); + params = TestMeshAgainstLegacy.parametersOf(fixture.caseDef); + testCase.verifyEqual(params.nSteps, double(fixture.state.NSTEP)); + testCase.verifyEqual(params.dt, fixture.state.DT); + end + + function stabilityCheckAgreesWithLegacyCriterion(testCase, caseName) + % Legacy NAYFES0 stops when min(LI)/sqrt(E/rho) < DT. + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', caseName + ".mat")); + params = TestMeshAgainstLegacy.parametersOf(fixture.caseDef); + mesh = ldem.mesh.buildMesh(params); + legacyCritical = min(fixture.state.LI) / sqrt(params.youngModulus / params.density); + testCase.verifyEqual(ldem.solver.checkStability(mesh.barLength, params), ... + legacyCritical, 'RelTol', 1e-12); + end + end + + methods (Static, Access = private) + function params = parametersOf(c) + %PARAMETERSOF Build ldem.Parameters from a reference-case definition. + params = ldem.Parameters( ... + testId = c.test, ... + seed = c.seed, ... + moduleLength = c.moduleLength, ... + nModules = c.modules, ... + dampingInitial = c.damping1, ... + dampingFinal = c.damping2, ... + dampingSwitchTime = c.dampingSwitchTime, ... + constitutiveDamping = c.con, ... + dt = c.dt, ... + totalTime = c.nSteps * c.dt, ... + controlNodes = c.controlNodes, ... + youngModulus = c.youngModulus, ... + density = c.density, ... + poissonRatio = c.poisson, ... + fractureEnergy = c.fractureEnergy, ... + criticalDistance = c.criticalDistance); + end + end +end diff --git a/tests/regression/TestSolverAgainstLegacy.m b/tests/regression/TestSolverAgainstLegacy.m new file mode 100644 index 0000000..742ae81 --- /dev/null +++ b/tests/regression/TestSolverAgainstLegacy.m @@ -0,0 +1,136 @@ +classdef TestSolverAgainstLegacy < LdemTestCase + %TESTSOLVERAGAINSTLEGACY The new solver reproduces the legacy simulation. + % + % Runs ldem.solver.simulate on the three reference cases and compares + % the final state with the one stored in the golden-master fixtures, + % which were generated by the (corrected) legacy driver. Covered: + % displacements, velocities, accelerations, bar forces, strains, + % damage state, damping switch, energies and the reaction and control + % node records of the beam. + % + % Not compared, because the legacy value is not defined (see + % docs/known-issues/KNOWN_ISSUES.md): the external energy (never computed) and the + % energy vectors, which are compared after summing over the nodes. + % + % See also TestMeshAgainstLegacy, TestMaterialAgainstLegacy. + + properties (TestParameter) + caseName = {'tension101_elastic', 'tension101_damage', 'bending102'} + end + + properties (Constant) + RelTol = 1e-9 + end + + methods (Test, TestTags = {'Regression'}) + function finalStateMatchesLegacy(testCase, caseName) + [fixture, state, ~] = testCase.runCase(caseName); + s = fixture.state; + nodal = @(x, y, z) [x(:), y(:), z(:)]; + + testCase.compare(state.time, s.TIME, 'time'); + testCase.compare(state.displacement, nodal(s.U(2, :), s.V(2, :), s.W(2, :)), 'displacement'); + testCase.compare(state.previousDisplacement, nodal(s.U(1, :), s.V(1, :), s.W(1, :)), 'previous displacement'); + testCase.compare(state.velocity, nodal(s.VLX, s.VLY, s.VLZ), 'velocity'); + testCase.compare(state.acceleration, nodal(s.ACX, s.ACY, s.ACZ), 'acceleration'); + testCase.compare(state.force, nodal(s.FRX, s.FRY, s.FRZ), 'nodal force'); + end + + function barStateMatchesLegacy(testCase, caseName) + [fixture, state, ~] = testCase.runCase(caseName); + s = fixture.state; + + testCase.compare(state.strain, s.SS(:), 'strain'); + testCase.compare(state.strainRate, s.DSS(:), 'strain rate'); + testCase.compare(state.axialForce, s.F(:), 'axial force'); + testCase.compare(state.history.tensionStiffness, s.E2(:), 'tension stiffness'); + testCase.compare(state.history.maxStrain, s.EM(:), 'largest strain'); + testCase.verifyEqual(state.history.isUndamaged, logical(s.DM(:)), 'Damage flags differ.'); + testCase.verifyEqual(state.history.isUnbroken, logical(s.FS(:)), 'Rupture flags differ.'); + end + + function energiesMatchLegacy(testCase, caseName) + [fixture, ~, record] = testCase.runCase(caseName); + s = fixture.state; + last = numel(record.energy.time); + + testCase.compare(record.energy.time(last), s.TIME, 'energy time'); + testCase.compare(record.energy.kinetic(last), sum(s.ENCN), 'kinetic energy'); + testCase.compare(record.energy.elastic(last), s.ENEL, 'elastic energy'); + testCase.compare(record.energy.damage(last), s.ENGD, 'damage energy'); + testCase.compare(record.energy.brokenBars(last), s.DEN, 'energy of broken bars'); + testCase.compare(record.energy.damageRate(last), s.DERIV, 'damage rate'); + testCase.compare(record.energy.damping(last), sum(s.ENDP), 'damping energy'); + end + + function beamReactionAndControlNodesMatchLegacy(testCase) + [fixture, ~, record] = testCase.runCase('bending102'); + s = fixture.state; + + % Reaction of the last stored step (legacy SIM01.DAT keeps only that one). + testCase.compare(record.reactions.force(end, 2), s.REACAOY, 'reaction Ry'); + row = sscanf(fixture.files.SIM01_DAT, '%f'); + testCase.compare(record.reactions.time(end), row(1), 'reaction time'); + testCase.compare(record.reactions.force(end, 2), row(2), 'reaction in SIM01'); + + % Acceleration of the control nodes (legacy LET.POS: time, ax(node 1), ax(node 2)). + pos = reshape(sscanf(fixture.files.LET_POS, '%f'), 3, []).'; + testCase.verifySize(record.controlNodes.time, [size(pos, 1) 1]); + testCase.compare(record.controlNodes.time, pos(:, 1), 'control time'); + testCase.compare(record.controlNodes.acceleration(:, 1, 1), pos(:, 2), 'ax node 1'); + testCase.compare(record.controlNodes.acceleration(:, 2, 1), pos(:, 3), 'ax node 2'); + end + + function dampingSwitchIsExercised(testCase, caseName) + % The reference cases change the damping inside the simulated + % time, so the comparison above also validates the switch. + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', caseName + ".mat")); + c = fixture.caseDef; + switchStep = round(c.dampingSwitchTime / c.dt); + testCase.verifyNotEqual(c.damping1, c.damping2); + testCase.verifyGreaterThanOrEqual(switchStep, 1); + testCase.verifyLessThan(switchStep, c.nSteps); + end + end + + methods (Access = private) + function [fixture, state, record] = runCase(testCase, caseName) + fixture = load(fullfile(testCase.RepoRoot, 'tests', 'fixtures', caseName + ".mat")); + c = fixture.caseDef; + fieldFile = fullfile(testCase.RepoRoot, 'examples', 'beam_102', 'arquivo_3lc_rnao_cv05'); + params = ldem.Parameters( ... + testId = c.test, ... + seed = c.seed, ... + moduleLength = c.moduleLength, ... + nModules = c.modules, ... + dampingInitial = c.damping1, ... + dampingFinal = c.damping2, ... + dampingSwitchTime = c.dampingSwitchTime, ... + constitutiveDamping = c.con, ... + dt = c.dt, ... + totalTime = c.nSteps * c.dt, ... + controlNodes = c.controlNodes, ... + youngModulus = c.youngModulus, ... + density = c.density, ... + poissonRatio = c.poisson, ... + fractureEnergy = c.fractureEnergy, ... + criticalDistance = c.criticalDistance, ... + randomFieldFile = fieldFile, ... + output = struct('snapshotEvery', 0, 'controlNodesEvery', c.everyN, ... + 'energyEvery', c.everyN, 'trackedBarEvery', 0)); + + mesh = ldem.mesh.buildMesh(params); + [barProps, history] = ldem.material.buildBarProperties(mesh, params); + scenario = ldem.scenarios.fromTestId(params.testId); + [state, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario); + end + + function compare(testCase, actual, expected, name) + % Relative comparison with an absolute floor tied to the data scale. + scale = max(abs(expected(:))); + floor = 1e-12 * scale + realmin; + testCase.verifyEqual(actual, expected, 'RelTol', testCase.RelTol, 'AbsTol', floor, ... + sprintf('%s differs from the legacy result.', name)); + end + end +end diff --git a/tests/run_tests.m b/tests/run_tests.m index 58fd4b6..0412280 100644 --- a/tests/run_tests.m +++ b/tests/run_tests.m @@ -1,8 +1,35 @@ -function results = run_tests() -%RUN_TESTS Executa a suite de testes matlab.unittest. -root = fileparts(fileparts(mfilename('fullpath'))); -addpath(fullfile(root, 'src', 'ldem')); -suite = matlab.unittest.TestSuite.fromFolder(fileparts(mfilename('fullpath'))); +function results = run_tests(options) +%RUN_TESTS Run the matlab.unittest suite of the repository. +% +% results = run_tests() runs every test in tests/ and its subfolders, +% except those tagged "Slow", and throws an error if any test fails. +% +% results = run_tests(IncludeSlow=true) also runs the slow tests (for +% example the one that builds the complete beam model of the example). +% +% Outputs: +% results matlab.unittest.TestResult array. +% +% Example: +% >> addpath tests +% >> run_tests +% >> run_tests(IncludeSlow=true) +% +% See also matlab.unittest.TestSuite. + +arguments + options.IncludeSlow (1,1) logical = false +end + +testsFolder = fileparts(mfilename('fullpath')); +addpath(testsFolder); + +suite = matlab.unittest.TestSuite.fromFolder(testsFolder, ... + 'IncludingSubfolders', true); +if ~options.IncludeSlow + suite = suite.selectIf(~matlab.unittest.selectors.HasTag('Slow')); +end + results = run(suite); disp(table(results)); assertSuccess(results); diff --git a/tests/tools/TestHalfStiffnessLaw.m b/tests/tools/TestHalfStiffnessLaw.m new file mode 100644 index 0000000..c24a36f --- /dev/null +++ b/tests/tools/TestHalfStiffnessLaw.m @@ -0,0 +1,32 @@ +classdef TestHalfStiffnessLaw < ldem.material.MaterialLaw + %TESTHALFSTIFFNESSLAW A constitutive law that is not in the registry (for the tests). + % + % The force of a bar is half of the linear elastic one, E1*strain/2. The + % tests pass an object of this class to the solver to check that a new law + % plugs in without touching the solver. + % + % See also ldem.material.MaterialLaw. + + properties (Constant) + name = "half_stiffness" + end + + methods + function [force, history] = evaluate(~, strain, ~, barProps, history, ~) + force = 0.5 * barProps.stiffness .* strain; + end + + function energy = energies(~, strain, barProps, ~, barLength) + elastic = sum(0.5 * barProps.stiffness .* (strain .* strain .* barLength ./ 2)); + energy = struct('elastic', elastic, 'damage', 0, 'brokenBars', 0); + end + + function value = barDamageEnergy(~, ~, ~, ~, ~) + value = 0; + end + + function stiffness = viscousStiffness(~, ~, barProps, ~) + stiffness = 0.5 * barProps.stiffness; + end + end +end diff --git a/tests/tools/TestUnregisteredScenario.m b/tests/tools/TestUnregisteredScenario.m new file mode 100644 index 0000000..78d0302 --- /dev/null +++ b/tests/tools/TestUnregisteredScenario.m @@ -0,0 +1,21 @@ +classdef TestUnregisteredScenario < ldem.scenarios.Scenario + %TESTUNREGISTEREDSCENARIO A scenario that is not in ldem.scenarios.registry (for the tests). + % + % It fixes nothing and applies no load. The tests use it to check that + % code which needs the registry refuses a scenario that is not in it. + % + % See also ldem.scenarios.Scenario, ldem.scenarios.registry. + + properties (Constant) + testId = 999 + end + + methods + function fixed = fixedDofs(~, nodes0, ~) + fixed = false(size(nodes0)); + end + + function state = applyLoads(~, state, ~, ~) + end + end +end diff --git a/tests/tools/referenceCases.m b/tests/tools/referenceCases.m new file mode 100644 index 0000000..e090066 --- /dev/null +++ b/tests/tools/referenceCases.m @@ -0,0 +1,58 @@ +function cases = referenceCases() +%REFERENCECASES Definitions of the small simulations used as golden masters. +% +% cases = referenceCases() returns a struct array. Each element describes +% one LDEM run that is small enough to execute in seconds but exercises a +% different part of the code: +% +% tension101_elastic TEST 101, elastic response only (no damage) +% tension101_damage TEST 101, low fracture energy -> softening + rupture +% bending102 TEST 102, beam with supports and reaction output +% +% Fields of every case: +% name Unique identifier (also the fixture file name). +% test Test number written to DATA0.DAT (101 or 102). +% modules [M N L] number of nodes along x, y, z. +% nSteps Number of time steps to integrate. +% fractureEnergy GFR, specific fracture energy [N/m]. +% ansysEvery OU3: write an ANSYS file every n steps. +% everyN OU6..OU9: write the other outputs every n steps. +% +% The remaining material and numerical parameters are shared (see below). +% +% The golden-master fixtures in tests/fixtures were produced by running +% these cases with the corrected original code (git tag legacy-reference). +% +% See also writeDataFile. + +shared = struct( ... + 'seed', 123, ... + 'moduleLength', 0.003, ... % [m] + 'damping1', 25000, ... % DF1 [1/s] + 'damping2', 15000, ... % DF2 [1/s], differs from DF1 to test the switch + 'dampingSwitchTime', 2e-5, ... % TDAF [s] -> switch at step 100 + 'con', 0, ... + 'dt', 2e-7, ... % [s] + 'controlNodes', [1 2], ... + 'poisson', 0.25, ... + 'density', 2000, ... % [kg/m^3] + 'youngModulus', 32e9, ... % [Pa] + 'criticalDistance', 0.028); % DEQ [m] + +specs = { ... + % name test modules nSteps GFR OU3 everyN + 'tension101_elastic', 101, [6 3 3], 200, 50.0, 100, 10; ... + 'tension101_damage', 101, [6 3 3], 1000, 0.1, 500, 20; ... + 'bending102', 102, [70 4 3], 150, 0.5, 75, 10}; + +cases = repmat(shared, size(specs, 1), 1); +for k = 1:size(specs, 1) + cases(k).name = specs{k, 1}; + cases(k).test = specs{k, 2}; + cases(k).modules = specs{k, 3}; + cases(k).nSteps = specs{k, 4}; + cases(k).fractureEnergy = specs{k, 5}; + cases(k).ansysEvery = specs{k, 6}; + cases(k).everyN = specs{k, 7}; +end +end diff --git a/tests/tools/writeDataFile.m b/tests/tools/writeDataFile.m new file mode 100644 index 0000000..6c198c4 --- /dev/null +++ b/tests/tools/writeDataFile.m @@ -0,0 +1,52 @@ +function writeDataFile(path, c) +%WRITEDATAFILE Write a DATA0.DAT input file from a case definition. +% +% writeDataFile(path, c) creates an input file in the format of the original +% program, which ldem.io.readInputFile reads. Only the first token of each +% line is read; the quoted label after it is a comment for humans. +% +% Inputs: +% path Full path of the file to create. +% c Case struct, see referenceCases. +% +% See also referenceCases. + +fid = fopen(path, 'w'); +if fid == -1 + error('ldem:tools:cannotOpenFile', 'Cannot create "%s".', path); +end +closer = onCleanup(@() fclose(fid)); + +nControl = numel(c.controlNodes); +totalTime = c.nSteps * c.dt; + +fprintf(fid, '%d '' TEST ''\n', c.test); +fprintf(fid, '%d '' SEED ''\n', c.seed); +fprintf(fid, '%.6g '' LCO ''\n', c.moduleLength); +fprintf(fid, '%d '' M ''\n', c.modules(1)); +fprintf(fid, '%d '' N ''\n', c.modules(2)); +fprintf(fid, '%d '' L ''\n', c.modules(3)); +fprintf(fid, '%.6g '' DF1 ''\n', c.damping1); +fprintf(fid, '%.6g '' DF2 ''\n', c.damping2); +fprintf(fid, '%.6g '' TDAF ''\n', c.dampingSwitchTime); +fprintf(fid, '%.6g '' CON ''\n', c.con); +fprintf(fid, '%.6g '' DT ''\n', c.dt); +fprintf(fid, '%.15g '' TTOT ''\n', totalTime); +fprintf(fid, '%d '' INCO ''\n', nControl); +for i = 1:nControl + fprintf(fid, '%d '' Ncon%d ''\n', c.controlNodes(i), i); +end +fprintf(fid, '9999999 '' OU2 ''\n'); +fprintf(fid, '%d '' OU3 ''\n', c.ansysEvery); +fprintf(fid, '0 '' OU4 ''\n'); +fprintf(fid, '0 '' OU5 ''\n'); +fprintf(fid, '%d '' OU6 ''\n', c.everyN); +fprintf(fid, '%d '' OU7 ''\n', c.everyN); +fprintf(fid, '%d '' OU8 ''\n', c.everyN); +fprintf(fid, '%d '' OU9 ''\n', c.everyN); +fprintf(fid, '%.6g '' PSN ''\n', c.poisson); +fprintf(fid, '%.6g '' ROH ''\n', c.density); +fprintf(fid, '%.6g '' YNG ''\n', c.youngModulus); +fprintf(fid, '%.6g '' GFR ''\n', c.fractureEnergy); +fprintf(fid, '%.6g '' DEQ ''\n', c.criticalDistance); +end diff --git a/tests/tools/writeTextFile.m b/tests/tools/writeTextFile.m new file mode 100644 index 0000000..9300cff --- /dev/null +++ b/tests/tools/writeTextFile.m @@ -0,0 +1,28 @@ +function writeTextFile(path, lines) +%WRITETEXTFILE Write a text file from a list of lines (for the tests). +% +% writeTextFile(path, lines) writes the lines, separated by line feeds, +% creating the folder if needed. +% +% Inputs: +% path Full path of the file. +% lines String array or cell array of lines. +% +% See also writeDataFile. + +arguments + path (1,1) string + lines (:,1) string +end + +folder = fileparts(path); +if strlength(folder) > 0 && ~isfolder(folder) + mkdir(folder); +end +fid = fopen(path, 'w'); +if fid == -1 + error('ldem:tools:cannotOpenFile', 'Cannot create "%s".', path); +end +fprintf(fid, '%s\n', lines); +fclose(fid); +end diff --git a/tests/unit/TestBilinearLaw.m b/tests/unit/TestBilinearLaw.m new file mode 100644 index 0000000..fe45eaf --- /dev/null +++ b/tests/unit/TestBilinearLaw.m @@ -0,0 +1,155 @@ +classdef TestBilinearLaw < LdemTestCase + %TESTBILINEARLAW Unit tests of ldem.material.bilinearLaw with hand-made bars. + % + % One bar with stiffness E1 = 100 N, critical strain EP = 1e-3 and + % rupture ratio KR = 5, so the rupture strain is ER = 5e-3. The + % expected forces are computed by hand from the law: + % softening force = E1 * (EP - (strain - EP)/(KR - 1)) + + properties (Constant) + E1 = 100 + EP = 1e-3 + KR = 5 + end + + methods (Access = private) + function [props, history] = makeBars(testCase, n) + props = struct( ... + 'stiffness', repmat(testCase.E1, n, 1), ... + 'criticalStrain', repmat(testCase.EP, n, 1), ... + 'ruptureRatio', repmat(testCase.KR, n, 1), ... + 'ruptureStrain', repmat(testCase.KR * testCase.EP, n, 1)); + history = struct( ... + 'tensionStiffness', repmat(testCase.E1, n, 1), ... + 'maxStrain', repmat(testCase.EP, n, 1), ... + 'isUndamaged', true(n, 1), ... + 'isUnbroken', true(n, 1)); + end + end + + methods (Test, TestTags = {'Unit'}) + function elasticTensionBelowCriticalStrain(testCase) + [props, history] = testCase.makeBars(1); + [force, after] = ldem.material.bilinearLaw(5e-4, 0, props, history, 0); + testCase.verifyEqual(force, 100 * 5e-4, 'RelTol', 1e-14); + testCase.verifyEqual(after, history, 'An elastic bar must not change state.'); + end + + function compressionIsAlwaysElastic(testCase) + [props, history] = testCase.makeBars(1); + [force, after] = ldem.material.bilinearLaw(-0.02, 0, props, history, 0); + testCase.verifyEqual(force, 100 * -0.02, 'RelTol', 1e-14); + testCase.verifyEqual(after, history); + end + + function softeningFollowsTheDescendingLine(testCase) + [props, history] = testCase.makeBars(1); + strain = 2e-3; + expected = 100 * (1e-3 - (strain - 1e-3) / 4); % 0.075 + [force, after] = ldem.material.bilinearLaw(strain, 0, props, history, 0); + + testCase.verifyEqual(force, expected, 'RelTol', 1e-12); + testCase.verifyEqual(after.tensionStiffness, expected / strain, 'RelTol', 1e-12); + testCase.verifyEqual(after.maxStrain, strain); + testCase.verifyFalse(after.isUndamaged); + testCase.verifyTrue(after.isUnbroken); + end + + function forceIsContinuousAtTheCriticalStrain(testCase) + [props, history] = testCase.makeBars(1); + elastic = ldem.material.bilinearLaw(1e-3 * (1 - 1e-9), 0, props, history, 0); + softening = ldem.material.bilinearLaw(1e-3 * (1 + 1e-9), 0, props, history, 0); + testCase.verifyEqual(softening, elastic, 'RelTol', 1e-6); + testCase.verifyEqual(elastic, 100 * 1e-3, 'RelTol', 1e-6); % peak force + end + + function forceVanishesAtTheRuptureStrain(testCase) + [props, history] = testCase.makeBars(1); + force = ldem.material.bilinearLaw(5e-3 * (1 - 1e-9), 0, props, history, 0); + testCase.verifyEqual(force, 0, 'AbsTol', 1e-9); + end + + function unloadingIsLinearTowardTheOrigin(testCase) + [props, history] = testCase.makeBars(1); + [~, history] = ldem.material.bilinearLaw(2e-3, 0, props, history, 0); + peakForce = 0.075; + + [force, after] = ldem.material.bilinearLaw(1e-3, 0, props, history, 0); + testCase.verifyEqual(force, peakForce * (1e-3 / 2e-3), 'RelTol', 1e-12); + testCase.verifyEqual(after.maxStrain, 2e-3, 'Unloading must not reduce maxStrain.'); + testCase.verifyEqual(after.tensionStiffness, history.tensionStiffness); + end + + function reloadingReturnsToTheSofteningLine(testCase) + [props, history] = testCase.makeBars(1); + [f1, history] = ldem.material.bilinearLaw(2e-3, 0, props, history, 0); + [~, history] = ldem.material.bilinearLaw(1e-3, 0, props, history, 0); + f2 = ldem.material.bilinearLaw(2e-3, 0, props, history, 0); + testCase.verifyEqual(f2, f1, 'RelTol', 1e-12); + end + + function ruptureIsPermanent(testCase) + [props, history] = testCase.makeBars(1); + [force, history] = ldem.material.bilinearLaw(6e-3, 0, props, history, 0); + testCase.verifyEqual(force, 0); + testCase.verifyFalse(history.isUnbroken); + testCase.verifyFalse(history.isUndamaged); + testCase.verifyEqual(history.tensionStiffness, 0); + + % A broken bar carries no tension even when the strain goes back down... + force = ldem.material.bilinearLaw(1e-3, 0, props, history, 0); + testCase.verifyEqual(force, 0); + % ...but still resists compression (contact). + force = ldem.material.bilinearLaw(-1e-3, 0, props, history, 0); + testCase.verifyEqual(force, -0.1, 'RelTol', 1e-14); + end + + function viscousTermIsAddedExceptWhenBroken(testCase) + [props, history] = testCase.makeBars(1); + damping = 0.1; rate = 10; + force = ldem.material.bilinearLaw(5e-4, rate, props, history, damping); + testCase.verifyEqual(force, 100 * 5e-4 + 100 * damping * rate, 'RelTol', 1e-14); + + force = ldem.material.bilinearLaw(-5e-4, rate, props, history, damping); + testCase.verifyEqual(force, -100 * 5e-4 + 100 * damping * rate, 'RelTol', 1e-14); + + force = ldem.material.bilinearLaw(6e-3, rate, props, history, damping); + testCase.verifyEqual(force, 0, 'A broken bar has no viscous force either.'); + end + + function vectorizedResultEqualsBarByBar(testCase) + strains = [5e-4; 2e-3; 6e-3; -1e-3; 3e-3]; + rates = [1; -2; 3; 0.5; -1]; + [props, history] = testCase.makeBars(numel(strains)); + + [forceAll, historyAll] = ldem.material.bilinearLaw(strains, rates, props, history, 0.05); + + for k = 1:numel(strains) + [p, h] = testCase.makeBars(1); + [f, hk] = ldem.material.bilinearLaw(strains(k), rates(k), p, h, 0.05); + testCase.verifyEqual(forceAll(k), f); + testCase.verifyEqual(historyAll.tensionStiffness(k), hk.tensionStiffness); + testCase.verifyEqual(historyAll.maxStrain(k), hk.maxStrain); + testCase.verifyEqual(historyAll.isUndamaged(k), hk.isUndamaged); + testCase.verifyEqual(historyAll.isUnbroken(k), hk.isUnbroken); + end + end + + function tensionForceNeverExceedsThePeak(testCase) + [props, history] = testCase.makeBars(1); + strains = linspace(0, 0.01, 200).'; + peak = 100 * 1e-3; + for k = 1:numel(strains) + [f, history] = ldem.material.bilinearLaw(strains(k), 0, props, history, 0); + testCase.verifyLessThanOrEqual(f, peak * (1 + 1e-12)); + end + end + + function sizeMismatchIsReported(testCase) + [props, history] = testCase.makeBars(3); + testCase.verifyError( ... + @() ldem.material.bilinearLaw([1e-3; 2e-3], [0; 0], props, history, 0), ... + 'ldem:material:sizeMismatch'); + end + end +end diff --git a/tests/unit/TestDeclarative.m b/tests/unit/TestDeclarative.m new file mode 100644 index 0000000..22ac695 --- /dev/null +++ b/tests/unit/TestDeclarative.m @@ -0,0 +1,373 @@ +classdef TestDeclarative < LdemTestCase + %TESTDECLARATIVE Unit tests of the declarative scenario ([[support]] and [[load]] blocks). + + properties (Access = private) + Folder (1,1) string + end + + methods (TestMethodSetup) + function makeFolder(testCase) + testCase.Folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + end + end + + methods (Access = private) + function path = writeCase(testCase, scenarioLines, extra) + % A small case whose [scenario] section is scenarioLines. + if nargin < 3 + extra = strings(0, 1); + end + path = fullfile(testCase.Folder, "custom.ldem"); + writeTextFile(path, [ ... + "format = 1" + "[mesh]" + "module_size = 3 mm" + "modules = [5, 2, 2]" + "[time]" + "step = 0.2 us" + "duration = 20 us" + string(extra(:)) + "[scenario]" + string(scenarioLines(:))]); + end + + function verifyCaseError(testCase, scenarioLines, id, fragment) + path = testCase.writeCase(scenarioLines); + try + ldem.io.readCase(path); + testCase.verifyFail("An error was expected for: " + strjoin(string(scenarioLines), " / ")); + catch err + testCase.verifyEqual(string(err.identifier), string(id)); + testCase.verifySubstring(err.message, fragment); + end + end + end + + methods (Test, TestTags = {'Unit'}) + function coordinatesAreParsedInEveryForm(testCase) + parse = @ldem.scenarios.parseCoordinate; + r = parse(0.5); + testCase.verifyEqual(r.lo, struct('base', "", 'offset', 0.5)); + testCase.verifyEqual(r.hi, r.lo); + r = parse("max - 0.5"); + testCase.verifyEqual(r.lo, struct('base', "max", 'offset', -0.5)); + r = parse(" MID "); + testCase.verifyEqual(r.lo, struct('base', "mid", 'offset', 0)); + r = parse("min + 1.5 modules"); + testCase.verifyEqual(r.lo, struct('base', "min", 'offset', 1.5)); + r = parse("2.5 modules"); + testCase.verifyEqual(r.lo, struct('base', "", 'offset', 2.5)); + r = parse([0 5]); + testCase.verifyEqual([r.lo.offset r.hi.offset], [0 5]); + r = parse(["min + 0.5" "max - 0.5"]); + testCase.verifyEqual([r.lo.base r.hi.base], ["min" "max"]); + end + + function badCoordinatesAreRefused(testCase) + for bad = {"maximum", "max * 2", "max -", "abc", [1 2 3], "", Inf} + testCase.verifyError(@() ldem.scenarios.parseCoordinate(bad{1}), 'ldem:case:badValue'); + end + end + + function coordinateTextRoundTrips(testCase) + for value = {0.5, "max - 0.5", "mid", "min + 1", [0 5], ["min + 0.5" "max - 0.5"], 2.25} + range = ldem.scenarios.parseCoordinate(value{1}); + text = ldem.scenarios.coordinateText(range); + testCase.verifyEqual(ldem.scenarios.parseCoordinate(testCase.evaluate(text)), range); + end + testCase.verifyEqual(ldem.scenarios.coordinateText(ldem.scenarios.parseCoordinate("max - 0.5")), """max - 0.5"""); + testCase.verifyEqual(ldem.scenarios.coordinateText(ldem.scenarios.parseCoordinate(0.5)), "0.5"); + end + + function selectionByKindIdsAndCoordinates(testCase) + p = ldem.Parameters(nModules = [6 3 3]); % 5 x 2 x 2 modules, 54 grid + 20 centre nodes + sel = @(varargin) ldem.scenarios.Declarative.makeSelector(varargin{:}); + select = @(s) ldem.scenarios.selectNodes(s, p); + + testCase.verifyEqual(nnz(select(sel())), 74); + testCase.verifyEqual(nnz(select(sel(nodes = "grid"))), 54); + testCase.verifyEqual(nnz(select(sel(nodes = "centre"))), 20); + testCase.verifyEqual(find(select(sel(ids = [3 60]))).', [3 60]); + % First layer of centre nodes along x: 2 x 2 of them. + testCase.verifyEqual(nnz(select(sel(x = 0.5))), 4); + % Last layer, with the reference max. + testCase.verifyEqual(find(select(sel(x = "max - 0.5"))), find(select(sel(x = 4.5)))); + % Grid nodes at the ends of the prism (x = 0 and x = max): 2 * 3 * 3. + testCase.verifyEqual(nnz(select(sel(x = "min"))) + nnz(select(sel(x = "max"))), 2 * 3 * 3); + % mid is half of the length: x = 2.5 is a layer of centre nodes. + testCase.verifyEqual(nnz(select(sel(x = "mid"))), 4); + % A range includes both ends. + testCase.verifyEqual(nnz(select(sel(nodes = "centre", x = [0.5 1.5]))), 8); + % Combined restrictions intersect. + testCase.verifyEqual(nnz(select(sel(nodes = "centre", x = 0.5, y = 0.5, z = 0.5))), 1); + testCase.verifyEqual(nnz(select(sel(nodes = "grid", x = 0.5))), 0); + end + + function selectionIgnoresThePerturbationOfTheMesh(testCase) + plain = ldem.Parameters(nModules = [6 3 3]); + shaken = ldem.Parameters(nModules = [6 3 3], meshPerturbation = 0.02); + sel = ldem.scenarios.Declarative.makeSelector(x = 2.5); + testCase.verifyEqual(ldem.scenarios.selectNodes(sel, plain), ldem.scenarios.selectNodes(sel, shaken)); + end + + function timeFunctions(testCase) + make = @ldem.scenarios.Declarative.makeFunction; + value = @(fn, t) ldem.scenarios.timeFunction(fn, t); + testCase.verifyEqual(value(make("constant", value = 3), 7), 3); + testCase.verifyEqual(value(make("linear", rate = -2), 5), -10); + ramp = make("ramp", rate = 1000, until = 0.35e-3); + testCase.verifyEqual(value(ramp, 0.1e-3), 0.1); + testCase.verifyEqual(value(ramp, 1), 0.35); + tab = make("table", times = [0 1 3], values = [0 10 0]); + testCase.verifyEqual(value(tab, 0.5), 5); + testCase.verifyEqual(value(tab, 2), 5); + testCase.verifyEqual(value(tab, -1), 0); % before the first time + testCase.verifyEqual(value(tab, 99), 0); % after the last one + bad = make("constant"); + bad.type = "spline"; + testCase.verifyError(@() ldem.scenarios.timeFunction(bad, 0), 'ldem:scenarios:badTimeFunction'); + end + + function malformedBlocksAreRefused(testCase) + make = @ldem.scenarios.Declarative.makeFunction; + testCase.verifyError(@() make("ramp", rate = 1), 'ldem:scenarios:badDefinition'); + testCase.verifyError(@() make("table", times = [0 1], values = 1), 'ldem:scenarios:badDefinition'); + testCase.verifyError(@() make("table", times = [1 0], values = [1 2]), 'ldem:scenarios:badDefinition'); + sel = ldem.scenarios.Declarative.makeSelector(); + testCase.verifyError(@() ldem.scenarios.Declarative.makeSupport(sel, "q"), 'ldem:scenarios:badDefinition'); + testCase.verifyError(@() ldem.scenarios.Declarative.makeSupport(sel, ""), 'ldem:scenarios:badDefinition'); + support = ldem.scenarios.Declarative.makeSupport(sel, "zx"); + testCase.verifyEqual(support.fix, [1 3]); + testCase.verifyError(@() ldem.scenarios.Declarative(supports = struct('a', 1)), 'ldem:scenarios:badDefinition'); + testCase.verifyError(@() ldem.scenarios.Declarative(loads = struct('a', 1)), 'ldem:scenarios:badDefinition'); + end + + function emptySelectionNamesTheBlock(testCase) + sel = ldem.scenarios.Declarative.makeSelector(x = 99); + scenario = ldem.scenarios.Declarative( ... + supports = ldem.scenarios.Declarative.makeSupport(sel, "x", name = "ghost")); + p = ldem.Parameters(testId = 900, nModules = [6 3 3]); + try + ldem.mesh.buildMesh(p, scenario); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:scenarios:noNodesSelected'); + testCase.verifySubstring(err.message, '[[support]] number 1 ("ghost")'); + end + end + + function scenarioDataIsPreparedOnlyWhenNeeded(testCase) + p = ldem.Parameters(testId = 101, nModules = [6 3 3]); + testCase.verifyFalse(isfield(ldem.mesh.buildMesh(p), 'scenarioData')); + + left = ldem.scenarios.Declarative.makeSelector(x = 0.5); + scenario = ldem.scenarios.Declarative( ... + supports = ldem.scenarios.Declarative.makeSupport(left, "x", reaction = true)); + mesh = ldem.mesh.buildMesh(ldem.Parameters(testId = 900, nModules = [6 3 3]), scenario); + testCase.verifyTrue(isfield(mesh, 'scenarioData')); + testCase.verifyTrue(mesh.scenarioData.hasReaction); + testCase.verifyEqual(numel(mesh.scenarioData.reactionNodes{1}), 4); + testCase.verifyEmpty(mesh.scenarioData.reactionNodes{2}); + end + + function reactionIsNaNUnlessMarked(testCase) + sel = ldem.scenarios.Declarative.makeSelector(x = 0.5); + plain = ldem.scenarios.Declarative(supports = ldem.scenarios.Declarative.makeSupport(sel, "x")); + p = ldem.Parameters(testId = 900, nModules = [6 3 3]); + mesh = ldem.mesh.buildMesh(p, plain); + state = struct('force', ones(size(mesh.nodes0))); + testCase.verifyTrue(all(isnan(plain.reactions(state, mesh, p)))); + + marked = ldem.scenarios.Declarative(supports = ldem.scenarios.Declarative.makeSupport(sel, "xy", reaction = true)); + mesh = ldem.mesh.buildMesh(p, marked); + testCase.verifyEqual(marked.reactions(state, mesh, p), [4 4 0]); + end + + function forceLoadsAddUpAndDisplacementLoadsSetThePosition(testCase) + p = ldem.Parameters(testId = 900, nModules = [6 3 3]); + import ldem.scenarios.Declarative + node = Declarative.makeSelector(ids = 60); + half = Declarative.makeFunction("constant", value = 5); + scenario = ldem.scenarios.Declarative(loads = [ ... + Declarative.makeLoad(node, "y", "force", half), ... + Declarative.makeLoad(node, "y", "force", Declarative.makeFunction("linear", rate = 100)), ... + Declarative.makeLoad(Declarative.makeSelector(ids = 61), "z", "displacement", Declarative.makeFunction("linear", rate = -2))]); + mesh = ldem.mesh.buildMesh(p, scenario); + testCase.verifyTrue(mesh.fixed(61, 3)); % a prescribed displacement is held + testCase.verifyFalse(any(mesh.fixed(60, :))); % a force load leaves the node free + + state = ldem.solver.initialState(mesh, struct('tensionStiffness', 1, 'maxStrain', 1, ... + 'isUndamaged', true, 'isUnbroken', true)); + state.time = 0.5; + state.appliedForce(:) = 99; % must be reset + state = scenario.applyLoads(state, mesh, p); + testCase.verifyEqual(state.appliedForce(60, 2), 5 + 50); + testCase.verifyEqual(nnz(state.appliedForce), 1); + testCase.verifyEqual(state.displacement(61, 3), mesh.nodes0(61, 3) - 1); + end + + function reproducesTheBuiltInScenarios(testCase) + import ldem.scenarios.Declarative + + % Uniaxial tension (test 101). + params = {'nModules', [6 3 3], 'totalTime', 2e-5, 'fractureEnergy', 0.1}; + reference = ldem.runSimulation(ldem.Parameters(params{:}, testId = 101)); + scenario = ldem.scenarios.Declarative( ... + supports = Declarative.makeSupport(Declarative.makeSelector(x = 0.5), "x"), ... + loads = Declarative.makeLoad(Declarative.makeSelector(x = "max - 0.5"), "x", "displacement", ... + Declarative.makeFunction("linear", rate = -400e-5))); + result = ldem.runSimulation(ldem.Parameters(params{:}, testId = 900), Scenario = scenario); + testCase.verifyEqual(result.final.displacement, reference.final.displacement); + testCase.verifyEqual(result.energy, reference.energy); + + % Four-point bending (test 102): a short run of the 70-module beam. + params = {'nModules', [70 4 3], 'totalTime', 3e-5, 'fractureEnergy', 0.5}; + reference = ldem.runSimulation(ldem.Parameters(params{:}, testId = 102)); + pull = Declarative.makeFunction("linear", rate = -400e-5); + scenario = ldem.scenarios.Declarative( ... + supports = [Declarative.makeSupport(Declarative.makeSelector(y = 0.5, x = 4.5), "xy"), ... + Declarative.makeSupport(Declarative.makeSelector(y = 0.5, x = "max - 4.5"), "y")], ... + loads = [Declarative.makeLoad(Declarative.makeSelector(y = "max - 0.5", x = 33.5), "y", "displacement", pull, reaction = true), ... + Declarative.makeLoad(Declarative.makeSelector(y = "max - 0.5", x = "max - 33.5"), "y", "displacement", pull, reaction = true)]); + result = ldem.runSimulation(ldem.Parameters(params{:}, testId = 900), Scenario = scenario); + testCase.verifyEqual(result.final.displacement, reference.final.displacement); + testCase.verifyEqual(result.energy, reference.energy); + testCase.verifyEqual(result.reactions.force, reference.reactions.force); + + % Beam clamped at both ends and loaded with a force (test 103). + params = {'nModules', [6 6 21], 'moduleLength', 0.001, 'dt', 3.5e-7, 'totalTime', 4e-5, ... + 'youngModulus', 3.87e9, 'density', 1500, 'fractureEnergy', 0.5, 'criticalDistance', 4.5e-3}; + reference = ldem.runSimulation(ldem.Parameters(params{:}, testId = 103), ... + Scenario = ldem.scenarios.ClampedBeam(forceRate = 1000, rampTime = 0.00035)); + scenario = ldem.scenarios.Declarative( ... + supports = [Declarative.makeSupport(Declarative.makeSelector(z = 0.5), "xyz", reaction = true), ... + Declarative.makeSupport(Declarative.makeSelector(z = "max - 0.5"), "xyz", reaction = true)], ... + loads = Declarative.makeLoad(Declarative.makeSelector(y = 0.5, z = "mid - 0.5"), "y", "force", ... + Declarative.makeFunction("ramp", rate = 1000, until = 0.00035))); + result = ldem.runSimulation(ldem.Parameters(params{:}, testId = 900), Scenario = scenario); + testCase.verifyEqual(result.final.displacement, reference.final.displacement); + testCase.verifyEqual(result.energy, reference.energy); + scale = max(abs(reference.reactions.force(:))); + testCase.verifyEqual(result.reactions.force, reference.reactions.force, ... + 'RelTol', 1e-12, 'AbsTol', 1e-12 * scale); + end + + function caseFileBlocksReproduceTheUniaxialTest(testCase) + path = testCase.writeCase([ ... + "type = ""custom""" + "[[support]]" + "name = ""left end""" + "x = 0.5" + "fix = [""x""]" + "[[load]]" + "x = ""max - 0.5""" + "direction = ""x""" + "type = ""displacement""" + "time_function = ""linear""" + "rate = -4 mm/s"], ["[material]"; "fracture_energy = 0.1 N/m"]); + c = ldem.io.readCase(path); + testCase.verifyClass(c.scenario, 'ldem.scenarios.Declarative'); + testCase.verifyEqual(c.params.testId, 900); + testCase.verifyEqual(c.scenario.supports.name, "left end"); + testCase.verifyEqual(c.scenario.loads.fn.rate, -4e-3); + + viaCase = ldem.runSimulation(c.params, Scenario = c.scenario); + builtin = ldem.runSimulation(ldem.Parameters(testId = 101, nModules = [6 3 3], ... + moduleLength = 0.003, dt = 2e-7, totalTime = 20e-6, fractureEnergy = 0.1)); + testCase.verifyEqual(viaCase.final.displacement, builtin.final.displacement); + end + + function caseFilesRoundTripTheBlocks(testCase) + import ldem.scenarios.Declarative + sel = Declarative.makeSelector(nodes = "centre", ids = [3 5], x = [0.5 "max - 0.5"], z = "mid"); + scenario = ldem.scenarios.Declarative( ... + supports = [Declarative.makeSupport(Declarative.makeSelector(x = 0.5), "xz", name = "wall", reaction = true), ... + Declarative.makeSupport(sel, "y")], ... + loads = [Declarative.makeLoad(Declarative.makeSelector(y = "max - 0.5"), "y", "force", ... + Declarative.makeFunction("ramp", rate = 2500, until = 1e-5), name = "push", reaction = true), ... + Declarative.makeLoad(Declarative.makeSelector(x = [0.5 1.5]), "z", "displacement", ... + Declarative.makeFunction("table", times = [0 1e-5 2e-5], values = [0 1e-4 1e-4])), ... + Declarative.makeLoad(Declarative.makeSelector(nodes = "grid"), "x", "force", Declarative.makeFunction("constant", value = 3))]); + p = ldem.Parameters(testId = 900, nModules = [6 3 3], totalTime = 2e-5); + path = fullfile(testCase.Folder, "blocks.ldem"); + + text = ldem.io.writeCase(path, p, scenario); + testCase.verifySubstring(text, '[[support]]'); + testCase.verifySubstring(text, '[[load]]'); + testCase.verifySubstring(text, '"mid"'); + c = ldem.io.readCase(path); + testCase.verifyEqual(c.scenario.supports, scenario.supports); + testCase.verifyEqual(c.scenario.loads, scenario.loads); + testCase.verifyEqual(c.params.toStruct(), p.toStruct()); + end + + function theCustomTemplateReadsBack(testCase) + path = fullfile(testCase.Folder, "template.ldem"); + text = ldem.io.writeTemplate(path, "custom"); + testCase.verifySubstring(text, '[[support]]'); + c = ldem.io.readCase(path); + testCase.verifyEqual(numel(c.scenario.supports), 1); + testCase.verifyEqual(numel(c.scenario.loads), 1); + report = ldem.check(path); % builds the mesh: the blocks select nodes + testCase.verifyEqual(report.params.testId, 900); + end + + function aCustomCaseWithoutBlocksIsReadable(testCase) + c = ldem.io.readCase(testCase.writeCase("type = ""custom""")); + testCase.verifyEmpty(c.scenario.supports); + testCase.verifyEmpty(c.scenario.loads); + end + + function blockErrorsNameTheirLine(testCase) + testCase.verifyCaseError(["type = ""custom"""; "[[support]]"; "x = 0.5"], ... + 'ldem:case:missingKey', 'needs "fix"'); + testCase.verifyCaseError(["type = ""custom"""; "[[support]]"; "fix = [""x""]"; "flavour = 1"], ... + 'ldem:case:unknownKey', 'flavour'); + testCase.verifyCaseError(["type = ""custom"""; "[[support]]"; "fix = [""q""]"], ... + 'ldem:case:badValue', 'Directions are x, y and z'); + testCase.verifyCaseError(["type = ""custom"""; "[[support]]"; "fix = [""x""]"; "x = ""max *"""], ... + 'ldem:case:badValue', 'not a coordinate'); + testCase.verifyCaseError(["type = ""custom"""; "[[support]]"; "fix = [""x""]"; "ids = [0]"], ... + 'ldem:case:badValue', 'node numbers'); + testCase.verifyCaseError(["type = ""custom"""; "[[support]]"; "fix = [""x""]"; "nodes = ""cntre"""], ... + 'ldem:case:badValue', "Did you mean 'centre'?"); + testCase.verifyCaseError(["type = ""custom"""; "[[support]]"; "fix = [""x""]"; "reaction = 1"], ... + 'ldem:case:badValue', 'true or false'); + testCase.verifyCaseError(["type = ""custom"""; "[[load]]"; "direction = ""x"""], ... + 'ldem:case:missingKey', 'needs "type"'); + end + + function loadFunctionKeysMustMatchTheFunction(testCase) + head = ["type = ""custom"""; "[[load]]"; "direction = ""y"""; "type = ""force"""]; + testCase.verifyCaseError([head; "time_function = ""constant"""], 'ldem:case:missingKey', 'needs the key "value"'); + testCase.verifyCaseError([head; "time_function = ""constant"""; "value = 1 N"; "rate = 2 N/s"], ... + 'ldem:case:inconsistentKey', 'does not apply when time_function = "constant"'); + testCase.verifyCaseError([head; "time_function = ""ramp"""; "rate = 2 N/s"], 'ldem:case:missingKey', '"until"'); + testCase.verifyCaseError([head; "time_function = ""linear"""; "rate = 2 mm/s"], 'ldem:case:badUnit', 'N/s'); + testCase.verifyCaseError([head; "time_function = ""constant"""; "value = 2 mm"], 'ldem:case:badUnit', 'N, kN, MN'); + testCase.verifyCaseError([head; "time_function = ""table"""; "times = [0, 1]"; "values = [1]"], ... + 'ldem:case:badValue', 'table needs'); + testCase.verifyCaseError([head; "time_function = ""spline"""], 'ldem:case:badValue', 'Allowed'); + % The right unit for a displacement load is a length. + c = ldem.io.readCase(testCase.writeCase(["type = ""custom"""; "[[load]]"; "direction = ""y"""; ... + "type = ""displacement"""; "time_function = ""constant"""; "value = 2 mm"])); + testCase.verifyEqual(c.scenario.loads.fn.value, 2e-3); + end + + function blocksNeedTheCustomType(testCase) + testCase.verifyCaseError(["type = ""uniaxial_tension"""; "[[support]]"; "fix = [""x""]"], ... + 'ldem:case:inconsistentKey', 'type = "custom"'); + testCase.verifyCaseError(["type = ""custom"""; "[support]"; "fix = [""x""]"], ... + 'ldem:case:syntax', 'double brackets'); + end + end + + methods (Static, Access = private) + function value = evaluate(text) + % The right-hand side of "key = value" as the parser reads it. + entries = ldem.io.parseCaseText("k = " + text, "t"); + value = entries.value; + end + end +end diff --git a/tests/unit/TestEnergies.m b/tests/unit/TestEnergies.m new file mode 100644 index 0000000..740d31e --- /dev/null +++ b/tests/unit/TestEnergies.m @@ -0,0 +1,117 @@ +classdef TestEnergies < LdemTestCase + %TESTENERGIES Unit tests of ldem.solver.computeEnergies with hand-made states. + + methods (Access = private) + function [mesh, barProps, history, state, params] = oneBar(~) + % One bar of length 1 between two nodes of mass 2 kg and 3 kg. + params = ldem.Parameters(); + mesh = struct('nodes0', [0 0 0; 1 0 0], 'bars', [1 2], 'barLength', 1, ... + 'mass', [2; 3], 'fixed', false(2, 3)); + barProps = struct('stiffness', 100, 'criticalStrain', 1e-3, ... + 'ruptureRatio', 5, 'ruptureStrain', 5e-3); + history = struct('tensionStiffness', 100, 'maxStrain', 1e-3, ... + 'isUndamaged', true, 'isUnbroken', true); + state = ldem.solver.initialState(mesh, history); + end + end + + methods (Test, TestTags = {'Unit'}) + function everythingIsZeroAtRest(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + for name = {'kinetic', 'elastic', 'damage', 'damping', 'internal', 'brokenBars', ... + 'damageRate', 'external', 'balance'} + testCase.verifyEqual(e.(name{1}), 0, name{1}); + end + end + + function kineticEnergyIsHalfMassTimesSpeedSquared(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.velocity = [3 4 0; 0 0 2]; % speeds 5 and 2 + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(e.kinetic, 0.5 * 2 * 25 + 0.5 * 3 * 4, 'RelTol', 1e-14); + end + + function elasticEnergyOfATensionedBar(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.strain = 5e-4; + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(e.elastic, 0.5 * 100 * (5e-4)^2 * 1, 'RelTol', 1e-14); + end + + function elasticEnergyOfACompressedBarUsesTheCompressionStiffness(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.history.tensionStiffness = 10; % damaged in tension + state.strain = -5e-4; + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(e.elastic, 0.5 * 100 * (5e-4)^2, 'RelTol', 1e-14); + end + + function damageEnergyOfASofteningBar(testCase) + % Bar loaded to strain 2e-3 on the softening branch (see TestBilinearLaw): + % work 1.375e-4 minus stored energy 7.5e-5. + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.strain = 2e-3; + state.history.tensionStiffness = 37.5; + state.history.maxStrain = 2e-3; + state.history.isUndamaged = false; + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(e.damage, 6.25e-5, 'RelTol', 1e-12); + testCase.verifyEqual(e.elastic, 0.5 * 37.5 * (2e-3)^2, 'RelTol', 1e-12); + testCase.verifyEqual(e.brokenBars, 0); + end + + function brokenBarDissipatesTheWholeFractureEnergy(testCase) + % Area under the whole softening curve: E1*EP*ER/2 per unit length. + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.strain = 6e-3; + state.history.tensionStiffness = 0; + state.history.maxStrain = 5e-3; % ER + state.history.isUndamaged = false; + state.history.isUnbroken = false; + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + expected = 0.5 * 100 * 1e-3 * 5e-3; + testCase.verifyEqual(e.damage, expected, 'RelTol', 1e-12); + testCase.verifyEqual(e.brokenBars, expected, 'RelTol', 1e-12); + end + + function internalEnergyIsTheSumOfItsParts(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.velocity = [1 0 0; 0 0 0]; + state.strain = 5e-4; + state.dampingEnergy = 0.25; + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(e.internal, e.kinetic + e.elastic + e.damage + 0.25, 'RelTol', 1e-14); + testCase.verifyEqual(e.damping, 0.25); + end + + function nodalKineticEnergyAddsUpToTheTotal(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.velocity = [3 4 0; 0 0 2]; + perNode = ldem.solver.nodalKineticEnergy(state, mesh); + testCase.verifyEqual(perNode, [0.5 * 2 * 25; 0.5 * 3 * 4], 'RelTol', 1e-14); + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(sum(perNode), e.kinetic, 'RelTol', 1e-14); + end + + function balanceIsExternalMinusInternal(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.strain = 5e-4; + state.externalEnergy = 1e-3; + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(e.external, 1e-3); + testCase.verifyEqual(e.balance, 1e-3 - e.internal, 'RelTol', 1e-14); + end + + function damageRateUsesThePreviousStep(testCase) + [mesh, barProps, ~, state, params] = testCase.oneBar(); + state.strain = 2e-3; + state.history.tensionStiffness = 37.5; + state.history.maxStrain = 2e-3; + state.history.isUndamaged = false; + state.previousDamageEnergy = 6.25e-5 - 1e-6; + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + testCase.verifyEqual(e.damageRate, 1e-6 / params.dt, 'RelTol', 1e-6); + end + end +end diff --git a/tests/unit/TestExamples.m b/tests/unit/TestExamples.m new file mode 100644 index 0000000..d4f92f9 --- /dev/null +++ b/tests/unit/TestExamples.m @@ -0,0 +1,81 @@ +classdef TestExamples < LdemTestCase + %TESTEXAMPLES The example scripts run and produce their files. + % + % The tension example is run completely. The clamped beam of example 1 + % (3086 nodes, 8000 steps, about 1 minute) is also run completely and is + % tagged "Slow". The beam_102 example has about 167,000 nodes and 1.1 + % million bars, so its test only builds the model (reading DATA0.DAT and + % the random field) without integrating; it is tagged "Slow" too. + + methods (Test, TestTags = {'Unit'}) + function tensionExampleRunsAndWritesItsFiles(testCase) + folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + script = fullfile(testCase.RepoRoot, 'examples', 'tension_101', 'runTension.m'); + testCase.assertTrue(isfile(script)); + testCase.addTeardown(@() close('all', 'hidden')); + + output = runScript(script, fullfile(folder, "output")); + + testCase.verifySubstring(output, 'bars'); + for name = ["results.mat", "snapshots.pvd", "snapshot_0000.mac", ... + "snapshot_0004.mac", "snapshot_0000.vtu", "snapshot_0004.vtu"] + testCase.verifyTrue(isfile(fullfile(folder, "output", name)), name + " is missing."); + end + + data = load(fullfile(folder, "output", "results.mat")); + counts = data.results.snapshots.barCounts(end, :); + testCase.verifyGreaterThan(counts(2) + counts(3), 0, ... + 'The example is meant to show damage, but no bar softened.'); + end + end + + methods (Test, TestTags = {'Slow'}) + function clampedBeamExampleRunsAndCarriesItsLoad(testCase) + folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + script = fullfile(testCase.RepoRoot, 'examples', 'example1_clamped_beam', 'runClampedBeam.m'); + testCase.assertTrue(isfile(script)); + testCase.addTeardown(@() close('all', 'hidden')); + + output = runScript(script, fullfile(folder, "output")); + + testCase.verifySubstring(output, 'Clamped beam with 3086 nodes, 8000 steps'); + for name = ["results.mat", "snapshots.pvd", "snapshot_0000.mac", "snapshot_0008.vtu"] + testCase.verifyTrue(isfile(fullfile(folder, "output", name)), name + " is missing."); + end + + data = load(fullfile(folder, "output", "results.mat")); + results = data.results; + % Five loaded nodes carry 1000 N/s * 0.35 ms = 0.35 N each; the + % clamped ends carry the total once the beam is at rest. + testCase.verifyEqual(results.reactions.force(end, 2), 5 * 0.35, 'RelTol', 5e-2); + e = results.energy; + testCase.verifyLessThan(max(abs(e.balance)) / e.external(end), 1e-2); + end + + function beamExampleModelIsBuiltFromItsInputFile(testCase) + here = fullfile(testCase.RepoRoot, 'examples', 'beam_102'); + params = ldem.Parameters.fromFile(fullfile(here, 'DATA0.DAT'), ... + randomFieldFile = fullfile(here, 'arquivo_3lc_rnao_cv05')); + mesh = ldem.mesh.buildMesh(params); + [barProps, history] = ldem.material.buildBarProperties(mesh, params); + + nBars = size(mesh.bars, 1); + testCase.verifyEqual(size(mesh.nodes0, 1), params.nNodes); + testCase.verifyLessThanOrEqual(nBars, 1126960, ... + 'The random field file has one value per bar.'); + testCase.verifySize(barProps.criticalStrain, [nBars 1]); + testCase.verifyGreaterThan(barProps.criticalStrainCv, 0); + testCase.verifyTrue(all(history.isUnbroken)); + testCase.verifyGreaterThan(nnz(mesh.fixed), 0); + end + end +end + +function output = runScript(script, outputFolder) %#ok +%RUNSCRIPT Run an example script with "outputFolder" defined, capturing its text. +% The examples use outputFolder when it exists in the workspace they run in, +% which here is the workspace of this function. +output = evalc('run(script)'); +end diff --git a/tests/unit/TestExporters.m b/tests/unit/TestExporters.m new file mode 100644 index 0000000..9e8a37b --- /dev/null +++ b/tests/unit/TestExporters.m @@ -0,0 +1,277 @@ +classdef TestExporters < LdemTestCase + %TESTEXPORTERS Unit tests of the ANSYS and VTK exporters and SnapshotWriter. + + properties + Params + Mesh + State + end + + methods (TestMethodSetup) + function buildSmallState(testCase) + % A small model advanced far enough to have damaged and broken bars. + params = ldem.Parameters(nModules=[4 3 3], totalTime=2e-4, fractureEnergy=0.1); + mesh = ldem.mesh.buildMesh(params); + [barProps, history] = ldem.material.buildBarProperties(mesh, params); + scenario = ldem.scenarios.fromTestId(params.testId); + params.validate(); + state = ldem.solver.simulate(params, mesh, barProps, history, scenario); + testCase.Params = params; + testCase.Mesh = mesh; + testCase.State = state; + end + + function makeSureSomeBarsAreDamaged(testCase) + h = testCase.State.history; + testCase.assumeTrue(any(~h.isUndamaged), ... + 'The test state must contain damaged bars to be meaningful.'); + end + end + + methods (Access = private) + function folder = tempFolder(testCase) + folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + end + end + + methods (Test, TestTags = {'Unit'}) + function ansysFileHasTheExpectedStructure(testCase) + path = fullfile(testCase.tempFolder(), "state.mac"); + counts = ldem.io.exportAnsys(path, testCase.Mesh, testCase.State); + lines = splitlines(string(fileread(path))); + nNodes = size(testCase.Mesh.nodes0, 1); + nBars = size(testCase.Mesh.bars, 1); + + testCase.verifyEqual(nnz(startsWith(lines, "N,")), nNodes); + testCase.verifyEqual(nnz(startsWith(lines, "E,")), nBars); + testCase.verifyEqual(nnz(startsWith(lines, "TYPE,")), nBars); + testCase.verifyEqual(counts.intact + counts.damaged + counts.broken, nBars); + testCase.verifyEqual(counts.intact, nnz(testCase.State.history.isUndamaged)); + testCase.verifyEqual(counts.broken, nnz(~testCase.State.history.isUnbroken)); + testCase.verifyGreaterThan(counts.damaged + counts.broken, 0); + testCase.verifyTrue(any(lines == sprintf("!BARRAS ROMPIDAS = %d", counts.broken))); + testCase.verifyTrue(startsWith(lines(1), "!ARQUIVO NO TEMPO = ")); + testCase.verifyFalse(any(contains(lines, "IFILE")), 'The invalid ET,IFILE,4 line must not appear.'); + testCase.verifyTrue(any(lines == "ET,3,4")); + end + + function ansysConstraintsListTheFixedDofs(testCase) + path = fullfile(testCase.tempFolder(), "state.mac"); + ldem.io.exportAnsys(path, testCase.Mesh, testCase.State); + lines = splitlines(string(fileread(path))); + constraints = lines(startsWith(lines, "D,") & count(lines, ",") == 2); + testCase.verifyEqual(numel(constraints), nnz(testCase.Mesh.fixed)); + testCase.verifyTrue(all(endsWith(constraints, "UX")), 'Tension fixes x only.'); + end + + function ansysAppliedLoadsAreTheImposedDisplacements(testCase) + path = fullfile(testCase.tempFolder(), "state.mac"); + ldem.io.exportAnsys(path, testCase.Mesh, testCase.State); + lines = splitlines(string(fileread(path))); + loads = lines(startsWith(lines, "D,") & count(lines, ",") == 3); + + imposed = testCase.State.displacement - testCase.Mesh.nodes0; + imposed(~testCase.Mesh.fixed) = 0; + testCase.verifyEqual(numel(loads), nnz(imposed)); + testCase.verifyNotEmpty(loads, 'The loaded nodes have moved by the end of the run.'); + for k = 1:numel(loads) + parts = split(loads(k), ","); + node = str2double(parts(2)); + direction = find(["UX" "UY" "UZ"] == parts(3)); + testCase.verifyTrue(testCase.Mesh.fixed(node, direction), ... + 'Only held degrees of freedom receive an imposed displacement.'); + testCase.verifyEqual(str2double(parts(4)), imposed(node, direction), 'RelTol', 1e-5); + end + end + + function ansysHasNoImposedDisplacementAtTimeZero(testCase) + path = fullfile(testCase.tempFolder(), "initial.mac"); + state = testCase.State; + state.displacement = testCase.Mesh.nodes0; + ldem.io.exportAnsys(path, testCase.Mesh, state); + lines = splitlines(string(fileread(path))); + testCase.verifyFalse(any(startsWith(lines, "D,") & count(lines, ",") == 3)); + end + + function ansysListsTheAppliedForces(testCase) + path = fullfile(testCase.tempFolder(), "forces.mac"); + state = testCase.State; + state.appliedForce = zeros(size(state.displacement)); + state.appliedForce([2 5], 2) = [3.5; -1]; + ldem.io.exportAnsys(path, testCase.Mesh, state); + lines = splitlines(string(fileread(path))); + testCase.verifyEqual(lines(startsWith(lines, "F,")), ["F,2,FY,3.5"; "F,5,FY,-1"]); + end + + function ansysHasNoForceSectionWithoutAppliedForces(testCase) + path = fullfile(testCase.tempFolder(), "noforces.mac"); + ldem.io.exportAnsys(path, testCase.Mesh, testCase.State); + lines = splitlines(string(fileread(path))); + testCase.verifyFalse(any(startsWith(lines, "F,"))); + testCase.verifyFalse(any(contains(lines, "FORCAS"))); + end + + function ansysCoordinatesAreTheCurrentPositions(testCase) + path = fullfile(testCase.tempFolder(), "state.mac"); + ldem.io.exportAnsys(path, testCase.Mesh, testCase.State); + lines = splitlines(string(fileread(path))); + node = split(lines(find(startsWith(lines, "N,"), 1, 'last')), ","); + last = size(testCase.State.displacement, 1); + testCase.verifyEqual(str2double(node(2)), last); + testCase.verifyEqual(str2double(node(3:5)).', ... + double(single(testCase.State.displacement(last, :))), 'RelTol', 1e-5); + end + + function ansysCannotWriteToAnInvalidPath(testCase) + testCase.verifyError( ... + @() ldem.io.exportAnsys(fullfile(testCase.tempFolder(), "missing", "x.mac"), ... + testCase.Mesh, testCase.State), 'ldem:io:cannotOpenFile'); + end + + function vtkCannotWriteToAnInvalidPath(testCase) + testCase.verifyError( ... + @() ldem.io.exportVtk(fullfile(testCase.tempFolder(), "missing", "x.vtu"), ... + testCase.Mesh, testCase.State), 'ldem:io:cannotOpenFile'); + end + + function pvdCannotWriteToAnInvalidPath(testCase) + testCase.verifyError( ... + @() ldem.io.writePvd(fullfile(testCase.tempFolder(), "missing", "x.pvd"), 0, "a.vtu"), ... + 'ldem:io:cannotOpenFile'); + end + + function vtkFileIsValidXml(testCase) + path = fullfile(testCase.tempFolder(), "state.vtu"); + ldem.io.exportVtk(path, testCase.Mesh, testCase.State); + + doc = xmlread(char(path)); + nNodes = size(testCase.Mesh.nodes0, 1); + nBars = size(testCase.Mesh.bars, 1); + + piece = doc.getElementsByTagName('Piece').item(0); + testCase.verifyEqual(double(string(piece.getAttribute('NumberOfPoints'))), nNodes); + testCase.verifyEqual(double(string(piece.getAttribute('NumberOfCells'))), nBars); + + arrays = doc.getElementsByTagName('DataArray'); + names = strings(arrays.getLength(), 1); + for k = 1:numel(names) + names(k) = string(arrays.item(k - 1).getAttribute('Name')); + end + for expected = ["displacement", "velocity", "damageState", "strain", ... + "axialForce", "barType", "position", "connectivity", "offsets", "types"] + testCase.verifyTrue(any(names == expected), "Missing array " + expected); + end + end + + function vtkArraysHaveTheRightNumberOfValues(testCase) + path = fullfile(testCase.tempFolder(), "state.vtu"); + ldem.io.exportVtk(path, testCase.Mesh, testCase.State); + doc = xmlread(char(path)); + nNodes = size(testCase.Mesh.nodes0, 1); + nBars = size(testCase.Mesh.bars, 1); + + expected = dictionary("position", 3 * nNodes, "displacement", 3 * nNodes, ... + "velocity", 3 * nNodes, "connectivity", 2 * nBars, "offsets", nBars, ... + "types", nBars, "damageState", nBars, "strain", nBars, "axialForce", nBars); + arrays = doc.getElementsByTagName('DataArray'); + for k = 0:arrays.getLength() - 1 + node = arrays.item(k); + name = string(node.getAttribute('Name')); + if isKey(expected, name) + values = sscanf(char(node.getTextContent()), '%f'); + testCase.verifyEqual(numel(values), expected(name), "Wrong size of " + name); + end + end + end + + function vtkConnectivityIsZeroBasedAndOffsetsAreCumulative(testCase) + path = fullfile(testCase.tempFolder(), "state.vtu"); + ldem.io.exportVtk(path, testCase.Mesh, testCase.State); + doc = xmlread(char(path)); + arrays = doc.getElementsByTagName('DataArray'); + data = struct(); + for k = 0:arrays.getLength() - 1 + node = arrays.item(k); + data.(char(node.getAttribute('Name'))) = sscanf(char(node.getTextContent()), '%f'); + end + testCase.verifyEqual(reshape(data.connectivity, 2, []).', testCase.Mesh.bars - 1); + testCase.verifyEqual(data.offsets, 2 * (1:size(testCase.Mesh.bars, 1)).'); + testCase.verifyTrue(all(data.types == 3), 'Every cell must be a VTK_LINE (3).'); + end + + function vtkDamageStateMatchesTheBars(testCase) + path = fullfile(testCase.tempFolder(), "state.vtu"); + ldem.io.exportVtk(path, testCase.Mesh, testCase.State); + doc = xmlread(char(path)); + arrays = doc.getElementsByTagName('DataArray'); + for k = 0:arrays.getLength() - 1 + if string(arrays.item(k).getAttribute('Name')) == "damageState" + values = sscanf(char(arrays.item(k).getTextContent()), '%d'); + end + end + h = testCase.State.history; + testCase.verifyEqual(nnz(values == 0), nnz(h.isUndamaged)); + testCase.verifyEqual(nnz(values == 2), nnz(~h.isUnbroken)); + testCase.verifyEqual(nnz(values == 1), nnz(~h.isUndamaged & h.isUnbroken)); + end + + function pvdListsTheFilesWithTheirTimes(testCase) + path = fullfile(testCase.tempFolder(), "series.pvd"); + ldem.io.writePvd(path, [0; 1e-4; 2e-4], ["a.vtu"; "b.vtu"; "c.vtu"]); + doc = xmlread(char(path)); + items = doc.getElementsByTagName('DataSet'); + testCase.verifyEqual(items.getLength(), 3); + testCase.verifyEqual(string(items.item(1).getAttribute('file')), "b.vtu"); + testCase.verifyEqual(str2double(string(items.item(2).getAttribute('timestep'))), 2e-4); + end + + function pvdRejectsMismatchedInputs(testCase) + testCase.verifyError( ... + @() ldem.io.writePvd(fullfile(testCase.tempFolder(), "x.pvd"), [0; 1], "a.vtu"), ... + 'ldem:io:sizeMismatch'); + end + + function snapshotWriterWritesFilesAndACollection(testCase) + folder = fullfile(testCase.tempFolder(), "out"); + writer = ldem.io.SnapshotWriter(testCase.Mesh, folder, ["ansys" "vtk"]); + writer.write(testCase.State); + later = testCase.State; + later.step = 10; + later.time = 2e-6; + writer.write(later); + snapshots = writer.finish(); + + for name = ["snapshot_0000.mac", "snapshot_0001.mac", "snapshot_0000.vtu", ... + "snapshot_0001.vtu", "snapshots.pvd"] + testCase.verifyTrue(isfile(fullfile(folder, name)), name + " was not written."); + end + testCase.verifyEqual(snapshots.step, [testCase.State.step; 10]); + testCase.verifySize(snapshots.barCounts, [2 3]); + testCase.verifyEqual(sum(snapshots.barCounts, 2), repmat(size(testCase.Mesh.bars, 1), 2, 1)); + testCase.verifyClass(snapshots.displacement{1}, 'single'); + testCase.verifyClass(snapshots.damageState{1}, 'uint8'); + end + + function snapshotWriterKeepsSnapshotsInMemoryWithoutFiles(testCase) + writer = ldem.io.SnapshotWriter(testCase.Mesh); + writer.write(testCase.State); + snapshots = writer.finish(); + testCase.verifyEqual(numel(snapshots.time), 1); + testCase.verifyEqual(sum(snapshots.barCounts), size(testCase.Mesh.bars, 1)); + end + + function snapshotWriterNeedsAFolderToExport(testCase) + testCase.verifyError(@() ldem.io.SnapshotWriter(testCase.Mesh, "", "vtk"), ... + 'ldem:io:noFolder'); + end + + function saveResultsRoundTrip(testCase) + results = struct('a', magic(3), 'nested', struct('b', "text", 'c', {{1, 'x'}})); + path = fullfile(testCase.tempFolder(), "sub", "results.mat"); + ldem.io.saveResults(path, results); + loaded = load(path); + testCase.verifyEqual(loaded.results, results); + end + end +end diff --git a/tests/unit/TestExtendsAndSweep.m b/tests/unit/TestExtendsAndSweep.m new file mode 100644 index 0000000..5d3dd1d --- /dev/null +++ b/tests/unit/TestExtendsAndSweep.m @@ -0,0 +1,329 @@ +classdef TestExtendsAndSweep < LdemTestCase + %TESTEXTENDSANDSWEEP Unit tests of case-file inheritance (extends) and of parameter sweeps. + + properties (Access = private) + Folder (1,1) string + end + + methods (TestMethodSetup) + function makeFolder(testCase) + testCase.Folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + end + end + + methods (Access = private) + function lines = base(~) + lines = [ ... + "format = 1" + "[mesh]" + "module_size = 3 mm" + "modules = [5, 2, 2]" + "[time]" + "step = 0.2 us" + "duration = 20 us" + "[material]" + "fracture_energy = 0.1 N/m" + "[scenario]" + "type = ""uniaxial_tension"""]; + end + + function path = put(testCase, relative, lines) + path = fullfile(testCase.Folder, relative); + writeTextFile(path, string(lines(:))); + end + + function verifyCaseError(testCase, path, id, fragment) + try + ldem.io.readCase(path); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(string(err.identifier), string(id)); + testCase.verifySubstring(err.message, fragment); + end + end + end + + methods (Test, TestTags = {'Unit'}) + function aChildOverridesAndInherits(testCase) + testCase.put("base.ldem", testCase.base()); + child = testCase.put("child.ldem", [ ... + "extends = ""base.ldem""" + "[material]" + "young_modulus = 10 GPa" + "[time]" + "duration = 40 us"]); + c = ldem.io.readCase(child); + testCase.verifyEqual(c.params.youngModulus, 10e9); % set by the child + testCase.verifyEqual(c.params.totalTime, 40e-6); % replaced by the child + testCase.verifyEqual(c.params.fractureEnergy, 0.1); % inherited, same section + testCase.verifyEqual(c.params.dt, 2e-7); % inherited + testCase.verifyEqual(c.params.nModules, [6 3 3]); + testCase.verifyEqual(c.info.parents, string(fullfile(testCase.Folder, "base.ldem"))); + end + + function theChildCanLeaveOutRequiredKeys(testCase) + testCase.put("base.ldem", testCase.base()); + child = testCase.put("child.ldem", ["extends = ""base.ldem"""; "title = ""Only the title"""]); + c = ldem.io.readCase(child); + testCase.verifyEqual(c.info.title, "Only the title"); + testCase.verifyEqual(c.params.totalTime, 20e-6); + end + + function relativePathsFollowTheFileThatWritesThem(testCase) + testCase.put("parent/base.ldem", [testCase.base(); "[material.scatter]"; "type = ""file"""; ... + "file = ""field.txt"""; "[output]"; "folder = ""out"""]); + child = testCase.put("child/child.ldem", ["extends = ""../parent/base.ldem"""; ... + "[material]"; "young_modulus = 10 GPa"]); + c = ldem.io.readCase(child); + testCase.verifyEqual(string(c.params.randomFieldFile), ... + string(fullfile(testCase.Folder, "parent", "field.txt"))); + testCase.verifyEqual(c.options.OutputFolder, string(fullfile(testCase.Folder, "parent", "out"))); + end + + function repeatedTablesAreReplacedAsAWhole(testCase) + testCase.put("base.ldem", [testCase.base(); "[[monitor.node]]"; "id = 2"; "[[monitor.node]]"; "id = 3"]); + keep = testCase.put("keep.ldem", ["extends = ""base.ldem"""; "[material]"; "density = 1500 kg/m3"]); + testCase.verifyEqual(ldem.io.readCase(keep).params.controlNodes, [2 3]); + replace = testCase.put("replace.ldem", ["extends = ""base.ldem"""; "[[monitor.node]]"; "id = 5"]); + testCase.verifyEqual(ldem.io.readCase(replace).params.controlNodes, 5); + end + + function changingTheTypeDropsTheKeysOfTheOldOne(testCase) + lines = testCase.base(); + lines = lines(~startsWith(lines, ["[scenario]" "type"])); + testCase.put("beam.ldem", [lines; "[scenario]"; "type = ""clamped_beam"""; "force_rate = 2 kN/s"; ... + "[damping]"; "type = ""mass_proportional"""; "initial = 100"; "final = 100"; ... + "[material.scatter]"; "type = ""generated"""; "cv = 0.1"]); + child = testCase.put("child.ldem", [ ... + "extends = ""beam.ldem""" + "[scenario]" + "type = ""uniaxial_tension""" + "[damping]" + "type = ""none""" + "[material.scatter]" + "type = ""none"""]); + c = ldem.io.readCase(child); + testCase.verifyClass(c.scenario, 'ldem.scenarios.UniaxialTension'); + testCase.verifyEqual(c.params.dampingModel, "none"); + testCase.verifyEqual(c.params.randomFieldCv, 0); + + % Same type: the inherited keys stay. + same = testCase.put("same.ldem", ["extends = ""beam.ldem"""; "[scenario]"; "type = ""clamped_beam"""]); + testCase.verifyEqual(ldem.io.readCase(same).scenario.forceRate, 2000); + end + + function severalParentsApplyInOrder(testCase) + testCase.put("a.ldem", testCase.base()); + testCase.put("b.ldem", ["[material]"; "young_modulus = 10 GPa"; "density = 1000 kg/m3"]); + testCase.put("c.ldem", ["[material]"; "young_modulus = 20 GPa"]); + child = testCase.put("child.ldem", ["extends = [""a.ldem"", ""b.ldem"", ""c.ldem""]"; ... + "[material]"; "poisson_ratio = 0.2"]); + c = ldem.io.readCase(child); + testCase.verifyEqual(c.params.youngModulus, 20e9); % the last parent wins + testCase.verifyEqual(c.params.density, 1000); + testCase.verifyEqual(c.params.poissonRatio, 0.2); + testCase.verifyEqual(numel(c.info.parents), 3); + end + + function chainsOfParentsWork(testCase) + testCase.put("a.ldem", testCase.base()); + testCase.put("b.ldem", ["extends = ""a.ldem"""; "[material]"; "young_modulus = 10 GPa"]); + child = testCase.put("c.ldem", ["extends = ""b.ldem"""; "[material]"; "density = 1000 kg/m3"]); + c = ldem.io.readCase(child); + testCase.verifyEqual(c.params.youngModulus, 10e9); + testCase.verifyEqual(c.params.density, 1000); + testCase.verifyEqual(c.params.fractureEnergy, 0.1); + testCase.verifyEqual(c.info.parents, string(fullfile(testCase.Folder, ["a.ldem"; "b.ldem"]))); + end + + function loopsAndMissingParentsAreErrors(testCase) + testCase.put("a.ldem", "extends = ""b.ldem"""); + testCase.put("b.ldem", "extends = ""a.ldem"""); + testCase.verifyCaseError(fullfile(testCase.Folder, "a.ldem"), 'ldem:case:extendsLoop', 'in a loop'); + lonely = testCase.put("lonely.ldem", "extends = ""missing.ldem"""); + testCase.verifyCaseError(lonely, 'ldem:io:fileNotFound', 'lonely.ldem:1 extends'); + bad = testCase.put("bad.ldem", "extends = 3"); + testCase.verifyCaseError(bad, 'ldem:case:badValue', 'in quotes'); + end + + function errorsNameTheFileWhereTheyAreWritten(testCase) + lines = testCase.base(); + lines(lines == "step = 0.2 us") = "step = 0.2 kg"; + testCase.put("base.ldem", lines); + child = testCase.put("child.ldem", "extends = ""base.ldem"""); + testCase.verifyCaseError(child, 'ldem:case:badUnit', 'base.ldem:6 [time] step'); + end + + function runKeepsTheParentsAndTheirHashes(testCase) + testCase.put("base.ldem", testCase.base()); + child = testCase.put("child.ldem", "extends = ""base.ldem"""); + results = ldem.run(child, OutputFolder = "", Verbose = false); + info = results.info.case; + testCase.verifyEqual(numel(info.parents), 1); + testCase.verifyEqual(strlength(info.parents.sha256), 64); + testCase.verifyEqual(info.original, string(fileread(child))); + % The resolved case has everything and needs no parent. + path = fullfile(testCase.Folder, "resolved.ldem"); + writeTextFile(path, splitlines(info.resolved)); + testCase.verifyEqual(ldem.io.readCase(path).params.toStruct(), results.params); + end + + function sweepBlocksAreReadAndChecked(testCase) + % sweep_mode is a key at the top of the file, before the first table. + path = fullfile(testCase.Folder, "sweep.ldem"); + writeTextFile(path, ["sweep_mode = ""zip"""; testCase.base(); ... + "[[sweep]]"; "key = ""material.fracture_energy"""; "values = [""0.1 N/m"", ""0.5 N/m""]"; ... + "[[sweep]]"; "key = ""time.duration"""; "values = [2e-5, 4e-5]"]); + c = ldem.io.readCase(path); + testCase.verifyEqual(c.info.sweepMode, "zip"); + testCase.verifyEqual(numel(c.info.sweep), 2); + testCase.verifyEqual(c.info.sweep(1).key, "material.fracture_energy"); + testCase.verifyEqual(c.info.sweep(1).values, {"0.1 N/m", "0.5 N/m"}); + testCase.verifyEqual(c.info.sweep(2).values, {2e-5, 4e-5}); + end + + function badSweepBlocks(testCase) + bad = @(lines) testCase.put("bad.ldem", [testCase.base(); string(lines(:))]); + testCase.verifyCaseError(bad(["[[sweep]]"; "key = ""time.duration"""]), 'ldem:case:missingKey', 'needs "key"'); + testCase.verifyCaseError(bad(["[[sweep]]"; "key = ""time.duraton"""; "values = [1]"]), ... + 'ldem:case:badValue', "Did you mean 'time.duration'?"); + testCase.verifyCaseError(bad(["[[sweep]]"; "key = ""mesh.modules"""; "values = [1]"]), ... + 'ldem:case:badValue', 'cannot be swept'); + testCase.verifyCaseError(bad(["[[sweep]]"; "key = ""load.rate"""; "values = [1]"]), ... + 'ldem:case:badValue', 'cannot be swept'); + testCase.verifyCaseError(bad(["[[sweep]]"; "key = 3"; "values = [1]"]), 'ldem:case:badValue', 'in quotes'); + testCase.verifyCaseError(bad(["[[sweep]]"; "key = ""time.duration"""; "values = []"]), ... + 'ldem:case:badValue', 'non-empty list'); + testCase.verifyCaseError(bad(["[sweep]"; "key = ""time.duration"""; "values = [1]"]), ... + 'ldem:case:syntax', 'double brackets'); + end + + function overridesChangeKeysOfTheCase(testCase) + path = testCase.put("case.ldem", testCase.base()); + overrides = struct('path', {"material.fracture_energy", "time.duration"}, ... + 'value', {"2 N/m", 3e-5}); + c = ldem.io.readCase(path, Overrides = overrides); + testCase.verifyEqual(c.params.fractureEnergy, 2); + testCase.verifyEqual(c.params.totalTime, 3e-5); + + testCase.verifyError(@() ldem.io.readCase(path, Overrides = struct('path', "mesh.nonsense", 'value', 1)), ... + 'ldem:sweep:unknownKey'); + testCase.verifyError(@() ldem.io.readCase(path, Overrides = struct('path', "support.fix", 'value', "x")), ... + 'ldem:sweep:unsupportedKey'); + % A bad value is reported where it is used. + try + ldem.io.readCase(path, Overrides = struct('path', "material.fracture_energy", 'value', "2 kg")); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:case:badUnit'); + testCase.verifySubstring(err.message, 'sweep [material] fracture_energy'); + end + end + + function overridesCanSetScenarioKeys(testCase) + lines = testCase.base(); + lines = lines(~startsWith(lines, ["[scenario]" "type"])); + path = testCase.put("beam.ldem", [lines; "[scenario]"; "type = ""clamped_beam"""]); + c = ldem.io.readCase(path, Overrides = struct('path', "scenario.force_rate", 'value', "3 kN/s")); + testCase.verifyEqual(c.scenario.forceRate, 3000); + end + + function dryRunListsTheCombinations(testCase) + path = testCase.put("sweep.ldem", [testCase.base(); ... + "[[sweep]]"; "key = ""material.fracture_energy"""; "values = [""0.1 N/m"", ""0.5 N/m"", ""1 N/m""]"; ... + "[[sweep]]"; "key = ""time.duration"""; "values = [2e-5, 4e-5]"]); + summary = ldem.sweep(path, DryRun = true, Verbose = false); + testCase.verifySize(summary, [6 9]); + testCase.verifyEqual(summary.status, repmat("planned", 6, 1)); + testCase.verifyEqual(summary.material_fracture_energy, ["0.1 N/m"; "0.5 N/m"; "1 N/m"; "0.1 N/m"; "0.5 N/m"; "1 N/m"]); + testCase.verifyEqual(summary.time_duration, ["2e-05"; "2e-05"; "2e-05"; "4e-05"; "4e-05"; "4e-05"]); + testCase.verifyTrue(all(endsWith(summary.folder, "run_" + compose("%03d", (1:6).')))); + testCase.verifyFalse(isfolder(fullfile(testCase.Folder, "sweep_sweep"))); % nothing was created + + % The mode of the file can be overridden: the lists of 3 and 2 values cannot be zipped. + testCase.verifyError(@() ldem.sweep(path, DryRun = true, Verbose = false, Mode = "zip"), ... + 'ldem:sweep:zipLengths'); + end + + function varyAddsKeysAndZipNeedsEqualLengths(testCase) + path = testCase.put("case.ldem", testCase.base()); + summary = ldem.sweep(path, DryRun = true, Verbose = false, ... + Vary = {"material.fracture_energy", [0.1 0.5], "time.duration", ["20 us", "30 us"]}, Mode = "zip"); + testCase.verifyEqual(height(summary), 2); + testCase.verifyError(@() ldem.sweep(path, DryRun = true, Verbose = false, Mode = "zip", ... + Vary = {"material.fracture_energy", [0.1 0.5], "time.duration", ["20 us", "30 us", "40 us"]}), ... + 'ldem:sweep:zipLengths'); + testCase.verifyError(@() ldem.sweep(path, DryRun = true, Verbose = false), 'ldem:sweep:noKeys'); + testCase.verifyError(@() ldem.sweep(path, DryRun = true, Vary = {"a"}), 'ldem:sweep:invalidRun'); + end + + function invalidRunsStopTheSweepBeforeItStarts(testCase) + path = testCase.put("case.ldem", testCase.base()); + try + ldem.sweep(path, Verbose = false, OutputFolder = fullfile(testCase.Folder, "out"), ... + Vary = {"time.step", ["0.2 us", "50 us"]}); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:sweep:invalidRun'); + testCase.verifySubstring(err.message, 'Run 2'); + testCase.verifySubstring(err.message, 'time.step = 50 us'); + end + testCase.verifyFalse(isfolder(fullfile(testCase.Folder, "out"))); + try + ldem.sweep(path, DryRun = true, Vary = {"mesh.nonsense", [1 2]}); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:sweep:invalidRun'); + testCase.verifySubstring(err.message, 'does not exist'); + end + end + + function aSweepRunsEveryCaseAndSummarisesThem(testCase) + lines = testCase.base(); + lines(lines == "duration = 20 us") = "duration = 200 us"; + path = testCase.put("case.ldem", lines); + out = fullfile(testCase.Folder, "runs"); + [summary, results] = ldem.sweep(path, Verbose = false, OutputFolder = out, Formats = "mat", ... + KeepResults = true, ... + Vary = {"material.fracture_energy", ["0.1 N/m", "50 N/m"]}); + + testCase.verifyEqual(summary.status, ["done"; "done"]); + testCase.verifyEqual(summary.run, [1; 2]); + for r = 1:2 + testCase.verifyTrue(isfile(fullfile(out, sprintf("run_%03d", r), "results.mat"))); + testCase.verifyTrue(isfile(fullfile(out, sprintf("run_%03d", r), "case.ldem"))); + end + testCase.verifyTrue(isfile(fullfile(out, "sweep_summary.csv"))); + testCase.verifyEqual(results{1}.params.fractureEnergy, 0.1); + testCase.verifyEqual(results{2}.params.fractureEnergy, 50); + testCase.verifyEqual(results{1}.info.case.overrides, "material.fracture_energy = 0.1 N/m"); + testCase.verifyGreaterThanOrEqual(summary.damagedBars(1), summary.damagedBars(2)); + testCase.verifyGreaterThan(summary.damagedBars(1), 0); + testCase.verifyTrue(all(summary.seconds > 0)); + + % The resolved case of a run has the varied value in it. + again = ldem.io.readCase(fullfile(out, "run_001", "case.ldem")); + testCase.verifyEqual(again.params.fractureEnergy, 0.1); + + table = readtable(fullfile(out, "sweep_summary.csv"), 'TextType', 'string'); + testCase.verifyEqual(height(table), 2); + testCase.verifyEqual(table.status, ["done"; "done"]); + end + + function resultsAreNotKeptUnlessAsked(testCase) + path = testCase.put("case.ldem", testCase.base()); + [summary, results] = ldem.sweep(path, Verbose = false, ... + OutputFolder = fullfile(testCase.Folder, "runs"), Formats = "mat", ... + Vary = {"time.duration", ["4 us", "6 us"]}); + testCase.verifyEqual(summary.status, ["done"; "done"]); + testCase.verifyEqual(results, cell(2, 1)); + end + + function runWarnsWhenTheCaseDefinesASweep(testCase) + path = testCase.put("sweep.ldem", [testCase.base(); ... + "[[sweep]]"; "key = ""material.fracture_energy"""; "values = [0.1, 0.5]"]); + testCase.verifyWarning(@() ldem.run(path, OutputFolder = "", Verbose = false), 'ldem:run:sweepIgnored'); + end + end +end diff --git a/tests/unit/TestGenerateRandomField.m b/tests/unit/TestGenerateRandomField.m new file mode 100644 index 0000000..046b522 --- /dev/null +++ b/tests/unit/TestGenerateRandomField.m @@ -0,0 +1,108 @@ +classdef TestGenerateRandomField < LdemTestCase + %TESTGENERATERANDOMFIELD Unit tests of ldem.material.generateRandomField. + + methods (Access = private) + function centres = gridCentres(~, n, spacing) + % Points of a regular n(1)-by-n(2)-by-n(3) grid with the given spacing. + [x, y, z] = ndgrid((0:n(1)-1) * spacing, (0:n(2)-1) * spacing, (0:n(3)-1) * spacing); + centres = [x(:), y(:), z(:)]; + end + end + + methods (Test, TestTags = {'Unit'}) + function oneValuePerBarAllPositive(testCase) + centres = testCase.gridCentres([10 6 6], 1e-3); + field = ldem.material.generateRandomField(centres, 0.2, 3e-3, 1); + testCase.verifySize(field, [size(centres, 1) 1]); + testCase.verifyGreaterThan(min(field), 0); + testCase.verifyTrue(all(isfinite(field))); + end + + function weibullOfThePolesHasMeanOneAndTheRequestedCv(testCase) + for cv = [0.01 0.05 0.2 1] + [~, info] = ldem.material.generateRandomField([0 0 0], cv, 1, 1); + k = info.weibullShape; + lambda = info.weibullScale; + m1 = lambda * gamma(1 + 1/k); + m2 = lambda^2 * gamma(1 + 2/k); + testCase.verifyEqual(m1, 1, 'RelTol', 1e-10); + testCase.verifyEqual(sqrt(m2 - m1^2) / m1, cv, 'RelTol', 1e-8); + end + end + + function polesHaveTheRequestedStatistics(testCase) + % Bars exactly on the poles take the pole values, so with a + % correlation length equal to the spacing the field is the + % (independent) pole values: check their sample mean and CV. + centres = testCase.gridCentres([40 40 40], 1); + field = ldem.material.generateRandomField(centres, 0.1, 1, 7); + testCase.verifyEqual(mean(field), 1, 'AbsTol', 0.005); + testCase.verifyEqual(std(field) / mean(field), 0.1, 'RelTol', 0.03); + end + + function interpolationReducesTheScatter(testCase) + centres = testCase.gridCentres([30 30 30], 1); + [~, info] = ldem.material.generateRandomField(centres, 0.1, 6, 7); + testCase.verifyLessThan(info.fieldCv, 0.1); + testCase.verifyGreaterThan(info.fieldCv, 0); + end + + function longerCorrelationMakesNeighboursMoreAlike(testCase) + centres = testCase.gridCentres([60 4 4], 1); + jump = @(f) mean(abs(diff(reshape(f, 60, []), 1, 1)), 'all') / mean(f); + short = ldem.material.generateRandomField(centres, 0.2, 1.5, 3); + long = ldem.material.generateRandomField(centres, 0.2, 10, 3); + testCase.verifyLessThan(jump(long), jump(short)); + end + + function fieldIsLinearBetweenTwoPoles(testCase) + % Along a line between two poles the field is a straight line. + centres = [linspace(0, 1, 11).', zeros(11, 1), zeros(11, 1)]; + field = ldem.material.generateRandomField(centres, 0.3, 1, 4); + testCase.verifyEqual(diff(field, 2), zeros(9, 1), 'AbsTol', 1e-12); + end + + function sameSeedSameFieldAndGlobalStreamUntouched(testCase) + centres = testCase.gridCentres([8 5 5], 1e-3); + rng(42); + before = rand(); + rng(42); + a = ldem.material.generateRandomField(centres, 0.1, 2e-3, 11); + after = rand(); + b = ldem.material.generateRandomField(centres, 0.1, 2e-3, 11); + c = ldem.material.generateRandomField(centres, 0.1, 2e-3, 12); + testCase.verifyEqual(a, b); + testCase.verifyNotEqual(a, c); + testCase.verifyEqual(after, before, 'The global random stream must not be used.'); + end + + function anisotropicCorrelationLength(testCase) + centres = testCase.gridCentres([10 10 10], 1); + [~, info] = ldem.material.generateRandomField(centres, 0.1, [1 2 5], 1); + testCase.verifyEqual(info.correlationLength, [1 2 5]); + testCase.verifyEqual(info.nPoles, [12 8 5]); + end + + function infoDescribesTheField(testCase) + centres = testCase.gridCentres([5 5 5], 1); + [field, info] = ldem.material.generateRandomField(centres, 0.05, 2, 515); + testCase.verifyEqual(info.source, "generated"); + testCase.verifyEqual(info.cv, 0.05); + testCase.verifyEqual(info.seed, 515); + testCase.verifyEqual(info.fieldMean, mean(field)); + testCase.verifyEqual(info.fieldCv, std(field) / mean(field)); + end + + function badCorrelationLengthIsRejected(testCase) + testCase.verifyError( ... + @() ldem.material.generateRandomField([0 0 0], 0.1, [1 2], 1), ... + 'ldem:material:badCorrelationLength'); + end + + function tooSmallCvIsRejected(testCase) + testCase.verifyError( ... + @() ldem.material.generateRandomField([0 0 0], 1e-7, 1, 1), ... + 'ldem:material:randomFieldCvTooSmall'); + end + end +end diff --git a/tests/unit/TestKeyReference.m b/tests/unit/TestKeyReference.m new file mode 100644 index 0000000..5f241e4 --- /dev/null +++ b/tests/unit/TestKeyReference.m @@ -0,0 +1,42 @@ +classdef TestKeyReference < LdemTestCase + %TESTKEYREFERENCE The key reference of the user guide is generated from the schema. + + methods (Test, TestTags = {'Unit'}) + function theGuideAgreesWithTheSchema(testCase) + file = fullfile(testCase.RepoRoot, "docs", "source", "case-keys.inc"); + testCase.assertTrue(isfile(file), ... + 'docs/source/case-keys.inc is missing: run ldem.schema.writeKeyReference("docs/source/case-keys.inc").'); + written = strrep(string(fileread(file)), char(13), ""); + generated = ldem.schema.writeKeyReference(); + testCase.verifyTrue(isequal(written, generated), ... + ['docs/source/case-keys.inc is out of date with ldem.schema.caseSchema: from the repository ' ... + 'root run ldem.schema.writeKeyReference("docs/source/case-keys.inc") and commit it.']); + end + + function everyKeyOfTheSchemaIsListed(testCase) + text = ldem.schema.writeKeyReference(); + schema = ldem.schema.caseSchema(); + for row = schema.' + key = string(regexprep(row.path, '^.*\.', '')); + testCase.verifySubstring(text, "``" + key + "``", row.path); + end + end + + function theTextHasTheExpectedShape(testCase) + text = ldem.schema.writeKeyReference(); + testCase.verifySubstring(text, ".. rubric:: ``[mesh]``"); + testCase.verifySubstring(text, ".. rubric:: ``[[support]]``"); + testCase.verifySubstring(text, "number + unit (m, cm, mm, um, km)"); + testCase.verifySubstring(text, "3 mm"); % default of module_size + testCase.verifySubstring(text, "required"); + testCase.verifyTrue(endsWith(text, newline)); + end + + function writesTheFile(testCase) + folder = testCase.applyFixture(matlab.unittest.fixtures.TemporaryFolderFixture).Folder; + path = fullfile(folder, "keys.inc"); + text = ldem.schema.writeKeyReference(path); + testCase.verifyEqual(strrep(string(fileread(path)), char(13), ""), text); + end + end +end diff --git a/tests/unit/TestLawsAndDamping.m b/tests/unit/TestLawsAndDamping.m new file mode 100644 index 0000000..fe63fe7 --- /dev/null +++ b/tests/unit/TestLawsAndDamping.m @@ -0,0 +1,281 @@ +classdef TestLawsAndDamping < LdemTestCase + %TESTLAWSANDDAMPING Unit tests of the constitutive laws and damping models. + + properties (Constant) + E1 = 1e6 % bar stiffness [N] + L = 0.01 % bar length [m] + Mass = 0.1 % mass of the free node [kg] + end + + properties (Access = private) + Folder (1,1) string + end + + methods (TestMethodSetup) + function makeFolder(testCase) + testCase.Folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + end + end + + methods (Access = private) + function [mesh, barProps, history] = oscillator(testCase) + % One bar: node 1 fixed, node 2 free along x (a spring of constant E1/L). + mesh = struct( ... + 'nodes0', [0 0 0; testCase.L 0 0], ... + 'bars', [1 2], ... + 'barLength', testCase.L, ... + 'mass', [testCase.Mass; testCase.Mass], ... + 'fixed', [true true true; false true true]); + barProps = struct('stiffness', testCase.E1, 'criticalStrain', 1, ... + 'ruptureRatio', 10, 'ruptureStrain', 10); + history = struct('tensionStiffness', testCase.E1, 'maxStrain', 1, ... + 'isUndamaged', true, 'isUnbroken', true); + end + + function [barProps, history, length] = threeBars(testCase) + % Bars 1-3 at strain 0.5e-3 (elastic), 2e-3 (softening) and 5e-3 (broken). + barProps = struct('stiffness', testCase.E1 * [1; 1; 1], ... + 'criticalStrain', 1e-3 * [1; 1; 1], 'ruptureRatio', 5 * [1; 1; 1], ... + 'ruptureStrain', 5e-3 * [1; 1; 1]); + history = struct('tensionStiffness', testCase.E1 * [1; 1; 1], ... + 'maxStrain', 1e-3 * [1; 1; 1], 'isUndamaged', true(3, 1), 'isUnbroken', true(3, 1)); + length = 0.01 * [1; 1; 1]; + end + + function path = writeCase(testCase, extra) + path = fullfile(testCase.Folder, "case.ldem"); + writeTextFile(path, [ ... + "format = 1" + "[mesh]" + "module_size = 3 mm" + "modules = [5, 2, 2]" + "[time]" + "step = 0.2 us" + "duration = 40 us" + "[scenario]" + "type = ""uniaxial_tension""" + string(extra(:))]); + end + end + + methods (Test, TestTags = {'Unit'}) + function registriesAgreeWithTheirClasses(testCase) + laws = ldem.material.lawRegistry(); + testCase.verifyEqual(numel(unique([laws.name])), numel(laws)); + for entry = laws + law = feval(entry.className); + testCase.verifyEqual(law.name, entry.name); + testCase.verifyInstanceOf(law, 'ldem.material.MaterialLaw'); + testCase.verifyClass(ldem.material.lawFromName(entry.name), entry.className); + testCase.verifyClass(ldem.material.lawFromName(upper(entry.name)), entry.className); + end + models = ldem.solver.dampingRegistry(); + testCase.verifyEqual(numel(unique([models.name])), numel(models)); + for entry = models + model = feval(entry.className); + testCase.verifyEqual(model.name, entry.name); + testCase.verifyInstanceOf(model, 'ldem.solver.DampingModel'); + testCase.verifyClass(ldem.solver.dampingFromName(entry.name), entry.className); + testCase.verifyTrue(all(ismember(entry.keys, ["initial" "final" "switch_time"]))); + end + end + + function unknownNamesAreSuggested(testCase) + testCase.verifyError(@() ldem.material.lawFromName("bilinar"), 'ldem:material:unknownLaw'); + try + ldem.material.lawFromName("bilinar"); + catch err + testCase.verifySubstring(err.message, "Did you mean 'bilinear'?"); + end + testCase.verifyError(@() ldem.solver.dampingFromName("mass"), 'ldem:solver:unknownDamping'); + end + + function parametersCheckTheNames(testCase) + p = ldem.Parameters(); + testCase.verifyEqual(p.constitutiveLaw, "bilinear"); + testCase.verifyEqual(p.dampingModel, "mass_proportional"); + testCase.verifyError(@() ldem.Parameters(constitutiveLaw = "plastic"), 'ldem:params:unknownLaw'); + testCase.verifyError(@() ldem.Parameters(dampingModel = "viscous"), 'ldem:params:unknownDampingModel'); + q = ldem.Parameters(constitutiveLaw = "linear_elastic", dampingModel = "none"); + testCase.verifyEqual(q.constitutiveLaw, "linear_elastic"); + end + + function bilinearObjectMatchesTheFunction(testCase) + [barProps, history] = testCase.threeBars(); + strain = [0.5e-3; 2e-3; 5e-3]; + rate = [1; -2; 3]; + params = ldem.Parameters(constitutiveDamping = 1e-6); + [expectedForce, expectedHistory] = ldem.material.bilinearLaw(strain, rate, barProps, history, 1e-6); + [force, after] = ldem.material.BilinearBarLaw().evaluate(strain, rate, barProps, history, params); + testCase.verifyEqual(force, expectedForce); + testCase.verifyEqual(after, expectedHistory); + end + + function bilinearEnergiesOfHandMadeBars(testCase) + [barProps, history, len] = testCase.threeBars(); + law = ldem.material.BilinearBarLaw(); + E = testCase.E1; + + % Elastic bar: only strain energy. + e = law.energies([0.5e-3; 0; 0], barProps, history, len); + testCase.verifyEqual(e.elastic, E * (0.5e-3)^2 * len(1) / 2, 'RelTol', 1e-12); + testCase.verifyEqual(e.damage, 0); + testCase.verifyEqual(e.brokenBars, 0); + + % Evaluate the softening and the broken bar, then read the energies. + params = ldem.Parameters(); + [~, history] = law.evaluate([0.5e-3; 2e-3; 5e-3], zeros(3, 1), barProps, history, params); + e = law.energies([0.5e-3; 2e-3; 5e-3], barProps, history, len); + EP = 1e-3; + EM = 2e-3; + E2 = history.tensionStiffness(2); + area = E * EP^2 - E2 * EM^2 + (E * EP + E2 * EM) * (EM - EP); + damageSoftening = len(2) * area / 2; + fractureEnergy = E * EP^2 * 5 * len(3) / 2; + testCase.verifyEqual(law.barDamageEnergy(2, barProps, history, len), damageSoftening, 'RelTol', 1e-12); + testCase.verifyEqual(law.barDamageEnergy(1, barProps, history, len), 0); + testCase.verifyEqual(e.brokenBars, fractureEnergy, 'RelTol', 1e-12); + testCase.verifyGreaterThan(e.damage, damageSoftening); % the broken bar adds its own + testCase.verifyEqual(law.viscousStiffness([-1; 1; 1], barProps, history), ... + [E; E2; history.tensionStiffness(3)]); + end + + function linearElasticLawHasNoDamage(testCase) + [barProps, history, len] = testCase.threeBars(); + law = ldem.material.LinearElasticBarLaw(); + params = ldem.Parameters(constitutiveDamping = 2e-6); + strain = [-1e-3; 2e-3; 9e-3]; % past the rupture strain of the bilinear law + rate = [3; -1; 2]; + [force, after] = law.evaluate(strain, rate, barProps, history, params); + testCase.verifyEqual(force, testCase.E1 * (strain + 2e-6 * rate), 'RelTol', 1e-12); + testCase.verifyEqual(after, history); + e = law.energies(strain, barProps, after, len); + testCase.verifyEqual(e.elastic, sum(testCase.E1 * strain.^2 .* len / 2), 'RelTol', 1e-12); + testCase.verifyEqual(e.damage, 0); + testCase.verifyEqual(e.brokenBars, 0); + testCase.verifyEqual(law.barDamageEnergy(3, barProps, after, len), 0); + testCase.verifyEqual(law.viscousStiffness(strain, barProps, after), barProps.stiffness); + end + + function aLawOutsideTheRegistryPlugsIntoTheSolver(testCase) + [mesh, barProps, history] = testCase.oscillator(); + params = ldem.Parameters(dt = 2e-7); + state = ldem.solver.initialState(mesh, history); + state.displacement(2, 1) = testCase.L * (1 + 1e-4); + state.previousDisplacement = state.displacement; + + elastic = ldem.solver.computeBarForces(state, mesh, barProps, params, ldem.material.LinearElasticBarLaw()); + half = ldem.solver.computeBarForces(state, mesh, barProps, params, TestHalfStiffnessLaw()); + testCase.verifyEqual(half.axialForce, 0.5 * elastic.axialForce, 'RelTol', 1e-12); + testCase.verifyEqual(half.force, 0.5 * elastic.force, 'RelTol', 1e-12); + + e = ldem.solver.computeEnergies(half, mesh, barProps, params, TestHalfStiffnessLaw()); + testCase.verifyEqual(e.elastic, 0.5 * testCase.E1 * (1e-4)^2 * testCase.L / 2, 'RelTol', 1e-9); + end + + function dampingModels(testCase) + p = ldem.Parameters(dt = 5e-7, dampingInitial = 100, dampingFinal = 40, dampingSwitchTime = 2.5e-6); + mp = ldem.solver.MassProportionalDamping(); + testCase.verifyEqual(mp.coefficient(1, p), ldem.solver.dampingCoefficient(1, p)); + testCase.verifyEqual(mp.coefficient(1, p), 100); + testCase.verifyEqual(mp.coefficient(10, p), 40); + none = ldem.solver.NoDamping(); + testCase.verifyEqual(none.coefficient(1, p), 0); + testCase.verifyEqual(none.coefficient(10, p), 0); + end + + function noDampingKeepsTheOscillatorUndamped(testCase) + [mesh, barProps, history] = testCase.oscillator(); + params = ldem.Parameters(dt = 2e-7, dampingModel = "none", dampingInitial = 5000, dampingFinal = 5000); + law = ldem.material.LinearElasticBarLaw(); + damping = ldem.solver.dampingFromName(params.dampingModel); + state = ldem.solver.initialState(mesh, history); + u0 = 1e-6; + omega = sqrt(testCase.E1 / testCase.L / testCase.Mass); + state.displacement(2, 1) = testCase.L + u0; + state.previousDisplacement(2, 1) = testCase.L + u0 * cos(omega * params.dt); + nSteps = 2000; + x = zeros(nSteps, 1); + for n = 1:nSteps + state.step = n; + state.time = state.time + params.dt; + state = ldem.solver.computeBarForces(state, mesh, barProps, params, law); + state = ldem.solver.integrateStep(state, mesh, barProps, params, law, damping); + x(n) = state.displacement(2, 1) - testCase.L; + end + t = params.dt * (1:nSteps).'; + testCase.verifyEqual(x, u0 * cos(omega * t), 'AbsTol', 2e-3 * u0); + testCase.verifyEqual(state.dampingEnergy, 0); + end + + function simulationsWithTheOtherLawAndDamping(testCase) + damaging = {'testId', 101, 'nModules', [6 3 3], 'totalTime', 2e-4, 'fractureEnergy', 0.1}; + bilinear = ldem.runSimulation(ldem.Parameters(damaging{:})); + elastic = ldem.runSimulation(ldem.Parameters(damaging{:}, constitutiveLaw = "linear_elastic")); + + testCase.verifyGreaterThan(bilinear.energy.damage(end), 0); + testCase.verifyEqual(elastic.energy.damage, zeros(size(elastic.energy.damage))); + testCase.verifyEqual(elastic.energy.brokenBars, zeros(size(elastic.energy.brokenBars))); + testCase.verifyEqual(elastic.final.damage.isUnbroken, true(size(elastic.final.damage.isUnbroken))); + % The elastic model keeps the energy balance closed. + testCase.verifyLessThan(abs(elastic.energy.balance(end)), 0.01 * abs(elastic.energy.external(end))); + + undamped = ldem.runSimulation(ldem.Parameters(damaging{:}, dampingModel = "none")); + damped = ldem.runSimulation(ldem.Parameters(damaging{:})); + testCase.verifyEqual(undamped.energy.damping, zeros(size(undamped.energy.damping))); + testCase.verifyGreaterThan(damped.energy.damping(end), 0); + end + + function caseFilesChooseTheLawAndTheDamping(testCase) + c = ldem.io.readCase(testCase.writeCase(strings(0, 1))); + testCase.verifyEqual(c.params.constitutiveLaw, "bilinear"); + testCase.verifyEqual(c.params.dampingModel, "mass_proportional"); + + c = ldem.io.readCase(testCase.writeCase(["[material]"; "law = ""Linear_Elastic"""; ... + "[damping]"; "type = ""none"""; "constitutive = 1 us"])); + testCase.verifyEqual(c.params.constitutiveLaw, "linear_elastic"); + testCase.verifyEqual(c.params.dampingModel, "none"); + testCase.verifyEqual(c.params.constitutiveDamping, 1e-6); + end + + function caseFileErrorsForLawAndDamping(testCase) + try + ldem.io.readCase(testCase.writeCase(["[material]"; "law = ""bilinar"""])); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:case:badValue'); + testCase.verifySubstring(err.message, "Did you mean 'bilinear'?"); + testCase.verifySubstring(err.message, 'linear_elastic'); + end + try + ldem.io.readCase(testCase.writeCase(["[damping]"; "type = ""none"""; "initial = 100"])); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:case:inconsistentKey'); + testCase.verifySubstring(err.message, 'type = "none"'); + end + % The default model accepts all three keys. + c = ldem.io.readCase(testCase.writeCase(["[damping]"; "initial = 100"; "final = 50"; "switch_time = 10 us"])); + testCase.verifyEqual(c.params.dampingFinal, 50); + end + + function writerKeepsTheLawAndTheDamping(testCase) + p = ldem.Parameters(constitutiveLaw = "linear_elastic", dampingModel = "none", ... + constitutiveDamping = 3e-6); + path = fullfile(testCase.Folder, "w.ldem"); + text = ldem.io.writeCase(path, p); + testCase.verifySubstring(text, '"linear_elastic"'); + testCase.verifyFalse(contains(text, "switch_time")); + c = ldem.io.readCase(path); + testCase.verifyEqual(c.params.constitutiveLaw, "linear_elastic"); + testCase.verifyEqual(c.params.dampingModel, "none"); + testCase.verifyEqual(c.params.constitutiveDamping, 3e-6); + + q = ldem.Parameters(dampingInitial = 1200, dampingFinal = 800, dampingSwitchTime = 2e-5); + ldem.io.writeCase(path, q); + r = ldem.io.readCase(path); + testCase.verifyEqual(r.params.toStruct(), q.toStruct()); + end + end +end diff --git a/tests/unit/TestMaterial.m b/tests/unit/TestMaterial.m new file mode 100644 index 0000000..1bd822a --- /dev/null +++ b/tests/unit/TestMaterial.m @@ -0,0 +1,176 @@ +classdef TestMaterial < LdemTestCase + %TESTMATERIAL Unit tests of the stiffness and bar-property computation. + + methods (Access = private) + function path = writeNumbers(testCase, values) + folder = testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder; + path = fullfile(folder, 'field.txt'); + fid = fopen(path, 'w'); + fprintf(fid, '%.10g\n', values); + fclose(fid); + end + end + + methods (Test, TestTags = {'Unit'}) + function latticeCoefficientsForKnownPoissonRatios(testCase) + [delta, alpha] = ldem.material.latticeCoefficients(0.25); + testCase.verifyEqual(delta, 1.125, 'RelTol', 1e-14); + testCase.verifyEqual(alpha, 0.4, 'RelTol', 1e-14); + + [delta, alpha] = ldem.material.latticeCoefficients(0); + testCase.verifyEqual(delta, 0); + testCase.verifyEqual(alpha, 0.5, 'RelTol', 1e-14); + end + + function latticeCoefficientsRejectIncompressibleLimit(testCase) + testCase.verifyError(@() ldem.material.latticeCoefficients(0.5), ... + 'ldem:params:badPoissonRatio'); + end + + function stiffnessDependsOnTheTypeOfBar(testCase) + params = ldem.Parameters(nModules=[4 4 4]); + mesh = ldem.mesh.buildMesh(params); + E1 = ldem.material.computeBarStiffness(mesh, params); + + [delta, alpha] = ldem.material.latticeCoefficients(params.poissonRatio); + reference = alpha * params.youngModulus * mesh.barLength.^2; + diagonalFactor = 2 * delta * (4/3) / sqrt(3); + + isGrid = mesh.barType == 1; + testCase.verifyEqual(E1(isGrid & mesh.barBoundaryFaces == 0), ... + reference(isGrid & mesh.barBoundaryFaces == 0), 'RelTol', 1e-14); + testCase.verifyEqual(E1(isGrid & mesh.barBoundaryFaces == 1), ... + reference(isGrid & mesh.barBoundaryFaces == 1) / 2, 'RelTol', 1e-14); + testCase.verifyEqual(E1(isGrid & mesh.barBoundaryFaces == 2), ... + reference(isGrid & mesh.barBoundaryFaces == 2) / 4, 'RelTol', 1e-14); + testCase.verifyEqual(E1(mesh.barType == 2), reference(mesh.barType == 2), 'RelTol', 1e-14); + testCase.verifyEqual(E1(mesh.barType == 3), ... + reference(mesh.barType == 3) * diagonalFactor, 'RelTol', 1e-14); + end + + function stiffnessIsPositiveAndScalesWithYoungModulus(testCase) + p1 = ldem.Parameters(nModules=[3 3 3], youngModulus=30e9); + p2 = ldem.Parameters(nModules=[3 3 3], youngModulus=60e9); + mesh = ldem.mesh.buildMesh(p1); + e1 = ldem.material.computeBarStiffness(mesh, p1); + e2 = ldem.material.computeBarStiffness(mesh, p2); + testCase.verifyGreaterThan(min(e1), 0); + testCase.verifyEqual(e2, 2 * e1, 'RelTol', 1e-14); + end + + function barPropertiesWithoutRandomField(testCase) + params = ldem.Parameters(nModules=[3 3 3]); + mesh = ldem.mesh.buildMesh(params); + [props, history] = ldem.material.buildBarProperties(mesh, params); + + nBars = size(mesh.bars, 1); + expectedEP = sqrt(params.fractureEnergy / (params.youngModulus * params.criticalDistance)); + testCase.verifyEqual(props.criticalStrain, repmat(expectedEP, nBars, 1), 'RelTol', 1e-14); + + [~, alpha] = ldem.material.latticeCoefficients(params.poissonRatio); + criticalLength = params.criticalDistance * 2 * params.failureAreaFactor / alpha; + testCase.verifyEqual(props.ruptureRatio, criticalLength ./ mesh.barLength, 'RelTol', 1e-14); + testCase.verifyEqual(props.ruptureStrain, props.ruptureRatio .* props.criticalStrain); + testCase.verifyEqual(props.criticalStrainCv, 0, 'AbsTol', 1e-12); + + testCase.verifyEqual(history.tensionStiffness, props.stiffness); + testCase.verifyEqual(history.maxStrain, props.criticalStrain); + testCase.verifyTrue(all(history.isUndamaged)); + testCase.verifyTrue(all(history.isUnbroken)); + end + + function randomFieldScalesTheCriticalStrain(testCase) + params = ldem.Parameters(nModules=[3 3 3]); + mesh = ldem.mesh.buildMesh(params); + nBars = size(mesh.bars, 1); + field = linspace(0.8, 1.2, nBars).'; + + [base, ~] = ldem.material.buildBarProperties(mesh, params); + [props, history] = ldem.material.buildBarProperties(mesh, params, RandomField=field); + + testCase.verifyEqual(props.criticalStrain, field .* base.criticalStrain, 'RelTol', 1e-14); + testCase.verifyEqual(history.maxStrain, props.criticalStrain); + testCase.verifyEqual(props.criticalStrainMean, mean(props.criticalStrain)); + testCase.verifyEqual(props.criticalStrainCv, ... + std(props.criticalStrain) / mean(props.criticalStrain), 'RelTol', 1e-14); + testCase.verifyGreaterThan(props.criticalStrainCv, 0); + end + + function randomFieldIsReadFromTheParametersFile(testCase) + probe = ldem.Parameters(nModules=[3 3 3]); + nBars = size(ldem.mesh.buildBars(probe.nModules), 1); + field = 1 + 0.1 * sin((1:nBars).'); + path = testCase.writeNumbers(field); + + params = ldem.Parameters(nModules=[3 3 3], randomFieldFile=path); + mesh = ldem.mesh.buildMesh(params); + [props, ~] = ldem.material.buildBarProperties(mesh, params); + [base, ~] = ldem.material.buildBarProperties(mesh, probe); + testCase.verifyEqual(props.criticalStrain, field .* base.criticalStrain, 'RelTol', 1e-9); + end + + function randomFieldIsGeneratedFromTheParameters(testCase) + params = ldem.Parameters(nModules=[6 4 4], randomFieldCv=0.1, ... + randomFieldCorrelationLength=2, randomFieldSeed=9); + probe = ldem.Parameters(nModules=[6 4 4]); + mesh = ldem.mesh.buildMesh(params); + [props, ~] = ldem.material.buildBarProperties(mesh, params); + [base, ~] = ldem.material.buildBarProperties(mesh, probe); + + expected = ldem.material.generateRandomField(mesh.barCentres, 0.1, ... + 2 * params.moduleLength, 9); + testCase.verifyEqual(props.randomField, expected); + testCase.verifyEqual(props.criticalStrain, expected .* base.criticalStrain, 'RelTol', 1e-12); + testCase.verifyEqual(props.randomFieldInfo.source, "generated"); + testCase.verifyEqual(props.randomFieldInfo.correlationLength, ... + repmat(2 * params.moduleLength, 1, 3)); + end + + function randomFieldIsStoredWithItsSource(testCase) + params = ldem.Parameters(nModules=[3 3 3]); + mesh = ldem.mesh.buildMesh(params); + nBars = size(mesh.bars, 1); + + props = ldem.material.buildBarProperties(mesh, params); + testCase.verifyEqual(props.randomField, ones(nBars, 1)); + testCase.verifyEqual(props.randomFieldInfo.source, "none"); + + given = 1 + 0.01 * (1:nBars).'; + props = ldem.material.buildBarProperties(mesh, params, RandomField=given); + testCase.verifyEqual(props.randomField, given); + testCase.verifyEqual(props.randomFieldInfo.source, "given"); + testCase.verifyEqual(props.randomFieldInfo.fieldMean, mean(given)); + + path = testCase.writeNumbers(given); + props = ldem.material.buildBarProperties(mesh, ... + ldem.Parameters(nModules=[3 3 3], randomFieldFile=path)); + testCase.verifyEqual(props.randomFieldInfo.source, "file"); + testCase.verifyEqual(props.randomFieldInfo.file, string(path)); + end + + function randomFieldOfWrongSizeIsRejected(testCase) + params = ldem.Parameters(nModules=[3 3 3]); + mesh = ldem.mesh.buildMesh(params); + testCase.verifyError( ... + @() ldem.material.buildBarProperties(mesh, params, RandomField=ones(5, 1)), ... + 'ldem:material:randomFieldSize'); + end + + function tooShortCriticalLengthIsRejected(testCase) + params = ldem.Parameters(nModules=[3 3 3], criticalDistance=0.001); + mesh = ldem.mesh.buildMesh(params); + testCase.verifyError(@() ldem.material.buildBarProperties(mesh, params), ... + 'ldem:material:criticalLengthTooShort'); + end + + function longerFractureEnergyDelaysDamage(testCase) + lowG = ldem.Parameters(nModules=[3 3 3], fractureEnergy=10); + highG = ldem.Parameters(nModules=[3 3 3], fractureEnergy=40); + mesh = ldem.mesh.buildMesh(lowG); + a = ldem.material.buildBarProperties(mesh, lowG); + b = ldem.material.buildBarProperties(mesh, highG); + testCase.verifyEqual(b.criticalStrain, 2 * a.criticalStrain, 'RelTol', 1e-12); + end + end +end diff --git a/tests/unit/TestMesh.m b/tests/unit/TestMesh.m new file mode 100644 index 0000000..853efde --- /dev/null +++ b/tests/unit/TestMesh.m @@ -0,0 +1,146 @@ +classdef TestMesh < LdemTestCase + %TESTMESH Unit tests of the ldem.mesh package using analytical results. + + properties (TestParameter) + % Sizes [M N L] covering cubes, prisms and the 2-node minimum. + sizes = {[2 2 2], [3 3 3], [4 3 2], [5 2 3], [6 4 5]} + end + + methods (Test, TestTags = {'Unit'}) + function nodeCount(testCase, sizes) + nodes = ldem.mesh.buildNodes(sizes, 0.01); + expected = prod(sizes) + prod(sizes - 1); + testCase.verifySize(nodes, [expected 3]); + end + + function nodeCoordinates(testCase) + lco = 0.5; + nodes = ldem.mesh.buildNodes([3 2 2], lco); + % Grid nodes: x runs fastest. + testCase.verifyEqual(nodes(1, :), [0 0 0]); + testCase.verifyEqual(nodes(2, :), [1 0 0] * lco); + testCase.verifyEqual(nodes(3, :), [2 0 0] * lco); + testCase.verifyEqual(nodes(4, :), [0 1 0] * lco); + testCase.verifyEqual(nodes(7, :), [0 0 1] * lco); + % Centre nodes come after the 12 grid nodes, at half-integer positions. + testCase.verifyEqual(nodes(13, :), [0.5 0.5 0.5] * lco); + testCase.verifyEqual(nodes(14, :), [1.5 0.5 0.5] * lco); + end + + function barCount(testCase, sizes) + M = sizes(1); N = sizes(2); L = sizes(3); + gridEdges = (M-1)*N*L + M*(N-1)*L + M*N*(L-1); + centreBars = (M-2)*(N-1)*(L-1) + (M-1)*(N-2)*(L-1) + (M-1)*(N-1)*(L-2); + diagonals = 8 * (M-1)*(N-1)*(L-1); + bars = ldem.mesh.buildBars(sizes); + testCase.verifySize(bars, [gridEdges + centreBars + diagonals, 2]); + end + + function barClassification(testCase) + % In a 4x4x4 prism: 144 grid edges (36 inside, 72 on faces, 36 on + % prism edges), 3*2*3*3 = 54 centre bars and 8*27 = 216 diagonals. + [bars, type, faces] = ldem.mesh.buildBars([4 4 4]); + testCase.verifySize(type, [size(bars, 1) 1]); + testCase.verifySize(faces, [size(bars, 1) 1]); + testCase.verifyEqual(nnz(type == 1), 144); + testCase.verifyEqual(nnz(type == 2), 54); + testCase.verifyEqual(nnz(type == 3), 216); + testCase.verifyEqual(nnz(type == 1 & faces == 0), 36); + testCase.verifyEqual(nnz(type == 1 & faces == 1), 72); + testCase.verifyEqual(nnz(type == 1 & faces == 2), 36); + testCase.verifyTrue(all(faces(type ~= 1) == 0)); + end + + function singleModuleHasTwentyBars(testCase) + bars = ldem.mesh.buildBars([2 2 2]); + testCase.verifySize(bars, [20 2]); + end + + function barsAreValidAndUnique(testCase, sizes) + bars = ldem.mesh.buildBars(sizes); + nNodes = prod(sizes) + prod(sizes - 1); + testCase.verifyGreaterThanOrEqual(min(bars, [], 'all'), 1); + testCase.verifyLessThanOrEqual(max(bars, [], 'all'), nNodes); + testCase.verifyTrue(all(bars(:, 1) ~= bars(:, 2)), 'A bar joins a node to itself.'); + unordered = sort(bars, 2); + testCase.verifySize(unique(unordered, 'rows'), size(bars), ... + 'The same pair of nodes is joined by more than one bar.'); + end + + function everyNodeIsConnected(testCase, sizes) + bars = ldem.mesh.buildBars(sizes); + nNodes = prod(sizes) + prod(sizes - 1); + testCase.verifyEqual(numel(unique(bars)), nNodes); + end + + function barLengthsAreEdgesAndDiagonals(testCase) + lco = 0.02; + nodes = ldem.mesh.buildNodes([4 3 3], lco); + bars = ldem.mesh.buildBars([4 3 3]); + len = ldem.mesh.computeBarGeometry(nodes, bars); + allowed = [lco, lco * sqrt(3) / 2]; + distance = min(abs(len - allowed), [], 2); + testCase.verifyLessThan(max(distance), 1e-14); + testCase.verifyEqual(min(len), lco * sqrt(3) / 2, 'RelTol', 1e-12); + end + + function barMidpointsLieBetweenEndNodes(testCase) + nodes = ldem.mesh.buildNodes([3 3 3], 1); + bars = ldem.mesh.buildBars([3 3 3]); + [~, mid] = ldem.mesh.computeBarGeometry(nodes, bars); + testCase.verifyEqual(mid, (nodes(bars(:, 1), :) + nodes(bars(:, 2), :)) / 2); + end + + function totalMassEqualsDensityTimesVolume(testCase, sizes) + lco = 0.01; rho = 2500; + mass = ldem.mesh.computeNodalMasses(sizes, lco, rho); + volume = prod(sizes - 1) * lco^3; + testCase.verifyEqual(sum(mass), rho * volume, 'RelTol', 1e-12); + end + + function massReductionAtFacesEdgesAndCorners(testCase) + lco = 1; rho = 2; + full = lco^3 * rho / 2; + mass = ldem.mesh.computeNodalMasses([4 4 4], lco, rho); + nodeAt = @(i, j, k) (k-1)*16 + (j-1)*4 + i; + testCase.verifyEqual(mass(nodeAt(2, 2, 2)), full); % interior + testCase.verifyEqual(mass(nodeAt(1, 2, 2)), full / 2); % face + testCase.verifyEqual(mass(nodeAt(1, 1, 2)), full / 4); % edge + testCase.verifyEqual(mass(nodeAt(1, 1, 1)), full / 8); % corner + testCase.verifyEqual(mass(65), full); % centre node + end + + function zeroLengthBarIsDetected(testCase) + nodes = [0 0 0; 0 0 0; 1 0 0]; + testCase.verifyError(@() ldem.mesh.computeBarGeometry(nodes, [1 2; 2 3]), ... + 'ldem:mesh:zeroLengthBar'); + end + + function barReferringToMissingNodeIsDetected(testCase) + nodes = [0 0 0; 1 0 0]; + testCase.verifyError(@() ldem.mesh.computeBarGeometry(nodes, [1 3]), ... + 'ldem:mesh:badConnectivity'); + end + + function buildMeshAssemblesEverything(testCase) + params = ldem.Parameters(testId=101, nModules=[6 3 3]); + mesh = ldem.mesh.buildMesh(params); + + nNodes = params.nNodes; + testCase.verifySize(mesh.nodes0, [nNodes 3]); + testCase.verifySize(mesh.fixed, [nNodes 3]); + testCase.verifyClass(mesh.fixed, 'logical'); + testCase.verifySize(mesh.mass, [nNodes 1]); + testCase.verifyEqual(mesh.nGridNodes, 54); + nBars = size(mesh.bars, 1); + testCase.verifySize(mesh.barLength, [nBars 1]); + testCase.verifySize(mesh.barCentres, [nBars 3]); + end + + function buildMeshRejectsUnknownTest(testCase) + params = ldem.Parameters(testId=999); + testCase.verifyError(@() ldem.mesh.buildMesh(params), ... + 'ldem:scenarios:unknownTest'); + end + end +end diff --git a/tests/unit/TestParameters.m b/tests/unit/TestParameters.m new file mode 100644 index 0000000..e4ef36d --- /dev/null +++ b/tests/unit/TestParameters.m @@ -0,0 +1,125 @@ +classdef TestParameters < LdemTestCase + %TESTPARAMETERS Unit tests of ldem.Parameters. + + methods (Test, TestTags = {'Unit'}) + function defaultsAreValid(testCase) + p = ldem.Parameters(); + testCase.verifyEqual(p.testId, 101); + testCase.verifyEqual(p.nModules, [6 3 3]); + end + + function nameValueOverridesProperties(testCase) + p = ldem.Parameters(testId=102, nModules=[70 4 3], dt=1e-7); + testCase.verifyEqual(p.testId, 102); + testCase.verifyEqual(p.nModules, [70 4 3]); + testCase.verifyEqual(p.dt, 1e-7); + end + + function dependentValues(testCase) + p = ldem.Parameters(nModules=[3 3 3], dt=2e-7, totalTime=4e-5, ... + dampingSwitchTime=1e-5, youngModulus=32e9, density=2000); + testCase.verifyEqual(p.nSteps, 200); + testCase.verifyEqual(p.dampingSwitchStep, 50); + testCase.verifyEqual(p.nNodes, 27 + 8); + testCase.verifyEqual(p.waveSpeed, 4000, 'RelTol', 1e-12); + testCase.verifyEqual(p.criticalTimeStep, ... + p.moduleLength * sqrt(3) / 2 / 4000, 'RelTol', 1e-12); + end + + function dependentPropertiesCannotBeSet(testCase) + testCase.verifyError(@() ldem.Parameters(nSteps=10), ?MException); + end + + function rejectsInvalidValues(testCase) + testCase.verifyError(@() ldem.Parameters(moduleLength=-1), ?MException); + testCase.verifyError(@() ldem.Parameters(nModules=[1 3 3]), ?MException); + testCase.verifyError(@() ldem.Parameters(nModules=[2.5 3 3]), ?MException); + testCase.verifyError(@() ldem.Parameters(poissonRatio=-0.1), ?MException); + testCase.verifyError(@() ldem.Parameters(youngModulus=0), ?MException); + testCase.verifyError(@() ldem.Parameters(dt=NaN), ?MException); + end + + function poissonRatioMustBeBelowOneHalf(testCase) + testCase.verifyError(@() ldem.Parameters(poissonRatio=0.5), ... + 'ldem:params:badPoissonRatio'); + p = ldem.Parameters(poissonRatio=0.499); + testCase.verifyEqual(p.poissonRatio, 0.499); + end + + function unstableTimeStepIsRejected(testCase) + testCase.verifyError(@() ldem.Parameters(dt=1e-5), ... + 'ldem:params:unstableTimeStep'); + end + + function timeStepJustBelowLimitIsAccepted(testCase) + probe = ldem.Parameters(); + p = ldem.Parameters(dt=0.999 * probe.criticalTimeStep, ... + totalTime=probe.criticalTimeStep); + testCase.verifyLessThan(p.dt, p.criticalTimeStep); + end + + function totalTimeShorterThanStepIsRejected(testCase) + testCase.verifyError(@() ldem.Parameters(dt=2e-7, totalTime=1e-7), ... + 'ldem:params:totalTimeTooShort'); + end + + function controlNodeMustExist(testCase) + testCase.verifyError(@() ldem.Parameters(nModules=[2 2 2], controlNodes=[1 99]), ... + 'ldem:params:controlNodeOutOfRange'); + end + + function atMostTenControlNodes(testCase) + testCase.verifyError(@() ldem.Parameters(controlNodes=1:11), ... + 'ldem:params:tooManyControlNodes'); + end + + function outputSettingsAreChecked(testCase) + bad = struct('snapshotEvery', -1, 'controlNodesEvery', 1, ... + 'energyEvery', 1, 'trackedBarEvery', 0); + testCase.verifyError(@() ldem.Parameters(output=bad), 'ldem:params:badOutput'); + + missing = struct('snapshotEvery', 1); + testCase.verifyError(@() ldem.Parameters(output=missing), 'ldem:params:badOutput'); + + tooOften = struct('snapshotEvery', 1, 'controlNodesEvery', 1, ... + 'energyEvery', 1, 'trackedBarEvery', 5); + testCase.verifyError(@() ldem.Parameters(output=tooOften), 'ldem:params:badOutput'); + end + + function meshPerturbationIsOffByDefaultAndMustBeNonNegative(testCase) + testCase.verifyEqual(ldem.Parameters().meshPerturbation, 0); + testCase.verifyEqual(ldem.Parameters(meshPerturbation=0.05).meshPerturbation, 0.05); + testCase.verifyError(@() ldem.Parameters(meshPerturbation=-0.1), ?MException); + testCase.verifyError(@() ldem.Parameters(meshPerturbation=Inf), ?MException); + end + + function valueSemantics(testCase) + a = ldem.Parameters(); + b = a; + b.seed = 999; + testCase.verifyEqual(a.seed, 123, 'Parameters must be a value class.'); + end + + function randomFieldSettingsAreValidated(testCase) + p = ldem.Parameters(randomFieldCv=0.05, randomFieldCorrelationLength=[2 2 4]); + testCase.verifyEqual(p.randomFieldCv, 0.05); + testCase.verifyEqual(p.randomFieldSeed, 515); + testCase.verifyError(@() ldem.Parameters(randomFieldCv=0.05, randomFieldFile="f.txt"), ... + 'ldem:params:twoRandomFields'); + testCase.verifyError(@() ldem.Parameters(randomFieldCv=1e-6), ... + 'ldem:params:badRandomFieldCv'); + testCase.verifyError(@() ldem.Parameters(randomFieldCv=5), ... + 'ldem:params:badRandomFieldCv'); + testCase.verifyError(@() ldem.Parameters(randomFieldCorrelationLength=[1 2]), ... + 'ldem:params:badCorrelationLength'); + testCase.verifyError(@() ldem.Parameters(randomFieldCorrelationLength=0), ?MException); + testCase.verifyError(@() ldem.Parameters(randomFieldCv=-0.1), ?MException); + end + + function validateCatchesChangesAfterConstruction(testCase) + p = ldem.Parameters(); + p.dt = 1e-5; + testCase.verifyError(@() p.validate(), 'ldem:params:unstableTimeStep'); + end + end +end diff --git a/tests/unit/TestParseCase.m b/tests/unit/TestParseCase.m new file mode 100644 index 0000000..db6140e --- /dev/null +++ b/tests/unit/TestParseCase.m @@ -0,0 +1,106 @@ +classdef TestParseCase < LdemTestCase + %TESTPARSECASE Unit tests of the syntax of the case files (.ldem and .json). + + methods (Access = private) + function e = parse(~, varargin) + e = ldem.io.parseCaseText(strjoin(string(varargin), newline), "t.ldem"); + end + end + + methods (Test, TestTags = {'Unit'}) + function readsSectionsKeysAndValueTypes(testCase) + e = testCase.parse( ... + 'title = "A # not a comment" # but this is', ... + '[mesh]', ... + 'modules = [5, 5, 50]', ... + 'module_size = 1 mm', ... + 'perturbation = 0.02', ... + 'seed = 123', ... + '[output]', ... + 'mat = true', ... + 'vtk = false', ... + 'formats = ["mat", "vtk"]'); + testCase.verifyEqual([e.section], ["" "mesh" "mesh" "mesh" "mesh" "output" "output" "output"]); + testCase.verifyEqual(e(1).value, "A # not a comment"); + testCase.verifyEqual(e(2).value, [5 5 50]); + testCase.verifyEqual(e(3).value, "1 mm"); + testCase.verifyEqual(e(4).value, 0.02); + testCase.verifyEqual(e(5).value, 123); + testCase.verifyTrue(e(6).value); + testCase.verifyFalse(e(7).value); + testCase.verifyEqual(e(8).value, ["mat" "vtk"]); + testCase.verifyEqual([e.line], [1 3 4 5 6 8 9 10]); + end + + function ignoresBlankLinesCommentsAndWindowsLineEnds(testCase) + text = "# header" + string(char([13 10])) + string(char([13 10])) + ... + "[time] # section" + string(char([13 10])) + "duration = 2.8 ms" + string(char([13 10])); + e = ldem.io.parseCaseText(text, "t.ldem"); + testCase.verifySize(e, [1 1]); + testCase.verifyEqual(e.value, "2.8 ms"); + end + + function repeatedTablesGetAnIndex(testCase) + e = testCase.parse('[[monitor.node]]', 'id = 2', '[[monitor.node]]', 'id = 5', 'name = "x"'); + testCase.verifyEqual([e.index], [1 2 2]); + testCase.verifyEqual([e.section], repmat("monitor.node", 1, 3)); + end + + function skipsAUtf8ByteOrderMark(testCase) + text = string(char([239 187 191])) + "format = 1"; + e = ldem.io.parseCaseText(text, "t.ldem"); + testCase.verifyEqual(e.key, "format"); + end + + function emptyAndTrailingCommaLists(testCase) + e = testCase.parse('a = []', 'b = [1, 2,]'); + testCase.verifyEmpty(e(1).value); + testCase.verifyEqual(e(2).value, [1 2]); + end + + function reportsSyntaxErrorsWithTheLine(testCase) + bad = { ... + "[mesh", ... + "[[mesh]", ... + "novalue", ... + "key = ", ... + "1key = 3", ... + "k = ""open", ... + "k = ""a"" b", ... + "k = [1, 2", ... + "k = [1, ""a""]", ... + "k = [1, x]", ... + "[a b]"}; + for k = 1:numel(bad) + try + ldem.io.parseCaseText("# first" + newline + bad{k}, "t.ldem"); + testCase.verifyFail("No error for: " + bad{k}); + catch err + testCase.verifyEqual(err.identifier, 'ldem:case:syntax', bad{k}); + testCase.verifySubstring(err.message, "t.ldem:2"); + end + end + end + + function rejectsRepeatedKeysAndSections(testCase) + testCase.verifyError(@() testCase.parse('[a]', 'x = 1', 'x = 2'), 'ldem:case:syntax'); + testCase.verifyError(@() testCase.parse('[a]', '[a]'), 'ldem:case:syntax'); + end + + function jsonGivesTheSameEntries(testCase) + json = '{"format": 1, "mesh": {"module_size": "1 mm", "modules": [5, 5, 50]}, "output": {"mat": true}, "monitor": {"node": [{"id": 2441}, {"id": 884, "name": "b"}]}}'; + e = ldem.io.parseCaseJson(json, "t.json"); + keys = [e.section] + "." + [e.key]; + testCase.verifyEqual(keys, [".format" "mesh.module_size" "mesh.modules" "output.mat" ... + "monitor.node.id" "monitor.node.id" "monitor.node.name"]); + testCase.verifyEqual([e.index], [0 0 0 0 1 2 2]); + testCase.verifyEqual(e(3).value, [5 5 50]); + testCase.verifyEqual(e(2).value, "1 mm"); + end + + function jsonErrorsAreSyntaxErrors(testCase) + testCase.verifyError(@() ldem.io.parseCaseJson('{"a": ', "t.json"), 'ldem:case:syntax'); + testCase.verifyError(@() ldem.io.parseCaseJson('[1, 2]', "t.json"), 'ldem:case:syntax'); + end + end +end diff --git a/tests/unit/TestPerturbNodes.m b/tests/unit/TestPerturbNodes.m new file mode 100644 index 0000000..b723393 --- /dev/null +++ b/tests/unit/TestPerturbNodes.m @@ -0,0 +1,80 @@ +classdef TestPerturbNodes < LdemTestCase + %TESTPERTURBNODES Unit tests of ldem.mesh.perturbNodes. + + properties + Nodes + Sizes = [8 6 6] + Lco = 0.01 + end + + methods (TestMethodSetup) + function createNodes(testCase) + testCase.Nodes = ldem.mesh.buildNodes(testCase.Sizes, testCase.Lco); + end + end + + methods (Test, TestTags = {'Unit'}) + function sameSeedGivesSameResult(testCase) + a = ldem.mesh.perturbNodes(testCase.Nodes, testCase.Sizes, testCase.Lco, 7, 0.02); + b = ldem.mesh.perturbNodes(testCase.Nodes, testCase.Sizes, testCase.Lco, 7, 0.02); + testCase.verifyEqual(a, b); + end + + function differentSeedGivesDifferentResult(testCase) + a = ldem.mesh.perturbNodes(testCase.Nodes, testCase.Sizes, testCase.Lco, 1, 0.02); + b = ldem.mesh.perturbNodes(testCase.Nodes, testCase.Sizes, testCase.Lco, 2, 0.02); + testCase.verifyNotEqual(a, b); + end + + function zeroVariationLeavesNodesUnchanged(testCase) + out = ldem.mesh.perturbNodes(testCase.Nodes, testCase.Sizes, testCase.Lco, 1, 0); + testCase.verifyEqual(out, testCase.Nodes); + end + + function nodesNearTheFacesDoNotMove(testCase) + out = ldem.mesh.perturbNodes(testCase.Nodes, testCase.Sizes, testCase.Lco, 1, 0.05); + moved = any(out ~= testCase.Nodes, 2); + lco = testCase.Lco; + M1 = testCase.Sizes(1) - 1; N1 = testCase.Sizes(2) - 1; L1 = testCase.Sizes(3) - 1; + x = testCase.Nodes(:, 1); y = testCase.Nodes(:, 2); z = testCase.Nodes(:, 3); + nearFace = z >= (L1 - 1.01)*lco | z <= 1.01*lco | ... + x >= (M1 - 1.01)*lco | x <= 1.01*lco | ... + y >= (N1 - 1.01)*lco | y <= 1.01*lco; + testCase.verifyFalse(any(moved & nearFace)); + testCase.verifyTrue(any(moved), 'Some interior node should have moved.'); + end + + function displacementsHaveTheRequestedScale(testCase) + cv = 0.02; + out = ldem.mesh.perturbNodes(testCase.Nodes, testCase.Sizes, testCase.Lco, 3, cv); + d = out - testCase.Nodes; + d = d(any(d ~= 0, 2), :); + testCase.verifyEqual(std(d(:)), cv * testCase.Lco, 'RelTol', 0.3); + end + + function enabledThroughParametersChangesTheMesh(testCase) + base = ldem.Parameters(nModules=testCase.Sizes); + perturbed = ldem.Parameters(nModules=testCase.Sizes, meshPerturbation=0.02); + a = ldem.mesh.buildMesh(base); + b = ldem.mesh.buildMesh(perturbed); + testCase.verifyNotEqual(a.nodes0, b.nodes0); + testCase.verifyEqual(a.bars, b.bars, 'Connectivity must not change.'); + end + + function zeroKeepsTheRegularLattice(testCase) + p = ldem.Parameters(nModules=testCase.Sizes, meshPerturbation=0); + mesh = ldem.mesh.buildMesh(p); + testCase.verifyEqual(mesh.nodes0, ... + ldem.mesh.buildNodes(testCase.Sizes, p.moduleLength)); + end + + function theValueIsTheScaleOfTheDisplacement(testCase) + small = ldem.mesh.buildMesh(ldem.Parameters(nModules=testCase.Sizes, meshPerturbation=0.01)); + large = ldem.mesh.buildMesh(ldem.Parameters(nModules=testCase.Sizes, meshPerturbation=0.04)); + regular = ldem.mesh.buildNodes(testCase.Sizes, 1); + regular = regular * ldem.Parameters().moduleLength; + testCase.verifyEqual(norm(large.nodes0 - regular), ... + 4 * norm(small.nodes0 - regular), 'RelTol', 1e-9); + end + end +end diff --git a/tests/unit/TestQuantities.m b/tests/unit/TestQuantities.m new file mode 100644 index 0000000..2227ac9 --- /dev/null +++ b/tests/unit/TestQuantities.m @@ -0,0 +1,89 @@ +classdef TestQuantities < LdemTestCase + %TESTQUANTITIES Unit tests of the units of the case files (ldem.schema). + + methods (Test, TestTags = {'Unit'}) + function convertsEveryDimension(testCase) + parse = @ldem.schema.parseQuantity; + testCase.verifyEqual(parse("3.87 GPa", "pressure"), 3.87e9); + testCase.verifyEqual(parse("32 GPa", "pressure"), 32e9); + testCase.verifyEqual(parse("1 mm", "length"), 1e-3); + testCase.verifyEqual(parse("28 mm", "length"), 0.028); + testCase.verifyEqual(parse("0.5 km", "length"), 500); + testCase.verifyEqual(parse("0.35 us", "time"), 3.5e-7); + testCase.verifyEqual(parse("2.8 ms", "time"), 2.8e-3); + testCase.verifyEqual(parse("1500 kg/m3", "density"), 1500); + testCase.verifyEqual(parse("2 g/cm3", "density"), 2000); + testCase.verifyEqual(parse("25 1/ms", "rate"), 25000); + testCase.verifyEqual(parse("0.5 kN/m", "toughness"), 500); + testCase.verifyEqual(parse("4 mm/s", "velocity"), 4e-3); + testCase.verifyEqual(parse("2 kN/s", "forcerate"), 2000); + testCase.verifyEqual(parse("24.5 modules", "modules"), 24.5); + end + + function numbersWithoutUnitAreSi(testCase) + testCase.verifyEqual(ldem.schema.parseQuantity(0.003, "length"), 0.003); + testCase.verifyEqual(ldem.schema.parseQuantity("3.87e9", "pressure"), 3.87e9); + testCase.verifyEqual(ldem.schema.parseQuantity(" 7 ", "number"), 7); + end + + function exponentInTheMantissaIsAccepted(testCase) + testCase.verifyEqual(ldem.schema.parseQuantity("3.5E-1 us", "time"), 3.5e-1 * 1e-6, 'RelTol', 1e-15); + end + + function wrongUnitsAndTextAreRejected(testCase) + testCase.verifyError(@() ldem.schema.parseQuantity("3 kg", "length"), 'ldem:case:badUnit'); + testCase.verifyError(@() ldem.schema.parseQuantity("fast", "time"), 'ldem:case:badQuantity'); + testCase.verifyError(@() ldem.schema.parseQuantity("3 mm", "number"), 'ldem:case:badUnit'); + testCase.verifyError(@() ldem.schema.parseQuantity(Inf, "time"), 'ldem:case:badQuantity'); + testCase.verifyError(@() ldem.schema.parseQuantity([1 2], "time"), 'ldem:case:badQuantity'); + testCase.verifyError(@() ldem.schema.parseQuantity("1", "colour"), 'ldem:schema:unknownDimension'); + end + + function errorMessageNamesTheLocation(testCase) + try + ldem.schema.parseQuantity("3 kg", "length", "case.ldem:7 [mesh] module_size"); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifySubstring(err.message, 'case.ldem:7 [mesh] module_size'); + testCase.verifySubstring(err.message, 'mm'); + end + end + + function formatsReadableUnits(testCase) + format = @ldem.schema.formatQuantity; + testCase.verifyEqual(format(3.5e-7, "time"), "0.35 us"); + testCase.verifyEqual(format(2.8e-3, "time"), "2.8 ms"); + testCase.verifyEqual(format(0.015, "time"), "15 ms"); + testCase.verifyEqual(format(0.003, "length"), "3 mm"); + testCase.verifyEqual(format(3.87e9, "pressure"), "3.87 GPa"); + testCase.verifyEqual(format(1500, "density"), "1500 kg/m3"); + testCase.verifyEqual(format(0, "time"), "0 s"); + testCase.verifyEqual(format(24.5, "modules"), "24.5 modules"); + end + + function formatThenParseGivesTheSameValue(testCase) + values = [1e-3 0.003 3.5e-7 2.8e-3 0.015 4.5e-3 3.87e9 32e9 0.1385 1/3 pi*1e-5 123456789.123 5e-10]; + for dimension = ["length" "time" "pressure" "density" "rate" "toughness" "number"] + for v = values + text = ldem.schema.formatQuantity(v, dimension); + testCase.verifyEqual(ldem.schema.parseQuantity(text, dimension), v, ... + "Round trip of " + string(v) + " as " + dimension + ": " + text); + end + end + end + + function shortestTextRoundTrips(testCase) + for x = [0 1 -4 32 0.1 3.5e-7 1/3 2/3 1e15 1e-300 123456.789] + testCase.verifyEqual(str2double(ldem.schema.shortestText(x)), x); + end + testCase.verifyEqual(ldem.schema.shortestText(0.1), "0.1"); + testCase.verifyEqual(ldem.schema.shortestText(32), "32"); + end + + function suggestsCloseWordsOnly(testCase) + words = ["young_modulus" "density" "poisson_ratio"]; + testCase.verifySubstring(ldem.schema.suggest("young_modulos", words), "young_modulus"); + testCase.verifyEqual(ldem.schema.suggest("zzzzzzzz", words), ""); + end + end +end diff --git a/tests/unit/TestReadCase.m b/tests/unit/TestReadCase.m new file mode 100644 index 0000000..475ca23 --- /dev/null +++ b/tests/unit/TestReadCase.m @@ -0,0 +1,421 @@ +classdef TestReadCase < LdemTestCase + %TESTREADCASE Unit tests of ldem.io.readCase and of the case-file keys. + + properties (Access = private) + Folder (1,1) string + Last = [] + end + + methods (TestMethodSetup) + function makeFolder(testCase) + testCase.Folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + end + end + + methods (Access = private) + function lines = minimal(~) + lines = [ ... + "format = 1" + "[mesh]" + "module_size = 3 mm" + "modules = [5, 2, 2]" + "[time]" + "step = 0.2 us" + "duration = 40 us" + "[scenario]" + "type = ""uniaxial_tension"""]; + end + + function c = read(testCase, extra, name) + % Minimal case plus extra lines (which may open new sections). + if nargin < 3 + name = "case.ldem"; + end + path = fullfile(testCase.Folder, name); + writeTextFile(path, [testCase.minimal(); string(extra(:))]); + c = ldem.io.readCase(path); + end + + function storeRead(testCase, extra) + % Keeps the result in Last, to read it after verifyWarning. + testCase.Last = testCase.read(extra); + end + + function verifyCaseError(testCase, extra, id, fragment) + path = fullfile(testCase.Folder, "bad.ldem"); + writeTextFile(path, [testCase.minimal(); string(extra(:))]); + try + ldem.io.readCase(path); + testCase.verifyFail("An error was expected for: " + strjoin(string(extra), " / ")); + catch err + testCase.verifyEqual(string(err.identifier), string(id)); + testCase.verifySubstring(err.message, fragment); + end + end + end + + methods (Test, TestTags = {'Unit'}) + function minimalCaseTakesTheDefaults(testCase) + c = testCase.read(strings(0, 1)); + p = c.params; + d = ldem.Parameters(); + testCase.verifyEqual(p.nModules, [6 3 3]); + testCase.verifyEqual(p.moduleLength, 0.003); + testCase.verifyEqual(p.dt, 2e-7); + testCase.verifyEqual(p.totalTime, 4e-5); + testCase.verifyEqual(p.testId, 101); + testCase.verifyEqual(p.youngModulus, d.youngModulus); + testCase.verifyEqual(p.output, d.output); + testCase.verifyEqual(p.controlNodes, d.controlNodes); + testCase.verifyClass(c.scenario, 'ldem.scenarios.UniaxialTension'); + testCase.verifyEqual(c.options.OutputFolder, ""); + testCase.verifyEqual(c.options.Formats, "mat"); + end + + function convertsUnitsOfTheMaterial(testCase) + c = testCase.read([ ... + "[material]" + "young_modulus = 3.87 GPa" + "density = 1.5 g/cm3" + "fracture_energy = 0.5 N/m" + "critical_distance = 4.5 mm" + "poisson_ratio = 0.2" + "failure_area_factor = 0.2" + "[damping]" + "initial = 2.5 1/ms" + "final = 1000" + "switch_time = 15 ms" + "constitutive = 1 us"]); + p = c.params; + testCase.verifyEqual(p.youngModulus, 3.87e9); + testCase.verifyEqual(p.density, 1500); + testCase.verifyEqual(p.fractureEnergy, 0.5); + testCase.verifyEqual(p.criticalDistance, 4.5e-3); + testCase.verifyEqual(p.poissonRatio, 0.2); + testCase.verifyEqual(p.failureAreaFactor, 0.2); + testCase.verifyEqual(p.dampingInitial, 2500); + testCase.verifyEqual(p.dampingFinal, 1000); + testCase.verifyEqual(p.dampingSwitchTime, 0.015); + testCase.verifyEqual(p.constitutiveDamping, 1e-6); + end + + function autoStepIsNinetyPercentOfTheCriticalOne(testCase) + path = fullfile(testCase.Folder, "auto.ldem"); + lines = testCase.minimal(); + writeTextFile(path, lines(~startsWith(lines, "step"))); % no step key + p = ldem.io.readCase(path).params; + testCase.verifyEqual(p.dt, 0.9 * p.criticalTimeStep, 'RelTol', 1e-12); + + lines(startsWith(lines, "step")) = "step = ""auto"""; % explicit + writeTextFile(path, lines); + testCase.verifyEqual(ldem.io.readCase(path).params.dt, p.dt); + end + + function outputCadenceInStepsOrTime(testCase) + c = testCase.read([ ... + "[output.snapshots]" + "every = 10 us" + "[output.control_nodes]" + "every = 5 steps" + "[output.energy]" + "every = 1 step"]); + testCase.verifyEqual(c.params.output.snapshotEvery, 50); + testCase.verifyEqual(c.params.output.controlNodesEvery, 5); + testCase.verifyEqual(c.params.output.energyEvery, 1); + c = testCase.read(["[output.snapshots]"; "every = 0"; "[output.energy]"; "every = 20"]); + testCase.verifyEqual(c.params.output.snapshotEvery, 0); + testCase.verifyEqual(c.params.output.energyEvery, 20); + end + + function cadenceThatIsNotAMultipleWarns(testCase) + testCase.verifyWarning(@() testCase.storeRead(["[output.snapshots]"; "every = 10.05 us"]), ... + 'ldem:case:cadenceNotMultiple'); + end + + function badCadences(testCase) + testCase.verifyCaseError(["[output.snapshots]"; "every = 0.05 us"], 'ldem:case:badValue', 'shorter than the time step'); + testCase.verifyCaseError(["[output.snapshots]"; "every = -3"], 'ldem:case:badValue', 'non-negative'); + testCase.verifyCaseError(["[output.snapshots]"; "every = 2.5 steps"], 'ldem:case:badValue', 'whole number'); + end + + function trackedBarSwitchesTheStrainHistoryOn(testCase) + c = testCase.read(["[monitor.bar]"; "tracked = 5"]); + testCase.verifyEqual(c.params.trackedBar, 5); + testCase.verifyEqual(c.params.output.trackedBarEvery, 1); + c = testCase.read(strings(0, 1)); + testCase.verifyEqual(c.params.output.trackedBarEvery, 0); + end + + function controlNodesByNumberAndByPosition(testCase) + c = testCase.read([ ... + "[[monitor.node]]" + "id = 2" + "[[monitor.node]]" + "name = ""first module""" + "at = [0.5, 0.5, 0.5]"]); + % The prism has 6*3*3 = 54 grid nodes; the first centre node is 55. + testCase.verifyEqual(c.params.controlNodes, [2 55]); + testCase.verifyEqual(c.info.controlNodeNames, ["node_2" "first module"]); + testCase.verifyEmpty(c.info.nodeNotes); + end + + function aPositionThatIsNotANodeWarnsAndNamesTheChosenOne(testCase) + extra = ["[[monitor.node]]"; "at = [0.45, 0.5, 0.5]"]; + testCase.verifyWarning(@() testCase.storeRead(extra), 'ldem:case:nodeApproximated'); + c = testCase.Last; + testCase.verifyEqual(c.params.controlNodes, 55); + testCase.verifySubstring(c.info.nodeNotes, "using node 55"); + end + + function badControlNodes(testCase) + testCase.verifyCaseError(["[[monitor.node]]"; "name = ""x"""], 'ldem:case:missingKey', 'either "id" or "at"'); + testCase.verifyCaseError(["[[monitor.node]]"; "id = 2"; "at = [1, 1, 1]"], ... + 'ldem:case:inconsistentKey', 'not both'); + testCase.verifyCaseError(["[[monitor.node]]"; "id = 0"], 'ldem:case:badValue', 'node number'); + testCase.verifyCaseError(["[[monitor.node]]"; "at = [1, 1]"], 'ldem:case:badValue', 'three numbers'); + testCase.verifyCaseError(["[[monitor.node]]"; "id = 5000"], 'ldem:params:controlNodeOutOfRange', 'bad.ldem'); + end + + function scenarioKeysBelongToTheScenarioClass(testCase) + lines = testCase.minimal(); + lines = lines(~startsWith(lines, ["[scenario]" "type"])); + path = fullfile(testCase.Folder, "beam.ldem"); + writeTextFile(path, [lines; "[scenario]"; "type = ""clamped_beam"""; ... + "force_rate = 2 kN/s"; "ramp_time = 1 ms"; "load_position = 2.5 modules"; ... + "load_height = 1.5"]); + c = ldem.io.readCase(path); + testCase.verifyClass(c.scenario, 'ldem.scenarios.ClampedBeam'); + testCase.verifyEqual(c.params.testId, 103); + testCase.verifyEqual(c.scenario.forceRate, 2000); + testCase.verifyEqual(c.scenario.rampTime, 1e-3); + testCase.verifyEqual(c.scenario.loadPosition, 2.5); + testCase.verifyEqual(c.scenario.loadHeight, 1.5); + + writeTextFile(path, [lines; "[scenario]"; "type = ""clamped_beam"""; "load_position = ""midspan"""]); + c = ldem.io.readCase(path); + testCase.verifyTrue(isnan(c.scenario.loadPosition)); + end + + function everyScenarioCanBeNamed(testCase) + lines = testCase.minimal(); + lines = lines(~startsWith(lines, ["[scenario]" "type"])); + path = fullfile(testCase.Folder, "any.ldem"); + for entry = ldem.scenarios.registry() + writeTextFile(path, [lines; "[scenario]"; "type = """ + entry.name + """"]); + c = ldem.io.readCase(path); + testCase.verifyClass(c.scenario, entry.className); + testCase.verifyEqual(c.params.testId, entry.testId); + end + end + + function scatterFromAFileIsRelativeToTheCase(testCase) + c = testCase.read(["[material.scatter]"; "type = ""file"""; "file = ""sub/field.txt"""]); + testCase.verifyEqual(c.params.randomFieldFile, string(fullfile(testCase.Folder, "sub/field.txt"))); + testCase.verifyEqual(c.params.randomFieldCv, 0); + end + + function scatterGeneratedInMemory(testCase) + c = testCase.read([ ... + "[material.scatter]" + "type = ""generated""" + "cv = 0.05" + "correlation_length = [2, 3, 4]" + "seed = 7"]); + p = c.params; + testCase.verifyEqual(p.randomFieldCv, 0.05); + testCase.verifyEqual(p.randomFieldCorrelationLength, [2 3 4]); + testCase.verifyEqual(p.randomFieldSeed, 7); + testCase.verifyEqual(p.randomFieldFile, ""); + c = testCase.read(["[material.scatter]"; "type = ""none"""]); + testCase.verifyEqual(c.params.randomFieldCv, 0); + end + + function scatterKeysMustFitTheType(testCase) + testCase.verifyCaseError(["[material.scatter]"; "cv = 0.1"], 'ldem:case:missingKey', 'type'); + testCase.verifyCaseError(["[material.scatter]"; "type = ""none"""; "seed = 1"], ... + 'ldem:case:inconsistentKey', 'type = "none"'); + testCase.verifyCaseError(["[material.scatter]"; "type = ""file"""; "cv = 0.1"], ... + 'ldem:case:inconsistentKey', 'type = "file"'); + testCase.verifyCaseError(["[material.scatter]"; "type = ""file"""], 'ldem:case:missingKey', '"file"'); + testCase.verifyCaseError(["[material.scatter]"; "type = ""generated"""; "file = ""f"""], ... + 'ldem:case:inconsistentKey', 'generated'); + testCase.verifyCaseError(["[material.scatter]"; "type = ""generated"""], 'ldem:case:missingKey', '"cv"'); + testCase.verifyCaseError(["[material.scatter]"; "type = ""lognormal"""], 'ldem:case:badValue', 'Allowed'); + end + + function outputFolderAndFormats(testCase) + c = testCase.read([ ... + "[output]" + "folder = ""results""" + "mat = true" + "ansys = false" + "vtk = true" + "[output.snapshots]" + "every = 100 steps"]); + testCase.verifyEqual(c.options.OutputFolder, string(fullfile(testCase.Folder, "results"))); + testCase.verifyEqual(c.options.Formats, ["mat" "vtk"]); + c = testCase.read(["[output]"; "mat = false"]); + testCase.verifyEmpty(c.options.Formats); + end + + function requestingFilesWithoutSnapshotsWarns(testCase) + testCase.verifyWarning(@() testCase.storeRead(["[output]"; "folder = ""o"""; "vtk = true"]), ... + 'ldem:case:noSnapshots'); + end + + function titleAndAuthorsAreKept(testCase) + lines = testCase.minimal(); + path = fullfile(testCase.Folder, "meta.ldem"); + writeTextFile(path, [lines(1); "title = ""My beam"""; "authors = [""A"", ""B""]"; lines(2:end)]); + c = ldem.io.readCase(path); + testCase.verifyEqual(c.info.title, "My beam"); + testCase.verifyEqual(c.info.authors, ["A" "B"]); + testCase.verifyEqual(c.info.format, 1); + end + + function jsonGivesTheSameAsTheTextFormat(testCase) + json = ['{"format":1,"mesh":{"module_size":"3 mm","modules":[5,2,2]},' ... + '"time":{"step":"0.2 us","duration":"40 us"},' ... + '"material":{"young_modulus":"30 GPa"},' ... + '"monitor":{"node":[{"id":2},{"id":7}]},' ... + '"scenario":{"type":"uniaxial_tension"}}']; + jsonPath = fullfile(testCase.Folder, "case.json"); + writeTextFile(jsonPath, string(json)); + fromJson = ldem.io.readCase(jsonPath); + fromText = testCase.read(["[material]"; "young_modulus = 30 GPa"; ... + "[[monitor.node]]"; "id = 2"; "[[monitor.node]]"; "id = 7"]); + testCase.verifyEqual(fromJson.params.toStruct(), fromText.params.toStruct()); + testCase.verifyEqual(ldem.Parameters.fromFile(jsonPath).toStruct(), fromText.params.toStruct()); + end + + function fromFileReadsCaseFilesAndAppliesOverrides(testCase) + path = fullfile(testCase.Folder, "o.ldem"); + writeTextFile(path, testCase.minimal()); + p = ldem.Parameters.fromFile(path, trackedBar = 11, seed = 9); + testCase.verifyEqual(p.trackedBar, 11); + testCase.verifyEqual(p.seed, 9); + testCase.verifyEqual(p.nModules, [6 3 3]); + end + + function unknownKeysAreSuggested(testCase) + testCase.verifyCaseError(["[material]"; "young_modulos = 3 GPa"], ... + 'ldem:case:unknownKey', "Did you mean 'young_modulus'?"); + testCase.verifyCaseError(["[matrial]"; "x = 1"], 'ldem:case:unknownKey', "Did you mean 'material'?"); + testCase.verifyCaseError("speed = 3", 'ldem:case:unknownKey', 'no key "speed"'); + testCase.verifyCaseError("flavour = 3", 'ldem:case:unknownKey', 'flavour'); + end + + function errorsNameTheLineSectionAndKey(testCase) + try + testCase.read(["[material]"; "young_modulus = 3 mm"]); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:case:badUnit'); + testCase.verifySubstring(err.message, 'case.ldem:11 [material] young_modulus'); + end + end + + function valuesRejectedByParametersNameTheirLine(testCase) + testCase.verifyCaseError(["[material]"; "young_modulus = -3 GPa"], 'ldem:case:invalidValue', ... + 'bad.ldem:11 [material] young_modulus'); + testCase.verifyCaseError(["[mesh2]"; "x = 1"], 'ldem:case:unknownKey', 'mesh2'); + end + + function crossChecksOfParametersKeepTheirIdentifier(testCase) + testCase.verifyCaseError(["[material]"; "poisson_ratio = 0.5"], 'ldem:params:badPoissonRatio', 'bad.ldem'); + end + + function typeErrors(testCase) + testCase.verifyCaseError(["[material]"; "poisson_ratio = ""high"""], 'ldem:case:badValue', 'Expected a number'); + testCase.verifyCaseError("[mesh]", 'ldem:case:syntax', 'appears twice'); + testCase.verifyCaseError(["[output]"; "mat = 1"], 'ldem:case:badValue', 'true or false'); + testCase.verifyCaseError(["[material]"; "law = ""exponential"""], 'ldem:case:badValue', 'bilinear'); + testCase.verifyCaseError(["[damping]"; "type = ""rayleigh"""], 'ldem:case:badValue', 'mass_proportional'); + end + + function requiredKeysAreChecked(testCase) + path = fullfile(testCase.Folder, "r.ldem"); + for drop = ["type" "modules" "duration"] + lines = testCase.minimal(); + lines = lines(~startsWith(lines, drop)); + writeTextFile(path, lines); + try + ldem.io.readCase(path); + testCase.verifyFail("Missing " + drop + " must fail."); + catch err + testCase.verifyEqual(err.identifier, 'ldem:case:missingKey'); + testCase.verifySubstring(err.message, drop); + end + end + end + + function badModulesAndFormat(testCase) + path = fullfile(testCase.Folder, "m.ldem"); + lines = testCase.minimal(); + lines(startsWith(lines, "modules")) = "modules = [5, 2]"; + writeTextFile(path, lines); + testCase.verifyError(@() ldem.io.readCase(path), 'ldem:case:badValue'); + lines(startsWith(lines, "modules")) = "modules = [5, 0, 2]"; + writeTextFile(path, lines); + testCase.verifyError(@() ldem.io.readCase(path), 'ldem:case:badValue'); + lines = testCase.minimal(); + lines(1) = "format = 2"; + writeTextFile(path, lines); + testCase.verifyError(@() ldem.io.readCase(path), 'ldem:case:unsupportedFormat'); + end + + function missingFileAndWrongExtension(testCase) + testCase.verifyError(@() ldem.io.readCase(fullfile(testCase.Folder, "none.ldem")), 'ldem:io:fileNotFound'); + path = fullfile(testCase.Folder, "case.txt"); + writeTextFile(path, testCase.minimal()); + testCase.verifyError(@() ldem.io.readCase(path), 'ldem:io:unknownExtension'); + end + + function unstableTimeStepNamesTheFile(testCase) + lines = testCase.minimal(); + lines(startsWith(lines, "step")) = "step = 4 ms"; + lines(startsWith(lines, "duration")) = "duration = 40 ms"; + path = fullfile(testCase.Folder, "u.ldem"); + writeTextFile(path, lines); + try + ldem.io.readCase(path); + testCase.verifyFail('An error was expected.'); + catch err + testCase.verifyEqual(err.identifier, 'ldem:params:unstableTimeStep'); + testCase.verifySubstring(err.message, 'u.ldem'); + end + end + + function theRegistryAgreesWithTheScenarioClasses(testCase) + reg = ldem.scenarios.registry(); + testCase.verifyEqual(numel(unique([reg.name])), numel(reg)); + testCase.verifyEqual(numel(unique([reg.testId])), numel(reg)); + for entry = reg + scenario = feval(entry.className); + testCase.verifyEqual(scenario.testId, entry.testId); + testCase.verifyClass(ldem.scenarios.fromName(entry.name), entry.className); + testCase.verifyClass(ldem.scenarios.fromTestId(entry.testId), entry.className); + for prop = string(fieldnames(entry.units)).' + testCase.verifyTrue(isprop(scenario, prop), entry.className + "." + prop); + end + end + testCase.verifyError(@() ldem.scenarios.fromName("rocket"), 'ldem:scenarios:unknownName'); + end + + function everyKeyOfTheSchemaIsConsistent(testCase) + schema = ldem.schema.caseSchema(); + testCase.verifyEqual(numel(unique(string({schema.path}))), numel(schema)); + kinds = ["integer" "number" "quantity" "string" "stringlist" "path" "intlist" ... + "numberlist" "bool" "enum" "stepOrAuto" "cadence" "coordinate" "loadQuantity"]; + props = string(properties('ldem.Parameters')); + for row = schema.' + testCase.verifyTrue(any(row.kind == kinds), row.path); + [~, ~] = ldem.schema.unitTable(row.dimension); % the dimension exists + if row.prop ~= "" && row.kind ~= "cadence" % cadences are fields of Parameters.output + testCase.verifyTrue(any(props == row.prop), row.path + " -> " + row.prop); + end + end + end + end +end diff --git a/tests/unit/TestReadInputFile.m b/tests/unit/TestReadInputFile.m new file mode 100644 index 0000000..f675010 --- /dev/null +++ b/tests/unit/TestReadInputFile.m @@ -0,0 +1,115 @@ +classdef TestReadInputFile < LdemTestCase + %TESTREADINPUTFILE Unit tests of ldem.io.readInputFile and Parameters.fromFile. + + methods (Access = private) + function path = writeFile(testCase, lines) + folder = testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder; + path = fullfile(folder, 'DATA.DAT'); + fid = fopen(path, 'w'); + fprintf(fid, '%s\n', lines{:}); + fclose(fid); + end + + function lines = validLines(~) + % Same layout as DATA0.DAT, with two control nodes. + lines = {"101 ' TEST '", "123 ' SEED '", "0.003 ' LCO '", ... + "6 ' M '", "3 ' N '", "3 ' L '", ... + "25000.00E+0 ' DF1 '", "30000 ' DF2 '", "0.015 ' TDAF '", ... + "0.00E-00 ' CON '", "2.00E-7 ' DT '", "4.0E-5 ' TTOT '", ... + "2 ' INCO '", "1 ' N1 '", "2 ' N2 '", ... + "9999999 ' OU2 '", "100 ' OU3 '", "0 ' OU4 '", "0 ' OU5 '", ... + "10 ' OU6 '", "10 ' OU7 '", "20 ' OU8 '", "5 ' OU9 '", ... + "2.50E-01 ' PSN '", "2000.0E+0 ' ROH '", "32.00E+9 ' YNG '", ... + "50.0E+00 ' GFR '", "0.028 ' DEQ '"}; + end + end + + methods (Test, TestTags = {'Unit'}) + function readsEveryValue(testCase) + v = ldem.io.readInputFile(testCase.writeFile(testCase.validLines())); + + testCase.verifyEqual(v.testId, 101); + testCase.verifyEqual(v.seed, 123); + testCase.verifyEqual(v.moduleLength, 0.003); + testCase.verifyEqual(v.nModules, [6 3 3]); + testCase.verifyEqual(v.dampingInitial, 25000); + testCase.verifyEqual(v.dampingFinal, 30000); + testCase.verifyEqual(v.dampingSwitchTime, 0.015); + testCase.verifyEqual(v.constitutiveDamping, 0); + testCase.verifyEqual(v.dt, 2e-7); + testCase.verifyEqual(v.totalTime, 4e-5); + testCase.verifyEqual(v.controlNodes, [1 2]); + testCase.verifyEqual(v.poissonRatio, 0.25); + testCase.verifyEqual(v.density, 2000); + testCase.verifyEqual(v.youngModulus, 32e9); + testCase.verifyEqual(v.fractureEnergy, 50); + testCase.verifyEqual(v.criticalDistance, 0.028); + end + + function mapsOutputCodes(testCase) + v = ldem.io.readInputFile(testCase.writeFile(testCase.validLines())); + testCase.verifyEqual(v.output.snapshotEvery, 100); % OU3 + testCase.verifyEqual(v.output.controlNodesEvery, 10); % OU6 + testCase.verifyEqual(v.output.energyEvery, 20); % OU8 + testCase.verifyEqual(v.output.trackedBarEvery, 1); % OU9 > 0 + end + + function ignoresBlankLinesAndTrailingText(testCase) + lines = testCase.validLines(); + lines = [lines(1:5), {""}, lines(6:end), {"", " "}]; + v = ldem.io.readInputFile(testCase.writeFile(lines)); + testCase.verifyEqual(v.nModules, [6 3 3]); + end + + function readsTheBundledBeamExample(testCase) + path = fullfile(testCase.RepoRoot, 'examples', 'beam_102', 'DATA0.DAT'); + v = ldem.io.readInputFile(path); + testCase.verifyEqual(v.testId, 102); + testCase.verifyEqual(v.nModules, [101 41 21]); + testCase.verifyEqual(v.controlNodes, 1:5); + testCase.verifyEqual(v.output.snapshotEvery, 10000); + end + + function fromFileReturnsValidatedParameters(testCase) + path = fullfile(testCase.RepoRoot, 'examples', 'beam_102', 'DATA0.DAT'); + p = ldem.Parameters.fromFile(path, trackedBar=42); + testCase.verifyClass(p, 'ldem.Parameters'); + testCase.verifyEqual(p.trackedBar, 42); + testCase.verifyEqual(p.nNodes, 101*41*21 + 100*40*20); + end + + function missingFile(testCase) + testCase.verifyError(@() ldem.io.readInputFile("does_not_exist.dat"), ... + 'ldem:io:fileNotFound'); + end + + function tooFewValues(testCase) + lines = testCase.validLines(); + path = testCase.writeFile(lines(1:8)); + testCase.verifyError(@() ldem.io.readInputFile(path), 'ldem:io:malformedInput'); + end + + function controlNodeCountDoesNotMatch(testCase) + % INCO says 3 but only 2 control nodes are listed. + lines = testCase.validLines(); + lines{13} = "3 ' INCO '"; + path = testCase.writeFile(lines); + testCase.verifyError(@() ldem.io.readInputFile(path), 'ldem:io:malformedInput'); + end + + function nonNumericValue(testCase) + lines = testCase.validLines(); + lines{3} = "abc ' LCO '"; + path = testCase.writeFile(lines); + testCase.verifyError(@() ldem.io.readInputFile(path), 'ldem:io:malformedInput'); + end + + function invalidControlNodeCount(testCase) + lines = testCase.validLines(); + lines{13} = "0 ' INCO '"; + path = testCase.writeFile(lines); + testCase.verifyError(@() ldem.io.readInputFile(path), 'ldem:io:malformedInput'); + end + end +end diff --git a/tests/unit/TestReadRandomField.m b/tests/unit/TestReadRandomField.m new file mode 100644 index 0000000..2c48b6d --- /dev/null +++ b/tests/unit/TestReadRandomField.m @@ -0,0 +1,51 @@ +classdef TestReadRandomField < LdemTestCase + %TESTREADRANDOMFIELD Unit tests of ldem.io.readRandomField. + + methods (Access = private) + function path = writeText(testCase, text) + folder = testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder; + path = fullfile(folder, 'field.txt'); + fid = fopen(path, 'w'); + fprintf(fid, '%s', text); + fclose(fid); + end + end + + methods (Test, TestTags = {'Unit'}) + function readsTheRequestedNumberOfValues(testCase) + path = testCase.writeText(sprintf('0.5\n1.0\n1.5\n2.0\n')); + field = ldem.io.readRandomField(path, 3); + testCase.verifyEqual(field, [0.5; 1.0; 1.5]); + end + + function acceptsValuesSeparatedByBlanks(testCase) + path = testCase.writeText('0.9 1.1 1.0'); + testCase.verifyEqual(ldem.io.readRandomField(path, 3), [0.9; 1.1; 1.0]); + end + + function missingFile(testCase) + testCase.verifyError(@() ldem.io.readRandomField("nope.txt", 3), ... + 'ldem:io:fileNotFound'); + end + + function fileWithTooFewValues(testCase) + path = testCase.writeText(sprintf('1\n1\n')); + testCase.verifyError(@() ldem.io.readRandomField(path, 5), ... + 'ldem:io:randomFieldTooShort'); + end + + function nonPositiveValue(testCase) + path = testCase.writeText(sprintf('1\n0\n1\n')); + testCase.verifyError(@() ldem.io.readRandomField(path, 3), ... + 'ldem:io:randomFieldInvalid'); + end + + function readsTheBundledExample(testCase) + path = fullfile(testCase.RepoRoot, 'examples', 'beam_102', 'arquivo_3lc_rnao_cv05'); + field = ldem.io.readRandomField(path, 1000); + testCase.verifySize(field, [1000 1]); + testCase.verifyGreaterThan(min(field), 0); + end + end +end diff --git a/tests/unit/TestRunCase.m b/tests/unit/TestRunCase.m new file mode 100644 index 0000000..7851f0a --- /dev/null +++ b/tests/unit/TestRunCase.m @@ -0,0 +1,136 @@ +classdef TestRunCase < LdemTestCase + %TESTRUNCASE Unit tests of ldem.run and ldem.check. + + properties (Access = private) + Folder (1,1) string + CasePath (1,1) string + end + + methods (TestMethodSetup) + function makeCase(testCase) + testCase.Folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + testCase.CasePath = fullfile(testCase.Folder, "small.ldem"); + writeTextFile(testCase.CasePath, [ ... + "format = 1" + "[mesh]" + "module_size = 3 mm" + "modules = [5, 2, 2]" + "[time]" + "step = 0.2 us" + "duration = 20 us" + "[scenario]" + "type = ""uniaxial_tension""" + "[output]" + "folder = ""out""" + "mat = true" + "ansys = false" + "vtk = true" + "[output.snapshots]" + "every = 50 steps" + "[output.control_nodes]" + "every = 10 steps" + "[output.energy]" + "every = 10 steps"]); + end + end + + methods (Test, TestTags = {'Unit'}) + function runMatchesRunSimulation(testCase) + viaCase = ldem.run(testCase.CasePath, OutputFolder = "", Verbose = false); + + c = ldem.io.readCase(testCase.CasePath); + direct = ldem.runSimulation(c.params, Scenario = c.scenario); + + testCase.verifyEqual(viaCase.final.displacement, direct.final.displacement); + testCase.verifyEqual(viaCase.energy, direct.energy); + testCase.verifyEqual(viaCase.controlNodes.displacement, direct.controlNodes.displacement); + testCase.verifyEqual(viaCase.params.dt, 2e-7); + testCase.verifyEqual(viaCase.final.step, 100); + end + + function runWritesTheFilesOfTheOutputSection(testCase) + ldem.run(testCase.CasePath, Verbose = false); + out = fullfile(testCase.Folder, "out"); + testCase.verifyTrue(isfile(fullfile(out, "results.mat"))); + testCase.verifyTrue(isfile(fullfile(out, "snapshots.pvd"))); + testCase.verifyTrue(isfile(fullfile(out, "snapshot_0000.vtu"))); + testCase.verifyFalse(isfile(fullfile(out, "snapshot_0000.mac"))); + end + + function resultsKeepTheCaseThatWasRun(testCase) + results = ldem.run(testCase.CasePath, Formats = "mat", Verbose = false); + info = results.info.case; + + fid = fopen(testCase.CasePath, 'r'); + bytes = fread(fid, Inf, '*uint8'); + fclose(fid); + digest = java.security.MessageDigest.getInstance('SHA-256'); + expected = string(lower(reshape(dec2hex(typecast(digest.digest(bytes), 'uint8'), 2).', 1, []))); + testCase.verifyEqual(info.sha256, expected); + testCase.verifyEqual(info.original, string(fileread(testCase.CasePath))); + testCase.verifyEqual(strlength(info.sha256), 64); + + % The resolved case reads back into the parameters that ran. + path = fullfile(testCase.Folder, "resolved.ldem"); + writeTextFile(path, splitlines(info.resolved)); + again = ldem.io.readCase(path); + testCase.verifyEqual(again.params.toStruct(), results.params); + end + + function theResolvedCaseIsSavedNextToTheResults(testCase) + results = ldem.run(testCase.CasePath, Verbose = false); + saved = fullfile(testCase.Folder, "out", "case.ldem"); + testCase.verifyTrue(isfile(saved)); + again = ldem.io.readCase(saved); + testCase.verifyEqual(again.params.toStruct(), results.params); + data = load(fullfile(testCase.Folder, "out", "results.mat")); + testCase.verifyEqual(data.results.info.case.sha256, results.info.case.sha256); + end + + function runSimulationWithoutACaseHasNoCaseInfo(testCase) + results = ldem.runSimulation(ldem.Parameters(totalTime = 2e-6)); + testCase.verifyFalse(isfield(results.info, 'case')); + end + + function runOptionsOverrideTheCase(testCase) + other = fullfile(testCase.Folder, "other"); + ldem.run(testCase.CasePath, OutputFolder = other, Formats = "mat", Verbose = false); + testCase.verifyTrue(isfile(fullfile(other, "results.mat"))); + testCase.verifyFalse(isfolder(fullfile(testCase.Folder, "out"))); + end + + function checkReportsTheModelWithoutSimulating(testCase) + report = ldem.check(testCase.CasePath); + testCase.verifyEqual(report.model.nNodes, 6 * 3 * 3 + 5 * 2 * 2); + testCase.verifyEqual(report.nSteps, 100); + testCase.verifyEqual(report.nSnapshots, 3); + testCase.verifyGreaterThan(report.snapshotMemoryMB, 0); + testCase.verifyEqual(report.randomField, "none"); + testCase.verifyEqual(report.timeStepRatio, 2e-7 / report.params.criticalTimeStep); + testCase.verifyEqual([report.controlNodes.number], [1 2]); + testCase.verifyEqual(report.controlNodes(1).position, [0 0 0]); + end + + function checkPrintsWhenThereIsNoOutput(testCase) + text = evalc('ldem.check(testCase.CasePath)'); + testCase.verifySubstring(text, 'UniaxialTension'); + end + + function checkSaysWhetherTheRandomFieldFileIsUsable(testCase) + path = fullfile(testCase.Folder, "scatter.ldem"); + lines = splitlines(string(fileread(testCase.CasePath))); + writeTextFile(path, [lines(1:end-1); "[material.scatter]"; "type = ""file"""; "file = ""missing.txt"""]); + report = ldem.check(path); + testCase.verifySubstring(report.randomField, "PROBLEM"); + + writeTextFile(fullfile(testCase.Folder, "field.txt"), string(ones(1000, 1))); + writeTextFile(path, [lines(1:end-1); "[material.scatter]"; "type = ""file"""; "file = ""field.txt"""]); + report = ldem.check(path); + testCase.verifySubstring(report.randomField, "file OK"); + + writeTextFile(path, [lines(1:end-1); "[material.scatter]"; "type = ""generated"""; "cv = 0.1"]); + testCase.verifySubstring(ldem.check(path).randomField, "generated"); + end + end +end diff --git a/tests/unit/TestRunSimulation.m b/tests/unit/TestRunSimulation.m new file mode 100644 index 0000000..68c6237 --- /dev/null +++ b/tests/unit/TestRunSimulation.m @@ -0,0 +1,264 @@ +classdef TestRunSimulation < LdemTestCase + %TESTRUNSIMULATION End-to-end tests of ldem.runSimulation and the post-processing. + + methods (Access = private) + function params = quickParams(~, output) + % A 100-step model on a small prism; output: how often to store results. + if nargin < 2 + output = struct('snapshotEvery', 25, 'controlNodesEvery', 10, ... + 'energyEvery', 10, 'trackedBarEvery', 0); + end + params = ldem.Parameters(nModules=[4 3 3], totalTime=2e-5, output=output); + end + + function folder = tempFolder(testCase) + folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + end + end + + methods (Test, TestTags = {'Unit'}) + function resultsHaveAllTheDocumentedParts(testCase) + results = ldem.runSimulation(testCase.quickParams()); + for name = ["info", "params", "mesh", "barProps", "controlNodes", "reactions", ... + "energy", "trackedBar", "snapshots", "final"] + testCase.verifyTrue(isfield(results, name), "Missing results." + name); + end + testCase.verifyEqual(results.info.version, ldem.version()); + testCase.verifyGreaterThan(results.info.elapsedSeconds, 0); + testCase.verifyEqual(results.params.nSteps, 100); + testCase.verifyEqual(results.final.step, 100); + testCase.verifySize(results.controlNodes.time, [10 1]); + testCase.verifySize(results.energy.time, [10 1]); + testCase.verifyEqual(numel(results.snapshots.time), 5); % 0, 25, 50, 75, 100 + testCase.verifyEqual(results.snapshots.step, (0:25:100).'); + end + + function resultsContainNoObjectsSoTheyLoadWithoutThePackage(testCase) + results = ldem.runSimulation(testCase.quickParams()); + testCase.verifyFalse(containsObject(results), ... + 'results must not hold ldem class instances.'); + end + + function nodalKineticEnergyIsStoredAndAddsUpToTheTotal(testCase) + results = ldem.runSimulation(testCase.quickParams()); + nNodes = size(results.mesh.nodes0, 1); + + testCase.verifySize(results.final.kineticEnergy, [nNodes 1]); + testCase.verifyEqual(sum(results.final.kineticEnergy), results.energy.kinetic(end), 'RelTol', 1e-12); + + snapshots = results.snapshots; + testCase.verifySize(snapshots.kineticEnergy, [5 1]); + testCase.verifyClass(snapshots.kineticEnergy{end}, 'single'); + testCase.verifyEqual(double(sum(snapshots.kineticEnergy{end})), results.energy.kinetic(end), 'RelTol', 1e-5); + testCase.verifyEqual(sum(snapshots.kineticEnergy{1}), single(0), 'At time zero nothing moves.'); + end + + function resultsDescribeTheModelAndTheMaterial(testCase) + params = testCase.quickParams(); + results = ldem.runSimulation(params); + m = results.model; + nBars = size(results.mesh.bars, 1); + + testCase.verifyEqual(m.nNodes, params.nNodes); + testCase.verifyEqual(m.nModules, [3 2 2]); + testCase.verifyEqual(m.nGridEdges + m.nCentreBars + m.nDiagonals, nBars); + testCase.verifyEqual(m.nGridNodes + m.nCentreNodes, m.nNodes); + testCase.verifyEqual(m.totalMass, params.density * m.prismVolume, 'RelTol', 1e-12); + + mat = results.material; + testCase.verifyEqual(mat.youngModulus, params.youngModulus); + testCase.verifyEqual(mat.alpha, 0.4, 'RelTol', 1e-12); + testCase.verifyEqual(mat.delta, 1.125, 'RelTol', 1e-12); + testCase.verifyEqual(mat.criticalStrainMean, results.barProps.criticalStrainMean); + testCase.verifyEqual(mat.criticalStrainCv, results.barProps.criticalStrainCv); + % With no random field all the strains are equal; allow for rounding of the mean. + testCase.verifyLessThanOrEqual(mat.criticalStrainMin, mat.criticalStrainMean * (1 + 1e-12)); + testCase.verifyGreaterThanOrEqual(mat.criticalStrainMax, mat.criticalStrainMean * (1 - 1e-12)); + testCase.verifyEqual(mat.ruptureRatioNormal, mat.criticalLength / params.moduleLength, 'RelTol', 1e-14); + end + + function energyPartsAddUp(testCase) + results = ldem.runSimulation(testCase.quickParams()); + e = results.energy; + testCase.verifyEqual(e.internal, e.kinetic + e.elastic + e.damage + e.damping, 'RelTol', 1e-12); + testCase.verifyGreaterThan(max(e.kinetic), 0); + end + + function nothingIsWrittenWithoutAnOutputFolder(testCase) + folder = testCase.tempFolder(); + oldFolder = cd(folder); + restore = onCleanup(@() cd(oldFolder)); + ldem.runSimulation(testCase.quickParams(), Formats=["mat" "ansys" "vtk"]); + listing = dir(folder); + testCase.verifyEqual(nnz(~[listing.isdir]), 0); + end + + function outputFilesAreWrittenForTheRequestedFormats(testCase) + folder = fullfile(testCase.tempFolder(), "run"); + results = ldem.runSimulation(testCase.quickParams(), OutputFolder=folder, ... + Formats=["mat" "ansys" "vtk"]); + + testCase.verifyTrue(isfile(fullfile(folder, "results.mat"))); + testCase.verifyTrue(isfile(fullfile(folder, "snapshots.pvd"))); + for k = 0:4 + testCase.verifyTrue(isfile(fullfile(folder, sprintf('snapshot_%04d.mac', k)))); + testCase.verifyTrue(isfile(fullfile(folder, sprintf('snapshot_%04d.vtu', k)))); + end + loaded = load(fullfile(folder, "results.mat")); + testCase.verifyEqual(loaded.results.final.displacement, results.final.displacement); + testCase.verifyEqual(loaded.results.energy.kinetic, results.energy.kinetic); + testCase.verifyEqual(loaded.results.params.nSteps, 100); + end + + function generatedRandomFieldIsSavedInTheResults(testCase) + params = testCase.quickParams(); + params.randomFieldCv = 0.05; + folder = fullfile(testCase.tempFolder(), "run"); + results = ldem.runSimulation(params, OutputFolder=folder); + + nBars = size(results.mesh.bars, 1); + testCase.verifySize(results.barProps.randomField, [nBars 1]); + testCase.verifyEqual(results.material.randomField.source, "generated"); + testCase.verifyEqual(results.params.randomFieldCv, 0.05); + + loaded = load(fullfile(folder, "results.mat")); + testCase.verifyEqual(loaded.results.barProps.randomField, results.barProps.randomField); + testCase.verifyEqual(loaded.results.material.randomField.seed, params.randomFieldSeed); + end + + function onlyTheRequestedFormatsAreWritten(testCase) + folder = fullfile(testCase.tempFolder(), "run"); + ldem.runSimulation(testCase.quickParams(), OutputFolder=folder, Formats="vtk"); + testCase.verifyTrue(isfile(fullfile(folder, "snapshot_0000.vtu"))); + testCase.verifyFalse(isfile(fullfile(folder, "snapshot_0000.mac"))); + testCase.verifyFalse(isfile(fullfile(folder, "results.mat"))); + end + + function snapshotFormatsWithoutSnapshotStepsWarn(testCase) + params = ldem.Parameters(nModules=[3 3 3], totalTime=2e-6); % snapshotEvery = 0 + folder = fullfile(testCase.tempFolder(), "run"); + testCase.verifyWarning( ... + @() ldem.runSimulation(params, OutputFolder=folder, Formats="vtk"), ... + 'ldem:output:noSnapshots'); + testCase.verifyFalse(isfile(fullfile(folder, "snapshot_0000.vtu"))); + end + + function unknownFormatIsRejected(testCase) + testCase.verifyError(@() ldem.runSimulation(ldem.Parameters(), Formats="docx"), ?MException); + end + + function invalidParametersAreCaughtBeforeRunning(testCase) + params = ldem.Parameters(); + params.dt = 1e-5; % unstable, set after construction + testCase.verifyError(@() ldem.runSimulation(params), 'ldem:params:unstableTimeStep'); + end + + function aCustomScenarioIsUsed(testCase) + params = testCase.quickParams(); + still = ldem.scenarios.UniaxialTension(loadingVelocity=0); + results = ldem.runSimulation(params, Scenario=still); + testCase.verifyEqual(max(abs(results.final.velocity), [], 'all'), 0); + testCase.verifyEqual(results.final.displacement, results.mesh.nodes0); + end + + function runsAreDeterministic(testCase) + a = ldem.runSimulation(testCase.quickParams()); + b = ldem.runSimulation(testCase.quickParams()); + testCase.verifyEqual(a.final, b.final); + testCase.verifyEqual(a.energy, b.energy); + end + + function aRunFromAnInputFileMatchesTheEquivalentParameters(testCase) + testsDir = fullfile(testCase.RepoRoot, 'tests', 'tools'); + testCase.applyFixture(matlab.unittest.fixtures.PathFixture(testsDir)); + cases = referenceCases(); + c = cases(strcmp({cases.name}, 'tension101_elastic')); + path = fullfile(testCase.tempFolder(), "DATA0.DAT"); + writeDataFile(path, c); + + fromFile = ldem.runSimulation(ldem.Parameters.fromFile(path)); + direct = ldem.runSimulation(ldem.Parameters( ... + testId = c.test, seed = c.seed, moduleLength = c.moduleLength, ... + nModules = c.modules, dampingInitial = c.damping1, dampingFinal = c.damping2, ... + dampingSwitchTime = c.dampingSwitchTime, constitutiveDamping = c.con, ... + dt = c.dt, totalTime = c.nSteps * c.dt, controlNodes = c.controlNodes, ... + youngModulus = c.youngModulus, density = c.density, poissonRatio = c.poisson, ... + fractureEnergy = c.fractureEnergy, criticalDistance = c.criticalDistance, ... + output = struct('snapshotEvery', c.ansysEvery, 'controlNodesEvery', c.everyN, ... + 'energyEvery', c.everyN, 'trackedBarEvery', 1))); + testCase.verifyEqual(fromFile.final.displacement, direct.final.displacement); + testCase.verifyEqual(fromFile.energy.kinetic, direct.energy.kinetic); + end + + function plotEnergyDrawsSixCurves(testCase) + results = ldem.runSimulation(testCase.quickParams()); + fig = figure('Visible', 'off'); + testCase.addTeardown(@close, fig); + ax = ldem.post.plotEnergy(results, axes(fig)); + testCase.verifyEqual(numel(ax.Children), 6); + testCase.verifyEqual(ax.XLabel.String, 'Time [s]'); + end + + function plotsUseTheCurrentAxesByDefault(testCase) + results = ldem.runSimulation(testCase.quickParams()); + fig = figure('Visible', 'off'); + testCase.addTeardown(@close, fig); + ax = ldem.post.plotEnergy(results); + testCase.verifyEqual(ax, fig.CurrentAxes); + + bending = ldem.runSimulation(ldem.Parameters(testId=102, nModules=[70 4 3], ... + totalTime=2e-6, output=struct('snapshotEvery', 0, 'controlNodesEvery', 2, ... + 'energyEvery', 0, 'trackedBarEvery', 0))); + ax = ldem.post.plotReaction(bending); + testCase.verifyEqual(ax, fig.CurrentAxes); + end + + function plotEnergyNeedsAnEnergyHistory(testCase) + params = testCase.quickParams(struct('snapshotEvery', 0, ... + 'controlNodesEvery', 0, 'energyEvery', 0, 'trackedBarEvery', 0)); + results = ldem.runSimulation(params); + testCase.verifyError(@() ldem.post.plotEnergy(results), 'ldem:post:noData'); + end + + function plotReactionShowsTheBeamReaction(testCase) + params = ldem.Parameters(testId=102, nModules=[70 4 3], totalTime=2e-6, ... + output=struct('snapshotEvery', 0, 'controlNodesEvery', 2, ... + 'energyEvery', 0, 'trackedBarEvery', 0)); + results = ldem.runSimulation(params); + fig = figure('Visible', 'off'); + testCase.addTeardown(@close, fig); + ax = ldem.post.plotReaction(results, axes(fig)); + testCase.verifyEqual(numel(ax.Children), 1); % only Ry is defined + end + + function plotReactionIsNotAvailableForTension(testCase) + results = ldem.runSimulation(testCase.quickParams()); + testCase.verifyError(@() ldem.post.plotReaction(results), 'ldem:post:noData'); + end + end +end + +function tf = containsObject(value) +%CONTAINSOBJECT True if a struct tree holds an instance of a class of the ldem package. +tf = false; +if isstruct(value) + for element = value(:).' + for name = fieldnames(element).' + if containsObject(element.(name{1})) + tf = true; + return + end + end + end +elseif iscell(value) + for k = 1:numel(value) + if containsObject(value{k}) + tf = true; + return + end + end +else + tf = startsWith(string(class(value)), "ldem."); +end +end diff --git a/tests/unit/TestScenarios.m b/tests/unit/TestScenarios.m new file mode 100644 index 0000000..6db44e0 --- /dev/null +++ b/tests/unit/TestScenarios.m @@ -0,0 +1,187 @@ +classdef TestScenarios < LdemTestCase + %TESTSCENARIOS Unit tests of ldem.scenarios and ldem.solver.checkStability. + + methods (Test, TestTags = {'Unit'}) + function factoryReturnsTheRightClass(testCase) + testCase.verifyClass(ldem.scenarios.fromTestId(101), ... + 'ldem.scenarios.UniaxialTension'); + testCase.verifyClass(ldem.scenarios.fromTestId(102), ... + 'ldem.scenarios.FourPointBending'); + testCase.verifyClass(ldem.scenarios.fromTestId(103), ... + 'ldem.scenarios.ClampedBeam'); + end + + function factoryRejectsUnknownTest(testCase) + testCase.verifyError(@() ldem.scenarios.fromTestId(7), ... + 'ldem:scenarios:unknownTest'); + end + + function everyScenarioIsRegisteredUnderItsOwnId(testCase) + for id = [101 102 103] + testCase.verifyEqual(ldem.scenarios.fromTestId(id).testId, id); + end + end + + function tensionHoldsTheCentreNodesOfBothEndColumnsInX(testCase) + params = ldem.Parameters(testId=101, nModules=[6 3 3]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + scenario = ldem.scenarios.UniaxialTension(); + fixed = scenario.fixedDofs(nodes, params); + loaded = scenario.loadedNodes(nodes, params); + + testCase.verifySize(fixed, [params.nNodes 3]); + testCase.verifyFalse(any(fixed(:, 2:3), 'all'), 'Only x may be fixed.'); + % Centre nodes of the first and of the last column of modules: + % 2 columns of (N-1)*(L-1) = 4 nodes. + testCase.verifyEqual(nnz(fixed(:, 1)), 8); + lco = params.moduleLength; + testCase.verifyEqual(unique(round(nodes(fixed(:, 1), 1) / lco * 2) / 2).', [0.5, 4.5]); + % The loaded nodes are the right column, and they are held (exact prescribed motion). + testCase.verifyEqual(nnz(loaded), 4); + testCase.verifyTrue(all(fixed(loaded, 1))); + end + + function bendingFixesYAtEverySupportAndLoadPoint(testCase) + params = ldem.Parameters(testId=102, nModules=[70 4 3]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + fixed = ldem.scenarios.FourPointBending().fixedDofs(nodes, params); + + testCase.verifySize(fixed, [params.nNodes 3]); + testCase.verifyFalse(any(fixed(:, 3)), 'z must stay free.'); + testCase.verifyTrue(all(fixed(fixed(:, 1), 2)), ... + 'A node fixed in x must also be fixed in y (left support).'); + testCase.verifyGreaterThan(nnz(fixed(:, 2)), nnz(fixed(:, 1))); + end + + function bendingLoadsBothPointsOnTheTopFace(testCase) + params = ldem.Parameters(testId=102, nModules=[70 4 3]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + scenario = ldem.scenarios.FourPointBending(); + loaded = scenario.loadedNodes(nodes, params); + lco = params.moduleLength; + + % Two lines of (L-1) centre nodes, at 33.5 modules from each end. + testCase.verifyEqual(nnz(loaded), 2 * (params.nModules(3) - 1)); + testCase.verifyEqual(unique(round(nodes(loaded, 1) / lco * 2) / 2).', [33.5, 35.5]); + testCase.verifyEqual(unique(round(nodes(loaded, 2) / lco * 2) / 2).', 2.5); + fixed = scenario.fixedDofs(nodes, params); + testCase.verifyTrue(all(fixed(loaded, 2)), 'Loaded nodes must be held in y.'); + end + + function bendingPositionsAreParameters(testCase) + % A short beam with supports and load points placed by the user. + params = ldem.Parameters(testId=102, nModules=[30 4 3]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + scenario = ldem.scenarios.FourPointBending(supportPosition=2.5, loadPosition=10.5); + lco = params.moduleLength; + + loaded = scenario.loadedNodes(nodes, params); + testCase.verifyEqual(unique(round(nodes(loaded, 1) / lco * 2) / 2).', [10.5, 18.5]); + fixed = scenario.fixedDofs(nodes, params); + testCase.verifyEqual(unique(round(nodes(fixed(:, 1), 1) / lco * 2) / 2).', 2.5); + testCase.verifyEqual(scenario.supportPosition, 2.5); + testCase.verifyEqual(ldem.scenarios.FourPointBending().supportPosition, 4.5, ... + 'The defaults must be the legacy values.'); + end + + function bendingReportsPositionsThatMatchNoNode(testCase) + % The default positions need a beam longer than about 70 modules. + params = ldem.Parameters(testId=102, nModules=[30 4 3]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + testCase.verifyError( ... + @() ldem.scenarios.FourPointBending().fixedDofs(nodes, params), ... + 'ldem:scenarios:noNodesSelected'); + % Positions that fall between two lines of centre nodes. + scenario = ldem.scenarios.FourPointBending(supportPosition=2.0, loadPosition=10.5); + testCase.verifyError(@() scenario.fixedDofs(nodes, params), ... + 'ldem:scenarios:noNodesSelected'); + end + + function clampedBeamHoldsTheCentreNodesOfBothEndLayers(testCase) + params = ldem.Parameters(testId=103, nModules=[4 4 11]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + fixed = ldem.scenarios.ClampedBeam().fixedDofs(nodes, params); + + testCase.verifySize(fixed, [params.nNodes 3]); + clamped = any(fixed, 2); + testCase.verifyTrue(all(fixed(clamped, :), 'all'), 'A clamped node is held in x, y and z.'); + % Two layers of (M-1)*(N-1) = 9 centre nodes. + testCase.verifyEqual(nnz(clamped), 18); + z = round(nodes(clamped, 3) / params.moduleLength * 2) / 2; + testCase.verifyEqual(unique(z).', [0.5, 9.5]); + end + + function clampedBeamLoadsTheMidSpanLineOnTheBottomFace(testCase) + params = ldem.Parameters(testId=103, nModules=[4 4 11]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + scenario = ldem.scenarios.ClampedBeam(); + loaded = scenario.loadedNodes(nodes, params); + lco = params.moduleLength; + + testCase.verifyEqual(nnz(loaded), 3); + testCase.verifyEqual(unique(round(nodes(loaded, 3) / lco * 2) / 2), 4.5); + testCase.verifyEqual(unique(round(nodes(loaded, 2) / lco * 2) / 2), 0.5); + testCase.verifyFalse(any(loaded & any(scenario.fixedDofs(nodes, params), 2)), ... + 'The load must not sit on a clamped node.'); + end + + function clampedBeamForceGrowsLinearlyThenStaysConstant(testCase) + params = ldem.Parameters(testId=103, nModules=[4 4 11]); + mesh = ldem.mesh.buildMesh(params); + scenario = ldem.scenarios.ClampedBeam(forceRate=1000, rampTime=0.00035); + [~, history] = ldem.material.buildBarProperties(mesh, params); + state = ldem.solver.initialState(mesh, history); + loaded = scenario.loadedNodes(mesh.nodes0, params); + + for t = [1e-4, 3.5e-4, 1e-3] + state.time = t; + state = scenario.applyLoads(state, mesh, params); + testCase.verifyEqual(state.appliedForce(loaded, 2), ... + 1000 * min(t, 0.00035) * ones(3, 1), 'AbsTol', 1e-12); + end + other = state.appliedForce; + other(loaded, 2) = 0; + testCase.verifyEqual(other, zeros(size(other)), 'Only y of the loaded nodes may carry force.'); + testCase.verifyEqual(state.displacement, mesh.nodes0, 'A force scenario must not move nodes.'); + end + + function clampedBeamReactionSumsTheBarForceOnTheClampedEnds(testCase) + params = ldem.Parameters(testId=103, nModules=[4 4 11]); + mesh = ldem.mesh.buildMesh(params); + [~, history] = ldem.material.buildBarProperties(mesh, params); + state = ldem.solver.initialState(mesh, history); + state.force(:, 2) = (1:params.nNodes).'; + reaction = ldem.scenarios.ClampedBeam().reactions(state, mesh, params); + testCase.verifyEqual(reaction, [0, sum(find(mesh.fixed(:, 2))), 0]); + end + + function clampedBeamReportsALoadLineThatMatchesNoNode(testCase) + params = ldem.Parameters(testId=103, nModules=[4 4 11]); + nodes = ldem.mesh.buildNodes(params.nModules, params.moduleLength); + scenario = ldem.scenarios.ClampedBeam(loadPosition=4); % grid nodes, not centre nodes + testCase.verifyError(@() scenario.loadedNodes(nodes, params), ... + 'ldem:scenarios:noNodesSelected'); + end + + function stabilityCheckReturnsCriticalStep(testCase) + params = ldem.Parameters(); + lengths = [0.003; 0.0026; 0.003]; + critical = ldem.solver.checkStability(lengths, params); + testCase.verifyEqual(critical, 0.0026 / params.waveSpeed, 'RelTol', 1e-12); + end + + function stabilityCheckRejectsShortBars(testCase) + params = ldem.Parameters(); + testCase.verifyError( ... + @() ldem.solver.checkStability([1e-5; 0.003], params), ... + 'ldem:params:unstableTimeStep'); + end + + function regularLatticeMatchesParametersEstimate(testCase) + params = ldem.Parameters(nModules=[4 3 3]); + mesh = ldem.mesh.buildMesh(params); + critical = ldem.solver.checkStability(mesh.barLength, params); + testCase.verifyEqual(critical, params.criticalTimeStep, 'RelTol', 1e-12); + end + end +end diff --git a/tests/unit/TestSimulate.m b/tests/unit/TestSimulate.m new file mode 100644 index 0000000..4201ec1 --- /dev/null +++ b/tests/unit/TestSimulate.m @@ -0,0 +1,261 @@ +classdef TestSimulate < LdemTestCase + %TESTSIMULATE Unit tests of the scenario loads and of ldem.solver.simulate. + + methods (Access = private) + function [params, mesh, barProps, history, scenario] = smallModel(~, varargin) + params = ldem.Parameters(varargin{:}); + mesh = ldem.mesh.buildMesh(params); + [barProps, history] = ldem.material.buildBarProperties(mesh, params); + scenario = ldem.scenarios.fromTestId(params.testId); + end + end + + methods (Test, TestTags = {'Unit'}) + function tensionLoadMovesTheLastColumnOfCentreNodes(testCase) + [params, mesh, ~, history, scenario] = testCase.smallModel(testId=101); + state = ldem.solver.initialState(mesh, history); + state.time = 1e-4; + state = scenario.applyLoads(state, mesh, params); + + loaded = scenario.loadedNodes(mesh.nodes0, params); + testCase.verifyEqual(nnz(loaded), (params.nModules(2) - 1) * (params.nModules(3) - 1)); + testCase.verifyEqual(state.displacement(loaded, 1), ... + mesh.nodes0(loaded, 1) - 400e-5 * 1e-4, 'RelTol', 1e-14); + % Everything else is untouched, and y, z of the loaded nodes too. + testCase.verifyEqual(state.displacement(~loaded, :), mesh.nodes0(~loaded, :)); + testCase.verifyEqual(state.displacement(loaded, 2:3), mesh.nodes0(loaded, 2:3)); + end + + function loadingVelocityCanBeChanged(testCase) + [params, mesh, ~, history, ~] = testCase.smallModel(testId=101); + scenario = ldem.scenarios.UniaxialTension(loadingVelocity=-1e-3); + state = ldem.solver.initialState(mesh, history); + state.time = 2e-4; + state = scenario.applyLoads(state, mesh, params); + loaded = scenario.loadedNodes(mesh.nodes0, params); + % Negative velocity pulls the loaded nodes away from the fixed end. + testCase.verifyGreaterThan(min(state.displacement(loaded, 1) - mesh.nodes0(loaded, 1)), 0); + end + + function bendingLoadMovesBothLoadPoints(testCase) + [params, mesh, ~, history, scenario] = testCase.smallModel(testId=102, nModules=[70 4 3]); + state = ldem.solver.initialState(mesh, history); + state.time = 1e-4; + state = scenario.applyLoads(state, mesh, params); + + loaded = scenario.loadedNodes(mesh.nodes0, params); + testCase.verifyEqual(nnz(loaded), 2 * (params.nModules(3) - 1)); + testCase.verifyEqual(state.displacement(loaded, 2), ... + mesh.nodes0(loaded, 2) - 400e-5 * 1e-4, 'RelTol', 1e-14); + testCase.verifyTrue(all(mesh.fixed(loaded, 2)), 'Loaded nodes must be held in y.'); + testCase.verifyEqual(state.displacement(~loaded, :), mesh.nodes0(~loaded, :)); + end + + function reactionIsUndefinedForTensionAndSummedForBending(testCase) + [params, mesh, ~, history, tension] = testCase.smallModel(testId=101); + state = ldem.solver.initialState(mesh, history); + testCase.verifyTrue(all(isnan(tension.reactions(state, mesh, params)))); + + [params, mesh, ~, history, bending] = testCase.smallModel(testId=102, nModules=[70 4 3]); + state = ldem.solver.initialState(mesh, history); + atTop = mesh.fixed(:, 2) & mesh.nodes0(:, 2) >= params.moduleLength * (params.nModules(2) - 1.51); + state.force(atTop, 2) = 1.5; + r = bending.reactions(state, mesh, params); + testCase.verifyEqual(r, [0, 1.5 * nnz(atTop), 0]); + end + + function simulateStoresTheRequestedResults(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel( ... + nModules=[4 3 3], totalTime=4e-6, controlNodes=[1 2 3], ... + output=struct('snapshotEvery', 0, 'controlNodesEvery', 4, ... + 'energyEvery', 5, 'trackedBarEvery', 0)); + [state, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario); + + testCase.verifyEqual(state.step, 20); + testCase.verifyEqual(state.time, 20 * params.dt, 'RelTol', 1e-12); + testCase.verifySize(record.controlNodes.time, [5 1]); + testCase.verifySize(record.controlNodes.displacement, [5 3 3]); + testCase.verifySize(record.controlNodes.acceleration, [5 3 3]); + testCase.verifySize(record.reactions.force, [5 3]); + testCase.verifySize(record.energy.time, [4 1]); + testCase.verifyEqual(record.controlNodes.time, (4:4:20).' * params.dt, 'RelTol', 1e-12); + testCase.verifyEqual(record.energy.time, (5:5:20).' * params.dt, 'RelTol', 1e-12); + testCase.verifyEmpty(record.trackedBar.time); + testCase.verifyEqual(record.controlNodes.displacement(end, :, :), ... + reshape(state.displacement(params.controlNodes, :), 1, 3, 3)); + end + + function simulateRecordsTheTrackedBarAtEveryStep(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel( ... + nModules=[4 3 3], totalTime=2e-6, trackedBar=5, ... + output=struct('snapshotEvery', 0, 'controlNodesEvery', 0, ... + 'energyEvery', 0, 'trackedBarEvery', 1)); + [state, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario); + + testCase.verifySize(record.trackedBar.time, [10 1]); + testCase.verifyEqual(record.trackedBar.bar, 5); + testCase.verifyEqual(record.trackedBar.strain(end), state.strain(5)); + testCase.verifyEqual(record.trackedBar.force(end), state.axialForce(5)); + testCase.verifyEqual(record.trackedBar.criticalStrain(1), barProps.criticalStrain(5)); + testCase.verifyEmpty(record.controlNodes.time); + testCase.verifyEmpty(record.energy.time); + end + + function aTrackedBarThatDoesNotExistIsIgnored(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel( ... + nModules=[3 3 3], totalTime=1e-6, trackedBar=999999, ... + output=struct('snapshotEvery', 0, 'controlNodesEvery', 0, ... + 'energyEvery', 0, 'trackedBarEvery', 1)); + [~, record] = ldem.solver.simulate(params, mesh, barProps, history, scenario); + testCase.verifyEmpty(record.trackedBar.time); + end + + function snapshotFunctionIsCalledAtTimeZeroAndPeriodically(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel( ... + nModules=[3 3 3], totalTime=4e-6, ... + output=struct('snapshotEvery', 5, 'controlNodesEvery', 0, ... + 'energyEvery', 0, 'trackedBarEvery', 0)); + snapshotLog("reset"); + ldem.solver.simulate(params, mesh, barProps, history, scenario, ... + SnapshotFcn=@(state) snapshotLog("add", state)); + steps = snapshotLog("read"); + testCase.verifyEqual(steps, [0 5 10 15 20]); + end + + function simulateIsDeterministic(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel(nModules=[4 3 3], totalTime=4e-6); + a = ldem.solver.simulate(params, mesh, barProps, history, scenario); + b = ldem.solver.simulate(params, mesh, barProps, history, scenario); + testCase.verifyEqual(a.displacement, b.displacement); + testCase.verifyEqual(a.force, b.force); + end + + function loadedModelDeformsAndStaysFinite(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel(nModules=[6 3 3], totalTime=2e-5); + state = ldem.solver.simulate(params, mesh, barProps, history, scenario); + testCase.verifyTrue(all(isfinite(state.displacement), 'all')); + testCase.verifyGreaterThan(max(abs(state.velocity), [], 'all'), 0); + % Free nodes move too, not only the loaded ones (the equation of motion is integrated). + moved = any(state.displacement ~= mesh.nodes0, 2) & ~scenario.loadedNodes(mesh.nodes0, params); + testCase.verifyTrue(any(moved)); + end + + function nonFiniteResultsAreReported(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel(nModules=[3 3 3], totalTime=1e-6); + barProps.stiffness(:) = NaN; + history.tensionStiffness(:) = NaN; + testCase.verifyError( ... + @() ldem.solver.simulate(params, mesh, barProps, history, scenario), ... + 'ldem:solver:nonFinite'); + end + + function unstableTimeStepForTheMeshIsReported(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel(nModules=[3 3 3], totalTime=1e-6); + mesh.barLength(1) = mesh.barLength(1) / 100; % an unusually short bar + testCase.verifyError( ... + @() ldem.solver.simulate(params, mesh, barProps, history, scenario), ... + 'ldem:params:unstableTimeStep'); + end + + function aDamagedTrackedBarReportsItsDissipatedEnergy(testCase) + output = struct('snapshotEvery', 0, 'controlNodesEvery', 0, ... + 'energyEvery', 0, 'trackedBarEvery', 0); + base = {'nModules', [6 3 3], 'totalTime', 2e-4, 'fractureEnergy', 0.1}; + + % First find a bar that softens in this simulation. + probe = ldem.runSimulation(ldem.Parameters(base{:}, 'output', output)); + bar = find(~probe.final.damage.isUndamaged, 1); + testCase.assumeNotEmpty(bar, 'The probe run must damage at least one bar.'); + + output.trackedBarEvery = 1; + results = ldem.runSimulation(ldem.Parameters(base{:}, 'trackedBar', bar, 'output', output)); + tracked = results.trackedBar; + + testCase.verifyEqual(tracked.damageEnergy(1), 0, 'A bar starts undamaged.'); + testCase.verifyGreaterThan(tracked.damageEnergy(end), 0); + testCase.verifyTrue(all(diff(tracked.damageEnergy) >= -1e-18), ... + 'Dissipated energy cannot decrease.'); + + % Same formula as ldem.solver.computeEnergies, for this bar only. + h = results.final.damage; + E1 = results.barProps.stiffness(bar); + E2 = h.tensionStiffness(bar); + EP = results.barProps.criticalStrain(bar); + EM = h.maxStrain(bar); + expected = results.mesh.barLength(bar) / 2 * ... + (E1*EP^2 - E2*EM^2 + (E1*EP + E2*EM) * (EM - EP)); + testCase.verifyEqual(tracked.damageEnergy(end), expected, 'RelTol', 1e-12); + end + + function bendingScenarioAcceptsALoadingVelocity(testCase) + scenario = ldem.scenarios.FourPointBending(loadingVelocity=1e-3); + testCase.verifyEqual(scenario.loadingVelocity, 1e-3); + testCase.verifyEqual(ldem.scenarios.FourPointBending().loadingVelocity, 400e-5); + end + + function energyBalanceClosesInTheBeamTest(testCase) + % The load acts on held degrees of freedom, so external work equals + % the stored plus dissipated energy. + params = ldem.Parameters(testId=102, nModules=[70 4 3], totalTime=6e-5, ... + output=struct('snapshotEvery', 0, 'controlNodesEvery', 0, ... + 'energyEvery', 10, 'trackedBarEvery', 0)); + results = ldem.runSimulation(params); + e = results.energy; + testCase.verifyGreaterThan(e.external(end), 0); + testCase.verifyEqual(e.internal(end), e.external(end), 'RelTol', 1e-2); + testCase.verifyLessThan(max(abs(e.balance)) / e.external(end), 1e-2); + end + + function clampedBeamCarriesTheAppliedForceAtRest(testCase) + % Heavy damping brings the beam to rest, where the clamped ends + % carry exactly the force applied at mid-span, and the work of the + % applied force equals the stored plus dissipated energy. + params = ldem.Parameters(testId=103, nModules=[4 4 11], moduleLength=1e-3, ... + dt=3.5e-7, totalTime=1e-3, youngModulus=3.87e9, density=1500, ... + criticalDistance=4.5e-3, dampingInitial=20000, dampingFinal=20000, ... + dampingSwitchTime=1, controlNodes=1, ... + output=struct('snapshotEvery', 0, 'controlNodesEvery', 10, ... + 'energyEvery', 10, 'trackedBarEvery', 0)); + results = ldem.runSimulation(params); + e = results.energy; + + nLoaded = params.nModules(1) - 1; + totalForce = nLoaded * 1000 * 0.00035; + testCase.verifyEqual(results.reactions.force(end, 2), totalForce, 'RelTol', 1e-2); + testCase.verifyEqual(results.reactions.force(end, [1 3]), [0 0], 'AbsTol', 1e-3 * totalForce); + testCase.verifyGreaterThan(e.external(end), 0); + testCase.verifyLessThan(max(abs(e.balance)) / e.external(end), 1e-2); + end + + function energyBalanceClosesInTensionWithSofteningAndRupture(testCase) + % With softening and rupture: the dissipated energy is accounted too. + params = ldem.Parameters(nModules=[6 3 3], totalTime=2e-4, fractureEnergy=0.1, ... + output=struct('snapshotEvery', 0, 'controlNodesEvery', 0, ... + 'energyEvery', 10, 'trackedBarEvery', 0)); + results = ldem.runSimulation(params); + e = results.energy; + + testCase.verifyGreaterThan(nnz(~results.final.damage.isUndamaged), 0, 'The test needs damage.'); + testCase.verifyGreaterThan(e.damage(end), 0); + testCase.verifyEqual(e.internal(end), e.external(end), 'RelTol', 1e-2); + testCase.verifyLessThan(max(abs(e.balance)) / e.external(end), 1e-2); + end + + function verboseModePrintsProgress(testCase) + [params, mesh, barProps, history, scenario] = testCase.smallModel(nModules=[3 3 3], totalTime=2e-6); %#ok + text = evalc('ldem.solver.simulate(params, mesh, barProps, history, scenario, Verbose=true);'); + testCase.verifySubstring(text, 'step 10 / 10'); + end + end +end + +function steps = snapshotLog(command, state) +%SNAPSHOTLOG Collect the step numbers passed to a snapshot callback. +persistent log +if command == "reset" + log = []; +elseif command == "add" + log(end + 1) = state.step; +end +steps = log; +end diff --git a/tests/unit/TestSolver.m b/tests/unit/TestSolver.m new file mode 100644 index 0000000..46f8024 --- /dev/null +++ b/tests/unit/TestSolver.m @@ -0,0 +1,309 @@ +classdef TestSolver < LdemTestCase + %TESTSOLVER Unit tests of the solver routines with analytical solutions. + % + % The main model is a single bar: node 1 is fixed and node 2 (mass m) + % moves along x. The bar force is E1*strain, so it behaves as a spring + % of constant k = E1/L and natural frequency omega = sqrt(k/m). + + properties (Constant) + E1 = 1e6 % bar stiffness [N] + L = 0.01 % bar length [m] + Mass = 0.1 % mass of the free node [kg] + Stretch = 1e-6 % initial elongation [m] + end + + methods (Access = private) + function [mesh, barProps, history] = oscillator(testCase) + mesh = struct( ... + 'nodes0', [0 0 0; testCase.L 0 0], ... + 'bars', [1 2], ... + 'barLength', testCase.L, ... + 'mass', [testCase.Mass; testCase.Mass], ... + 'fixed', [true true true; false true true]); + barProps = struct( ... + 'stiffness', testCase.E1, ... + 'criticalStrain', 1, ... + 'ruptureRatio', 10, ... + 'ruptureStrain', 10); + history = struct('tensionStiffness', testCase.E1, 'maxStrain', 1, ... + 'isUndamaged', true, 'isUnbroken', true); + end + + function omega = naturalFrequency(testCase) + omega = sqrt(testCase.E1 / testCase.L / testCase.Mass); + end + + function [x, states, params] = runOscillator(testCase, damping, nSteps) + % Release node 2 from rest at x = L + Stretch and integrate. + params = ldem.Parameters(dt=2e-7, dampingInitial=damping, dampingFinal=damping, ... + dampingSwitchTime=1); + [mesh, barProps, history] = testCase.oscillator(); + state = ldem.solver.initialState(mesh, history); + + omega = testCase.naturalFrequency(); + c = damping; + omegaD = sqrt(omega^2 - c^2 / 4); + u0 = testCase.Stretch; + % Exact position one step before time zero, for zero initial velocity. + previous = @(t) u0 * exp(-c * t / 2) * (cos(omegaD * t) + c / (2 * omegaD) * sin(omegaD * t)); + state.displacement(2, 1) = testCase.L + u0; + state.previousDisplacement(2, 1) = testCase.L + previous(-params.dt); + + x = zeros(nSteps, 1); + states = cell(nSteps, 1); + for n = 1:nSteps + state.step = n; + state.time = state.time + params.dt; + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + state = ldem.solver.integrateStep(state, mesh, barProps, params); + x(n) = state.displacement(2, 1) - testCase.L; + states{n} = state; + end + end + + function [state, params] = runWithAppliedForce(testCase, force, nSteps) + % Apply a constant force along x on the free node of the spring. + params = ldem.Parameters(dt=2e-7, dampingInitial=4000, dampingFinal=4000, ... + dampingSwitchTime=1); + [mesh, barProps, history] = testCase.oscillator(); + state = ldem.solver.initialState(mesh, history); + for n = 1:nSteps + state.step = n; + state.time = state.time + params.dt; + state.appliedForce(2, 1) = force; + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + state = ldem.solver.integrateStep(state, mesh, barProps, params); + end + end + end + + methods (Test, TestTags = {'Unit'}) + function constantForceGivesTheDiscreteParabola(testCase) + % u_n = a*dt^2*n*(n+1)/2 for the scheme started from rest. + params = ldem.Parameters(dampingInitial=0, dampingFinal=0); + mesh = struct('nodes0', [0 0 0], 'bars', zeros(0, 2), 'barLength', zeros(0, 1), ... + 'mass', 2, 'fixed', false(1, 3)); + barProps = struct('stiffness', zeros(0, 1)); + history = struct(); + state = ldem.solver.initialState(mesh, history); + force = 6; + a = force / 2; + + for n = 1:20 + state.step = n; + state.force = [force 0 0]; + state.strain = zeros(0, 1); + state.history = struct('tensionStiffness', zeros(0, 1)); + state = ldem.solver.integrateStep(state, mesh, barProps, params); + testCase.verifyEqual(state.displacement(1), a * params.dt^2 * n * (n + 1) / 2, ... + 'RelTol', 1e-12); + end + testCase.verifyEqual(state.displacement(2:3), [0 0]); + end + + function undampedOscillatorFollowsTheCosine(testCase) + nSteps = 2000; % about two periods + [x, ~, params] = testCase.runOscillator(0, nSteps); + t = (1:nSteps).' * params.dt; + expected = testCase.Stretch * cos(testCase.naturalFrequency() * t); + testCase.verifyEqual(x, expected, 'AbsTol', 1e-3 * testCase.Stretch); + end + + function dampedOscillatorDecaysAsExpected(testCase) + damping = 4000; % [1/s] + nSteps = 2500; + [x, ~, params] = testCase.runOscillator(damping, nSteps); + t = (1:nSteps).' * params.dt; + omegaD = sqrt(testCase.naturalFrequency()^2 - damping^2 / 4); + expected = testCase.Stretch * exp(-damping * t / 2) .* ... + (cos(omegaD * t) + damping / (2 * omegaD) * sin(omegaD * t)); + testCase.verifyEqual(x, expected, 'AbsTol', 1e-3 * testCase.Stretch); + testCase.verifyLessThan(abs(x(end)), 0.7 * testCase.Stretch); + end + + function energyIsConservedWithoutDamping(testCase) + nSteps = 2000; + [~, states, params] = testCase.runOscillator(0, nSteps); + [mesh, barProps, ~] = testCase.oscillator(); + initial = 0.5 * testCase.E1 / testCase.L * testCase.Stretch^2; + for n = [1 500 1000 2000] + e = ldem.solver.computeEnergies(states{n}, mesh, barProps, params); + testCase.verifyEqual(e.kinetic + e.elastic, initial, 'RelTol', 2e-3); + testCase.verifyEqual(e.damping, 0); + end + end + + function dampingEnergyBalancesTheLostEnergy(testCase) + damping = 4000; + nSteps = 2500; + [~, states, params] = testCase.runOscillator(damping, nSteps); + [mesh, barProps, ~] = testCase.oscillator(); + initial = 0.5 * testCase.E1 / testCase.L * testCase.Stretch^2; + for n = [500 1500 2500] + e = ldem.solver.computeEnergies(states{n}, mesh, barProps, params); + testCase.verifyEqual(e.kinetic + e.elastic + e.damping, initial, 'RelTol', 5e-3); + end + testCase.verifyGreaterThan(e.damping, 0); + end + + function fixedDofsDoNotMove(testCase) + [~, states, ~] = testCase.runOscillator(1000, 50); + last = states{end}; + testCase.verifyEqual(last.displacement(1, :), [0 0 0]); + testCase.verifyEqual(last.displacement(2, 2:3), [0 0]); + end + + function movingSupportBalancesTheEnergy(testCase) + % Node 1 is held but moves with constant velocity (prescribed motion); + % node 2 is free. The work done at node 1 must equal the energy stored. + params = ldem.Parameters(dt=2e-7, dampingInitial=0, dampingFinal=0); + [mesh, barProps, history] = testCase.oscillator(); + mesh.fixed(1, :) = true; + % The kinetic energy of a prescribed node is not supplied by the work + % of the bar force, so make it negligible (a real lattice has the same + % property: the prescribed nodes are a tiny part of the mass). + mesh.mass(1) = 1e-12; + state = ldem.solver.initialState(mesh, history); + velocity = 1e-3; % [m/s] + + nSteps = 3000; + for n = 1:nSteps + state.step = n; + state.time = state.time + params.dt; + state.displacement(1, 1) = velocity * state.time; % prescribed + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + state = ldem.solver.integrateStep(state, mesh, barProps, params); + end + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + + testCase.verifyGreaterThan(e.external, 0, 'Pushing the structure is positive work.'); + testCase.verifyEqual(e.internal, e.external, 'RelTol', 5e-3); + testCase.verifyEqual(e.balance, e.external - e.internal); + end + + function appliedForceStretchesTheSpringToItsStaticValue(testCase) + % A constant force on the free node of the spring settles at F/k. + force = 10; % [N] + [state, params] = testCase.runWithAppliedForce(force, 20000); + expected = force * testCase.L / testCase.E1; + testCase.verifyEqual(state.displacement(2, 1) - testCase.L, expected, 'RelTol', 2e-3); + testCase.verifyEqual(state.appliedForce(2, 1), force); + testCase.verifyEqual(params.dt, 2e-7); + end + + function appliedForceWorkBalancesTheEnergy(testCase) + % External work = elastic + kinetic + damping energy; at rest half + % of F*x is stored and half was dissipated. + force = 10; + [state, params] = testCase.runWithAppliedForce(force, 20000); + [mesh, barProps, ~] = testCase.oscillator(); + e = ldem.solver.computeEnergies(state, mesh, barProps, params); + + x = force * testCase.L / testCase.E1; + testCase.verifyEqual(e.external, force * x, 'RelTol', 2e-3); + testCase.verifyEqual(e.elastic, force * x / 2, 'RelTol', 2e-3); + testCase.verifyEqual(e.balance / e.external, 0, 'AbsTol', 2e-3); + testCase.verifyGreaterThan(e.damping, 0); + end + + function aSupportThatDoesNotMoveDoesNoWork(testCase) + [~, states, ~] = testCase.runOscillator(1000, 500); + testCase.verifyEqual(states{end}.externalEnergy, 0); + end + + function integrateRejectsZeroMass(testCase) + params = ldem.Parameters(); + [mesh, barProps, history] = testCase.oscillator(); + mesh.mass(2) = 0; + state = ldem.solver.initialState(mesh, history); + testCase.verifyError(@() ldem.solver.integrateStep(state, mesh, barProps, params), ... + 'ldem:solver:zeroMass'); + end + + function stretchedBarPullsItsNodesTogether(testCase) + params = ldem.Parameters(); + [mesh, barProps, history] = testCase.oscillator(); + state = ldem.solver.initialState(mesh, history); + state.displacement(2, 1) = testCase.L + testCase.Stretch; + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + + expectedForce = testCase.E1 * testCase.Stretch / testCase.L; + testCase.verifyEqual(state.axialForce, expectedForce, 'RelTol', 1e-9); + testCase.verifyEqual(state.force(1, :), [expectedForce 0 0], 'RelTol', 1e-9, 'AbsTol', 1e-12); + testCase.verifyEqual(state.force(2, :), [-expectedForce 0 0], 'RelTol', 1e-9, 'AbsTol', 1e-12); + end + + function compressedBarPushesItsNodesApart(testCase) + params = ldem.Parameters(); + [mesh, barProps, history] = testCase.oscillator(); + state = ldem.solver.initialState(mesh, history); + state.displacement(2, 1) = testCase.L - testCase.Stretch; + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + + testCase.verifyLessThan(state.axialForce, 0); + testCase.verifyLessThan(state.force(1, 1), 0); + testCase.verifyGreaterThan(state.force(2, 1), 0); + end + + function barDirectionIsFollowedWhenItRotates(testCase) + params = ldem.Parameters(); + [mesh, barProps, history] = testCase.oscillator(); + state = ldem.solver.initialState(mesh, history); + state.displacement(2, :) = [testCase.L, 0, 0] + testCase.L * 1e-3 * [0.6 0.8 0]; + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + direction = state.force(1, :) / norm(state.force(1, :)); + delta = state.displacement(2, :) - state.displacement(1, :); + testCase.verifyEqual(direction, delta / norm(delta), 'AbsTol', 1e-12); + end + + function forcesOnTheLatticeAddUpToZero(testCase) + % Internal forces are in equilibrium: Newton's third law. + params = ldem.Parameters(nModules=[4 3 3]); + mesh = ldem.mesh.buildMesh(params); + [barProps, history] = ldem.material.buildBarProperties(mesh, params); + state = ldem.solver.initialState(mesh, history); + rng(1); + state.displacement = mesh.nodes0 + 1e-6 * randn(size(mesh.nodes0)); + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + + testCase.verifyGreaterThan(max(abs(state.force), [], 'all'), 0); + testCase.verifyLessThan(max(abs(sum(state.force, 1))), 1e-9 * max(abs(state.force), [], 'all')); + end + + function latticeAtRestHasNoForce(testCase) + params = ldem.Parameters(nModules=[4 3 3]); + mesh = ldem.mesh.buildMesh(params); + [barProps, history] = ldem.material.buildBarProperties(mesh, params); + state = ldem.solver.initialState(mesh, history); + state = ldem.solver.computeBarForces(state, mesh, barProps, params); + testCase.verifyEqual(state.force, zeros(size(state.force)), 'AbsTol', 1e-9); + testCase.verifyEqual(state.strain, zeros(size(state.strain)), 'AbsTol', 1e-14); + end + + function coincidentNodesAreReported(testCase) + params = ldem.Parameters(); + [mesh, barProps, history] = testCase.oscillator(); + state = ldem.solver.initialState(mesh, history); + state.displacement(2, :) = state.displacement(1, :); + testCase.verifyError(@() ldem.solver.computeBarForces(state, mesh, barProps, params), ... + 'ldem:solver:zeroLengthBar'); + end + + function dampingCoefficientSwitchesAtTheSwitchStep(testCase) + params = ldem.Parameters(dt=2e-7, dampingInitial=100, dampingFinal=50, ... + dampingSwitchTime=1e-5); % switch step 50 + testCase.verifyEqual(ldem.solver.dampingCoefficient(1, params), 100); + testCase.verifyEqual(ldem.solver.dampingCoefficient(49, params), 100); + testCase.verifyEqual(ldem.solver.dampingCoefficient(50, params), 50); + testCase.verifyEqual(ldem.solver.dampingCoefficient(500, params), 50); + end + + function dampingNeverSwitchesWhenTheSwitchStepIsZero(testCase) + % Same behaviour as the legacy code (STEP == NDAMF with NDAMF = 0). + params = ldem.Parameters(dt=2e-7, dampingInitial=100, dampingFinal=50, ... + dampingSwitchTime=0); + testCase.verifyEqual(ldem.solver.dampingCoefficient(1, params), 100); + testCase.verifyEqual(ldem.solver.dampingCoefficient(1000, params), 100); + end + end +end diff --git a/tests/unit/TestWriteCase.m b/tests/unit/TestWriteCase.m new file mode 100644 index 0000000..d4b78f1 --- /dev/null +++ b/tests/unit/TestWriteCase.m @@ -0,0 +1,230 @@ +classdef TestWriteCase < LdemTestCase + %TESTWRITECASE Unit tests of ldem.io.writeCase, writeTemplate and convertLegacyInput. + + properties (Access = private) + Folder (1,1) string + end + + methods (TestMethodSetup) + function makeFolder(testCase) + testCase.Folder = string(testCase.applyFixture( ... + matlab.unittest.fixtures.TemporaryFolderFixture).Folder); + end + end + + methods (Test, TestTags = {'Unit'}) + function roundTripKeepsParametersAndScenario(testCase) + output = struct('snapshotEvery', 400, 'controlNodesEvery', 3, ... + 'energyEvery', 7, 'trackedBarEvery', 1); + p = ldem.Parameters(testId = 103, seed = 77, moduleLength = 0.002, ... + nModules = [6 6 21], dt = 3.5e-7, totalTime = 1.4e-4, ... + dampingInitial = 2500, dampingFinal = 1800, dampingSwitchTime = 5e-5, ... + constitutiveDamping = 1e-6, controlNodes = [3 40 100], ... + youngModulus = 3.87e9, density = 1500, poissonRatio = 0.2, ... + fractureEnergy = 0.5, criticalDistance = 4.5e-3, failureAreaFactor = 0.14, ... + trackedBar = 33, meshPerturbation = 0.02, ... + randomFieldCv = 0.05, randomFieldCorrelationLength = [2 3 4], randomFieldSeed = 9, ... + output = output); + scenario = ldem.scenarios.ClampedBeam(forceRate = 1234.5, rampTime = 2e-4, ... + loadPosition = 7.5, loadHeight = 1.5); + path = fullfile(testCase.Folder, "round.ldem"); + + ldem.io.writeCase(path, p, scenario); + c = ldem.io.readCase(path); + + testCase.verifyEqual(c.params.toStruct(), p.toStruct()); + testCase.verifyEqual(c.scenario.forceRate, 1234.5); + testCase.verifyEqual(c.scenario.rampTime, 2e-4); + testCase.verifyEqual(c.scenario.loadPosition, 7.5); + testCase.verifyEqual(c.scenario.loadHeight, 1.5); + end + + function defaultsAndMidspanRoundTrip(testCase) + p = ldem.Parameters(testId = 103); + path = fullfile(testCase.Folder, "defaults.ldem"); + text = ldem.io.writeCase(path, p); + testCase.verifySubstring(text, 'load_position = "midspan"'); + c = ldem.io.readCase(path); + testCase.verifyEqual(c.params.toStruct(), p.toStruct()); + testCase.verifyTrue(isnan(c.scenario.loadPosition)); + end + + function randomFieldFileIsWrittenRelativeToTheCase(testCase) + file = fullfile(testCase.Folder, "data", "field.txt"); + p = ldem.Parameters(randomFieldFile = file); + path = fullfile(testCase.Folder, "case.ldem"); + text = ldem.io.writeCase(path, p); + testCase.verifySubstring(text, 'file = "data/field.txt"'); + testCase.verifyEqual(string(ldem.io.readCase(path).params.randomFieldFile), ... + string(fullfile(testCase.Folder, "data/field.txt"))); + end + + function randomFieldFileOfAnotherFolderUsesDotDot(testCase) + file = fullfile(testCase.Folder, "shared", "field.txt"); + p = ldem.Parameters(randomFieldFile = file); + path = fullfile(testCase.Folder, "a", "b", "case.ldem"); + text = ldem.io.writeCase(path, p); + testCase.verifySubstring(text, 'file = "../../shared/field.txt"'); + testCase.verifyEqual(strrep(string(ldem.io.readCase(path).params.randomFieldFile), '\', '/'), ... + strrep(string(fullfile(testCase.Folder, "shared", "field.txt")), '\', '/')); + end + + function exampleCaseFilesMatchTheirDataFiles(testCase) + examples = fullfile(testCase.RepoRoot, "examples"); + field = fullfile(examples, "beam_102", "arquivo_3lc_rnao_cv05"); + legacy = ldem.Parameters.fromFile(fullfile(examples, "beam_102", "DATA0.DAT"), ... + randomFieldFile = field); + c = ldem.io.readCase(fullfile(examples, "beam_102", "case.ldem")); + testCase.verifyEqual(testCase.normalizePaths(c.params.toStruct()), ... + testCase.normalizePaths(legacy.toStruct())); + testCase.verifyClass(c.scenario, 'ldem.scenarios.FourPointBending'); + + legacy = ldem.Parameters.fromFile(fullfile(examples, "example1_clamped_beam", "DATA0.DAT"), ... + randomFieldFile = field, trackedBar = 14398); + c = ldem.io.readCase(fullfile(examples, "example1_clamped_beam", "case.ldem")); + testCase.verifyEqual(testCase.normalizePaths(c.params.toStruct()), ... + testCase.normalizePaths(legacy.toStruct())); + testCase.verifyClass(c.scenario, 'ldem.scenarios.ClampedBeam'); + testCase.verifyEqual(c.scenario.forceRate, 1000); + testCase.verifyEqual(c.scenario.rampTime, 0.00035); + end + + function trackedBarIsACommentWhenOff(testCase) + p = ldem.Parameters(trackedBar = 55); + text = ldem.io.writeCase("", p); + testCase.verifySubstring(text, '# tracked = 55'); + output = p.output; + output.trackedBarEvery = 1; + p.output = output; + text = ldem.io.writeCase("", p); + testCase.verifyTrue(contains(text, newline + "tracked = 55") || contains(text, "tracked = 55")); + end + + function filesAreOnlyEnabledWhenThereAreSnapshots(testCase) + p = ldem.Parameters(); % snapshotEvery = 0 + c = testCase.readBack(ldem.io.writeCase("", p), "none.ldem"); + testCase.verifyEqual(c.options.Formats, "mat"); + output = p.output; + output.snapshotEvery = 10; + p.output = output; + c = testCase.readBack(ldem.io.writeCase("", p), "some.ldem"); + testCase.verifyEqual(c.options.Formats, ["mat" "ansys" "vtk"]); + c = testCase.readBack(ldem.io.writeCase("", p, [], Formats = "vtk", OutputFolder = "out"), "vtk.ldem"); + testCase.verifyEqual(c.options.Formats, "vtk"); + testCase.verifyEqual(c.options.OutputFolder, string(fullfile(testCase.Folder, "out"))); + end + + function commentsCanBeOmitted(testCase) + p = ldem.Parameters(); + withComments = ldem.io.writeCase("", p); + without = ldem.io.writeCase("", p, [], Comments = false); + testCase.verifySubstring(withComments, "Legacy: YNG"); + testCase.verifyFalse(contains(without, "#")); + c = testCase.readBack(without, "plain.ldem"); + testCase.verifyEqual(c.params.toStruct(), p.toStruct()); + end + + function titleAuthorsHeaderAndNodeNames(testCase) + p = ldem.Parameters(controlNodes = [1 2]); + text = ldem.io.writeCase("", p, [], Title = "My test", Authors = ["Ana" "Luis"], ... + Header = "Line one", ControlNodeNames = ["left" "right"]); + c = testCase.readBack(text, "meta.ldem"); + testCase.verifyEqual(c.info.title, "My test"); + testCase.verifyEqual(c.info.authors, ["Ana" "Luis"]); + testCase.verifyEqual(c.info.controlNodeNames, ["left" "right"]); + testCase.verifySubstring(text, "# Line one"); + end + + function writesTheFileInAnewFolder(testCase) + path = fullfile(testCase.Folder, "new", "deeper", "case.ldem"); + ldem.io.writeCase(path, ldem.Parameters()); + testCase.verifyTrue(isfile(path)); + end + + function everyTemplateReadsBack(testCase) + for entry = ldem.scenarios.registry() + path = fullfile(testCase.Folder, entry.name + ".ldem"); + ldem.io.writeTemplate(path, entry.name); + c = ldem.io.readCase(path); + testCase.verifyClass(c.scenario, entry.className); + testCase.verifyEqual(c.params.testId, entry.testId); + end + testCase.verifyError(@() ldem.io.writeTemplate("", "rocket"), 'ldem:scenarios:unknownName'); + end + + function everyKeyOfTheSchemaAppearsInATemplate(testCase) + text = ldem.io.writeTemplate("", "uniaxial_tension"); + schema = ldem.schema.caseSchema(); + onlyWithAnOption = ["material.scatter.file" "material.scatter.cv" ... + "material.scatter.correlation_length" "material.scatter.seed" ... + "monitor.bar.tracked" "format" "title" "authors" "scenario.type" ... + "extends" "sweep_mode"]; + for row = schema.' + if startsWith(row.path, ["monitor.node" "support." "load." "sweep."]) || any(row.path == onlyWithAnOption) + continue + end + key = string(regexprep(row.path, '^.*\.', '')); + testCase.verifyTrue(contains(text, key + " "), row.path); + end + end + + function legacyExamplesConvertToTheSameParameters(testCase) + for name = ["beam_102" "example1_clamped_beam"] + dataFile = fullfile(testCase.RepoRoot, "examples", name, "DATA0.DAT"); + path = fullfile(testCase.Folder, name + ".ldem"); + ldem.io.convertLegacyInput(dataFile, path); + fromCase = ldem.io.readCase(path); + legacy = ldem.Parameters.fromFile(dataFile); + testCase.verifyEqual(fromCase.params.toStruct(), legacy.toStruct(), name); + testCase.verifyClass(fromCase.scenario, class(ldem.scenarios.fromTestId(legacy.testId))); + testCase.verifyEqual(ldem.Parameters.fromFile(path).toStruct(), legacy.toStruct(), name); + end + end + + function theConverterNeverGuessesTheTrackedBar(testCase) + dataFile = fullfile(testCase.RepoRoot, "examples", "example1_clamped_beam", "DATA0.DAT"); + text = ldem.io.convertLegacyInput(dataFile, ""); + testCase.verifySubstring(text, "The legacy value OU2 was 14398"); + c = testCase.readBack(text, "ou2.ldem"); + testCase.verifyEqual(c.params.trackedBar, ldem.Parameters().trackedBar); + end + + function converterOptionsAreApplied(testCase) + dataFile = fullfile(testCase.RepoRoot, "examples", "example1_clamped_beam", "DATA0.DAT"); + field = fullfile(testCase.Folder, "field.txt"); + path = fullfile(testCase.Folder, "conv.ldem"); + ldem.io.convertLegacyInput(dataFile, path, RandomFieldFile = field, TrackedBar = 14398, ... + Title = "Beam", Authors = "Rodrigo", OutputFolder = "out"); + c = ldem.io.readCase(path); + testCase.verifyEqual(c.params.trackedBar, 14398); + testCase.verifyEqual(c.params.output.trackedBarEvery, 1); + testCase.verifyEqual(string(c.params.randomFieldFile), string(fullfile(testCase.Folder, "field.txt"))); + testCase.verifyEqual(c.info.title, "Beam"); + testCase.verifyEqual(c.info.authors, "Rodrigo"); + end + + function aScenarioOutsideTheRegistryIsRefused(testCase) + testCase.verifyError(@() ldem.io.writeCase("", ldem.Parameters(), TestWriteCase.unregistered()), ... + 'ldem:io:unregisteredScenario'); + end + end + + methods (Access = private) + function s = normalizePaths(~, s) + % The random-field path may differ in separators (\ or /) and in .. + s.randomFieldFile = string(java.io.File(char(s.randomFieldFile)).getCanonicalPath()); + end + + function c = readBack(testCase, text, name) + path = fullfile(testCase.Folder, name); + writeTextFile(path, splitlines(string(text))); + c = ldem.io.readCase(path); + end + end + + methods (Static, Access = private) + function s = unregistered() + s = TestUnregisteredScenario(); + end + end +end