Skip to content

Material cards: tensile tests to *MAT_024

Module: crashmetrics.materials (NumPy only).

The goal of this part of the package is the full path from a tensile test to a checked LS-DYNA *MAT_PIECEWISE_LINEAR_PLASTICITY (*MAT_024) card. It is built in steps; available now:

Step Functions Status
1. Read the test (CSV, text, .xlsx; force-elongation or stress-strain) read_tensile, TensileTest ✅
2. Clean the curve (fracture cut, smoothing, toe correction) clean_tensile ✅
3. Tensile properties (E, Rp0.2, Rm, Ag, A) tensile_properties ✅
4. Lüders plateau: ReH, ReL, Ae; flat or removed for the card luders_plateau, smooth_luders ✅
5. Several specimens: mean curve and scatter mean_curve, property_scatter ✅
6. Machine compliance (cross-head strain) correct_compliance ✅
7. True stress-strain true_curve ✅
8. Necking (Considère) necking_point ✅
9. Effective plastic strain from the yield point plastic_curve ✅
10. Extrapolation: Swift, Voce, Hockett-Sherby, Swift-Voce fit_hardening, compare_fits, extrapolate_curve ✅
11. n and K values n_value ✅
13. Cowper-Symonds C and P from tests at several rates fit_cowper_symonds ✅
14. Strain-rate table, written as *DEFINE_TABLE (linear or ln rates, model units) rate_table_from_model, rate_table_from_curves, RateTable.keyword ✅
15. Table checks: crossing curves, rate order, ln-rate form RateTable.check ✅
16. Johnson-Cook rate term fit_johnson_cook_rate ✅
17. *MAT_PIECEWISE_LINEAR_PLASTICITY card Mat024, Mat024.keyword ✅
18. *DEFINE_CURVE / *DEFINE_TABLE in fixed format Mat024.keyword, RateTable.keyword ✅
19. Unit systems mm-ms-kg, mm-s-t, mm-s-kg, m-s-kg unit_system= ✅
20. Simple failure strain (FAIL) with element size failure_strain, fracture_strain ✅
21. Include file with a provenance header Mat024.write ✅
22. Read *MAT_024 cards with their curves and tables from a deck read_keyword, KeywordDeck.material ✅
23. Card checker check_keyword ✅
24. Convert cards to another unit system convert_keyword ✅
25. Compare two cards compare_cards, Mat024.stress ✅
26. Single-element tension test deck and its check single_element_deck, verify_single_element ✅
27. Summary table card_summary, summary_markdown ✅
28. Material library with provenance MaterialLibrary ✅

Failure beyond a single FAIL strain (stress state, element size, *MAT_ADD_DAMAGE_GISSMO) has its own guide: Failure with GISSMO.

Units: stress in MPa, force in N, lengths in mm, strain dimensionless (mm/mm, not %). E is in MPa (210 000 for steel).

Step 1: read the test

from crashmetrics.materials import read_tensile, TensileTest

# Force-elongation from the test machine: give the specimen size.
test = read_tensile("DP-L01.csv", gauge_length=80.0, width=20.0, thickness=1.2)

# Engineering stress-strain already computed; columns by name or index.
test = read_tensile("results.xlsx", sheet="Data", strain="Eng. strain",
                    stress="Eng. stress")

# From arrays.
test = TensileTest.from_force_elongation(force_n, elongation_mm, gauge_length=50.0,
                                         diameter=10.0)
test = TensileTest(strain, stress_mpa, name="DP600-L1")
  • Files: .csv, .txt, .dat with any separator (comma, semicolon, tab, spaces; detected) and decimal points or commas (detected), or Excel .xlsx (values of any sheet). Old .xls: save as .xlsx or CSV.
  • Columns: by header name (case-insensitive, a unique part is enough) or 0-based index. Without names, columns called "stress" and "strain", or "force"/"load" and "elongation"/"extension"/ "displacement", are used.
  • Headers: every text row above the data counts, so a units row under the names works. Units in the header (Force [kN], Strain (%), Stress (GPa)) are converted; otherwise give strain_unit="%", force_unit="kN" and so on.
  • Cross-section: area (mm²), width and thickness (flat specimen) or diameter (round specimen); stress is force over the original area.
  • test.info records the file, sheet, columns and units used.

Step 2: clean the curve

from crashmetrics.materials import clean_tensile

clean = clean_tensile(test, smooth=21)
clean.info["cleaning"]     # cut point, smoothing window, toe shift, points removed

clean_tensile does, in order:

Step What it does Settings
Cut after fracture Ends the curve before the first sudden stress drop after the maximum (more than 10 % of Rm from one point to the next), or where the stress falls below 10 % of Rm cut_fracture=True, fracture_drop=0.1
Smoothing Savitzky-Golay filter (quadratic) on the stress; off by default smooth=21 (odd number of points)
Toe correction Fits the elastic line between 10 and 40 % of Rm, shifts the strain so the line passes through the origin, and replaces the toe points by the origin (as ISO 6892-1) toe=True, modulus_window=(0.1, 0.4) or modulus_stress=(lo, hi) in MPa

Use the smallest smoothing window that removes the noise: it rounds a sharp yield point. For materials with a yield point (Lüders plateau), set modulus_stress below the yield.

Step 3: tensile properties

from crashmetrics.materials import tensile_properties

p = tensile_properties(clean)
p.modulus, p.yield_strength, p.tensile_strength   # MPa
p.uniform_elongation, p.elongation_after_fracture  # Ag, A (plastic, -)
print(p.summary("DP-L01"))
Property Definition (ISO 6892-1)
modulus (E) Least-squares slope between 10 and 40 % of Rm (modulus_window), with its R²
yield_strength (Rp0.2) First crossing of the curve with the elastic line moved by 0.2 % strain (offset=0.002), interpolated
tensile_strength (Rm) Maximum engineering stress
uniform_elongation_total (Agt), uniform_elongation (Ag) Total and plastic strain at Rm (Ag = Agt − Rm / E)
fracture_strain_total (At), elongation_after_fracture (A) Total and plastic strain at the last point (cut the curve at fracture first)

Rm and Ag on noisy data

The engineering curve is flat around Rm, so noise moves the maximum along it: Rm comes out slightly high and Agt can shift by a percent or more. Smooth the curve first (step 2).

Step 4: Lüders plateau (discontinuous yielding)

Mild and some micro-alloyed steels yield with a drop of stress (upper yield strength ReH) and then a plateau (around the lower yield strength ReL) while Lüders bands cross the specimen, before uniform hardening starts. A *MAT_024 element cannot reproduce this, so the plateau is measured and then replaced:

from crashmetrics.materials import luders_plateau, smooth_luders

p = luders_plateau(clean)          # None if the material yields continuously
p.upper_yield, p.lower_yield       # ReH, ReL (MPa)
p.elongation                       # Ae, yield point elongation (-)

card_curve = smooth_luders(clean, mode="remove")   # or mode="flat"
Item Definition
ReH Stress before the first drop of more than drop (1 %) below the running maximum
ReL Lowest stress on the plateau; the transient dip straight after ReH is ignored when the plateau dips again later (ISO 6892-1)
End of plateau From here on the stress stays above ReL × (1 + band), band = 2 %
Ae Strain from ReH to the end of the plateau
smooth_luders mode Result Use
"flat" Spike and oscillations replaced by a line at ReL; the plateau strain stays Keeps the measured strain at a given stress
"remove" Plateau strain taken out; hardening starts at ReL on the elastic line Common for crash cards: the plateau is a band-propagation effect, not a material law for one element

Smooth noisy data only lightly (a short smooth= window) before luders_plateau: smoothing rounds the ReH spike. Noise lowers the measured ReL slightly (it is a minimum).

Step 5: several specimens

Clean every specimen first (toe correction aligns them at the origin), then:

from crashmetrics.materials import mean_curve, property_scatter, scatter_summary

