pycba.analysis.BeamAnalysis#

class BeamAnalysis(L, EI, R=None, LM=None, eletype=None, D=None, supports=None, GAv=None, kf=None)[source]#

Bases: object

Direct-stiffness continuous beam analyser.

Assembles the global stiffness matrix from individual span stiffness matrices, applies support boundary conditions (including elastic springs and prescribed displacements), solves the linear system for nodal displacements, and recovers support reactions and distributed load effects along each member.

After calling analyze(), results are available through beam_results:

  • beam_results.R — reactions at fully-fixed DOFs.

  • beam_results.Rs — spring forces k_s × u_i at spring DOFs.

  • beam_results.D — global nodal displacement vector.

  • beam_results.results — concatenated member load-effect arrays (x, M, V, D, R).

Construct a beam analysis object.

Parameters:
  • L (ndarray) – Span lengths. Length N for an N-span beam.

  • EI (Union[float, ndarray]) – Flexural rigidity of each span. A single scalar (or a single SectionEI) is applied to all spans; otherwise one entry per span is required. A span whose rigidity is given as a SectionEI is treated as non-prismatic (variable EI) and analysed by flexibility integration; scalar entries use the closed-form prismatic element.

  • R (Optional[ndarray]) –

    Nodal restraint vector, length 2(N+1). Two entries per node (vertical DOF then rotational DOF), ordered left to right:

    • -1 — fully restrained (zero displacement unless overridden by D).

    • 0 — free.

    • +k — elastic spring stiffness in consistent units.

    Provide either R or the friendlier supports, not both.

  • LM (Optional[List[List[Union[int, float]]]]) –

    Load matrix: a list of load descriptors. The number of columns per entry depends on the load type:

    1. UDL — [span, 1, w].

    2. Point load — [span, 2, P, a].

    3. Partial UDL — [span, 3, w, a, c].

    4. Moment load — [span, 4, M, a].

    5. Trapezoidal — [span, 5, w1, w2] (full span) or [span, 5, w1, w2, a, c] (partial).

    6. Imposed curvature — [span, 6, k0, k1, ...] where the free curvature field is κ(x) = k0 + k1·x + (e.g. creep, shrinkage or thermal curvature).

  • eletype (Optional[ndarray]) –

    Element type for each span, controlling which end(s) carry moment. Each entry may be an integer code, a MemberType, or its name string (e.g. "FP"):

    1. FF Fixed–fixed (default).

    2. FP Fixed–pinned (moment release at right end).

    3. PF Pinned–fixed (moment release at left end).

    4. PP Pinned–pinned (moment releases at both ends).

    At an internal hinge, only one of the two members meeting at that node should have a pinned end.

  • D (Optional[list]) – Prescribed-displacement vector, length 2(N+1) (same as R). Use None for DOFs whose displacement is unknown (the default). Provide a float for DOFs with a known displacement (e.g. a support settlement — negative = downward). Fixed supports (R = -1) default to zero displacement unless D provides an explicit override.

  • supports (Optional[Sequence]) –

    A friendlier alternative to R: one entry per node (left to right), each a support name or a raw [vertical, rotation] DOF pair. Recognised names (case-insensitive):

    • "p" / "pin" / "pinned" and "r" / "roller" — vertical held, rotation free.

    • "e" / "encastre" / "fixed" / "clamped" — fully fixed.

    • "f" / "free" — unrestrained (e.g. a cantilever tip).

    Elastic springs are given as a raw pair, e.g. [5e4, 0] for a vertical spring. Lowered to R via supports_to_R(); mutually exclusive with R.

  • GAv (Union[float, SectionEI, Sequence, None]) – Transverse shear rigidity G·A_v of each span. A span given a finite GAv is analysed as a shear-deformable Timoshenko element; None (the default) keeps the exact Euler–Bernoulli element. Broadcasts like EI: a single scalar (or one SectionEI for a variable GAv(x)) applies to all spans, otherwise one entry per span.

  • kf (Union[float, Sequence, None]) – Winkler foundation modulus (modulus of subgrade reaction per unit beam length). A span with a finite kf rests on an elastic (Winkler) foundation, modelled as a statically-condensed beam-on-elastic-foundation super-element. Like EI: a scalar applies to all spans, otherwise one entry per span (each None or a modulus). Supported for prismatic, fixed-fixed spans without GAv, carrying UDL / point / partial-UDL loads.

Raises:

ValueError – If both R and supports (or neither) are given, R and D have different lengths, or EI is not scalar and its length differs from len(L).

Methods

add_ic

Append an imposed-curvature (initial-strain) member load.

add_ml

Append a concentrated moment load.

add_pl

Append a point load.

add_pudl

Append a partial uniformly-distributed load.

add_trap

Append a trapezoidal (linearly varying) distributed load.

add_udl

Append a full-span uniformly-distributed load.

analyze

Execute the direct-stiffness analysis.

at

Interpolate the load effects at a global coordinate x (convenience for pycba.results.BeamResults.at()).

is_stable

Return whether the structure is stable (not a mechanism).

modal

Free-vibration (modal) analysis: natural frequencies and mode shapes.

plot_beam

Draw a structural schematic of the beam.

plot_bmd

Plot the bending-moment diagram.

plot_dsd

Plot the deflected-shape diagram.

plot_reactions

Draw the support reactions as labelled arrows on the beam schematic.

plot_results

Plot bending moment, shear force, and deflection diagrams.

plot_sfd

Plot the shear-force diagram.

set_loads

Replace the current load matrix with a new one.

to_csv

Write the member load effects to a CSV file; convenience for pycba.results.BeamResults.to_csv().

to_dataframe

Member load effects as a pandas.DataFrame (x, M, V, R, D); convenience for pycba.results.BeamResults.to_dataframe().

Attributes

beam

The underlying Beam object.

beam_results

Post-analysis results object.

property beam_results: BeamResults#

Post-analysis results object.

None until analyze() has been called successfully. Provides nodal displacements (D), reactions at fixed supports (R), spring forces (Rs), and per-member load-effect arrays (vRes, results).

Type:

BeamResults

at(x, attrs=('M', 'V', 'R', 'D'))[source]#

Interpolate the load effects at a global coordinate x (convenience for pycba.results.BeamResults.at()). Returns a dict, or None with a message if analyze() has not been run.

to_dataframe()[source]#

Member load effects as a pandas.DataFrame (x, M, V, R, D); convenience for pycba.results.BeamResults.to_dataframe().

to_csv(path, **kwargs)[source]#

Write the member load effects to a CSV file; convenience for pycba.results.BeamResults.to_csv(). Returns path (or None if the analysis has not been run).

property beam: Beam#

The underlying Beam object.

Provides direct access to span geometry, stiffness matrices, restraints, and prescribed displacements.

Type:

Beam

set_loads(LM)[source]#

Replace the current load matrix with a new one.

Any loads previously added via add_udl(), add_pl(), add_pudl(), or add_ml() are discarded.

Parameters:

LM (List[List[Union[int, float]]]) – New load matrix in the same format as the LM argument of __init__().

add_udl(i_member, w)[source]#

Append a full-span uniformly-distributed load.

Parameters:
  • i_member (int) – 1-based member index.

  • w (float) – Load intensity. Positive values act downward.

add_pl(i_member, p, a)[source]#

Append a point load.

Parameters:
  • i_member (int) – 1-based member index.

  • p (float) – Load magnitude. Positive values act downward.

  • a (float) – Distance from the left end of the span to the load.

add_pudl(i_member, w, a, c)[source]#

Append a partial uniformly-distributed load.

Any portion of the load that extends beyond the end of the span is silently ignored.

Parameters:
  • i_member (int) – 1-based member index.

  • w (float) – Load intensity. Positive values act downward.

  • a (float) – Distance from the left end of the span to the start of the load.

  • c (float) – Length (cover) of the partial UDL.

add_ml(i_member, m, a)[source]#

Append a concentrated moment load.

Parameters:
  • i_member (int) – 1-based member index.

  • m (float) – Moment magnitude. Positive values are counter-clockwise.

  • a (float) – Distance from the left end of the span to the load.

add_ic(i_member, kappa)[source]#

Append an imposed-curvature (initial-strain) member load.

The free curvature field κ(x) = k0 + k1·x + k2·x² + is imposed over the member. On a simply-supported span it produces no internal forces (only a free deflected shape); on a restrained or continuous structure its restraint generates real moments and reactions. This is the mechanism for applying creep, shrinkage and thermal curvatures to a continuous beam (see pycba.load.LoadIC).

Parameters:
  • i_member (int) – 1-based member index.

  • kappa (float or array_like of float) – Imposed-curvature polynomial coefficients in increasing powers of x: [k0, k1, k2, ...]. A scalar is a uniform curvature.

add_trap(i_member, w1, w2, a=None, c=None)[source]#

Append a trapezoidal (linearly varying) distributed load.

When a and c are omitted the load covers the full span, varying from w1 at the left end to w2 at the right end. When a and c are given the load covers the region from a to a + c, varying from w1 to w2 over that length.