mean = mean_curve(cleaned, points=300)     # common strain grid up to the shortest curve
mean.mean, mean.std, mean.minimum, mean.maximum
card_input = mean.as_test("DP600 mean")    # continue the chain with the mean curve

print(scatter_summary(property_scatter(cleaned)))   # E, Rp, Rm, Ag, A: mean, std, CV
  • The mean is taken at equal strains, linearly interpolated, up to the end of the shortest curve (or strain_max).
  • After necking the strain is local to the neck and differs between specimens; for a card, use the mean up to the uniform elongation and extrapolate from there.
  • property_scatter reports the sample standard deviation and the coefficient of variation; typical CVs for sheet steel are about 1-3 % for Rp and Rm.

Step 6: machine compliance (no extensometer)

Strain from the cross-head travel includes the deflection of the frame, load cell and grips: the elastic slope comes out far too low (often 50-150 GPa for steel), and every strain is too large. With the material's real Young's modulus:

from crashmetrics.materials import correct_compliance

fixed = correct_compliance(test, modulus=210_000.0)   # MPa
fixed.info["compliance"]["measured_modulus"]          # slope before, MPa
fixed.info["compliance_mm_per_n"]                     # machine compliance, mm/N

Every strain is reduced by stress × (1/E_measured − 1/E), which assumes a linear (elastic) machine. Apply it before clean_tensile; strains after necking are local and are not made right by this. Use an extensometer when you can.

Steps 7-11: the hardening curve

*MAT_024 needs true stress against effective plastic strain, from the yield point to large strains (crash elements reach 50-100 % plastic strain), but a tensile test is valid only up to necking. The chain:

from crashmetrics.materials import (
    compare_fits, extrapolate_curve, fit_hardening, n_value, necking_point,
    plastic_curve, true_curve,
)

neck = necking_point(clean)            # at Rm; Considère ratio ~ 1
curve = plastic_curve(clean)           # (eps_p, true stress) from Rp0.2 to necking
fits = fit_hardening(curve)            # Swift, Voce, Hockett-Sherby, Swift-Voce
print(compare_fits(fits, strains=(0.1, 0.3, 0.5, 1.0)))
card_curve = extrapolate_curve(curve, fits["swift_voce"], strain_max=1.0)
nv = n_value(clean)                    # n10-Ag and K

7-9. True stress, necking, plastic strain

Step Formula Notes
True strain and stress eps = ln(1 + e), sigma = s (1 + e) Constant volume, uniform deformation: valid up to necking (true_curve stops there)
Necking Maximum engineering stress, located by a parabola over ±1 % strain Equivalent to Considère, d sigma / d eps = sigma; the Considère ratio of the data is reported as a check
Effective plastic strain eps_p = eps - sigma / E E fitted on the curve, or given

plastic_curve(start=...) chooses where the card curve starts:

start First point Use
"offset" (default) (0, Rp0.2): plastic strain counted from 0.2 % The usual *MAT_024 convention: SIGY = Rp0.2
"zero" Where the plastic strain becomes positive (end of the linear part) Keeps the elastic-plastic transition below Rp0.2

10. Extrapolation beyond necking

Law Equation Large-strain behaviour
Swift K (eps0 + eps_p)^n Keeps hardening (power law): the highest stress at large strain
Voce sigma0 + Q (1 - exp(-beta eps_p)) Saturates: the lowest
Hockett-Sherby sigma_s - (sigma_s - sigma0) exp(-a eps_p^m) Saturates more slowly
Swift-Voce alpha Swift + (1 - alpha) Voce In between; often the best compromise for AHSS

Each law is fitted by least squares (Levenberg-Marquardt, NumPy only) to the measured part, and reported with:

  • RMS error and R² on the measured part: all laws usually fit it well.
  • Considère ratio at necking: (d sigma / d eps) / sigma of the law. A law that reproduces the test necks at the measured strain (ratio 1). Below 1 it hardens too little and a simulation of the tensile test necks too early; above 1, too late.
  • Stress at large strain (compare_fits): the laws agree up to necking and part beyond it. That spread is what the choice decides; without data past necking (DIC, shear or bulge tests, or an inverse simulation of the tensile test) it is an engineering judgement.

extrapolate_curve keeps the measured points up to necking and adds points law points up to strain_max, shifting the law by the small stress difference at necking so the curve has no step. fit_range= restricts the fit (for example from 2 % plastic strain to necking, when the yield region does not follow the law).

11. n and K values

n_value fits ln(true stress) = ln K + n ln(true strain) over an engineering strain range, by default from 10 % to Ag ("n10-Ag"); use strain_range=(0.10, 0.20) for n10-20, and strain="plastic" for the true plastic strain. For certificates, ISO 10275 and ASTM E646 define the exact procedure.

Steps 13-16: strain rate

Crash structures deform at 10-1000 /s, where steels are clearly stronger than in a quasi-static test. *MAT_024 takes the rate effect either as Cowper-Symonds C and P on the card (the whole curve scaled by one factor) or as a rate table: LCSS pointing to a *DEFINE_TABLE with one hardening curve per strain rate.

from crashmetrics.materials import (
    fit_cowper_symonds, fit_johnson_cook_rate, rate_table_from_curves,
    rate_table_from_model,
)

measured = {0.001: curve_qs, 1.0: curve_1, 100.0: curve_100, 500.0: curve_500}
cs = fit_cowper_symonds(measured)          # cs.c (1/s), cs.p
jc = fit_johnson_cook_rate(measured)       # jc.c with rate0 = lowest rate

table = rate_table_from_model(static_extrapolated, cs,
                              [0.001, 0.01, 0.1, 1, 10, 100, 500, 1000])
print(table.check(log_rates=True, unit_system="mm-ms-kg").summary())
text = table.keyword(2000, unit_system="mm-ms-kg", log_rates=True)

13 and 16. Rate laws

Law Factor on the reference curve Card
Cowper-Symonds (1 + (rate/C)^(1/P)) / (1 + (rate_ref/C)^(1/P)) C (1/s; 1/ms in mm-ms-kg) and P on *MAT_024
Johnson-Cook 1 + c ln(rate / rate0), 1 below rate0 A table generated from it
  • The curves (from plastic_curve) are compared at a few plastic strains from the yield point to 90 % of the smallest necking strain, against the lowest-rate curve. The reference test is not static (0.001 /s), and the fit takes that into account.
  • Both laws scale the whole curve by one factor. When the measured rate effect changes with strain (often smaller at large strain), a table from the measured curves represents the tests better.

14. Rate table and *DEFINE_TABLE

Builder Curves
rate_table_from_model(curve, law, rates) The reference curve times the law's factor, at any rates you choose
rate_table_from_curves({rate: curve}) Each test's own (extrapolated) curve

All curves share one plastic strain grid (points, default 50, dense near yield). RateTable.keyword(table_id, unit_system=..., log_rates=...) writes the *DEFINE_TABLE and its *DEFINE_CURVE cards directly after it, as LS-DYNA requires, with:

  • rates converted to the model's time unit (1/s → 1/ms for mm-ms-kg) and stresses to its stress unit (GPa for mm-ms-kg, MPa for mm-s-t; UNIT_SYSTEMS);
  • log_rates=True: the table holds ln(rate). LS-DYNA reads a table as logarithmic when its first value is negative, which check verifies. Logarithmic tables interpolate much better between rates that are decades apart.

15. Table checks

RateTable.check() (also run by keyword, which refuses a table with errors):

Check Why
❌ A curve below the curve of a lower rate at any strain Crossing curves mean negative rate sensitivity: noisy, mesh-dependent results. Typical cause: curves extrapolated with different laws
❌ Rates not strictly increasing LS-DYNA needs ascending table values
❌ Curves not starting at zero plastic strain *MAT_024 convention
❌ ln-rate table whose first value is not negative LS-DYNA would read all values as plain rates
⚠️ Softening along a curve Usually an extrapolation or data problem
⚠️ Rates more than 100× apart in a linear table Linear interpolation in rate between them is poor; use log_rates
⚠️ No quasi-static curve (lowest rate above 0.01 /s) Slow loading would use the lowest curve