Parameters:
  • i_member (int) – 1-based member index.

  • w1 (float) – Load intensity at the start of the load. Positive values act downward.

  • w2 (float) – Load intensity at the end of the load. Positive values act downward.

  • a (Optional[float]) – Distance from the left end of the span to the start of the load. If given, c must also be provided.

  • c (Optional[float]) – Length (cover) of the load. Required when a is provided.

analyze(npts=None, check_stability=True)[source]#

Execute the direct-stiffness analysis.

Assembles the unrestricted global stiffness matrix, validates the model, applies boundary conditions (including spring supports and prescribed displacements), solves for nodal displacements, and recovers support reactions. Results are stored in beam_results.

Parameters:
  • npts (Optional[int]) – Number of evaluation points along each member for computing distributed load effects (bending moment, shear, deflection). Must be greater than 3; defaults to 100 if omitted or 3.

  • check_stability (bool) – If True (default), check the assembled stiffness for a mechanism before solving and raise a clear error (see is_stable() / _check_stability()). Set False to skip the check for an unusual but intentionally near-singular model. The check runs at most once per structure: its result is cached and only re-evaluated if the beam structure changes, so it adds no cost to looped analyses (e.g. a moving load) that vary only the loads.

Returns:

0 on successful completion.

Return type:

int

Raises:

ValueError – If the model is invalid (see _validate()) or if the structure is geometrically unstable (see _check_stability() and _solver()).

modal(mass, n_modes=10, nseg=12)[source]#

Free-vibration (modal) analysis: natural frequencies and mode shapes.

Assembles a consistent mass matrix alongside the stiffness matrix on a refined mesh (each span split into nseg Euler-Bernoulli sub-elements) and solves the generalized eigenproblem K φ = ω² M φ. Supports, including elastic springs, are applied at the original span nodes; the analysis is independent of any applied loads.

Parameters:
  • mass (float or array_like) – Mass per unit length, a scalar for every span or one value per span (consistent units, e.g. kg/m if EI is in N·m²).

  • n_modes (int) – Number of lowest modes to return. The default is 10.

  • nseg (int) – Sub-elements per span for the refined mesh. The default is 12.

Returns:

The natural frequencies (omega rad/s, f Hz) and mode shapes.

Return type:

pycba.modal.ModalResults

Notes

Supported for prismatic, fixed-fixed spans without shear flexibility (GAv); other combinations raise a clear NotImplementedError.

is_stable()[source]#

Return whether the structure is stable (not a mechanism).

Runs the same free-DOF stability check as analyze() but returns a boolean instead of raising, so the model can be validated up front without solving. A True result is cached (keyed on the beam’s structure_version), so a subsequent analyze() does not repeat the check unless the structure changes.

Returns:

True if the free-DOF stiffness partition is non-singular to within _STABILITY_RCOND, otherwise False.

Return type:

bool

plot_beam(loads=None, *, tikz=None, ax=None, save=None, compile=False, load_cases=None, **kwargs)[source]#

Draw a structural schematic of the beam.

Convenience wrapper around pycba.beam.Beam.plot() so the model can be drawn directly from the analysis object (mirroring plot_results()) without reaching through beam. Renders with matplotlib by default; saving to a .tex path (or passing tikz=True) produces TikZ/stanli output instead.

The beam structure (geometry, supports, internal hinges) is always drawn; the loads layer is optional and its source is selected with loads:

  • None (default) - the beam’s own load matrix.

  • [] - draw the bare structure only.

  • a PyCBA load matrix, a LoadCase, or a LoadCombination (supply its LoadCases via load_cases).

Parameters:
  • loads (list | LoadCase | LoadCombination, optional) – The load source to draw.

  • tikz (bool, optional) – Backend selector. None (default) infers it from save (a .tex target renders TikZ, anything else uses matplotlib); pass True/False to force the backend.

  • ax (matplotlib.axes.Axes, optional) – Axes to draw into (matplotlib backend only); a new figure is created if omitted.

  • save (str or pathlib.Path, optional) – If given, also write the visualisation to this path. A .tex target writes the TikZ source (and selects the TikZ backend); any other extension is saved by matplotlib.

  • compile (bool) – Under the TikZ backend with save set, also run pdflatex to produce a PDF (a .pdf save target enables this automatically).

  • load_cases (pycba.load_cases.LoadCases, optional) – Required only when loads is a LoadCombination.

  • **kwargs – Forwarded to the backend renderer (dimensions, labels, load_values, color for matplotlib; standalone, scale, dimensions, labels, load_values for TikZ). units selects the display unit system (see pycba.set_units()).