Steps 17-21: the *MAT_024 card

from crashmetrics.materials import Mat024, failure_strain, fracture_strain

fail = failure_strain(uniform=curve.necking_strain,
                      fracture=fracture_strain(0.55),     # reduction of area 55 %
                      element_size=2.5, neck_length=1.2)  # mm
mat = Mat024(mid=600, density=7850.0, modulus=210_000.0, curve=card_curve,
             c=40.4, p=5.0, fail=fail, title="DP600 1.2 mm",
             provenance={"tests": "DP600-L1..L3", "hardening": "Swift-Voce"})
mat.write("dp600.k", "mm-ms-kg")               # include file
print(mat.keyword("mm-s-t"))                   # or just the text

Mat024(mid=601, density=7850.0, modulus=210_000.0, table=rate_table, vp=1)

Mat024 takes engineering units: density in kg/m³, modulus and stresses in MPa, C in 1/s. The unit system is chosen only when writing:

unit_system Length, time, mass Stress Density 7850 kg/m³ E 210 GPa C 40.4 /s
"mm-ms-kg" mm, ms, kg GPa 7.85e-6 210.0 0.0404
"mm-s-t" mm, s, t MPa 7.85e-9 210000.0 40.4
"mm-s-kg" mm, s, kg kPa 7.85e-6 2.1e8 40.4
"m-s-kg" m, s, kg Pa 7850.0 2.1e11 40.4

What is written:

Field Value
MID, RO, E, PR As given (PR 0.3 by default), converted
SIGY The first stress of the curve (of the lowest-rate curve of a table), so it matches LCSS
ETAN, EPS1-8, ES1-8 0 (the curve is in LCSS)
FAIL, TDEL As given; FAIL 0 means no failure
C, P Cowper-Symonds, converted to the model's time unit; must be 0 with a rate table
LCSS The curve or table ID (default MID + 1000), written right after the card
VP 0 (scale the yield stress with rate, default) or 1 (viscoplastic)
  • A single curve is resampled to points (default 50) plastic strains, denser near yield, keeping the necking point; values are written with 8 significant digits in 20-character fields.
  • write() adds a header ($ comments) naming the material, the crashmetrics version, the date, the unit system and every provenance entry, then *KEYWORD ... *END, so the file can be included as it is and traced later.
  • Mat024 refuses obvious unit mistakes in its input: a density below 1 or above 30 000 (not kg/m³), a modulus outside 100 MPa to 10⁶ MPa.

20. Simple failure strain

FAIL = uniform + (fracture − uniform) × min(1, neck length / element size)

The strain to fracture is reached only in the neck (about one sheet thickness long); an element larger than the neck averages it with the uniformly strained material. fracture_strain(Z) gives the neck strain ln(1 / (1 − Z)) from the reduction of area Z of the broken specimen. This ignores the stress state (triaxiality) and is meant for screening; use a damage model such as GISSMO for failure predictions (Failure with GISSMO; mat.write(..., damage=card) puts the *MAT_ADD_DAMAGE_GISSMO card in the same include).

Steps 22-28: existing cards, verification, library

These work on any *MAT_024 card, also without test data: a supplier's deck, an old project, a colleague's include.

from crashmetrics.materials import (
    MaterialLibrary, card_summary, check_keyword, compare_cards, convert_keyword,
    read_keyword, single_element_deck, verify_single_element,
)

deck = read_keyword("supplier.k")               # *MAT_024 + curves + tables
for result in check_keyword(deck):
    print(result.summary())
print(convert_keyword(deck, "mm-ms-kg"))        # same cards, other units

supplier = deck.material(101)                   # Mat024 in kg/m³, MPa, 1/s
print(compare_cards(supplier, ours).summary())

Path("one_element.k").write_text(single_element_deck(ours, "mm-ms-kg"))
# ... run LS-DYNA in that folder ...
print(verify_single_element("run_dir", ours, "mm-ms-kg").summary())

lib = MaterialLibrary("materials")
lib.save(ours, "dp600")                          # JSON with provenance
lib.export("dp600", "dp600.k", "mm-s-t")

22. Reading

read_keyword reads *MAT_PIECEWISE_LINEAR_PLASTICITY / *MAT_024 (with _TITLE), every *DEFINE_CURVE (SFA, SFO, OFFA, OFFO applied) and *DEFINE_TABLE (the curves right after it belong to it). Fixed 10/20 character fields, long format (*KEYWORD LONG=Y or +) and comma-separated lines are understood; &parameters are recorded but not evaluated; *INCLUDE files are not followed (listed in deck.notes). deck.material(mid) turns a card into a Mat024 in engineering units, with the unit system guessed from density and E (guess_unit_system).

23. Checks

Check Level
Density and E of different unit systems (7.85e-6 with 210000, the classic copy-paste mistake), or not of the given one ❌
Poisson's ratio outside 0-0.5; LCSS not in the deck; no hardening at all ❌
Curve not starting at zero plastic strain; strain not increasing; zero or negative stress ❌
Hardening slope above E anywhere (unstable) ❌
Rate table values not increasing, curves missing, curves crossing ❌
SIGY not matching the curve's first stress ⚠️
Softening ⚠️
Curve detail lost when LS-DYNA re-samples it at LCINT (default 100) equal intervals ⚠️
Curve ending below 50 % plastic strain (LS-DYNA extrapolates the last segment) ⚠️
C and P together with a rate table; table rates implausible for the time unit; &parameters ⚠️

The LCINT check matters for long curves: a curve to 100 % plastic strain re-sampled at 100 equal intervals has its first point after the yield point at 1 %, so the bend between yield and 1 % strain is lost.

24 and 25. Conversion and comparison

convert_keyword(deck, "mm-ms-kg") rewrites the cards with their original points, IDs and titles in the new unit system (density, E, stresses, C, TDEL and table rates converted). compare_cards(a, b) lists density, E, PR, SIGY, C, P, FAIL and the stress at chosen plastic strains and rates, with the difference in %. Mat024.stress(strain, rate) gives the stress a card produces, with Cowper-Symonds scaling or table interpolation in ln(rate) and linear extrapolation beyond the last point.

26. Single-element verification

single_element_deck(mat, unit_system, size=1.0, strain=0.5, rate=1.0) writes a complete model: one fully integrated solid (ELFORM 2), a cube pulled in z at a constant nominal rate with a smooth start, symmetry constraints so the lateral faces are free (uniaxial stress), output spcforc, nodout, glstat and d3plot. The card is written without C and P unless rate_effect=True. After the run, verify_single_element(run_dir, mat, unit_system) reads the z reaction force and the top displacement, converts them to true stress against plastic strain, and compares with the card: within 2 % passes. A difference shows what the solver does with the card (re-discretisation, extrapolation, rate scaling, units).

27 and 28. Summary and library

card_summary(cards) gives one row per card (density, E, SIGY, stress at chosen strains, rate model, FAIL, provenance); summary_markdown makes a table of it. MaterialLibrary(folder) stores each card as a JSON file in engineering units with its curve or table, provenance, a note, the date and the crashmetrics version; load, names, info, summary and export (to a .k in any unit system) work on it. The files are plain JSON, so they can be compared and kept in version control.

Complete example

A semicolon-separated machine export with decimal commas, force in kN, a seating toe, noise and fracture, compared with the exact values of the synthetic steel:

"""Example 23: read, clean and evaluate a tensile test (first step to *MAT_024).

A tensile test of a dual-phase steel sheet as a test machine exports it:
a semicolon-separated CSV with decimal commas, force in kN and
extensometer elongation in mm, with a seating toe at the start, noise,
and the fracture at the end. The data is synthetic (Swift hardening,
E = 210 GPa) so the result can be checked.

1. Read the file (columns found by name, units from the header).
2. Clean the curve: cut after fracture, smooth, toe correction.
3. Tensile properties: E, Rp0.2, Rm, Ag, A.
"""

from pathlib import Path

import numpy as np

from crashmetrics.materials import clean_tensile, read_tensile, tensile_properties

# --- A machine export (synthetic) ------------------------------------------------
E, K, EPS0, N = 210_000.0, 1000.0, 0.004, 0.17      # MPa, MPa, -, -
WIDTH, THICKNESS, GAUGE = 20.0, 1.2, 80.0          # mm

sig_y = K * EPS0 ** N
sig = np.concatenate((np.linspace(0.0, sig_y, 80, endpoint=False),
                      K * (EPS0 + np.linspace(0.0, 0.25, 1500)) ** N))
eps_p = np.concatenate((np.zeros(80), np.linspace(0.0, 0.25, 1500)))
eps_true = sig / E + eps_p
strain = np.expm1(eps_true)
stress = sig * np.exp(-eps_true)
strain = np.concatenate((strain, strain[-1] + [2e-4, 4e-4]))   # fracture
stress = np.concatenate((stress, [150.0, 5.0]))
strain = strain + 0.0025 + 0.0015 * np.clip(1 - stress / 50.0, 0, 1) ** 2  # toe
stress = stress + np.random.default_rng(23).normal(0.0, 3.0, len(stress))  # noise

force_kn = stress * WIDTH * THICKNESS / 1000.0
elongation = strain * GAUGE
lines = ["Specimen;DP-L01", "Time;Force;Elongation", "s;kN;mm"]
lines += [f"{i * 0.02:.2f};{f:.5f};{d:.5f}".replace(".", ",")
          for i, (f, d) in enumerate(zip(force_kn, elongation))]
Path("DP-L01.csv").write_text("\n".join(lines) + "\n", encoding="cp1252")

# --- 1. Read ------------------------------------------------------------------
test = read_tensile("DP-L01.csv", gauge_length=GAUGE, width=WIDTH,
                    thickness=THICKNESS)
print(f"Read {len(test)} points of {test.name}: columns {test.info['columns']}, "
      f"units {test.info['units']}")

# --- 2. Clean -------------------------------------------------------------------
clean = clean_tensile(test, smooth=21)
log = clean.info["cleaning"]
print(f"Cut after fracture at {log['cut_after_strain'] * 100:.2f} % strain "
      f"({log['points_cut']} points), smoothed over {log['smoothing_window']} "
      f"points, toe: strain shifted by {log['toe_strain_shift'] * 100:.3f} % and "
      f"{log['toe_points_removed']} points replaced by the origin")

# --- 3. Properties ------------------------------------------------------------
raw = tensile_properties(test)
props = tensile_properties(clean)
print()
print(props.summary(clean.name))

# --- Check against the exact values of the synthetic steel -----------------------
ep = np.linspace(0.0, 0.25, 500_001)
s_true = K * (EPS0 + ep) ** N
e_true = s_true / E + ep
s_eng, e_eng = s_true * np.exp(-e_true), np.expm1(e_true)
peak = int(np.argmax(s_eng))
rp = s_eng[np.flatnonzero(s_eng - E * (e_eng - 0.002) <= 0)[0]]
print()
print("              exact     raw   cleaned")
print(f"Rp0.2 MPa   {rp:7.1f} {raw.yield_strength:7.1f} {props.yield_strength:9.1f}")
print(f"Rm MPa      {s_eng[peak]:7.1f} {raw.tensile_strength:7.1f} "
      f"{props.tensile_strength:9.1f}")
print(f"Agt %       {e_eng[peak] * 100:7.2f} {raw.uniform_elongation_total * 100:7.2f} "
      f"{props.uniform_elongation_total * 100:9.2f}")
print("Raw: the toe adds strain and the noise moves the maximum on the flat top;")
print("the cleaned curve gives the material's values.")

Output:

Read 1582 points of DP-L01: columns {'force': 'DP-L01 Force kN', 'elongation': 'Elongation mm'}, units {'force': 'kN', 'elongation': 'mm'}
Cut after fracture at 29.14 % strain (2 points), smoothed over 21 points, toe: strain shifted by 0.250 % and 13 points replaced by the origin

Tensile properties of DP-L01
  E           209.7 GPa   (R² 0.9999)
  Rp0.2       416.7 MPa
  Rm          627.2 MPa   (Rp/Rm 0.664)
  Ag          18.35 %     (Agt 18.65 %)
  A           28.59 %     (At 28.89 %)

              exact     raw   cleaned
Rp0.2 MPa     417.2   413.5     416.7
Rm MPa        624.5   635.1     627.2
Agt %         18.40   20.64     18.65
Raw: the toe adds strain and the noise moves the maximum on the flat top;
the cleaned curve gives the material's values.

Three mild-steel specimens with Lüders plateaus, one measured with the cross-head: compliance correction, ReH / ReL / Ae, the plateau replaced, the mean curve and the scatter:

"""Example 24: several specimens, Lüders plateau and machine compliance.

Three tensile specimens of a mild steel sheet (synthetic data, 1 MPa
noise), each with a Lüders plateau. Specimen 3 was tested without an
extensometer: its strain comes from the cross-head, so it includes the
machine compliance.

1. Correct the compliance of specimen 3 with E = 210 GPa.
2. Clean all three; find ReH, ReL and the yield point elongation Ae.
3. Replace the plateau for a *MAT_024 card (flat at ReL, or removed).
4. Mean curve of the three and the scatter of their properties.
"""

import numpy as np

from crashmetrics.materials import (
    TensileTest,
    clean_tensile,
    correct_compliance,
    luders_plateau,
    mean_curve,
    property_scatter,
    scatter_summary,
    smooth_luders,
)

E = 210_000.0                                      # MPa
rng = np.random.default_rng(24)


def mild_steel(name, reh, rel, ae_end, k, seed_shift):
    """Elastic to ReH, dip, plateau oscillating 0-6 MPa above ReL to ae_end,
    then hardening up to fracture."""
    e_el = np.linspace(0.0, reh / E, 60)
    e_pl = np.linspace(reh / E + 1e-5, ae_end, 300)
    phase = (e_pl - e_pl[0]) / (ae_end - e_pl[0])
    s_pl = rel + 3.0 + 3.0 * np.cos(2 * np.pi * (7 + seed_shift) * phase)
    s_pl[:12] = np.linspace(rel - 8.0, rel + 6.0, 12)              # transient dip
    e_h = np.linspace(ae_end + 1e-4, 0.32, 500)
    x = e_h - ae_end
    s_h = rel + 6.0 + k * x ** 0.55 * np.exp(-1.7 * x)
    strain = np.concatenate((e_el, e_pl, e_h, [0.3201, 0.3202]))
    stress = np.concatenate((e_el * E, s_pl, s_h, [60.0, 4.0]))   # fracture
    return TensileTest(strain, stress + rng.normal(0.0, 1.0, len(stress)), name)


specimens = [mild_steel("MS-1", 318.0, 289.0, 0.024, 690.0, 0),
             mild_steel("MS-2", 324.0, 292.0, 0.027, 700.0, 1),
             mild_steel("MS-3", 321.0, 290.0, 0.025, 680.0, 2)]

# --- 1. Machine compliance of specimen 3 (cross-head strain) -------------------
crosshead = 1 / 95_000.0 - 1 / E                    # extra strain per MPa
ms3 = specimens[2]
specimens[2] = TensileTest(ms3.strain + ms3.stress * crosshead, ms3.stress,
                           "MS-3", {"area_mm2": 25.0, "gauge_length_mm": 80.0})
fixed = correct_compliance(specimens[2], modulus=E)
c = fixed.info["compliance"]
print(f"MS-3 cross-head strain: measured E {c['measured_modulus'] / 1000:.1f} GPa; "
      f"machine compliance {fixed.info['compliance_mm_per_n'] * 1e6:.2f} µm/N "
      "removed")
specimens[2] = fixed

# --- 2. Clean and find the Lüders plateau ---------------------------------------
clean = [clean_tensile(t) for t in specimens]
print()
print("Specimen   ReH    ReL    Ae")
for t in clean:
    p = luders_plateau(t)
    assert p is not None
    print(f"{t.name:8} {p.upper_yield:6.1f} {p.lower_yield:6.1f} "
          f"{p.elongation * 100:5.2f} %")