Returns:

  • matplotlib.axes.Axes – The axes drawn into (default matplotlib backend).

  • str – The LaTeX source, when tikz=True and save is not given.

  • pathlib.Path – The written file, when tikz=True and save is given.

plot_results(show_beam=True, show=True, units=None, figsize=None, backend=None, show_reactions=True)[source]#

Plot bending moment, shear force, and deflection diagrams.

Produces a figure of bending moment, shear force, and deflection along the beam. Bending moment is plotted with the sagging-positive convention (y-axis inverted so sagging appears below the beam line). By default the loaded-beam schematic is drawn as a top panel sharing the x-axis, so the model and its load effects can be read together.

Parameters:
  • show_beam (bool) – Draw the beam/loading schematic as a top panel above the result diagrams (default True). Set False for the bare three-panel moment/shear/deflection figure.

  • show (bool) – Call matplotlib.pyplot.show() before returning (default True). Set False to obtain the figure handles without displaying — e.g. to savefig or restyle the figure first.

  • units (str or pycba.units.UnitSystem, optional) – Display unit system for the axis labels and the deflection scale (e.g. "SI", "US-ft", "N-mm", "none"). Defaults to the global default (see pycba.set_units()); the analysis itself is unit-agnostic and unaffected.

  • figsize (tuple(float, float), optional) – Figure size in inches. Defaults to 10 wide and ~3 in per subplot row (so the diagrams are not squashed), consistent with the other PyCBA result plots; pass an explicit tuple to override.

  • backend ({"matplotlib", "plotly"}, optional) – Plotting backend; defaults to the global default (see pycba.set_backend()). With "plotly" an interactive, hover-to-read figure of the three diagrams (sharing the x-axis) is returned; the show_beam, show and figsize arguments do not apply.

Returns:

  • matplotlib.figure.Figure – The figure, or None if analyze() has not been called. With backend="plotly" a single plotly.graph_objects.Figure is returned instead of the (figure, axes) pair.

  • numpy.ndarray of matplotlib.axes.Axes – The panel axes (length 4 when show_beam is True, else 3).

Notes

Has no effect and prints a warning if analyze() has not been called yet.

plot_reactions(ax=None, units=None, show=True, figsize=None, color='tab:green')[source]#

Draw the support reactions as labelled arrows on the beam schematic.

Vertical reactions are drawn as straight arrows in the force direction (positive upward) and moment reactions (at fixed / encastre supports) as curved arrows, each annotated with its magnitude; elastic spring-support forces are included. Requires analyze() to have been run.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – Axes to draw into; a new figure is created if omitted.

  • units (str or pycba.units.UnitSystem, optional) – Display unit system (see pycba.set_units()).

  • show (bool) – Call matplotlib.pyplot.show() before returning (default True).

  • figsize (tuple(float, float), optional) – Figure size when a new axes is created.

  • color (str) – Colour for the reaction arrows and labels.

Returns:

None (with a message) if the analysis has not been run.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes) or None

plot_bmd(ax=None, units=None, backend=None, **kwargs)[source]#

Plot the bending-moment diagram.

Uses the sagging-positive convention (the y-axis is inverted so sagging appears below the beam line), matching plot_results(). Pass an existing ax to overlay a second analysis for comparison; the axis is set up only on the first call, so the overlay is not re-inverted.

Parameters:
  • ax (matplotlib.axes.Axes, optional) – Axes to draw into; a new figure is created if omitted.

  • units (str or pycba.units.UnitSystem, optional) – Display unit system (see pycba.set_units()).

  • backend ({"matplotlib", "plotly"}, optional) – Plotting backend; defaults to the global default (see pycba.set_backend()). With "plotly" an interactive figure is returned and ax/**kwargs do not apply.

  • **kwargs – Forwarded to the curve plot (color, ls, lw, label).

Returns:

The axes drawn into (None before analyze()), or a plotly.graph_objects.Figure with backend="plotly".

Return type:

matplotlib.axes.Axes or None

plot_sfd(ax=None, units=None, backend=None, **kwargs)[source]#

Plot the shear-force diagram.

See plot_bmd() for the parameters (overlay via ax, units, backend and matplotlib **kwargs).

Returns:

The axes drawn into (None before analyze()), or a plotly.graph_objects.Figure with backend="plotly".

Return type:

matplotlib.axes.Axes or None

plot_dsd(ax=None, units=None, backend=None, **kwargs)[source]#

Plot the deflected-shape diagram.

See plot_bmd() for the parameters (overlay via ax, units, backend and matplotlib **kwargs).

Returns:

The axes drawn into (None before analyze()), or a plotly.graph_objects.Figure with backend="plotly".

Return type:

matplotlib.axes.Axes or None