# --- 3. Plateau replaced for a material card -------------------------------------
flat = smooth_luders(clean[0], mode="flat")
removed = smooth_luders(clean[0], mode="remove")
print()
print(f"MS-1 for a card: flat at ReL {flat.info['luders']['lower_yield']:.1f} MPa, "
      f"or plateau removed ({removed.info['luders']['strain_removed'] * 100:.2f} % "
      "strain taken out)")

# --- 4. Mean curve and scatter ----------------------------------------------------
cards = [smooth_luders(t, mode="remove") for t in clean]
mean = mean_curve(cards, points=200)
print()
print(f"Mean of {mean.count} specimens up to {mean.strain[-1] * 100:.1f} % strain")
for target in (0.01, 0.05, 0.15, 0.25):
    i = int(np.argmin(np.abs(mean.strain - target)))
    print(f"  strain {mean.strain[i] * 100:5.1f} %: {mean.mean[i]:6.1f} MPa "
          f"± {mean.std[i]:4.1f} (min {mean.minimum[i]:6.1f}, max "
          f"{mean.maximum[i]:6.1f})")
print()
print("Scatter of the tensile properties (curves with the plateau removed):")
print(scatter_summary(property_scatter(cards)))

Output:

MS-3 cross-head strain: measured E 94.8 GPa; machine compliance 18.52 µm/N removed

Specimen   ReH    ReL    Ae
MS-1      317.2  286.2  2.18 %
MS-2      325.4  290.2  2.50 %
MS-3      321.2  287.3  2.28 %

MS-1 for a card: flat at ReL 286.2 MPa, or plateau removed (2.19 % strain taken out)

Mean of 3 specimens up to 29.5 % strain
  strain   1.0 %:  345.7 MPa ±  3.0 (min  342.8, max  348.9)
  strain   5.0 %:  416.3 MPa ±  3.1 (min  413.6, max  419.6)
  strain  15.0 %:  484.5 MPa ±  3.7 (min  481.3, max  488.5)
  strain  25.0 %:  507.0 MPa ±  3.0 (min  504.2, max  510.2)

Scatter of the tensile properties (curves with the plateau removed):
           mean      std      CV       min       max
E        209.90     0.11   0.05%    209.77    209.97  GPa
Rp       315.37     3.69   1.17%    312.49    319.53  MPa
Rm       511.32     4.42   0.86%    507.68    516.24  MPa
Ag        28.89     0.16   0.57%     28.71     29.03  %
A         29.42     0.17   0.57%     29.23     29.56  %

From a noisy DP steel test to the card curve, with the four laws compared against the known "true" hardening of the synthetic material:

"""Example 25: from a tensile test to the extrapolated *MAT_024 hardening curve.

A dual-phase steel tensile test (synthetic, with noise): the true
hardening of this "material" is a Swift-Voce mix, so it is known at
every strain and the extrapolation can be judged.

1. Clean the test; true stress-strain; necking (Considère).
2. Effective plastic strain from Rp0.2 to necking: the measured part.
3. Fit Swift, Voce, Hockett-Sherby and Swift-Voce; compare them beyond
   necking, where the test gives no data.
4. Extrapolate with the chosen law to 100 % plastic strain.
5. n and K values.
"""

import numpy as np

from crashmetrics.materials import (
    TensileTest,
    clean_tensile,
    compare_fits,
    extrapolate_curve,
    fit_hardening,
    n_value,
    necking_point,
    plastic_curve,
)

E = 210_000.0


def truth(p):
    """True stress (MPa) of the synthetic DP steel at plastic strain p."""
    swift = 1050.0 * (0.004 + p) ** 0.19
    voce = 420.0 + 330.0 * (1.0 - np.exp(-14.0 * p))
    return 0.6 * swift + 0.4 * voce


p = np.linspace(0.0, 0.2, 1500)
sig = np.concatenate((np.linspace(0.0, truth(0.0), 70, endpoint=False), truth(p)))
eps = sig / E + np.concatenate((np.zeros(70), p))
strain, stress = np.expm1(eps), sig * np.exp(-eps)
strain = np.concatenate((strain, strain[-1] + [2e-4, 4e-4]))          # fracture
stress = np.concatenate((stress, [200.0, 5.0]))
stress = stress + np.random.default_rng(25).normal(0.0, 1.5, len(stress))
test = clean_tensile(TensileTest(strain, stress, "DP-T1"), smooth=15)

# --- 1. Necking ---------------------------------------------------------------
neck = necking_point(test)
print(f"Necking: engineering strain {neck.engineering_strain * 100:.2f} %, "
      f"Rm {neck.engineering_stress:.1f} MPa; true strain "
      f"{neck.true_strain:.4f}, true stress {neck.true_stress:.1f} MPa "
      f"(Considère ratio {neck.considere_ratio:.2f})")

# --- 2. Measured plastic curve ----------------------------------------------------
curve = plastic_curve(test)                  # starts at Rp0.2, plastic strain 0
print(f"Plastic curve: {len(curve.plastic_strain)} points, yield (SIGY) "
      f"{curve.yield_stress:.1f} MPa, measured up to plastic strain "
      f"{curve.necking_strain:.4f}, E {curve.modulus / 1000:.1f} GPa")

# --- 3. Hardening laws -----------------------------------------------------------
fits = fit_hardening(curve)
print()
print("Fits to the measured part, and their stress (MPa) at plastic strain:")
print(compare_fits(fits, strains=(0.1, 0.3, 0.5, 1.0)))
exact = [truth(e + 0.002) for e in (0.1, 0.3, 0.5, 1.0)]
print(f"{'truth':15} {'':8} {'':8} {'':9} " + " ".join(f"{v:8.1f}" for v in exact))
for name, f in fits.items():
    print(f"  {name:13} " + ", ".join(f"{k} {v:.4g}" for k, v in f.params.items()))

# --- 4. Extrapolated card curve ----------------------------------------------------
chosen = fits["swift_voce"]
full = extrapolate_curve(curve, chosen, strain_max=1.0, points=30)
print()
print(f"Card curve ({chosen.law}): {len(full.plastic_strain)} points from "
      f"{full.plastic_strain[0]:.1f} to {full.plastic_strain[-1]:.1f} plastic strain")
for e in (0.0, 0.05, 0.15, 0.5, 1.0):
    i = int(np.argmin(np.abs(full.plastic_strain - e)))
    print(f"  eps_p {full.plastic_strain[i]:6.3f}: {full.stress[i]:7.1f} MPa "
          f"(truth {truth(full.plastic_strain[i] + 0.002):7.1f})")

# --- 5. n and K -------------------------------------------------------------------
nv = n_value(test)
print()
print(f"n10-Ag = {nv.n:.3f}, K = {nv.k:.0f} MPa (R² {nv.r2:.4f}, "
      f"{nv.points} points)")

Output:

Necking: engineering strain 18.31 %, Rm 622.0 MPa; true strain 0.1681, true stress 735.9 MPa (Considère ratio 0.97)
Plastic curve: 1221 points, yield (SIGY) 409.7 MPa, measured up to plastic strain 0.1626, E 209.8 GPa

Fits to the measured part, and their stress (MPa) at plastic strain:
law              RMS MPa       R2 Considere     @0.1     @0.3     @0.5       @1
swift               2.08  0.99938     1.131    677.6    830.1    914.5   1043.9
voce                3.80  0.99793     0.640    682.9    758.4    762.8    763.1
hockett_sherby      0.68  0.99993     0.896    679.9    791.2    817.6    829.3
swift_voce          0.58  0.99995     0.923    679.8    798.5    845.6    911.7
truth                                          679.6    801.1    853.4    930.7
  swift         K 1042, eps0 0.007432, n 0.1931
  voce          sigma0 430, Q 333.1, beta 14.24
  hockett_sherby sigma0 404.9, sigma_s 830.4, a 5.919, m 0.7554
  swift_voce    alpha 0.7361, K 994.7, eps0 0.006789, n 0.1374, sigma0 155.6, Q 522.1, beta 12.99

Card curve (swift_voce): 1251 points from 0.0 to 1.0 plastic strain
  eps_p  0.000:   409.7 MPa (truth   410.0)
  eps_p  0.050:   601.1 MPa (truth   600.7)
  eps_p  0.150:   727.6 MPa (truth   726.9)
  eps_p  0.498:   846.9 MPa (truth   852.9)
  eps_p  1.000:   913.5 MPa (truth   930.7)

n10-Ag = 0.172, K = 1001 MPa (R² 0.9983, 544 points)

Tests at four strain rates to Cowper-Symonds, a checked *DEFINE_TABLE, and a table that fails the check because its curves cross:

"""Example 26: strain-rate tests to Cowper-Symonds and a *DEFINE_TABLE.

Tensile tests of one steel at 0.001, 1, 100 and 500 /s (synthetic, 2 MPa
noise; dynamic tests are noisier in practice). The "true" rate effect is
Cowper-Symonds with C = 40.4 /s and P = 5.

1. Each test: clean -> plastic curve -> Swift-Voce fit -> extrapolate.
2. Fit Cowper-Symonds (card fields C, P) and the Johnson-Cook rate term.
3. Rate table from the static curve and the fitted law: check, write.
4. Rate table from separately extrapolated curves, where 100 /s was
   extrapolated with Swift (keeps hardening) and 500 /s with Voce
   (saturates): the check finds where the curves cross.
"""

import numpy as np

from crashmetrics.materials import (
    TensileTest,
    clean_tensile,
    extrapolate_curve,
    fit_cowper_symonds,
    fit_hardening,
    fit_johnson_cook_rate,
    plastic_curve,
    rate_table_from_curves,
    rate_table_from_model,
)

E, C, P = 210_000.0, 40.4, 5.0
rng = np.random.default_rng(26)


def tensile(rate):
    """Engineering curve of the steel at a strain rate (true law: Swift-Voce
    static hardening times the Cowper-Symonds factor)."""
    def law(p):
        static = 0.6 * 1000.0 * (0.005 + p) ** 0.18 + 0.4 * (
            380.0 + 300.0 * (1 - np.exp(-15.0 * p)))
        return static * (1 + (rate / C) ** (1 / P))

    p = np.linspace(0.0, 0.2, 1200)
    sig = np.concatenate((np.linspace(0.0, law(0.0), 60, endpoint=False), law(p)))
    eps = sig / E + np.concatenate((np.zeros(60), p))
    strain, stress = np.expm1(eps), sig * np.exp(-eps)
    stress = stress + rng.normal(0.0, 2.0, len(stress))
    return TensileTest(strain, stress, f"{rate:g}/s")


# --- 1. Each test to an extrapolated curve ------------------------------------------
measured, extrapolated = {}, {}
print("rate /s   SIGY MPa  necking eps_p  Swift-Voce RMS MPa")
for rate in (0.001, 1.0, 100.0, 500.0):
    curve = plastic_curve(clean_tensile(tensile(rate), smooth=15))
    fit = fit_hardening(curve, ["swift_voce"])["swift_voce"]
    measured[rate] = curve
    extrapolated[rate] = extrapolate_curve(curve, fit, strain_max=1.0, points=30)
    print(f"{rate:8g} {curve.yield_stress:10.1f} {curve.necking_strain:14.4f} "
          f"{fit.rms:19.2f}")

# --- 2. Rate laws --------------------------------------------------------------------
cs = fit_cowper_symonds(measured)
jc = fit_johnson_cook_rate(measured)
print()
print(f"Cowper-Symonds: C = {cs.c:.1f} /s ({cs.c / 1000:.4f} /ms), P = {cs.p:.2f} "
      f"(truth 40.4, 5); RMS of the stress ratio {cs.rms:.4f}")
print(f"Johnson-Cook:   c = {jc.c:.4f} with rate0 = {jc.reference_rate:g} /s; "
      f"RMS {jc.rms:.4f}")
print("Dynamic / quasi-static stress:")
for rate in (1.0, 10.0, 100.0, 1000.0):
    print(f"  {rate:6g} /s: Cowper-Symonds {float(cs.ratio(rate)[()]):.3f}, "
          f"Johnson-Cook {float(jc.ratio(rate)[()]):.3f}")

# --- 3. Table from the static curve and the law -------------------------------------
rates = [0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 500.0, 1000.0]
table = rate_table_from_model(extrapolated[0.001], cs, rates, points=40)
check = table.check(log_rates=True, unit_system="mm-ms-kg")
print()
print(f"Table from Cowper-Symonds: {len(table.rates)} rates x "
      f"{len(table.plastic_strain)} points")
print(check.summary())
text = table.keyword(2000, unit_system="mm-ms-kg", log_rates=True,
                     title="steel rate table")
print("\n".join(text.splitlines()[:13]))
print(f"... {len(text.splitlines())} lines")

# --- 4. Table from curves extrapolated with different laws ---------------------------
mixed = dict(extrapolated)
for rate, law in ((100.0, "swift"), (500.0, "voce")):
    fit = fit_hardening(measured[rate], [law])[law]
    mixed[rate] = extrapolate_curve(measured[rate], fit, strain_max=1.0, points=30)
direct = rate_table_from_curves(mixed, points=40)
print()
print("Table from curves extrapolated separately (100 /s Swift, 500 /s Voce):")
print(direct.check(log_rates=True, unit_system="mm-ms-kg").summary())

Output:

rate /s   SIGY MPa  necking eps_p  Swift-Voce RMS MPa
   0.001      450.1         0.1481                0.81
       1      592.5         0.1317                0.74
     100      883.6         0.1449                0.85
     500     1063.4         0.1437                0.82

Cowper-Symonds: C = 40.2 /s (0.0402 /ms), P = 5.01 (truth 40.4, 5); RMS of the stress ratio 0.0020
Johnson-Cook:   c = 0.0887 with rate0 = 0.001 /s; RMS 0.2094
Dynamic / quasi-static stress:
       1 /s: Cowper-Symonds 1.319, Johnson-Cook 1.613
      10 /s: Cowper-Symonds 1.569, Johnson-Cook 1.817
     100 /s: Cowper-Symonds 1.963, Johnson-Cook 2.021
    1000 /s: Cowper-Symonds 2.588, Johnson-Cook 2.225

Table from Cowper-Symonds: 8 rates x 40 points
Rate table check: passed
*DEFINE_TABLE_TITLE
steel rate table
$#    tbid       sfa      offa
      2000       1.0       0.0
$#             value
          -13.815511
          -11.512925
          -9.2103404
          -6.9077553
          -4.6051702
          -2.3025851
         -0.69314718
                   0
... 373 lines

Table from curves extrapolated separately (100 /s Swift, 500 /s Voce):
Rate table check: FAILED
  error: curve at 500 /s is below the curve at 100 /s at plastic strain 0.5199-1 (curves cross)

From the tensile test to the include file, with Cowper-Symonds and a simple failure strain, and the same material with a rate table:

"""Example 27: tensile test to a *MAT_024 include file.

The whole chain for a DP600 sheet (synthetic test data, 1.5 MPa noise):

1. Clean the test, plastic curve from Rp0.2, Swift-Voce extrapolation.
2. Simple failure strain for 2.5 mm shells of 1.2 mm sheet, from the
   reduction of area (screening only; GISSMO is better).
3. Card with Cowper-Symonds C and P, written in mm-ms-kg with a
   provenance header.
4. The same material with a strain-rate table instead, in mm-s-t.
"""

import datetime as dt
from pathlib import Path

import numpy as np

from crashmetrics.materials import (
    CowperSymonds,
    Mat024,
    TensileTest,
    clean_tensile,
    extrapolate_curve,
    failure_strain,
    fit_hardening,
    fracture_strain,
    plastic_curve,
    rate_table_from_model,
    tensile_properties,
)

E = 210_000.0


def truth(p):
    return 0.6 * 980.0 * (0.004 + p) ** 0.17 + 0.4 * (370.0 + 290.0 * (
        1 - np.exp(-16.0 * p)))


p = np.linspace(0.0, 0.2, 1400)
sig = np.concatenate((np.linspace(0.0, truth(0.0), 60, endpoint=False), truth(p)))
eps = sig / E + np.concatenate((np.zeros(60), p))
stress = sig * np.exp(-eps) + np.random.default_rng(27).normal(0.0, 1.5, 1460)
test = clean_tensile(TensileTest(np.expm1(eps), stress, "DP600-L1"), smooth=15)

# --- 1. Hardening curve ------------------------------------------------------------
props = tensile_properties(test)
curve = plastic_curve(test)
fit = fit_hardening(curve, ["swift_voce"])["swift_voce"]
full = extrapolate_curve(curve, fit, strain_max=1.0, points=40)
print(f"Rp0.2 {props.yield_strength:.0f} MPa, Rm {props.tensile_strength:.0f} MPa, "
      f"necking at plastic strain {curve.necking_strain:.3f}; Swift-Voce RMS "
      f"{fit.rms:.2f} MPa")

# --- 2. Failure strain -------------------------------------------------------------
eps_frac = fracture_strain(0.55)                     # reduction of area 55 %
fail = failure_strain(uniform=curve.necking_strain, fracture=eps_frac,
                      element_size=2.5, neck_length=1.2)
print(f"Fracture strain {eps_frac:.3f} in the neck; FAIL for 2.5 mm elements "
      f"{fail:.3f}")

# --- 3. Card with Cowper-Symonds ---------------------------------------------------
mat = Mat024(mid=600, density=7850.0, modulus=E, curve=full, c=40.4, p=5.0,
             fail=fail, title="DP600 1.2 mm",
             provenance={"tests": "DP600-L1, 0.001 /s, rolling direction",
                         "hardening": "measured to necking, Swift-Voce beyond",
                         "rate": "Cowper-Symonds C 40.4 /s, P 5",
                         "failure": "FAIL from Z = 55 %, 2.5 mm shells"})
path = mat.write(Path("dp600_mat024.k"), "mm-ms-kg", points=30,
                 date=dt.date(2026, 11, 2))
lines = path.read_text().splitlines()
print()
# (line 2 of the header names the crashmetrics version, left out here)
print("\n".join([lines[0], *lines[2:22]]))
print("...")
print("\n".join(lines[-3:]))

# --- 4. The same material with a rate table (mm-s-t) -------------------------------
table = rate_table_from_model(full, CowperSymonds(40.4, 5.0, 0.0, 0.0, 0),
                              [0.001, 1.0, 10.0, 100.0, 1000.0], points=30)
tabled = Mat024(mid=601, density=7850.0, modulus=E, table=table, vp=1,
                title="DP600 1.2 mm table")
text = tabled.keyword("mm-s-t")
print()
print("\n".join(text.splitlines()[:21]))
print(f"... {len(text.splitlines())} lines: the card, the table and 5 curves")

Output:

Rp0.2 397 MPa, Rm 586 MPa, necking at plastic strain 0.133; Swift-Voce RMS 0.59 MPa
Fracture strain 0.799 in the neck; FAIL for 2.5 mm elements 0.453

$ DP600 1.2 mm (*MAT_024, MID 600)
$ Units: mm-ms-kg (mm, ms, kg, kN, GPa)
$ tests: DP600-L1, 0.001 /s, rolling direction
$ hardening: measured to necking, Swift-Voce beyond
$ rate: Cowper-Symonds C 40.4 /s, P 5
$ failure: FAIL from Z = 55 %, 2.5 mm shells
*KEYWORD
*MAT_PIECEWISE_LINEAR_PLASTICITY_TITLE
DP600 1.2 mm
$#     mid        ro         e        pr      sigy      etan      fail      tdel
       600   7.85e-6     210.0       0.3 0.3982837       0.0 0.4526455       0.0
$#       c         p      lcss      lcsr        vp
    0.0404       5.0      1600         0       0.0
$#    eps1      eps2      eps3      eps4      eps5      eps6      eps7      eps8
       0.0       0.0       0.0       0.0       0.0       0.0       0.0       0.0
$#     es1       es2       es3       es4       es5       es6       es7       es8
       0.0       0.0       0.0       0.0       0.0       0.0       0.0       0.0
*DEFINE_CURVE_TITLE
DP600 1.2 mm hardening
$#    lcid      sidr       sfa       sfo      offa      offo
      1600         0       1.0       1.0       0.0       0.0
...
          0.80095518           0.8231282
                   1          0.84216204
*END

*MAT_PIECEWISE_LINEAR_PLASTICITY_TITLE
DP600 1.2 mm table
$#     mid        ro         e        pr      sigy      etan      fail      tdel
       601   7.85e-9  210000.0       0.3 446.02739       0.0       0.0       0.0
$#       c         p      lcss      lcsr        vp
       0.0       0.0      1601         0       1.0
$#    eps1      eps2      eps3      eps4      eps5      eps6      eps7      eps8
       0.0       0.0       0.0       0.0       0.0       0.0       0.0       0.0
$#     es1       es2       es3       es4       es5       es6       es7       es8
       0.0       0.0       0.0       0.0       0.0       0.0       0.0       0.0
*DEFINE_TABLE_TITLE
DP600 1.2 mm table rates
$#    tbid       sfa      offa
      1601       1.0       0.0
$#             value
          -6.9077553
                   0
           2.3025851
           4.6051702
           6.9077553
*DEFINE_CURVE_TITLE
... 195 lines: the card, the table and 5 curves

A supplier deck checked, converted, compared with your own card, verified with a single element, and stored in a library:

"""Example 28: check, convert, compare, verify and store *MAT_024 cards.

A supplier sends a deck in mm-s-t with three DP600 cards; one has a unit
mix-up, one a rate table whose curves cross. The steps:

1. Read the cards and check them.
2. Convert the good card to mm-ms-kg.
3. Compare it with our own card.
4. Write a single-element tension test to verify a card in LS-DYNA, and
   compare its result with the card (the LS-DYNA output is replaced here
   by the exact response of the card, as no solver runs in this example).
5. Summary table, and the cards stored in a material library with their
   provenance.
"""

import datetime as dt
from pathlib import Path

import numpy as np

from crashmetrics.materials import (
    HardeningCurve,
    Mat024,
    MaterialLibrary,
    card_summary,
    check_keyword,
    compare_cards,
    compare_tension,
    convert_keyword,
    read_keyword,
    single_element_deck,
    summary_markdown,
)

SUPPLIER = """*KEYWORD
$ Supplier deck, units mm-s-t
*MAT_PIECEWISE_LINEAR_PLASTICITY_TITLE
DP600 supplier
$#     mid        ro         e        pr      sigy      etan      fail      tdel
       101   7.85e-9  210000.0       0.3     380.0       0.0       0.0       0.0
      40.0       5.0       201         0       0.0
       0.0       0.0       0.0       0.0       0.0       0.0       0.0       0.0
       0.0       0.0       0.0       0.0       0.0       0.0       0.0       0.0
*DEFINE_CURVE
201,0,1.0,1.0
0.000,380.0
0.005,440.0
0.020,520.0
0.050,590.0
0.100,650.0
0.200,710.0
0.400,770.0
0.700,820.0
1.000,855.0
*MAT_PIECEWISE_LINEAR_PLASTICITY_TITLE
DP600 copied from an mm-ms-kg deck
       102   7.85e-6  210000.0       0.3     380.0
       0.0       0.0       201         0       0.0
*MAT_PIECEWISE_LINEAR_PLASTICITY_TITLE
DP600 rate table
       103   7.85e-9  210000.0       0.3     380.0
       0.0       0.0       300         0       1.0
*DEFINE_TABLE
300
-6.9
0.0
4.6
*DEFINE_CURVE
301
0.0,380.0
0.2,710.0
1.0,855.0
*DEFINE_CURVE
302
0.0,440.0
0.2,780.0
1.0,920.0
*DEFINE_CURVE
303
0.0,520.0
0.2,850.0
1.0,900.0
*END
"""
Path("supplier.k").write_text(SUPPLIER)

# --- 1. Read and check -------------------------------------------------------------
deck = read_keyword("supplier.k")
print(f"Read {len(deck.materials)} *MAT_024 cards, {len(deck.curves)} curves, "
      f"{len(deck.tables)} table")
for result in check_keyword(deck):
    print(result.summary())

# --- 2. Convert the good card to mm-ms-kg -----------------------------------------
text = convert_keyword(deck, "mm-ms-kg", mids=[101])
print()
print("MID 101 in mm-ms-kg:")
print("\n".join(text.splitlines()[:6]))

# --- 3. Compare with our own card --------------------------------------------------
p = np.concatenate(([0.0], np.geomspace(1e-3, 1.0, 40)))
ours = Mat024(mid=600, density=7850.0, modulus=210_000.0,
              curve=HardeningCurve(p, 0.6 * 980.0 * (0.004 + p) ** 0.17 + 0.4 * (
                  370.0 + 290.0 * (1 - np.exp(-16.0 * p))), 210_000.0, 0.13),
              c=40.4, p=5.0, title="DP600 ours",
              provenance={"tests": "DP600-L1..L3", "hardening": "Swift-Voce"})
supplier = deck.material(101)
print()
print(compare_cards(supplier, ours, strains=(0.0, 0.05, 0.2, 0.5, 1.0),
                    rates=(None, 100.0), names=("supplier", "ours")).summary())

# --- 4. Single-element verification --------------------------------------------------
deck_text = single_element_deck(ours, "mm-ms-kg", strain=0.6, rate=1.0)
Path("single_element.k").write_text(deck_text)
print()
print(f"single_element.k: {len(deck_text.splitlines())} lines; run it, then "
      "verify_single_element(run_dir, ours, 'mm-ms-kg')")
ep = np.linspace(0.0, 0.55, 120)              # stand-in for the LS-DYNA result
sig = ours.stress(ep)
u = np.expm1(ep + sig / ours.modulus)
print(compare_tension(u, sig / (1.0 + u), ours).summary())
print(compare_tension(u, 1.03 * sig / (1.0 + u), ours).summary(),
      "(a 3 % stiffer response)")

# --- 5. Summary and library ----------------------------------------------------------
print()
print(summary_markdown(card_summary([supplier, ours], strains=(0.05, 0.5))))
lib = MaterialLibrary("materials")
lib.save(ours, "dp600_ours", overwrite=True, date=dt.date(2026, 11, 2),
         note="validated in 1-element")
lib.save(supplier, "dp600_supplier", overwrite=True, date=dt.date(2026, 11, 2),
         note="as received")
print()
print(f"Library: {lib.names()}; dp600_ours saved {lib.info('dp600_ours')['saved']}, "
      f"provenance {lib.info('dp600_ours')['provenance']}")
lib.export("dp600_ours", "dp600_ours_mm-s-t.k", "mm-s-t", date=dt.date(2026, 11, 2))
print("Exported dp600_ours in mm-s-t:",
      read_keyword("dp600_ours_mm-s-t.k").materials[600].e, "MPa")

Output:

Read 3 *MAT_024 cards, 4 curves, 1 table
MID 101 (mm-s-t): passed
  warning: curve 201: re-sampled at 100 equal intervals (LCINT) the curve changes by up to 3.8 %; add points near yield, shorten the curve or raise LCINT
MID 102 (unit system unknown): FAILED
  error: RO 7.85e-06 and E 210000 do not belong to one unit system (mm-ms-kg: 7.85e-6 / 210; mm-s-t: 7.85e-9 / 210000)
  warning: curve 201: re-sampled at 100 equal intervals (LCINT) the curve changes by up to 3.8 %; add points near yield, shorten the curve or raise LCINT
MID 103 (mm-s-t): FAILED
  error: table 300: curve 303 below curve 302 at plastic strain 1 (curves cross)

MID 101 in mm-ms-kg:
*MAT_PIECEWISE_LINEAR_PLASTICITY_TITLE
DP600 supplier
$#     mid        ro         e        pr      sigy      etan      fail      tdel
       101   7.85e-6     210.0       0.3      0.38       0.0       0.0       0.0
$#       c         p      lcss      lcsr        vp
      0.04       5.0       201         0       0.0

                                 supplier         ours   diff %
density kg/m3                        7850         7850     0.00
E MPa                             2.1e+05      2.1e+05     0.00
PR                                    0.3          0.3     0.00
SIGY MPa                              380          378    -0.53
C 1/s                                  40         40.4     1.00
P                                       5            5     0.00
FAIL                                    0            0     0.00
stress static @ 0 MPa                 380          378    -0.53
stress static @ 0.05 MPa              590       569.78    -3.43
stress static @ 0.2 MPa               710       707.89    -0.30
stress static @ 0.5 MPa            786.67       787.22     0.07
stress static @ 1 MPa                 855        852.4    -0.30
stress 100/s @ 0 MPa               836.43       831.12    -0.63
stress 100/s @ 0.05 MPa            1298.7       1252.8    -3.53
stress 100/s @ 0.2 MPa             1562.8       1556.5    -0.41
stress 100/s @ 0.5 MPa             1731.6       1730.9    -0.04
stress 100/s @ 1 MPa                 1882       1874.2    -0.41

single_element.k: 112 lines; run it, then verify_single_element(run_dir, ours, 'mm-ms-kg')
Single element: max difference 0.00 %, RMS 0.00 % over plastic strain 0.00462-0.55 -> passed
Single element: max difference 3.10 %, RMS 3.01 % over plastic strain 0.00456-0.55 -> CHECK (a 3 % stiffer response)

| mid | title | density | E_GPa | sigy | stress@0.05 | stress@0.5 | rate | fail |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 101 | DP600 supplier | 7850 | 210 | 380 | 590 | 786.7 | Cowper-Symonds C 40/s P 5 | 0 |
| 600 | DP600 ours | 7850 | 210 | 378 | 569.8 | 787.2 | Cowper-Symonds C 40.4/s P 5 | 0 |

Library: ['dp600_ours', 'dp600_supplier']; dp600_ours saved 2026-11-02, provenance {'tests': 'DP600-L1..L3', 'hardening': 'Swift-Voce'}
Exported dp600_ours in mm-s-t: 210000.0 MPa

References

  • ISO 6892-1:2019. Metallic materials — Tensile testing — Part 1: Method of test at room temperature.
  • H. W. Swift (1952). Plastic instability under plane stress. Journal of the Mechanics and Physics of Solids 1(1), 1-18.
  • E. Voce (1948). The relationship between stress and strain for homogeneous deformation. Journal of the Institute of Metals 74, 537-562.
  • J. E. Hockett, O. D. Sherby (1975). Large strain deformation of polycrystalline metals at low homologous temperatures. Journal of the Mechanics and Physics of Solids 23(2), 87-98.
  • A. Considère (1885). Mémoire sur l'emploi du fer et de l'acier dans les constructions. Annales des Ponts et Chaussées 9, 574-775.
  • G. R. Cowper, P. S. Symonds (1957). Strain-hardening and strain-rate effects in the impact loading of cantilever beams. Technical Report No. 28, Division of Applied Mathematics, Brown University.
  • G. R. Johnson, W. H. Cook (1983). A constitutive model and data for metals subjected to large strains, high strain rates and high temperatures. Proceedings of the 7th International Symposium on Ballistics, The Hague, 541-547.
  • J. H. Hollomon (1945). Tensile deformation. Transactions of AIME 162, 268-290.
  • A. Savitzky, M. J. E. Golay (1964). Smoothing and differentiation of data by simplified least squares procedures. Analytical Chemistry 36(8), 1627-1639.