diff --git a/README.md b/README.md index 16ed14e0..67c330e3 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ Got a question? Please ask on [gitter](https://gitter.im/anaStruct/lobby). * non-linear nodes :heavy_check_mark: * geometrical non linearity :heavy_check_mark: * load cases and load combinations :heavy_check_mark: +* imposed displacements/rotations of supports (settlement) :heavy_check_mark: +* thermal loads (uniform temperature change and temperature gradient) :heavy_check_mark: * generic type of section - rectangle and circle :heavy_check_mark: * EU, US, UK steel section database :heavy_check_mark: diff --git a/anastruct/fem/elements.py b/anastruct/fem/elements.py index b204c418..cb385119 100644 --- a/anastruct/fem/elements.py +++ b/anastruct/fem/elements.py @@ -3,7 +3,7 @@ import copy from functools import lru_cache from math import cos, sin -from typing import TYPE_CHECKING, Dict, List, Literal, Optional +from typing import TYPE_CHECKING, Dict, List, Literal, Optional, Tuple import numpy as np @@ -31,6 +31,15 @@ CACHE_BOUND = 32000 +# A plastic hinge is a rotational spring in series with the element: it starts at this multiple of +# the rotational stiffness 4 EI / l of the element, and an end that is stiffer than the second +# multiple is elastic again +PLASTIC_INITIAL_STIFFNESS = 100.0 +PLASTIC_ELASTIC_STIFFNESS = 1.0e6 +# a plastic hinge softer than this multiple of 4 EI / l makes the structure a mechanism +PLASTIC_MECHANISM_STIFFNESS = 1.0e-6 + + class Element: def __init__( self, @@ -85,6 +94,9 @@ def __init__( self.q_direction: Optional[str] = None self.q_angle: Optional[float] = None self.dead_load: float = 0.0 + # (alpha * delta_t, alpha * delta_t_gradient / h): free thermal strain and + # curvature of the element + self.temperature_load: Tuple[float, float] = (0.0, 0.0) self.N_1: Optional[float] = None self.N_2: Optional[float] = None self.bending_moment: Optional[np.ndarray] = None @@ -97,6 +109,9 @@ def __init__( self.max_total_deflection: Optional[float] = None self.max_extension: Optional[float] = None self.nodes_plastic: List[bool] = [False, False] + # rotational stiffness of the plastic hinge at the two ends, in series with the + # element (None: the end is elastic) + self.plastic_stiffness: List[Optional[float]] = [None, None] self.compile_constitutive_matrix(initial=True) self.compile_stiffness_matrix() self.section_name = section_name # needed for element annotation @@ -198,47 +213,224 @@ def compile_kinematic_matrix(self) -> None: """Compile the kinematic matrix of the element""" self.kinematic_matrix = kinematic_matrix(self.a1, self.a2, self.l) + def reset_plastic(self) -> None: + """Make both ends of the element elastic again (no plastic hinge)""" + self.nodes_plastic = [False, False] + self.plastic_stiffness = [None, None] + + def _effective_springs(self) -> "Spring": + """Rotational springs at the two ends: the springs of the user and the plastic hinges + + A plastic hinge is a rotational spring in series with the element (and with a spring of + the user): the flexibilities add. A hinge (stiffness 0) stays a hinge. + + Returns: + Spring: The stiffness of the rotational spring of each end that has one + """ + + def combined(end: Literal[1, 2], plastic: Optional[float]) -> Optional[float]: + user = (self.springs or {}).get(end) + if user == 0: + return 0.0 + flexibility = (1.0 / user if user else 0.0) + ( + 1.0 / plastic if plastic else 0.0 + ) + return 1.0 / flexibility if flexibility > 0 else None + + springs: "Spring" = {} + first = combined(1, self.plastic_stiffness[0]) + second = combined(2, self.plastic_stiffness[1]) + if first is not None: + springs[1] = first + if second is not None: + springs[2] = second + return springs + + @property + def end_rotational_stiffness(self) -> Tuple[float, float]: + """Rotational stiffness of the connections at the two element ends + + These are the stiffnesses that determine the fixed-end forces due to a + distributed load: 0 for a hinge, the spring stiffness `k` for a rotational + spring (also the plastic hinge, which is a spring in series), and (practically) + infinite for a rigid connection. A truss element carries no moment, so both ends + are hinges. + + Returns: + Tuple[float, float]: Rotational stiffness at node 1 and node 2 + """ + if self.type == "truss": + return 0.0, 0.0 + + springs = self._effective_springs() + stiffness = [] + for end in (1, 2): + released = self.constitutive_matrix[end][end] == 0 + spring = springs.get(end) + if released: + stiffness.append(0.0) + elif spring: + stiffness.append(float(spring)) + else: + stiffness.append(float(self.constitutive_matrix[end][end]) * 1e6) + return stiffness[0], stiffness[1] + + def refresh_nodes(self, node_map: Dict[int, "Node"]) -> None: + """Use the current nodes of the system instead of the copies of the post-processing + + The post-processing replaces the nodes of the element by copies with the results. They + also hold the hinge status at that time, which the constitutive matrix depends on. + + Args: + node_map (Dict[int, Node]): Nodes of the system + """ + self.node_map = { + self.node_id1: node_map[self.node_id1], + self.node_id2: node_map[self.node_id2], + } + def compile_constitutive_matrix(self, initial: bool = False) -> None: """Compile the constitutive matrix of the element""" if initial: # if element is just being created self.constitutive_matrix = constitutive_matrix( - self.EA, self.EI, self.l, self.springs, False, False + self.EA, self.EI, self.l, self._effective_springs(), False, False ) else: self.constitutive_matrix = constitutive_matrix( self.EA, self.EI, self.l, - self.springs, + self._effective_springs(), self.node_1.hinge, self.node_2.hinge, ) def update_stiffness(self, factor: float, node: Literal[1, 2]) -> None: - """Update the stiffness matrix of the element + """Multiply the stiffness of the plastic hinge at an end of the element with a factor + + The plastic hinge is a rotational spring in series with the element. It starts as a stiff + spring (`PLASTIC_INITIAL_STIFFNESS` times the rotational stiffness 4 EI / l of the + element) and the iteration of the plastic moment changes it by a factor: a hinge that + carries the plastic moment has the secant stiffness mp / (plastic rotation). A spring + that becomes stiffer than `PLASTIC_ELASTIC_STIFFNESS` times 4 EI / l makes the end + elastic again (unloading). Args: - factor (float): Factor to multiply the stiffness matrix with + factor (float): Factor to multiply the stiffness of the plastic hinge with node (Literal[1, 2]): Node ID of the node to update (1 or 2) """ - if node == 1: - self.constitutive_matrix[1][1] *= factor - self.constitutive_matrix[1][2] *= factor - self.constitutive_matrix[2][1] *= factor - elif node == 2: - self.constitutive_matrix[1][2] *= factor - self.constitutive_matrix[2][1] *= factor - self.constitutive_matrix[2][2] *= factor + reference = 4 * self.EI / self.l + current = self.plastic_stiffness[node - 1] + if current is None: + current = PLASTIC_INITIAL_STIFFNESS * reference + updated = current * factor + if updated > PLASTIC_ELASTIC_STIFFNESS * reference: + self.plastic_stiffness[node - 1] = None + self.nodes_plastic[node - 1] = False + else: + self.plastic_stiffness[node - 1] = updated + self.nodes_plastic[node - 1] = True + self.compile_constitutive_matrix() self.compile_stiffness_matrix() + def _end_releases(self) -> List[Optional[float]]: + """Rotational stiffness of the connection at the two element ends + + Returns: + List[Optional[float]]: For each end: None for a rigid connection, 0 for a hinge + (a hinge node, or a spring with stiffness 0) and the stiffness k of a + rotational spring + """ + + springs = self._effective_springs() + + def release(end: Literal[1, 2], hinge: bool) -> Optional[float]: + spring = springs.get(end) + if hinge or spring == 0: + return 0.0 + return float(spring) if spring else None + + return [ + release(1, self.node_1.hinge), + release(2, self.node_2.hinge), + ] + + def _stiffness_with_releases( + self, geometric: np.ndarray, releases: List[Optional[float]] + ) -> np.ndarray: + """Stiffness matrix of the element with the geometric stiffness and released ends + + The beam is connected to the node by a rotational spring (a hinge is a spring with + stiffness 0). The rotation of the beam end is an internal degree of freedom, which + is eliminated from the sum of the elastic and the geometric stiffness of the beam + (static condensation), so that the geometric stiffness is that of the displacement + field the released end really has. + + Args: + geometric (np.ndarray): Geometric stiffness matrix of the beam + releases (List[Optional[float]]): Rotational stiffness of the two ends, see + `_end_releases` + + Returns: + np.ndarray: Stiffness matrix of the element + """ + beam_stiffness = constitutive_matrix( + self.EA, self.EI, self.l, None, False, False + ) + beam = self.kinematic_matrix.T @ beam_stiffness @ self.kinematic_matrix + beam = beam + geometric + + rotation_dofs = (2, 5) + released_ends = [end for end in (0, 1) if releases[end] is not None] + n = 6 + len(released_ends) + + # beam degrees of freedom = node degrees of freedom, with the internal rotations + # instead of the node rotations at the released ends + transform = np.zeros((6, n)) + for dof in range(6): + if dof not in [rotation_dofs[end] for end in released_ends]: + transform[dof, dof] = 1.0 + for j, end in enumerate(released_ends): + transform[rotation_dofs[end], 6 + j] = 1.0 + stiffness = transform.T @ beam @ transform + + for j, end in enumerate(released_ends): + k = releases[end] + if k: + node_dof, internal_dof = rotation_dofs[end], 6 + j + stiffness[node_dof, node_dof] += k + stiffness[internal_dof, internal_dof] += k + stiffness[node_dof, internal_dof] -= k + stiffness[internal_dof, node_dof] -= k + + node_part = stiffness[:6, :6] + coupling = stiffness[:6, 6:] + internal_part = stiffness[6:, 6:] + condensed: np.ndarray = node_part - coupling @ np.linalg.solve( + internal_part, coupling.T + ) + return condensed + def compile_geometric_non_linear_stiffness_matrix(self) -> None: """Compile the geometric non-linear stiffness matrix of the element""" self.compile_stiffness_matrix() assert self.N_1 is not None - self.stiffness_matrix += geometric_stiffness_matrix( - self.l, self.N_1, self.a1, self.a2 + # the geometric stiffness is that of a constant normal force: the mean of the two ends, + # so that it does not depend on the direction in which the element was drawn when the + # normal force varies (a load in the direction of the element) + normal_force = self.N_1 if self.N_2 is None else (self.N_1 + self.N_2) / 2 + geometric = geometric_stiffness_matrix( + self.l, normal_force, self.a1, self.a2, self.angle, self.type == "truss" ) + releases = self._end_releases() + if self.type != "truss" and any(release is not None for release in releases): + # hinges, springs and plastic hinges: condensed with the elastic stiffness + self.stiffness_matrix = self._stiffness_with_releases(geometric, releases) + return + + self.stiffness_matrix += geometric + def reset(self) -> None: """Reset the element's solve state""" self.element_displacement_vector = np.zeros(6) @@ -283,6 +475,10 @@ def __add__(self, other: Element) -> Element: el.q_perp_load[0] + other.q_perp_load[0], el.q_perp_load[1] + other.q_perp_load[1], ) + el.temperature_load = ( + el.temperature_load[0] + other.temperature_load[0], + el.temperature_load[1] + other.temperature_load[1], + ) el.node_map[self.node_id1] = el.node_1 + other.node_1 el.node_map[self.node_id2] = el.node_2 + other.node_2 @@ -330,45 +526,71 @@ def constitutive_matrix( ) -> np.ndarray: """Generate the constitutive matrix of an element + The matrix relates the element deformations (axial elongation and the two end + rotations relative to the chord) to the element forces (axial force and the two end + moments). The end releases are taken into account as follows: + + * A hinge (a hinge node, or a rotational spring with stiffness 0) carries no moment. + Its rotation is eliminated by static condensation (Schur complement) of the + bending stiffness [[4, -2], [-2, 4]] * EI / l. An element with one hinge therefore + has a rotational stiffness of 3 EI / l at the other end, and an element with two + hinges has no bending stiffness. + * A rotational spring k at an end acts in series with the element, so the + flexibilities add: C = C_element + diag(1 / k1, 1 / k2). The result is exact for + any k, from k -> 0 (hinge) to k -> infinity (rigid connection). + * A hinge prevails over a spring at the same end. + Args: EA (float): Axial stiffness EI (float): Bending stiffness l (float): Length - spring (Optional[Spring]): Spring stiffnesses at node 1 and node 2 + spring (Optional[Spring]): Rotational spring stiffnesses at node 1 and node 2 + (0 is a hinge) node_1_hinge (Optional[bool]): Whether node 1 is a hinge node_2_hinge (Optional[bool]): Whether node 2 is a hinge Returns: np.ndarray: Constitutive matrix of the element """ - matrix = np.array( - [[EA / l, 0, 0], [0, 4 * EI / l, -2 * EI / l], [0, -2 * EI / l, 4 * EI / l]] - ) - - if node_1_hinge or (spring is not None and 1 in spring and spring[1] == 0): - matrix[1][1] = matrix[1][2] = matrix[2][1] = 0 - - if node_2_hinge or (spring is not None and 2 in spring and spring[2] == 0): - matrix[1][2] = matrix[2][1] = matrix[2][2] = 0 - - if spring is not None: - # stiffness matrix K: - # [[ k, k ] - # [ k, k ]] + matrix = np.zeros((3, 3)) + matrix[0][0] = EA / l + + # bending part, relating the end rotations (relative to the chord) to the end moments + bending = EI / l * np.array([[4.0, -2.0], [-2.0, 4.0]]) + + # an end is released (hinge) when it is a hinge node or has a rotational spring + # with stiffness 0 + spring = spring or {} + spring_stiffness = [spring.get(1), spring.get(2)] # None: no spring + released = [ + bool(node_1_hinge) or spring_stiffness[0] == 0, + bool(node_2_hinge) or spring_stiffness[1] == 0, + ] + spring_flexibility = [1 / k if k else 0.0 for k in spring_stiffness] + active = [i for i in (0, 1) if not released[i]] + condensed = [i for i in (0, 1) if released[i]] + + if active: + # static condensation of the released rotations: the moment at a hinge is zero, + # so the stiffness of the remaining rotations is the Schur complement + # (a fixed-hinge element has 3EI/l instead of 4EI/l) + stiffness = bending[np.ix_(active, active)] + if condensed: + stiffness = stiffness - ( + bending[np.ix_(active, condensed)] + @ np.linalg.inv(bending[np.ix_(condensed, condensed)]) + @ bending[np.ix_(condensed, active)] + ) - # flexibility matrix C: - # [[ c, c ] = [[ 1/k, 1/k ] - # `[ c, c ]] [ 1/k, 1/k ]] + # rotational springs at the ends act in series with the (condensed) element: + # the flexibilities add, C = C_element + diag(1 / k1, 1 / k2) + flexibility = np.linalg.inv(stiffness) + np.diag( + [spring_flexibility[i] for i in active] + ) + stiffness = np.linalg.inv(flexibility) - # flexibility matrix c + springs on both sides: - # [[ c11 + 1/k1, c12 ] - # [ c21 , c21 + 1/k2 ]] - if 1 in spring and spring[1] != 0: # not hinge - matrix[1][1] = 1 / (1 / matrix[1][1] + 1 / spring[1]) - matrix[2][1] = 1 / (1 / matrix[2][1] + 1 / spring[1]) - if 2 in spring and spring[2] != 0: # not hinge - matrix[2][1] = 1 / (1 / matrix[2][1] + 1 / spring[2]) - matrix[1][2] = 1 / (1 / matrix[1][2] + 1 / spring[2]) + rows = [i + 1 for i in active] + matrix[np.ix_(rows, rows)] = stiffness return matrix @@ -391,24 +613,73 @@ def stiffness_matrix( return kinematic_transposed_times_constitutive @ var_kinematic_matrix # type: ignore -def geometric_stiffness_matrix(l: float, N: float, a1: float, a2: float) -> np.ndarray: +def geometric_stiffness_matrix( + l: float, + N: float, + a1: float, + a2: float, + angle: Optional[float] = None, + truss: bool = False, +) -> np.ndarray: """Generate the geometric stiffness matrix of an element + The matrix is derived for the displacements in the global directions. The angle at a + node differs from the angle of the element (`angle`) when the node has an inclined + roller support: the translations of that node are then given in the rotated system of + the support. The matrix of the element is transformed to that system, in the same way + as the kinematic matrix (the rotation of the node, with the angle of the element + replaced by the angle at the node, is R(a_node - angle)). + Args: l (float): Length N (float): Axial force a1 (float): Angle of the element at node 1 a2 (float): Angle of the element at node 2 + angle (Optional[float], optional): Angle of the element itself. Defaults to None, the + angle at node 1. + truss (bool, optional): A truss element has no bending stiffness: the matrix of a + string, N / l times the transverse translations, without the rotation terms of a + beam. Defaults to False. Returns: np.ndarray: Geometric stiffness matrix of the element """ - c1 = cos(a1) - s1 = sin(a1) - c2 = cos(a2) - s2 = sin(a2) + if angle is None: + angle = a1 + matrix = _geometric_stiffness_matrix(l, N, angle) + if truss: + # the transverse part of the beam matrix is 6/5 * N / l (a cubic displacement field); + # a string has N / l, and the node rotations are not a degree of freedom + matrix = matrix * (5 / 6) + matrix[[2, 5], :] = 0.0 + matrix[:, [2, 5]] = 0.0 + if a1 != angle or a2 != angle: + transform = np.eye(6) + for node, node_angle in ((0, a1), (3, a2)): + delta = node_angle - angle + transform[node : node + 2, node : node + 2] = [ + [cos(delta), -sin(delta)], + [sin(delta), cos(delta)], + ] + matrix = transform.T @ matrix @ transform + return matrix + + +def _geometric_stiffness_matrix(l: float, N: float, angle: float) -> np.ndarray: + """Geometric stiffness matrix of an element for the displacements in the global directions + + Args: + l (float): Length + N (float): Axial force + angle (float): Angle of the element + + Returns: + np.ndarray: Geometric stiffness matrix of the element + """ + c1 = c2 = cos(angle) + s1 = s2 = sin(angle) # http://people.duke.edu/~hpgavin/cee421/frame-finite-def.pdf - return ( # type: ignore + matrix: np.ndarray = ( N / l * np.array( @@ -442,7 +713,7 @@ def geometric_stiffness_matrix(l: float, N: float, a1: float, a2: float) -> np.n 6 / 5 * s1 * c1, l / 10 * s1, 6 / 5 * s2**2, - -6 / 5 * s1 * c2, + -6 / 5 * s2 * c2, l / 10 * s2, ], [ @@ -463,5 +734,8 @@ def geometric_stiffness_matrix(l: float, N: float, a1: float, a2: float) -> np.n ], ] ) - * np.array([1, -1, 1, 1, -1, 1]) - ) # conversion from coordinate system + # conversion from coordinate system: the y-axis points the other way, K -> S K S + # (the rows and the columns, so that the matrix stays symmetric) + * np.outer([1, -1, 1, 1, -1, 1], [1, -1, 1, 1, -1, 1]) + ) + return matrix diff --git a/anastruct/fem/plotter/mpl.py b/anastruct/fem/plotter/mpl.py index 4f2f9ee0..0682572b 100644 --- a/anastruct/fem/plotter/mpl.py +++ b/anastruct/fem/plotter/mpl.py @@ -358,7 +358,18 @@ def __internal_hinges_patch(self, max_val: float, axes_i: int = 0) -> None: axes_i (int, optional): Which set of axes to plot on (for multi-plot windows). Defaults to 0. """ radius = PATCH_SIZE * max_val / 2 - for node in self.system.internal_hinges: + + # the internal hinges, and every element end that is released (hinge) by the + # spring of the element + hinge_nodes = {node.id: node for node in self.system.internal_hinges} + for element in self.system.element_map.values(): + springs = element.springs or {} + if springs.get(1) == 0: + hinge_nodes[element.node_id1] = self.system.node_map[element.node_id1] + if springs.get(2) == 0: + hinge_nodes[element.node_id2] = self.system.node_map[element.node_id2] + + for node in hinge_nodes.values(): support_patch = mpatches.Circle( (node.vertex.x, node.vertex.y), radius, diff --git a/anastruct/fem/postprocess.py b/anastruct/fem/postprocess.py index 3c8858cc..cfd67d86 100644 --- a/anastruct/fem/postprocess.py +++ b/anastruct/fem/postprocess.py @@ -32,6 +32,10 @@ def node_results_system(self) -> None: Results place in SystemElements class: self.system.node_map (list) """ for k, v in self.system.node_element_map.items(): + # the node objects are replaced below; keep what is not a result + elements = self.system.node_map[k].elements + hinge = self.system.node_map[k].hinge + # reset nodes in case of iterative calculation self.system.node_map[k].reset() @@ -56,6 +60,9 @@ def node_results_system(self) -> None: self.system.node_map[k].uy = -node.uy self.system.node_map[k].phi_z = -node.phi_z + self.system.node_map[k].elements = elements + self.system.node_map[k].hinge = hinge + def reaction_forces(self) -> None: """Determines the reaction forces on the system level. Results place in SystemElements class: self.system.reaction_forces (list) @@ -83,9 +90,7 @@ def reaction_forces(self) -> None: node.Fx *= -1 node.Fy *= -1 node.Tz *= -1 - node.ux = 0.0 - node.uy = 0.0 - node.phi_z = 0.0 + # keep the (possibly imposed) displacements of the support node def element_results(self) -> None: """Determines the element results for all elements in the system on element level.""" @@ -159,10 +164,12 @@ def node_results(self, element: "Element") -> None: Fy = node.Fy ux = node.ux uy = node.uy - node.Fy = c * Fy + s * Fx - node.Fx = -(c * Fx + s * Fy) - node.ux = c * ux + s * uy - node.uy = c * uy + s * ux + # from the system of the support to the global system: R(angle), the + # inverse of the transformation of the loads and the kinematic matrix + node.Fx = c * Fx - s * Fy + node.Fy = s * Fx + c * Fy + node.ux = c * ux - s * uy + node.uy = s * ux + c * uy @staticmethod def determine_axial_force(element: "Element", con: int) -> None: diff --git a/anastruct/fem/system.py b/anastruct/fem/system.py index ae30419f..7967f783 100644 --- a/anastruct/fem/system.py +++ b/anastruct/fem/system.py @@ -91,8 +91,11 @@ def __init__( EI (float, optional): Bending stiffness. Defaults to 5e3. load_factor (float, optional): Load factor by which to multiply all loads. Defaults to 1.0. mesh (int, optional): Number of mesh elements, only used for plotting. Defaults to 50. - invert_y_loads (bool, optional): Whether to invert the y-direction of the loads, such that a positive - Fy load will be in the direction of gravity. Defaults to True. + invert_y_loads (bool, optional): Whether to invert the y-direction of the loads. The y-axis of the + calculation points down, so with the default (True) the loads follow the y-axis of the structure: + a positive Fy (and q, and imposed uy) acts in the +y direction (upwards in a drawing with y up) and a + downward load is negative. If False, a positive Fy acts in the -y direction (the direction of + gravity in such a drawing). Defaults to True. """ # init object self.post_processor = post_sl(self) @@ -118,7 +121,7 @@ def __init__( ) # maps node ids to Element objects # keys matrix index (for both row and columns), values K, are processed # assemble_system_matrix - self.system_spring_map: Dict[int, float] = {} + self.system_spring_map: Dict[Tuple[int, int], float] = {} # list of indexes that remain after conditions are applied self._remainder_indexes: List[int] = [] @@ -128,6 +131,13 @@ def __init__( self.supports_hinged: List[Node] = [] self.supports_rotational: List[Node] = [] self.internal_hinges: List[Node] = [] + # node ids declared with add_internal_hinge (internal_hinges also holds the + # nodes where the elements are released by their springs) + self._explicit_internal_hinges: Set[int] = set() + # position of every node id in internal_hinges (the list is updated in place) + self._internal_hinge_index: Dict[int, int] = {} + # position of every node id in the system matrix (nodes can be removed) + self._node_index: Optional[Dict[int, int]] = None self.supports_roll: List[Node] = [] self.supports_spring_x: List[Tuple[Node, bool]] = [] self.supports_spring_y: List[Tuple[Node, bool]] = [] @@ -152,6 +162,19 @@ def __init__( self.loads_dead_load: Set[int] = ( set() ) # element ids with q-load due to dead load + self.loads_displacement: Dict[ + int, Tuple[Optional[float], Optional[float], Optional[float]] + ] = {} # node ids with imposed displacements {node_id: (ux, uy, phi_z)} + self.loads_temperature: Dict[int, Tuple[float, float]] = ( + {} + ) # element ids with a temperature load {element_id: (alpha * delta_t, alpha * delta_t_gradient / h)} + + # boolean mask of the restrained degrees of freedom, set once by process_supports + self._restrained_dofs: Optional[np.ndarray] = None + + # map of system matrix indexes to imposed (non-zero) displacement values, + # processed in system_components.assembly.process_supports + self._prescribed_displacements: Dict[int, float] = {} # results self.reaction_forces: Dict[int, Node] = {} # node objects @@ -177,6 +200,34 @@ def __init__( self.reduced_system_matrix: Optional[np.ndarray] = None self._vertices: Dict[Vertex, int] = {} # maps vertices to node ids + def _reset_plastic_state(self) -> None: + """Back to the elastic stiffness of all the elements + + A plastic iteration reduces the stiffness of the elements at the plastic hinges. A + linear calculation, and every new plastic iteration, starts from the elastic stiffness. + """ + for element in self.element_map.values(): + element.reset_plastic() + element.refresh_nodes(self.node_map) + element.compile_constitutive_matrix() + element.compile_stiffness_matrix() + + def _invalidate_solution(self) -> None: + """A change of the model (supports, elements) makes the solution out of date. + + The supports are processed once, at the first solve, and the displacement vector holds + the solution of the previous calculation. After a solve both are reset, so that the + next solve processes the supports of the changed model, and the elements start with + their elastic stiffness again. + """ + if self.system_displacement_vector is None: + return + self.system_displacement_vector = None + self._restrained_dofs = None + self._prescribed_displacements = {} + self.buckling_factor = None + self._reset_plastic_state() + @property def id_last_element(self) -> int: """ID of the last element added to the structure @@ -320,6 +371,14 @@ def add_truss_element( The two nodes of the element or the next node of the element. EA (Optional[float], optional): Axial stiffness of the new element. Defaults to None. + Note: + A truss element has no bending stiffness, so a bar of a truss does not buckle between + its nodes in a second order calculation. To determine the buckling load of a bar, + model it as an element with hinges at both ends, `add_element(location, EA=EA, EI=EI, + spring={1: 0, 2: 0})`: it behaves like a truss element, and `discretize()` divides it + with the hinges at its ends only, see `solve(geometrical_non_linear=True, + discretize_kwargs=...)`. + Returns: int: ID of the new element """ @@ -369,7 +428,10 @@ def add_element( mp (Optional[MpType], optional): Maximum plastic moment of each end node. Keys are integers representing the nodes. Values are the bending moment capacity. Defaults to None. spring (Optional[Spring], optional): Rotational spring or hinge (k=0) of each end node. - Keys are integers representing the nodes. Values are the bending moment capacity. Defaults to None. + Keys are integers representing the nodes (1 or 2). Values are the rotational spring + stiffness k (moment per radian). k=0 is a hinge, a large k approaches a rigid connection. + The element stiffness is condensed exactly, see :ref:`End releases `. + Defaults to None. Optional Keyword Args: element_type (ElementType): "general" (axial and lateral force) or "truss" (axial force only) @@ -386,10 +448,9 @@ def add_element( int: ID of the new element """ - if mp is None: - mp = {} - if spring is None: - spring = {} + # copy the dictionaries, so that elements never share (and modify) one object + mp = {} if mp is None else dict(mp) + spring = {} if spring is None else dict(spring) element_type = kwargs.get("element_type", "general") @@ -410,10 +471,20 @@ def add_element( if element_type == "truss": EI = 1e-14 + self._invalidate_solution() + + previous_point = self._previous_point + point_1, point_2 = system_components.util.det_vertices(self, location) + if point_1 == point_2: + self._previous_point = previous_point + raise FEMException( + "Invalid parameters", + f"An element needs two different locations, but both are {point_1}.", + ) + # add the element number self.count += 1 - point_1, point_2 = system_components.util.det_vertices(self, location) node_id1, node_id2 = system_components.util.det_node_ids(self, point_1, point_2) ( @@ -480,6 +551,7 @@ def remove_element(self, element_id: int) -> None: Args: element_id (int): ID of the element to remove """ + self._invalidate_solution() element = self.element_map[element_id] node_id1 = element.node_id1 node_id2 = element.node_id2 @@ -493,6 +565,9 @@ def remove_element(self, element_id: int) -> None: # Check if node is now orphaned, and remove it and its loads if so if len(self.node_map[node_id].elements) == 0: system_components.util.remove_node_id(self, node_id) + else: + # the remaining elements may (no longer) form an internal hinge + system_components.util.check_internal_hinges(self, node_id) # Remove element_id self.element_map.pop(element_id) @@ -500,6 +575,8 @@ def remove_element(self, element_id: int) -> None: self.loads_q.pop(element_id) if element_id in self.loads_dead_load: self.loads_dead_load.remove(element_id) + if element_id in self.loads_temperature: + self.loads_temperature.pop(element_id) if element_id in self.non_linear_elements: self.non_linear_elements.pop(element_id) @@ -723,6 +800,7 @@ def insert_node( g=element_to_split.dead_load, mp=mp1, spring=spring1, + element_type=element_to_split.type, ) element_id2 = self.add_element( [location_vertex, vertex_end], @@ -731,31 +809,57 @@ def insert_node( g=element_to_split.dead_load, mp=mp2, spring=spring2, + element_type=element_to_split.type, ) + for new_element_id in (element_id1, element_id2): + self.element_map[new_element_id].section_name = ( + element_to_split.section_name + ) - # Copy the q-loads from the old element to the new elements + # Copy the q-loads from the old element to the new elements. The stored values contain + # the load factor and the orientation of the y-axis, so they are copied as they are, + # interpolated linearly over the old element. if element_id_to_split in self.loads_q: - q_load_start = element_to_split.q_load[0] - q_load_end = element_to_split.q_load[1] - q_perp_load_start = element_to_split.q_perp_load[0] - q_perp_load_end = element_to_split.q_perp_load[1] - location_q_load = factor * (q_load_end - q_load_start) + q_load_start - location_q_perp_load = ( - factor * (q_perp_load_end - q_perp_load_start) + q_perp_load_start - ) - assert element_to_split.q_angle is not None - self.q_load( - q=[-q_load_start, -location_q_load], - element_id=element_id1, - rotation=np.degrees(element_to_split.q_angle), - q_perp=[q_perp_load_start, location_q_perp_load], - ) - self.q_load( - q=[-location_q_load, -q_load_end], - element_id=element_id2, - rotation=np.degrees(element_to_split.q_angle), - q_perp=[location_q_perp_load, q_perp_load_end], - ) + + def interpolate(start_value: float, end_value: float, at: float) -> float: + return start_value + (end_value - start_value) * at + + forces_q = self.loads_q[element_id_to_split] + for new_element_id, (at_start, at_end) in ( + (element_id1, (0.0, factor)), + (element_id2, (factor, 1.0)), + ): + self.loads_q[new_element_id] = [ + ( + interpolate(forces_q[0][0], forces_q[1][0], at), + interpolate(forces_q[0][1], forces_q[1][1], at), + ) + for at in (at_start, at_end) + ] + new_element = self.element_map[new_element_id] + q_start, q_end = element_to_split.q_load + q_perp_start, q_perp_end = element_to_split.q_perp_load + new_element.q_load = ( + interpolate(q_start, q_end, at_start), + interpolate(q_start, q_end, at_end), + ) + new_element.q_perp_load = ( + interpolate(q_perp_start, q_perp_end, at_start), + interpolate(q_perp_start, q_perp_end, at_end), + ) + new_element.q_direction = element_to_split.q_direction + new_element.q_angle = element_to_split.q_angle + + # Copy the thermal load from the old element to the new elements (the free + # strain and curvature are uniform over the element) + if element_id_to_split in self.loads_temperature: + for new_element_id in (element_id1, element_id2): + self.loads_temperature[new_element_id] = self.loads_temperature[ + element_id_to_split + ] + self.element_map[new_element_id].temperature_load = ( + self.loads_temperature[element_id_to_split] + ) # Remove the old element from everywhere it's referenced self.remove_element(element_id_to_split) @@ -878,8 +982,12 @@ def solve( force_linear (bool, optional): Force a linear calculation, even when the system has non-linear nodes. Defaults to False. verbosity (int, optional): Log calculation outputs (0), or silence (1). Defaults to 0. - max_iter (int, optional): Maximum allowed iterations. Defaults to 200. + max_iter (int, optional): Maximum allowed iterations of the plastic iteration of non-linear nodes. + A FEMException ("ConvergenceError") is raised if it does not converge: the structure may be a + mechanism, or the iteration may need more iterations (increase max_iter). Defaults to 200. geometrical_non_linear (int, optional): Calculate second order effects and determine the buckling factor. + This can be combined with non linear nodes (`mp=`): every step of the plastic iteration is then + a second order analysis, and the buckling factor is that of the elastic structure. Defaults to False. Optional Keyword Args: @@ -905,6 +1013,11 @@ def solve( naked = kwargs.get("naked", False) + if self.non_linear and force_linear and not naked: + # a linear calculation is elastic: no plastic reduction of an earlier calculation + # (the plastic iteration itself calls this method with naked=True) + self._reset_plastic_state() + if not naked: if not self.validate(): if all( @@ -926,8 +1039,15 @@ def solve( ), "There are no forces on the structure" if self.non_linear and not force_linear: + if geometrical_non_linear: + # the buckling factor is that of the elastic structure + self.buckling_factor = ( + system_components.solver.determine_buckling_factor( + self, kwargs.get("discretize_kwargs", None) + ) + ) return system_components.solver.stiffness_adaptation( - self, verbosity, max_iter + self, verbosity, max_iter, bool(geometrical_non_linear) ) system_components.assembly.assemble_system_matrix(self) @@ -958,11 +1078,14 @@ def solve( self._remainder_indexes, reduced_displacement_vector, ) + # prescribe the imposed (non-zero) displacements on the restrained indexes + for index, displacement in self._prescribed_displacements.items(): + self.system_displacement_vector[index] = displacement # determine the displacement vector of the elements for el in self.element_map.values(): - index_node_1 = (el.node_1.id - 1) * 3 - index_node_2 = (el.node_2.id - 1) * 3 + index_node_1 = system_components.util.dof_index(self, el.node_1.id) + index_node_2 = system_components.util.dof_index(self, el.node_2.id) # node 1 ux, uy, phi el.element_displacement_vector[:3] = self.system_displacement_vector[ @@ -983,11 +1106,13 @@ def solve( # check the values in the displacement vector for extreme values, indicating a # flawed calculation - assert np.any(self.system_displacement_vector < 1e6), ( - "The displacements of the structure exceed 1e6. " - "Check your support conditions," - "or your elements Young's modulus" - ) + if not np.all(np.abs(self.system_displacement_vector) < 1e6): + raise FEMException( + "StabilityError", + "The displacements of the structure exceed 1e6. " + "Check your support conditions, " + "or your elements Young's modulus", + ) return self.system_displacement_vector @@ -1003,10 +1128,15 @@ def validate(self, min_eigen: float = 1e-9) -> bool: """ ss = copy.copy(self) + if ss.system_displacement_vector is None: + # not solved yet: the hinges and the supports are processed on the copy + for node_id in ss.node_map: + system_components.util.check_internal_hinges(ss, node_id) + system_components.assembly.process_supports(ss) system_components.assembly.prep_matrix_forces(ss) assert ss.system_force_vector is not None - assert ( - np.abs(ss.system_force_vector).sum() != 0 + assert np.abs(ss.system_force_vector).sum() != 0 or any( + displacement != 0 for displacement in ss._prescribed_displacements.values() ), "There are no forces on the structure" ss._remainder_indexes = [] system_components.assembly.assemble_system_matrix(ss) @@ -1014,7 +1144,9 @@ def validate(self, min_eigen: float = 1e-9) -> bool: system_components.assembly.process_conditions(ss) assert ss.reduced_system_matrix is not None - w, _ = np.linalg.eig(ss.reduced_system_matrix) + # the reduced stiffness matrix is symmetric: real eigenvalues, and faster + reduced = np.asarray(ss.reduced_system_matrix) + w = np.linalg.eigvalsh((reduced + reduced.T) / 2) return bool(np.all(w > min_eigen)) def add_support_hinged(self, node_id: Union[int, Sequence[int]]) -> None: @@ -1031,6 +1163,7 @@ def add_support_hinged(self, node_id: Union[int, Sequence[int]]) -> None: # add the support to the support list for the plotter self.supports_hinged.append(self.node_map[id_]) + self._invalidate_solution() def add_support_rotational(self, node_id: Union[int, Sequence[int]]) -> None: """Model a rotational support at a given node. @@ -1046,11 +1179,13 @@ def add_support_rotational(self, node_id: Union[int, Sequence[int]]) -> None: # add the support to the support list for the plotter self.supports_rotational.append(self.node_map[id_]) + self._invalidate_solution() def add_internal_hinge(self, node_id: Union[int, Sequence[int]]) -> None: """Model a internal hinge at a given node. - This may alternatively be done by setting a spring restraint to zero (`{1: 0}` or `{2: 0}`). - The effect is the same, though this function may be easier to use. + This releases all the elements that meet in the node, also the rigidly connected ones. A node + where every element has a spring restraint of zero (`{1: 0}` or `{2: 0}`) is a hinge as well; if + some elements are rigidly connected, only the elements with a spring of zero are released. Args: node_id (Union[int, Sequence[int]]): Represents the nodes ID @@ -1061,8 +1196,10 @@ def add_internal_hinge(self, node_id: Union[int, Sequence[int]]) -> None: for id_ in node_id: id_ = _negative_index_to_id(id_, self.node_map.keys()) - # add the support to the support list for the plotter - self.internal_hinges.append(self.node_map[id_]) + # the node is a hinge from now on, also when no element is released + self._explicit_internal_hinges.add(id_) + system_components.util.check_internal_hinges(self, id_) + self._invalidate_solution() def add_support_roll( self, @@ -1115,6 +1252,7 @@ def add_support_roll( # add the support to the support list for the plotter self.supports_roll.append(self.node_map[id_]) + self._invalidate_solution() self.supports_roll_direction.append(direction_i) self.supports_roll_rotate.append(rotate_) @@ -1138,6 +1276,7 @@ def add_support_fixed( # add the support to the support list for the plotter self.supports_fixed.append(self.node_map[id_]) + self._invalidate_solution() def add_support_spring( self, @@ -1156,7 +1295,17 @@ def add_support_spring( roll (Union[Sequence[bool], bool], optional): If set to True, only the translation of the spring is controlled. Defaults to False. """ - self.supports_spring_args.append((node_id, translation, k, roll)) + # resolve negative node ids now, the node they refer to must not change when + # nodes are added later (the arguments are also used to copy the supports) + resolved_node_id: Union[Sequence[int], int] + if isinstance(node_id, collections.abc.Iterable): + resolved_node_id = [ + _negative_index_to_id(i, self.node_map.keys()) for i in node_id + ] + else: + resolved_node_id = _negative_index_to_id(node_id, self.node_map.keys()) + self.supports_spring_args.append((resolved_node_id, translation, k, roll)) + self._invalidate_solution() # The stiffness of the spring is added in the system matrix at the location that # represents the node and the displacement. if not isinstance(node_id, collections.abc.Iterable): @@ -1172,13 +1321,19 @@ def add_support_spring( for id_, translation_, k_, roll_ in zip(node_id, translation, k, roll): id_ = _negative_index_to_id(id_, self.node_map.keys()) - system_components.util.support_check(self, id_) + if translation_ == 3: + # only a spring that restrains the rotation conflicts with a hinge + system_components.util.support_check(self, id_) - # determine the location in the system matrix - # row and column are the same - matrix_index = (id_ - 1) * 3 + translation_ - 1 + if not np.isfinite(k_) or k_ < 0: + raise FEMException( + "Invalid parameters", + f"The stiffness of a spring support must be finite and not negative, but is {k_}. " + "A rigid support is a fixed, hinged or roll support.", + ) - self.system_spring_map[matrix_index] = k_ + # the stiffness is added to the system matrix at the degree of freedom of the node + self.system_spring_map[(id_, translation_)] = k_ # add the support to the support list for the plotter if translation_ == 1: @@ -1262,34 +1417,82 @@ def q_load( ) else: rotation[i] = math.radians(rotation[i]) + if self.orientation_cs > 0: + # invert_y_loads=False: the load of a rotation r is the mirror image (in the + # x-axis) of the default one, so rotation 0 is 'x' and rotation 90 is 'y' + rotation[i] = -rotation[i] direction[i] = "angle" cos = math.cos(rotation[i]) sin = math.sin(rotation[i]) + # With invert_y_loads=False a positive load in the y-direction acts the other way + # (like Fy), but a load in the x-direction ('x') or along the element + # ('parallel') does not (like Fx): their sign stays that of the default, and the + # load perpendicular to them (q_perp) is the y-like one. + same_as_default = (direction[i] == "angle" and self.orientation_cs > 0) or ( + direction_flag and direction[i] in ("x", "parallel") + ) + q_factor = -1.0 if same_as_default else float(self.orientation_cs) + q_perp_factor = -float(self.orientation_cs) if same_as_default else 1.0 self.loads_q[id_] = [ ( - (q_perp_arr[i][0] * cos + q_arr[i][0] * sin) * self.load_factor, - (q_arr[i][0] * self.orientation_cs * cos + q_perp_arr[i][0] * sin) + ( + q_perp_arr[i][0] * q_perp_factor * cos + - q_arr[i][0] * q_factor * sin + ) + * self.load_factor, + ( + q_arr[i][0] * q_factor * cos + + q_perp_arr[i][0] * q_perp_factor * sin + ) * self.load_factor, ), ( - (q_perp_arr[i][1] * cos + q_arr[i][1] * sin) * self.load_factor, - (q_arr[i][1] * self.orientation_cs * cos + q_perp_arr[i][1] * sin) + ( + q_perp_arr[i][1] * q_perp_factor * cos + - q_arr[i][1] * q_factor * sin + ) + * self.load_factor, + ( + q_arr[i][1] * q_factor * cos + + q_perp_arr[i][1] * q_perp_factor * sin + ) * self.load_factor, ), ] el = self.element_map[id_] el.q_load = ( - self.orientation_cs * self.load_factor * q_arr[i][0], - self.orientation_cs * self.load_factor * q_arr[i][1], + q_factor * self.load_factor * q_arr[i][0], + q_factor * self.load_factor * q_arr[i][1], ) el.q_perp_load = ( - q_perp_arr[i][0] * self.load_factor, - q_perp_arr[i][1] * self.load_factor, + q_perp_factor * q_perp_arr[i][0] * self.load_factor, + q_perp_factor * q_perp_arr[i][1] * self.load_factor, ) el.q_direction = direction[i] el.q_angle = rotation[i] + def dead_load( + self, + element_id: Union[int, Sequence[int]], + g: Union[float, Sequence[float]], + ) -> None: + """Apply a dead load (self-weight) to an element, like the `g` of `add_element`. + + The load is multiplied by the `load_factor`. Applying it again to the same element + replaces the earlier dead load. + + Args: + element_id (Union[int, Sequence[int]]): The element ID to which to apply the load + g (Union[float, Sequence[float]]): Weight per unit of length + """ + n_elems = len(element_id) if isinstance(element_id, Sequence) else 1 + element_ids = arg_to_list(element_id, n_elems) + weights = arg_to_list(g, n_elems) + for element_idi, weight in zip(element_ids, weights): + id_ = _negative_index_to_id(element_idi, self.element_map.keys()) + system_components.assembly.dead_load(self, weight * self.load_factor, id_) + def point_load( self, node_id: Union[int, Sequence[int]], @@ -1307,8 +1510,10 @@ def point_load( rotation (Union[float, Sequence[float]], optional): Rotate the force clockwise by the given angle in degrees. Defaults to 0.0. - Raises: - FEMException: Point loads may not be placed at the location of inclined roller supports + Note: + The load may be placed at the node of an inclined roller support: the degrees of + freedom of that node are in the system of the support, and the load is transformed to + it when solving. The reaction of such a roller is normal to its free direction. """ if isinstance(Fy, (int, float)) and Fy == 0.0 and Fz is not None: Fy = Fz # for backwards compatibility with old y/z axes behaviour @@ -1320,21 +1525,13 @@ def point_load( for i, node_idi in enumerate(node_id): id_ = _negative_index_to_id(node_idi, self.node_map.keys()) - if ( - id_ in self.inclined_roll - and np.mod(self.inclined_roll[id_], np.pi / 2) != 0 - ): - raise FEMException( - "StabilityError", - "Point loads may not be placed at the location of inclined roller supports", - ) self.plotter.max_system_point_load = max( self.plotter.max_system_point_load, (Fx[i] ** 2 + Fy[i] ** 2) ** 0.5 ) cos = math.cos(math.radians(rotation[i])) sin = math.sin(math.radians(rotation[i])) self.loads_point[id_] = ( - (Fx[i] * cos + Fy[i] * sin) * self.load_factor, + (Fx[i] * cos - self.orientation_cs * Fy[i] * sin) * self.load_factor, (Fy[i] * self.orientation_cs * cos + Fx[i] * sin) * self.load_factor, ) @@ -1360,6 +1557,169 @@ def moment_load( id_ = _negative_index_to_id(node_idi, self.node_map.keys()) self.loads_moment[id_] = Tz[i] * self.load_factor + def imposed_displacement( + self, + node_id: int, + ux: Optional[float] = None, + uy: Optional[float] = None, + phi_z: Optional[float] = None, + ) -> None: + """Apply an imposed displacement (support settlement) and/or rotation to a node. + + The imposed values are prescribed to the restrained degrees of freedom of the node, + so a support restraining the respective degree of freedom is required. The sign + conventions follow the corresponding loads: `ux` acts like a positive `Fx` point + load, `uy` like a positive `Fy` point load (with the default `invert_y_loads=True` + a positive `uy` is in the +y direction, upwards, so a settlement is a negative + `uy`) and `phi_z` like a positive `Tz` moment load. Note that the getters report + rotations positive in the clockwise direction, so an imposed `phi_z` is reported + with the opposite sign by `get_node_displacements`, like the rotation caused by a + moment load `Tz`. + Like the loads, imposed displacements are multiplied by the `load_factor`, so + that they can be superposed in a :class:`.LoadCombination` (see + :meth:`.LoadCase.imposed_displacement`). + + Calling this method again for the same node overrides only the components that + are passed; components left as `None` keep their previously imposed value. Pass + 0 to clear a previously imposed component. + + Args: + node_id (int): The node ID to which to apply the imposed displacement + ux (Optional[float], optional): Imposed displacement in the global x direction. + Defaults to None (not imposed). + uy (Optional[float], optional): Imposed displacement in the global y direction. + Defaults to None (not imposed). + phi_z (Optional[float], optional): Imposed rotation about the global z-axis + in radians. Defaults to None (not imposed). + + Raises: + FEMException: If no displacement or rotation is imposed at all + FEMException: If the system has already been solved, if the node is an + inclined roller support, or if a rotation is imposed on an internal + hinge + FEMException: If the degree of freedom is not restrained by a support (raised when + solving). A displacement can only be imposed in a direction that a support restrains: + not in the free direction of a roller, not for the rotation of a hinged support, and + not for an inclined roller, which restrains only the translation normal to its free + direction. The message explains which of these applies. + + Note: + Impose the displacements before the first `solve()`, just like supports. + Imposed displacements are carried over by `discretize()`. Imposed + displacements on inclined roller supports are not supported. + """ + if ux is None and uy is None and phi_z is None: + raise FEMException( + "Invalid parameters", + "Impose at least one of ux, uy or phi_z.", + ) + if self.system_displacement_vector is not None: + raise FEMException( + "Invalid parameters", + "Imposed displacements must be applied before the system is solved.", + ) + id_ = _negative_index_to_id(node_id, self.node_map.keys()) + if id_ in self.inclined_roll: + raise FEMException( + "Invalid parameters", + system_components.util.describe_unrestrained_dof( + self, id_, 1 if ux is not None else 2 if uy is not None else 3 + ), + ) + if phi_z is not None and any(hinge.id == id_ for hinge in self.internal_hinges): + raise FEMException( + "Invalid parameters", + "A rotation cannot be imposed on an internal hinge.", + ) + prev_ux, prev_uy, prev_phi_z = self.loads_displacement.get( + id_, (None, None, None) + ) + self.loads_displacement[id_] = ( + ux * self.load_factor if ux is not None else prev_ux, + ( + (uy * self.orientation_cs * self.load_factor) + if uy is not None + else prev_uy + ), + phi_z * self.load_factor if phi_z is not None else prev_phi_z, + ) + + def thermal_load( + self, + element_id: Union[int, Sequence[int]], + delta_t: Union[float, Sequence[float]], + alpha: Union[float, Sequence[float]], + delta_t_gradient: Optional[Union[float, Sequence[float]]] = None, + h: Optional[Union[float, Sequence[float]]] = None, + ) -> None: + """Apply a thermal load to an element. + + A uniform temperature change `delta_t` causes a free axial strain + `alpha * delta_t` of the element. A linear temperature gradient over the + section depth, `delta_t_gradient` (temperature difference between the two + faces of the element), causes a free curvature + `alpha * delta_t_gradient / h`, with `h` the section depth. A positive + gradient corresponds to a warmer upper face (the face pointing towards the + positive global y-direction for a horizontal element): the upper fibres are + longer, so a cantilever fixed at its first node deflects downwards (towards the + colder face, a negative `uy` in `get_node_displacements`) and a simply supported + beam cambers upwards. The sign does not depend on `invert_y_loads`. In general + the warmer face is the face on the left + of the element when looking from its first to its second node. Elements that + are not vertical are oriented from left to right, so this is their upper + face; for vertical elements it depends on the order in which the end points + were entered. + + Args: + element_id (Union[int, Sequence[int]]): The element ID to which to apply the load + delta_t (Union[float, Sequence[float]]): Uniform temperature change of the + element (positive is heating) + alpha (Union[float, Sequence[float]]): Coefficient of thermal expansion + of the element material + delta_t_gradient (Optional[Union[float, Sequence[float]]], optional): + Temperature difference over the section depth. Requires `h`. + Defaults to None (no gradient). + h (Optional[Union[float, Sequence[float]]], optional): Section depth over + which `delta_t_gradient` acts. Defaults to None. + + Raises: + FEMException: If `delta_t_gradient` is set without a valid section depth `h` + + Note: + Calling this method again for an element replaces its previous thermal + load (like `q_load`); give the uniform change and the gradient in one call. + Thermal loads are removed by `remove_loads()` and are carried over by + `discretize()` and `insert_node()`. The element result curves + `deflection` and `extension` (relative to the element chord) do not + include the free thermal curvature and strain; nodal displacements, + reactions and the internal force diagrams are exact. + The equivalent nodal forces are derived with the (condensed) stiffness + matrix of the element, so end hinges and rotational springs + (`spring=`) and internal hinges are accounted for exactly. + """ + n_elems = len(element_id) if isinstance(element_id, Sequence) else 1 + element_id = arg_to_list(element_id, n_elems) + delta_t = arg_to_list(delta_t, n_elems) + alpha = arg_to_list(alpha, n_elems) + delta_t_gradient = arg_to_list(delta_t_gradient, n_elems) + h = arg_to_list(h, n_elems) + + for i, element_idi in enumerate(element_id): + id_ = _negative_index_to_id(element_idi, self.element_map.keys()) + if delta_t_gradient[i] is not None and (h[i] is None or h[i] == 0): + raise FEMException( + "Invalid parameters", + "A temperature gradient requires a section depth `h`.", + ) + strain = alpha[i] * delta_t[i] * self.load_factor + curvature = ( + alpha[i] * delta_t_gradient[i] / h[i] * self.load_factor + if delta_t_gradient[i] is not None + else 0.0 + ) + self.loads_temperature[id_] = (strain, curvature) + self.element_map[id_].temperature_load = (strain, curvature) + @overload def show_structure( self, @@ -2219,68 +2579,162 @@ def discretize(self, n: int = 10) -> None: """Discretize the elements. Takes an already defined :class:`.SystemElements` object and increases the number of elements. + Every element is divided into n sub-elements. The supports, the loads (point loads, moment loads, + q-loads, self-weights, thermal loads), the imposed displacements and the internal hinges are carried over + to the new mesh. Rotational springs, hinges (`spring=`) and plastic moments (`mp=`) belong to the ends of + the original element, so only the outer sub-elements get them. Truss elements stay truss elements and are + not divided: they have no bending stiffness, so the nodes between collinear truss elements would be + mechanisms. + Args: n (int, optional): Divide the elements into n sub-elements.. Defaults to 10. """ + # copies, so that a (shallow) copy of this system that shares the plotter with + # it keeps its own plotter + old_plotter = copy.copy(self.plotter) + old_plot_values = copy.copy(self.plot_values) ss = SystemElements( - EA=self.EA, EI=self.EI, load_factor=self.load_factor, mesh=self.plotter.mesh + EA=self.EA, + EI=self.EI, + load_factor=self.load_factor, + mesh=self.plotter.mesh, + figsize=self.figsize, + invert_y_loads=self.orientation_cs == -1, ) + # elements: old element id -> ids of its sub-elements + sub_elements: Dict[int, List[int]] = {} for element in self.element_map.values(): - g = self.element_map[element.id].dead_load - mp = ( - self.non_linear_elements[element.id] - if element.id in self.non_linear_elements - else {} - ) - - el_v_range = vertex_range(element.vertex_1, element.vertex_2, n) - for last_v, v in zip(el_v_range, el_v_range[1:]): - loc = [last_v, v] - ss.add_element( - loc, + springs = element.springs or {} + mp = self.non_linear_elements.get(element.id, {}) + + # a truss element is not divided: it has no bending stiffness, so the + # nodes between two collinear truss elements would be mechanisms + parts = 1 if element.type == "truss" else n + # the ends of the original element, with the sub-element they belong to + ends: Tuple[Tuple[Literal[1, 2], int], ...] = ((1, 0), (2, parts - 1)) + + vertices = vertex_range(element.vertex_1, element.vertex_2, parts) + vertices[0], vertices[-1] = element.vertex_1, element.vertex_2 + sub_elements[element.id] = [] + for i, (vertex_1, vertex_2) in enumerate(zip(vertices, vertices[1:])): + sub_spring: "Spring" = {} + sub_mp: "MpType" = {} + for end, position in ends: + if i == position: + if end in springs: + sub_spring[end] = springs[end] + if end in mp: + sub_mp[end] = mp[end] + sub_id = ss.add_element( + [vertex_1, vertex_2], EA=element.EA, EI=element.EI, - g=g, - mp=mp, - spring=element.springs, + g=element.dead_load, + mp=sub_mp, + spring=sub_spring, + element_type=element.type, ) - last_v = v + ss.element_map[sub_id].section_name = element.section_name + sub_elements[element.id].append(sub_id) + + # nodes: old node id -> id of the node at the same location + node_ids: Dict[int, int] = {} + for node_id, node in self.node_map.items(): + new_id = ss._vertices.get(node.vertex) + if new_id is None: + new_id = ss.find_node_id(node.vertex) + assert new_id is not None + node_ids[node_id] = new_id # supports for node, direction, rotate in zip( self.supports_roll, self.supports_roll_direction, self.supports_roll_rotate ): - ss.add_support_roll((node.id - 1) * n + 1, direction, None, rotate) + angle = ( + -float(np.degrees(self.inclined_roll[node.id])) + if node.id in self.inclined_roll + else None + ) + ss.add_support_roll(node_ids[node.id], direction, angle, rotate) for node in self.supports_fixed: - ss.add_support_fixed((node.id - 1) * n + 1) + ss.add_support_fixed(node_ids[node.id]) for node in self.supports_hinged: - ss.add_support_hinged((node.id - 1) * n + 1) + ss.add_support_hinged(node_ids[node.id]) for node in self.supports_rotational: - ss.add_support_rotational((node.id - 1) * n + 1) + ss.add_support_rotational(node_ids[node.id]) for args in self.supports_spring_args: - ss.add_support_spring((args[0] - 1) * n + 1, *args[1:]) - - # loads - for node_id, forces in self.loads_point.items(): - ss.point_load( - (node_id - 1) * n + 1, - Fx=forces[0] / self.load_factor, - Fy=forces[1] / self.orientation_cs / self.load_factor, - ) - - for node_id, forces_moment in self.loads_moment.items(): - ss.moment_load((node_id - 1) * n + 1, forces_moment / self.load_factor) + spring_nodes = args[0] + if isinstance(spring_nodes, collections.abc.Iterable): + new_nodes: Union[int, List[int]] = [ + node_ids[_negative_index_to_id(i, self.node_map.keys())] + for i in spring_nodes + ] + else: + new_nodes = node_ids[ + _negative_index_to_id(spring_nodes, self.node_map.keys()) + ] + ss.add_support_spring(new_nodes, *args[1:]) + for node_id in self._explicit_internal_hinges: + ss.add_internal_hinge(node_ids[node_id]) + + # loads: the stored values already contain the load factor and the orientation + for node_id, force in self.loads_point.items(): + ss.loads_point[node_ids[node_id]] = force + for node_id, moment in self.loads_moment.items(): + ss.loads_moment[node_ids[node_id]] = moment + + def interpolate(start: float, end: float, fraction: float) -> float: + return start + (end - start) * fraction + + # the q-loads vary linearly over the original element for element_id, forces_q in self.loads_q.items(): - ss.q_load( - q=[i[1] / self.orientation_cs / self.load_factor for i in forces_q], - element_id=element_id, - direction="y", - q_perp=[i[0] / self.load_factor for i in forces_q], - ) + element = self.element_map[element_id] + for i, sub_id in enumerate(sub_elements[element_id]): + parts = len(sub_elements[element_id]) + fractions = (i / parts, (i + 1) / parts) + ss.loads_q[sub_id] = [ + ( + interpolate(forces_q[0][0], forces_q[1][0], fraction), + interpolate(forces_q[0][1], forces_q[1][1], fraction), + ) + for fraction in fractions + ] + sub_element = ss.element_map[sub_id] + sub_element.q_load = ( + interpolate(element.q_load[0], element.q_load[1], fractions[0]), + interpolate(element.q_load[0], element.q_load[1], fractions[1]), + ) + sub_element.q_perp_load = ( + interpolate( + element.q_perp_load[0], element.q_perp_load[1], fractions[0] + ), + interpolate( + element.q_perp_load[0], element.q_perp_load[1], fractions[1] + ), + ) + sub_element.q_direction = element.q_direction + sub_element.q_angle = element.q_angle + + # the thermal load (free strain and curvature) is uniform over the element + for element_id, temperature_load in self.loads_temperature.items(): + for sub_id in sub_elements[element_id]: + ss.loads_temperature[sub_id] = temperature_load + ss.element_map[sub_id].temperature_load = temperature_load + + # imposed displacements are stored with the load factor and orientation applied + for node_id, displacement in self.loads_displacement.items(): + ss.loads_displacement[node_ids[node_id]] = displacement self.__dict__ = ss.__dict__.copy() + # keep the plotter (with its scaling of the loads) and point the helper + # objects, which were created for `ss`, at this system + self.plotter, self.plot_values = old_plotter, old_plot_values + self.plotter.system = self + self.plot_values.system = self + self.post_processor = post_sl(self) + def remove_loads(self, dead_load: bool = False) -> None: """Remove all the applied loads from the structure. @@ -2290,13 +2744,24 @@ def remove_loads(self, dead_load: bool = False) -> None: self.loads_point = {} self.loads_q = {} self.loads_moment = {} + self.loads_temperature = {} + + # release the imposed displacements; the restrained degrees of freedom + # return to zero + if self.system_displacement_vector is not None: + for index in self._prescribed_displacements: + self.system_displacement_vector[index] = 0.0 + self.loads_displacement = {} + self._prescribed_displacements = {} for k in self.element_map: # pylint: disable=consider-using-dict-items self.element_map[k].q_load = (0.0, 0.0) + self.element_map[k].q_perp_load = (0.0, 0.0) + self.element_map[k].temperature_load = (0.0, 0.0) if dead_load: self.element_map[k].dead_load = 0 - if dead_load: - self.loads_dead_load = set() + # (loads_dead_load is not cleared: the loads of all the elements of that set are + # processed when solving, also the q-loads, so an element must stay in it) def apply_load_case(self, loadcase: LoadCase) -> None: """Apply a load case to the structure. diff --git a/anastruct/fem/system_components/assembly.py b/anastruct/fem/system_components/assembly.py index 461f7191..368964b7 100644 --- a/anastruct/fem/system_components/assembly.py +++ b/anastruct/fem/system_components/assembly.py @@ -3,6 +3,11 @@ import numpy as np +from anastruct.basic import FEMException +from anastruct.fem.system_components.util import ( + describe_unrestrained_dof, + dof_index, +) from anastruct.fem.elements import det_axial, det_moment, det_shear if TYPE_CHECKING: @@ -26,7 +31,7 @@ def set_force_vector( """ assert system.system_force_vector is not None for id_, direction, force in force_list: - system.system_force_vector[(id_ - 1) * 3 + direction - 1] += force + system.system_force_vector[dof_index(system, id_) + direction - 1] += force return system.system_force_vector @@ -37,13 +42,55 @@ def prep_matrix_forces(system: "SystemElements") -> None: Args: system (SystemElements): System to which the force vector is applied """ - system.system_force_vector = system.system_force_vector = np.zeros( - len(system._vertices) * 3 - ) + system.system_force_vector = np.zeros(len(system.node_map) * 3) apply_perpendicular_q_load(system) apply_parallel_qn_load(system) apply_point_load(system) apply_moment_load(system) + apply_temperature_load(system) + + +def apply_temperature_load(system: "SystemElements") -> None: + """Apply a temperature load to the system + + The equivalent nodal forces are derived from the free thermal eigen strains of + the element: e0 = [alpha * delta_t * l, -kappa * l / 2, -kappa * l / 2], with + kappa = alpha * delta_t_gradient / h the free thermal curvature. The sign of the + curvature follows from the kinematic matrix: the relative end rotations are positive + for a curvature that bends the element towards its right-hand side (looking from + its first to its second node), which is the side of the colder face. A positive + gradient is a warmer face on the left (the upper face of a horizontal element), so + the free end of a cantilever bends towards the colder face. The fixed-end + forces are obtained with the element's own kinematic and condensed constitutive + matrices, so (internal) hinges and springs at the element ends are accounted for + automatically. + + Args: + system (SystemElements): System to which the temperature load is applied + """ + for element_id, (strain, curvature) in system.loads_temperature.items(): + element = system.element_map[element_id] + if strain == 0 and curvature == 0: + continue + + e0 = np.array( + [strain * element.l, -curvature * element.l / 2, -curvature * element.l / 2] + ) + if element.type == "truss": + e0[1] = e0[2] = 0.0 + + primary_force = element.kinematic_matrix.T @ element.constitutive_matrix @ e0 + + element.element_primary_force_vector -= primary_force + + # Set force vector + assert system.system_force_vector is not None + for node_id, part in ( + (element.node_id1, primary_force[0:3]), + (element.node_id2, primary_force[3:]), + ): + start = dof_index(system, node_id) + system.system_force_vector[start : start + 3] += part def apply_moment_load(system: "SystemElements") -> None: @@ -53,6 +100,21 @@ def apply_moment_load(system: "SystemElements") -> None: system (SystemElements): System to which the moment load is applied """ for node_id, Tz in system.loads_moment.items(): + if Tz != 0 and system.node_map[node_id].hinge: + raise FEMException( + "Invalid parameters", + f"A moment load at node {node_id} can not be carried: the node is an internal " + "hinge (no element transfers a moment there). Place the moment load at a node " + "where an element is rigidly connected.", + ) + if Tz != 0 and all( + element.type == "truss" for element in system.node_element_map[node_id] + ): + raise FEMException( + "Invalid parameters", + f"A moment load at node {node_id} can not be carried: only truss elements, " + "which have no bending stiffness, are connected to the node.", + ) set_force_vector(system, [(node_id, 3, Tz)]) @@ -64,6 +126,14 @@ def apply_point_load(system: "SystemElements") -> None: """ for node_id in system.loads_point: Fx, Fy = system.loads_point[node_id] + if node_id in system.inclined_roll: + # The degrees of freedom of a node with an inclined roller support are in the + # system of the support, rotated by delta with respect to the global system + # (u_global = R(delta) u_support, see the kinematic matrix), so the load + # is given in that system as well: f_support = R(delta)^T f_global. + delta = system.inclined_roll[node_id] + cos_d, sin_d = math.cos(delta), math.sin(delta) + Fx, Fy = cos_d * Fx + sin_d * Fy, -sin_d * Fx + cos_d * Fy # system force vector. set_force_vector( system, @@ -87,8 +157,7 @@ def apply_perpendicular_q_load(system: "SystemElements") -> None: if q_perpendicular == 0 and qi_perpendicular == 0: continue - kl = element.constitutive_matrix[1][1] * 1e6 - kr = element.constitutive_matrix[2][2] * 1e6 + kl, kr = element.end_rotational_stiffness # minus because of systems positive rotation left_moment = det_moment( @@ -121,12 +190,12 @@ def apply_perpendicular_q_load(system: "SystemElements") -> None: # Set force vector assert system.system_force_vector is not None - system.system_force_vector[ - (element.node_id1 - 1) * 3 : (element.node_id1 - 1) * 3 + 3 - ] += primary_force[0:3] - system.system_force_vector[ - (element.node_id2 - 1) * 3 : (element.node_id2 - 1) * 3 + 3 - ] += primary_force[3:] + for node_id, part in ( + (element.node_id1, primary_force[0:3]), + (element.node_id2, primary_force[3:]), + ): + start = dof_index(system, node_id) + system.system_force_vector[start : start + 3] += part def apply_parallel_qn_load(system: "SystemElements") -> None: @@ -198,8 +267,9 @@ def assemble_system_matrix( system.system_matrix = np.zeros((shape, shape)) assert system.system_matrix is not None - for matrix_index, K in system.system_spring_map.items(): + for (node_id, translation), K in system.system_spring_map.items(): # first index is row, second is column + matrix_index = dof_index(system, node_id) + translation - 1 system.system_matrix[matrix_index][matrix_index] += K # Determine the elements location in the stiffness matrix. @@ -231,8 +301,8 @@ def assemble_system_matrix( element_matrix = element.stiffness_matrix # n1 and n2 are starting indexes of the rows and the columns for node 1 and node 2 - n1 = (element.node_1.id - 1) * 3 - n2 = (element.node_2.id - 1) * 3 + n1 = dof_index(system, element.node_1.id) + n2 = dof_index(system, element.node_2.id) system.system_matrix[n1 : n1 + 3, n1 : n1 + 3] += element_matrix[0:3, :3] system.system_matrix[n1 : n1 + 3, n2 : n2 + 3] += element_matrix[0:3, 3:] @@ -262,10 +332,10 @@ def set_displacement_vector( np.ndarray: System displacement vector with the applied displacements on the nodes """ if system.system_displacement_vector is None: - system.system_displacement_vector = np.ones(len(system._vertices) * 3) * np.nan + system.system_displacement_vector = np.ones(len(system.node_map) * 3) * np.nan for i in nodes_list: - index = (i[0] - 1) * 3 + i[1] - 1 + index = dof_index(system, i[0]) + i[1] - 1 try: system.system_displacement_vector[index] = 0 @@ -285,11 +355,19 @@ def process_conditions(system: "SystemElements") -> None: system (SystemElements): System to be processed """ indexes = [] + system._remainder_indexes = [] # remove the unsolvable values from the matrix and vectors assert system.shape_system_matrix is not None assert system.system_displacement_vector is not None + # The restrained degrees of freedom are determined once, in process_supports. The + # displacement vector can not be used again after a solve: it then holds the + # solution, and a degree of freedom that is exactly 0 (e.g. the transverse + # displacements of a column under an axial load) is not a restrained one. + restrained = system._restrained_dofs + if restrained is None: + restrained = system.system_displacement_vector == 0 for i in range(system.shape_system_matrix): - if system.system_displacement_vector[i] == 0: + if restrained[i] or i in system._prescribed_displacements: indexes.append(i) else: system._remainder_indexes.append(i) @@ -300,6 +378,19 @@ def process_conditions(system: "SystemElements") -> None: assert system.system_force_vector is not None assert system.system_matrix is not None system.reduced_force_vector = np.delete(system.system_force_vector, indexes, 0) + + # correct the reduced force vector for imposed (non-zero) displacements: + # K_ff * u_f = F_f - K_fr * u_r + if system._prescribed_displacements: + prescribed_indexes = sorted(system._prescribed_displacements.keys()) + prescribed_values = np.array( + [system._prescribed_displacements[i] for i in prescribed_indexes] + ) + system.reduced_force_vector -= ( + system.system_matrix[np.ix_(system._remainder_indexes, prescribed_indexes)] + @ prescribed_values + ) + system.reduced_system_matrix = np.delete(system.system_matrix, indexes, 0) system.reduced_system_matrix = np.delete(system.reduced_system_matrix, indexes, 1) @@ -310,6 +401,10 @@ def process_supports(system: "SystemElements") -> None: Args: system (SystemElements): System to be processed """ + if system.system_displacement_vector is None: + # also a model without any support (which is unstable, but not an error here) + system.system_displacement_vector = np.ones(len(system.node_map) * 3) * np.nan + for node in system.supports_hinged: set_displacement_vector(system, [(node.id, 1), (node.id, 2)]) @@ -334,6 +429,8 @@ def process_supports(system: "SystemElements") -> None: for node in system.internal_hinges: set_displacement_vector(system, [(node.id, 3)]) for el in system.node_element_map[node.id]: + # the node copies of the post-processing hold the hinge status of an earlier solve + el.refresh_nodes(system.node_map) el.compile_constitutive_matrix() el.compile_stiffness_matrix() @@ -361,3 +458,37 @@ def process_supports(system: "SystemElements") -> None: el.compile_kinematic_matrix() el.compile_stiffness_matrix() + + # imposed (non-zero) displacements and rotations on restrained degrees of freedom + assert system.system_displacement_vector is not None + for node_id, (ux, uy, phi_z) in system.loads_displacement.items(): + if node_id in system.inclined_roll: + raise FEMException( + "Invalid parameters", + describe_unrestrained_dof( + system, node_id, 1 if ux is not None else 2 if uy is not None else 3 + ), + ) + if phi_z is not None and any( + hinge.id == node_id for hinge in system.internal_hinges + ): + raise FEMException( + "Invalid parameters", + f"A rotation cannot be imposed on internal hinge {node_id}.", + ) + for direction, displacement in ((1, ux), (2, uy), (3, phi_z)): + if displacement is None or displacement == 0: + continue + index = dof_index(system, node_id) + direction - 1 + if np.isnan(system.system_displacement_vector[index]): + raise FEMException( + "StabilityError", + describe_unrestrained_dof(system, node_id, direction), + ) + system.system_displacement_vector[index] = displacement + system._prescribed_displacements[index] = displacement + + # the restrained degrees of freedom (value 0, or an imposed displacement) + system._restrained_dofs = system.system_displacement_vector == 0 + for index in system._prescribed_displacements: + system._restrained_dofs[index] = True diff --git a/anastruct/fem/system_components/solver.py b/anastruct/fem/system_components/solver.py index c740fa9d..ec9925d3 100644 --- a/anastruct/fem/system_components/solver.py +++ b/anastruct/fem/system_components/solver.py @@ -1,33 +1,82 @@ import copy import logging -from typing import TYPE_CHECKING, Optional +import math +from typing import TYPE_CHECKING, Dict, Optional, Tuple import numpy as np -from anastruct.basic import converge +from anastruct.basic import FEMException +from anastruct.fem.elements import PLASTIC_MECHANISM_STIFFNESS +from anastruct.fem.system_components.assembly import assemble_system_matrix if TYPE_CHECKING: from anastruct.fem.system import SystemElements +def second_order_step(system: "SystemElements") -> None: + """ + One linear step of a second order analysis with the current stiffness of the elements + (which may be reduced by plastic hinges): a first order solution gives the normal + forces N0, the geometric stiffness for N0 is added to the elements and the system + is solved again, (K + Kg(N0)) u = F. The results stay on the system, without the + post-processing. + + :param system: (SystemElements) + """ + for el in system.element_map.values(): + el.compile_stiffness_matrix() # the plastic reduction stays, the old Kg goes + system.solve(True, naked=True) + system.post_processor.node_results_elements() + for el in system.element_map.values(): + el.N_1 = math.sin(el.angle) * el.node_1.Fy - math.cos(el.angle) * el.node_1.Fx + el.N_2 = -math.sin(el.angle) * el.node_2.Fy + math.cos(el.angle) * el.node_2.Fx + el.compile_geometric_non_linear_stiffness_matrix() + system.solve(True, naked=True) + + def stiffness_adaptation( - system: "SystemElements", verbosity: int, max_iter: int + system: "SystemElements", + verbosity: int, + max_iter: int, + geometrical_non_linear: bool = False, ) -> np.ndarray: """ Non linear solver for the nodes by adapting the stiffness of the elements (nodes). + :param geometrical_non_linear: (bool) Every step of the iteration is a second order + analysis, see :func:`second_order_step`. :return: Vector with displacements. """ - system.solve(True, naked=True) + + def solve_step() -> None: + try: + if geometrical_non_linear: + second_order_step(system) + else: + system.solve(True, naked=True) + except np.linalg.LinAlgError as error: + raise FEMException( + "ConvergenceError", + "The structure is a mechanism: the plastic hinges can not carry the loads " + "(check the plastic moments mp and the loads).", + ) from error + + # start from the elastic stiffness: the plastic reduction of an earlier calculation + # would otherwise be the starting point of this one + system._reset_plastic_state() + + solve_step() if verbosity == 0: logging.info("Starting stiffness adaptation calculation.") # check validity assert all( - mp > 0 for mpd in system.non_linear_elements.values() for mp in mpd + mp > 0 for mpd in system.non_linear_elements.values() for mp in mpd.values() ), "Cannot solve for an mp = 0. If you want a hinge set the spring stiffness equal to 0." iteration = 0 + # (stiffness of the plastic hinge, |M|) of the previous iteration, per element end + history: Dict[Tuple[int, int], Tuple[float, float]] = {} while iteration < max_iter: factors = [] @@ -48,15 +97,47 @@ def stiffness_adaptation( el.element_force_vector[5] + el.element_primary_force_vector[5] ) - if abs(m_e) > mp: - el.nodes_plastic[node_no - 1] = True - if el.nodes_plastic[node_no - 1]: - factor = converge(m_e, mp) + # the end is plastic when the moment exceeds mp; a plastic hinge is a + # spring in series, its stiffness follows from the secant: k <- k * mp / |M| + # (a moment below mp makes it stiffer, until the end is elastic again) + current = el.plastic_stiffness[node_no - 1] + if current is None and abs(m_e) <= mp: + continue + factor = mp / abs(m_e) if m_e != 0 else 1.0e3 + if current is not None: + # the moment is nearly linear in the flexibility 1/k of the spring: with + # two iterates, a secant step in the flexibility converges much faster + # than the plain secant when mp is close to the elastic moment + previous = history.get((k, node_no)) + history[(k, node_no)] = (current, abs(m_e)) + if previous is not None and previous[0] != current: + slope = (abs(m_e) - previous[1]) / ( + 1 / current - 1 / previous[0] + ) + if slope < 0: + flexibility = 1 / current + (mp - abs(m_e)) / slope + if flexibility > 0: + factor = min( + max(1 / (current * flexibility), 0.01), 100 + ) + else: + history.pop((k, node_no), None) + el.update_stiffness(factor, node_no) + updated = el.plastic_stiffness[node_no - 1] + if updated is None: + # the end became elastic again: the structure has to be solved again + factors.append(0.0) + else: + if updated < PLASTIC_MECHANISM_STIFFNESS * 4 * el.EI / el.l: + raise FEMException( + "ConvergenceError", + "The structure is a mechanism: the plastic hinges can not carry " + "the loads (check the plastic moments mp and the loads).", + ) factors.append(factor) - el.update_stiffness(factor, node_no) if not np.allclose(factors, 1, 1e-3): - system.solve(force_linear=True, naked=True) + solve_step() else: system.post_processor.node_results_elements() system.post_processor.node_results_system() @@ -65,59 +146,157 @@ def stiffness_adaptation( break iteration += 1 + if geometrical_non_linear: + # the results are second order; the elements go back to the first order stiffness + for el in system.element_map.values(): + el.compile_stiffness_matrix() + if iteration >= max_iter: - logging.warning( - f"Couldn't solve the in the amount of iterations given. max_iter={max_iter}" + # the iteration of the last step has no post-processed results, and the results of + # an earlier calculation must not be mistaken for them + raise FEMException( + "ConvergenceError", + f"The plastic iteration did not converge in max_iter={max_iter} iterations. " + "The structure may be a mechanism (check the plastic moments mp and the loads), " + "or the iteration needs more iterations: increase max_iter.", ) - elif verbosity == 0: + if verbosity == 0: logging.info(f"Solved in {iteration} iterations") assert system.system_displacement_vector is not None return system.system_displacement_vector +def smallest_buckling_factor(k0: np.ndarray, kg: np.ndarray) -> float: + """ + Solve the generalized eigenvalue problem (K0 + λ Kg) x = 0 and return the smallest + positive λ. + + K0 is the (symmetric, positive definite) reduced stiffness matrix of the first order + analysis. Kg is the reduced geometric stiffness matrix for the first order normal + forces N0. Compression makes Kg negative, so a buckling mode, K0 x = -λ Kg x, has a + positive λ for the loads that cause compression. A tensile normal force stiffens the + structure and gives a negative λ, which is no buckling mode. + + Kg is singular when some members carry no normal force, so it is not inverted. The + problem is solved for ν = -1 / λ, the eigenvalues of K0⁻¹ Kg. + + Args: + k0 (np.ndarray): Reduced stiffness matrix of the first order analysis. + kg (np.ndarray): Reduced geometric stiffness matrix for the first order normal forces. + + Returns: + float: The smallest positive factor λ, or infinity when there is no buckling mode (no compression). + """ + if k0.size == 0: + # every degree of freedom is restrained: nothing can buckle + logging.warning("There are no free degrees of freedom: no buckling mode.") + return float("inf") + + try: + # K0 = L Lᵀ: ν are the eigenvalues of the symmetric matrix L⁻¹ Kg L⁻ᵀ + chol = np.linalg.cholesky(k0) + half = np.linalg.solve(chol, kg) + symmetric = np.linalg.solve(chol, half.T).T + nu = np.linalg.eigvalsh((symmetric + symmetric.T) / 2) + except np.linalg.LinAlgError: + # the stiffness matrix is not positive definite: the general eigenvalue problem + try: + nu = np.linalg.eigvals(np.linalg.solve(k0, kg)).real + except np.linalg.LinAlgError as error: + raise FEMException( + "StabilityError", + "The stiffness matrix is singular, the buckling factor can not be " + "determined. Check your support conditions.", + ) from error + + # buckling modes have a negative ν (compression); ignore ν = 0 (no geometric effect) + compressive = nu[nu < -1e-12 * max(float(np.max(np.abs(nu))), 1e-300)] + if compressive.size == 0: + logging.warning( + "There is no buckling mode: no compressive normal force acts on the free " + "degrees of freedom, so the buckling factor is infinite." + ) + return float("inf") + return float(np.min(-1.0 / compressive)) + + def det_linear_buckling(system: "SystemElements") -> float: """ - Determine linear buckling by solving the generalized eigenvalue problem (k -λkg)x = 0. + Determine linear buckling by solving the generalized eigenvalue problem (K0 + λKg0)x = 0. geometrical stiffness matrix at buckling point: Kg = f(N_max) 1st order forces: N0 Nmax = λN0 - Kg(Nmax) = λ(Kg(N0) = λKg0 + Kg(Nmax) = λKg(N0) = λKg0 2nd order analysis is solved by: - (K + λKg0)U = F + (K0 + λKg0)U = F - We are interested in the point that there is nog additional load F and displacement U + We are interested in the point that there is no additional load F and displacement U is possible. - (K + λKg0)ΔU = ΔF = 0 - (K + λKg0) = 0 + (K0 + λKg0)ΔU = ΔF = 0 Is the generalized eigenvalue problem: - (A - λB)x = 0 + (K0 + λKg0)x = 0, see :func:`smallest_buckling_factor`. :return: The factor the loads can be increased until the structure fails due to buckling. """ - system.solve() - - # buckling + # first order analysis: the stiffness matrix and the normal forces N0. The elements + # may still hold the geometric stiffness of an earlier second order calculation. + for el in system.element_map.values(): + el.compile_stiffness_matrix() + system.solve(force_linear=True) # also for non linear (plastic) elements + free = list(system._remainder_indexes) k0 = np.array(system.reduced_system_matrix) # copy + # the same matrix with the geometric stiffness of the elements added for el in system.element_map.values(): el.compile_geometric_non_linear_stiffness_matrix() - el.reset() + assemble_system_matrix(system) + assert system.system_matrix is not None + kg = np.array(system.system_matrix)[np.ix_(free, free)] - k0 + + # the elements are used again by the caller: back to the first order stiffness + for el in system.element_map.values(): + el.compile_stiffness_matrix() - system.solve() - kg = system.reduced_system_matrix - k0 - # solve (k -λkg)x = 0 + return smallest_buckling_factor(k0, kg) - # The following two lines are equivalent to the cleaner - # `scipy.linalg.eigvals(k0, kg)``, but doing this in numpy - # instead allows us to drop the very heavy scipy dependency - # that was needed for no other reason than this one line. - invkg_k0 = np.linalg.inv(kg) * k0 - eigenvalues = np.abs(np.linalg.eigvals(invkg_k0)) - return float(np.min(eigenvalues)) + +def determine_buckling_factor( + system: "SystemElements", discretize_kwargs: Optional[dict] = None +) -> float: + """ + Determine the buckling factor of the (elastic) structure for its loads. + + :param system: (SystemElements) + :param discretize_kwargs: (dict) Containing the kwargs passed to the discretize function + :return: The factor the loads can be increased until the structure fails due to buckling. + """ + buckling_system = copy.copy(system) + if discretize_kwargs is not None: + buckling_system.discretize(**discretize_kwargs) + + # the elements may be shared with the system, and hold the plastic reduction of an + # earlier calculation: use the elastic stiffness, and restore the elements afterwards + states = [ + (el, el.constitutive_matrix, list(el.nodes_plastic), list(el.plastic_stiffness)) + for el in buckling_system.element_map.values() + ] + try: + for el, _, _, _ in states: + el.reset_plastic() + el.refresh_nodes(buckling_system.node_map) + el.compile_constitutive_matrix() + el.compile_stiffness_matrix() + return det_linear_buckling(buckling_system) + finally: + for el, constitutive, nodes_plastic, plastic_stiffness in states: + el.constitutive_matrix = constitutive + el.nodes_plastic = nodes_plastic + el.plastic_stiffness = plastic_stiffness + el.compile_stiffness_matrix() def geometrically_non_linear( @@ -142,17 +321,23 @@ def geometrically_non_linear( buckling_factor: Optional[float] = None if return_buckling_factor: - buckling_system = copy.copy(system) - if discretize_kwargs is not None: - buckling_system.discretize(**discretize_kwargs) - - buckling_factor = det_linear_buckling(buckling_system) + buckling_factor = determine_buckling_factor(system, discretize_kwargs) - system.solve() + # first order analysis: the normal forces N0 (back to the first order stiffness, + # the elements may hold the geometric stiffness of an earlier calculation) + for el in system.element_map.values(): + el.compile_stiffness_matrix() + system.solve(force_linear=True) + # second order analysis for el in system.element_map.values(): el.compile_geometric_non_linear_stiffness_matrix() - system.solve() + system.solve(force_linear=True) + + # the results are second order; the elements go back to the first order stiffness, so + # that a next (linear) calculation, or another second order calculation, starts from it + for el in system.element_map.values(): + el.compile_stiffness_matrix() return buckling_factor diff --git a/anastruct/fem/system_components/util.py b/anastruct/fem/system_components/util.py index 3c35765c..ee5f7fe8 100644 --- a/anastruct/fem/system_components/util.py +++ b/anastruct/fem/system_components/util.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union +from typing import TYPE_CHECKING, Literal, Optional, Sequence, Tuple, Union import numpy as np @@ -11,9 +11,60 @@ from anastruct.fem.system import MpType, Spring, SystemElements +def dof_index(system: "SystemElements", node_id: int) -> int: + """Index of the first degree of freedom of a node in the system matrix and vectors + + The nodes are numbered 1, 2, ... in the order they are added, but removing an element can + remove a node and leave a gap in the ids. The degrees of freedom of the remaining nodes + follow each other in the order of their ids, three per node. + + Args: + system (SystemElements): System in which the node is located + node_id (int): Id of the node + + Returns: + int: Index of the displacement in x direction of the node (the next two are y and the + rotation) + """ + if system._node_index is None: + system._node_index = { + id_: position for position, id_ in enumerate(sorted(system.node_map)) + } + return system._node_index[node_id] * 3 + + +def remove_internal_hinge(system: "SystemElements", node_id: int) -> None: + """Remove a node from the internal hinges + + Args: + system (SystemElements): System in which the node is located + node_id (int): Id of the node + """ + system.internal_hinges.pop(system._internal_hinge_index.pop(node_id)) + system._internal_hinge_index = { + hinge.id: position for position, hinge in enumerate(system.internal_hinges) + } + + def check_internal_hinges(system: "SystemElements", node_id: int) -> None: """Identify internal hinges, set their hinge status + A node is an internal hinge when it is declared as one (`add_internal_hinge`), or + when every element that meets in the node has a hinge (`{1: 0}` or `{2: 0}`) at that + node, so nothing can transfer a moment. The rotation of the node is then + restrained and all the elements are released at the node. + + If one or more elements are rigidly connected in the node, they share the rotation + of the node, which is solved like any other degree of freedom (a moment load or a + rotational support at the node is carried by the rigid elements), and only the + elements with a hinge are released, through their own springs. A node with one + rigid element and released elements therefore behaves as a hinge for the rigid + element too, as long as the node carries no moment load or rotational support. + + The status follows from the springs as given by the user, which are never + modified here, and it is determined again every time, so it does not depend on + the order in which the elements were added. + Args: system (SystemElements): System in which the node is located node_id (int): Id of the node in the system @@ -21,39 +72,119 @@ def check_internal_hinges(system: "SystemElements", node_id: int) -> None: node = system.node_map[node_id] - hinges = [] - for el_id in node.elements: - el = system.element_map[el_id] - assert el.springs is not None - if node_id == el.node_id1 and 1 in el.springs and el.springs[1] == 0: - hinges.append(1) - elif node_id == el.node_id2 and 2 in el.springs and el.springs[2] == 0: - hinges.append(1) + # the elements per node of the system (node.elements is emptied by the + # post-processing, which replaces the node objects) + released = [] + for el in system.node_element_map.get(node_id, []): + end: Literal[1, 2] = 1 if node_id == el.node_id1 else 2 + released.append((el.springs or {}).get(end) == 0) + + is_hinge = node_id in system._explicit_internal_hinges or ( + len(released) > 0 and all(released) + ) + + # match by node id: the node objects in the node map are replaced by the + # post-processing, so an object from an earlier solve is not the current one + index = system._internal_hinge_index + if is_hinge: + if node_id in index: + system.internal_hinges[index[node_id]] = node else: - hinges.append(0) - - # If at least one element is connected - # and no more than one element is rigidly connected - if (1 < len(hinges) <= 1 + sum(hinges)) or (len(hinges) == 1 and sum(hinges) == 1): - system.internal_hinges.append(node) - - if node in system.internal_hinges: - node.hinge = True - - # If the elements aren't already all hinged, then set them to be - if len(hinges) - sum(hinges) >= 1: - for el_id in node.elements: - el = system.element_map[el_id] - assert el.springs is not None - if node_id == el.node_id1 and not ( - 1 in el.springs and el.springs[1] == 0 - ): - el.springs.update({1: 0}) - if node_id == el.node_id2 and not ( - 2 in el.springs and el.springs[2] == 0 - ): - el.springs.update({2: 0}) - system.element_map[el_id].springs = el.springs + index[node_id] = len(system.internal_hinges) + system.internal_hinges.append(node) + elif node_id in index: + remove_internal_hinge(system, node_id) + node.hinge = is_hinge + + +def describe_unrestrained_dof( + system: "SystemElements", node_id: int, direction: int +) -> str: + """Explain why an imposed displacement of a node can not be applied + + A displacement can only be imposed in a direction that a support restrains: in a free + direction the node moves as the structure requires, so its displacement is a result, not + a condition. This is the case for the free direction of a roller (sliding support), the + rotation of a hinged support, a spring support (which yields), and above all for an + inclined roller, which restrains only the translation normal to its free direction while + the imposed ux and uy are in the global directions. + + Args: + system (SystemElements): System in which the node is located + node_id (int): Id of the node + direction (int): The degree of freedom: 1 = ux, 2 = uy, 3 = phi_z + + Returns: + str: The explanation, with what the support at the node does restrain + """ + names = {1: "ux", 2: "uy", 3: "phi_z"} + translations = {1: "x", 2: "y"} + name = names[direction] + message = f"An imposed {name} at node {node_id} is not possible: " + + if node_id in system.inclined_roll: + # the free direction has the angle `angle`, the restrained one is normal to it + angle = -float(np.degrees(system.inclined_roll[node_id])) + return ( + message + + f"the node has an inclined roller support. It is free to move along the " + f"direction of {angle:g} degrees and restrains only the translation in the " + f"direction of {angle + 90:g} degrees, normal to it. A displacement can only be " + "imposed in a direction that a support restrains; the global ux and uy have a " + "component along the free direction, which can not be imposed (the node moves " + "there as the structure requires)." + ) + + for node, direction_i, rotate in zip( + system.supports_roll, + system.supports_roll_direction, + system.supports_roll_rotate, + ): + if node.id == node_id: + free = translations[1 if direction_i == 2 else 2] + return ( + message + + f"the node has a roller support that is free to move in the {free} " + f"direction (it restrains the {translations[direction_i]} translation" + + (" and the rotation" if not rotate else "") + + "). A displacement can only be imposed in a direction that a support " + "restrains." + ) + + if any(node.id == node_id for node in system.supports_hinged): + return ( + message + + "the node has a hinged support, which restrains the translations but not " + "the rotation. A displacement can only be imposed in a direction that a " + "support restrains." + ) + + if any(node.id == node_id for node in system.supports_rotational): + return ( + message + + "the node has a rotational support, which restrains only the rotation. A " + "displacement can only be imposed in a direction that a support restrains." + ) + + for supports in ( + system.supports_spring_x, + system.supports_spring_y, + system.supports_spring_z, + ): + if any(node.id == node_id for node, _ in supports): + return ( + message + + "the node has a spring support, which yields instead of restraining. A " + "displacement can only be imposed in a direction that a rigid support " + "restrains." + ) + + return ( + message + + "no support restrains that degree of freedom of the node. A displacement can " + "only be imposed in a direction that a support restrains (fixed, hinged, roller or " + "rotational support), and the support must be added to the system." + ) def append_node_id( @@ -76,6 +207,7 @@ def append_node_id( system.node_map[node_id1] = Node(node_id1, vertex=point_1) if node_id2 not in system.node_map: system.node_map[node_id2] = Node(node_id2, vertex=point_2) + system._node_index = None def remove_node_id( @@ -92,40 +224,44 @@ def remove_node_id( system (SystemElements): System in which the node is located node_id (int): Node id of the node """ - node = system.node_map[node_id] system._vertices.pop(system.node_map[node_id].vertex) system.node_map.pop(node_id) + system._node_index = None if node_id in system.loads_point: system.loads_point.pop(node_id) if node_id in system.loads_moment: system.loads_moment.pop(node_id) - if node in system.supports_fixed: - system.supports_fixed.remove(node) - if node in system.supports_hinged: - system.supports_hinged.remove(node) - if node in system.supports_rotational: - system.supports_rotational.remove(node) - if node in system.internal_hinges: - system.internal_hinges.remove(node) - if node in system.supports_roll: - ind = system.supports_roll.index(node) - system.supports_roll.remove(node) + # (the nodes of the supports are compared by id: after a solve the node objects of the + # node map are replaced by copies with the results) + for supports in ( + system.supports_fixed, + system.supports_hinged, + system.supports_rotational, + ): + supports[:] = [n for n in supports if n.id != node_id] + if node_id in system._internal_hinge_index: + remove_internal_hinge(system, node_id) + system._explicit_internal_hinges.discard(node_id) + for ind in reversed( + [i for i, n in enumerate(system.supports_roll) if n.id == node_id] + ): + system.supports_roll.pop(ind) system.supports_roll_direction.pop(ind) system.supports_roll_rotate.pop(ind) if node_id in system.inclined_roll: system.inclined_roll.pop(node_id) - if node in [item[0] for item in system.supports_spring_x]: - ind = [item[0] for item in system.supports_spring_x].index(node) - system.supports_spring_x.pop(ind) - if node in [item[0] for item in system.supports_spring_y]: - ind = [item[0] for item in system.supports_spring_y].index(node) - system.supports_spring_y.pop(ind) - if node in [item[0] for item in system.supports_spring_z]: - ind = [item[0] for item in system.supports_spring_z].index(node) - system.supports_spring_z.pop(ind) - if node_id in [item[0] for item in system.supports_spring_args]: - ind = [item[0] for item in system.supports_spring_args].index(node_id) - system.supports_spring_args.pop(ind) + for springs in ( + system.supports_spring_x, + system.supports_spring_y, + system.supports_spring_z, + ): + springs[:] = [item for item in springs if item[0].id != node_id] + system.supports_spring_args[:] = [ + item for item in system.supports_spring_args if item[0] != node_id + ] + for key in [key for key in system.system_spring_map if key[0] == node_id]: + system.system_spring_map.pop(key) + system.loads_displacement.pop(node_id, None) def det_vertices( @@ -197,7 +333,14 @@ def det_node_ids( if k in system._vertices: node_id = system._vertices[k] else: - node_id = len(system._vertices) + 1 + # (the ids have gaps after remove_element, so the count would reuse an id) + node_id = ( + max( + max(system.node_map, default=0), + max(system._vertices.values(), default=0), + ) + + 1 + ) system._vertices[k] = node_id node_ids.append(node_id) return node_ids[0], node_ids[1] @@ -222,8 +365,8 @@ def add_node( int: The node id of the added (or existing) node """ if point in system._vertices: + existing_node_id = system._vertices[point] if node_id is not None: - existing_node_id = system._vertices[point] if existing_node_id != node_id: raise FEMException( "Flawed inputs", @@ -242,6 +385,7 @@ def add_node( system._vertices[point] = node_id system.node_map[node_id] = Node(node_id, vertex=point) + system._node_index = None return node_id @@ -313,6 +457,8 @@ def force_elements_orientation( assert isinstance( spring, dict ), "The spring parameter should be a dictionary." + # do not modify the dictionary of the caller, it may be shared + spring = dict(spring) if 1 in spring and 2 in spring: spring[1], spring[2] = spring[2], spring[1] elif 1 in spring: @@ -321,6 +467,7 @@ def force_elements_orientation( spring[1] = spring.pop(2) if mp is not None: + mp = dict(mp) if 1 in mp and 2 in mp: mp[1], mp[2] = mp[2], mp[1] elif 1 in mp: diff --git a/anastruct/fem/util/load.py b/anastruct/fem/util/load.py index 64c8ac85..cc9f870a 100644 --- a/anastruct/fem/util/load.py +++ b/anastruct/fem/util/load.py @@ -1,4 +1,5 @@ import copy +import math import pprint from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Union @@ -94,10 +95,187 @@ def dead_load( self.c += 1 self.spec[f"dead_load-{self.c}"] = {"element_id": element_id, "g": g} + def imposed_displacement( + self, + node_id: int, + ux: Optional[float] = None, + uy: Optional[float] = None, + phi_z: Optional[float] = None, + ) -> None: + """ + Apply an imposed displacement (support settlement) and/or rotation to a node. + + The imposed values are multiplied by the load factor of the load combination, + so a settlement belongs to a single load case and is not counted again in the + other cases. + + :param node_id: (int) representing the node ID + :param ux: (flt) Imposed displacement in the global x direction + :param uy: (flt) Imposed displacement in the global y direction + :param phi_z: (flt) Imposed rotation about the global z-axis in radians + """ + self.c += 1 + self.spec[f"imposed_displacement-{self.c}"] = { + "node_id": node_id, + "ux": ux, + "uy": uy, + "phi_z": phi_z, + } + + def thermal_load( + self, + element_id: Union[int, Sequence[int]], + delta_t: Union[float, Sequence[float]], + alpha: Union[float, Sequence[float]], + delta_t_gradient: Optional[Union[float, Sequence[float]]] = None, + h: Optional[Union[float, Sequence[float]]] = None, + ) -> None: + """ + Apply a thermal load to an element. + + :param element_id: (int/ list) representing the element ID + :param delta_t: (flt/ list) Uniform temperature change of the element + :param alpha: (flt/ list) Coefficient of thermal expansion of the element material + :param delta_t_gradient: (flt/ list) Temperature difference over the section depth. + Requires `h`. + :param h: (flt/ list) Section depth over which `delta_t_gradient` acts + """ + self.c += 1 + self.spec[f"thermal_load-{self.c}"] = { + "element_id": element_id, + "delta_t": delta_t, + "alpha": alpha, + "delta_t_gradient": delta_t_gradient, + "h": h, + } + def __str__(self) -> str: return f"Loadcase {self.name}:\n" + pprint.pformat(self.spec) +def _clean(value: float) -> float: + """Zero for a value at rounding level (the decomposition of a load in an angle)""" + return 0.0 if abs(value) < 1e-12 else value + + +def _add_loads( + target: "SystemElements", case: "SystemElements", base: "SystemElements" +) -> None: + """Add the loads that a load case adds to the base system to the loads of `target` + + The loads of a load case replace the loads of the base system at the same node or + element, so the added loads are those of the case minus those of the base system. The + values are the stored ones, which contain the load factor of the case and the + orientation of the y-axis. + + Args: + target (SystemElements): System with the loads of the earlier load cases + case (SystemElements): Copy of the base system with the load case applied + base (SystemElements): The base system + """ + for node_id, (fx, fy) in case.loads_point.items(): + base_fx, base_fy = base.loads_point.get(node_id, (0.0, 0.0)) + target_fx, target_fy = target.loads_point.get(node_id, (0.0, 0.0)) + target.loads_point[node_id] = ( + target_fx + fx - base_fx, + target_fy + fy - base_fy, + ) + + for node_id, moment in case.loads_moment.items(): + target.loads_moment[node_id] = ( + target.loads_moment.get(node_id, 0.0) + + moment + - base.loads_moment.get(node_id, 0.0) + ) + + for element_id, element in case.element_map.items(): + base_element = base.element_map[element_id] + target_element = target.element_map[element_id] + + # a dead load of the case is added to the self-weight of the element + added_dead_load = element.dead_load - base_element.dead_load + if added_dead_load != 0: + target_element.dead_load += added_dead_load + target.loads_dead_load.add(element_id) + + # distributed loads, perpendicular and parallel to the element; the self-weight + # is part of both properties, so it is counted once, in the base system + # (a dead load of the case was added above, so it is not part of the added q-loads) + dead_perp = added_dead_load * math.cos(target_element.angle) + dead_par = -added_dead_load * math.sin(target_element.angle) + added_perp = [ + _clean(a - b - dead_perp) + for a, b in zip(element.all_qp_load, base_element.all_qp_load) + ] + added_par = [ + _clean(a - b - dead_par) + for a, b in zip(element.all_qn_load, base_element.all_qn_load) + ] + if any(value != 0 for value in added_perp + added_par): + if target_element.q_load == (0.0, 0.0) and target_element.q_perp_load == ( + 0.0, + 0.0, + ): + # the first distributed load on this element: keep its decomposition + target_element.q_load = element.q_load + target_element.q_perp_load = element.q_perp_load + target_element.q_angle = element.q_angle + target_element.q_direction = element.q_direction + else: + angle = target_element.angle + dead_load = target_element.dead_load + total_perp = [ + a + b for a, b in zip(target_element.all_qp_load, added_perp) + ] + total_par = [ + a + b for a, b in zip(target_element.all_qn_load, added_par) + ] + # the sum, as a load in the direction of the element: + # all_qp_load = q_perp + g * cos, all_qn_load = -q - g * sin + target_element.q_angle = angle + target_element.q_direction = "angle" + # (values at rounding level, from the decomposition in an angle, are zero) + target_element.q_perp_load = ( + _clean(total_perp[0] - dead_load * math.cos(angle)), + _clean(total_perp[1] - dead_load * math.cos(angle)), + ) + target_element.q_load = ( + _clean(-(total_par[0] + dead_load * math.sin(angle))), + _clean(-(total_par[1] + dead_load * math.sin(angle))), + ) + target.loads_q[element_id] = case.loads_q.get( + element_id, target.loads_q.get(element_id, [(0.0, 0.0), (0.0, 0.0)]) + ) + target.plotter.max_q = max(target.plotter.max_q, case.plotter.max_q) + + for element_id, (strain, curvature) in case.loads_temperature.items(): + base_strain, base_curvature = base.loads_temperature.get(element_id, (0.0, 0.0)) + target_strain, target_curvature = target.loads_temperature.get( + element_id, (0.0, 0.0) + ) + temperature_load = ( + target_strain + strain - base_strain, + target_curvature + curvature - base_curvature, + ) + target.loads_temperature[element_id] = temperature_load + target.element_map[element_id].temperature_load = temperature_load + + for node_id, displacements in case.loads_displacement.items(): + base_displacements = base.loads_displacement.get(node_id, (None, None, None)) + target_displacements = target.loads_displacement.get( + node_id, (None, None, None) + ) + combined = [] + for value, base_value, target_value in zip( + displacements, base_displacements, target_displacements + ): + if value is None: + combined.append(target_value) + else: + combined.append((target_value or 0.0) + value - (base_value or 0.0)) + target.loads_displacement[node_id] = (combined[0], combined[1], combined[2]) + + class LoadCombination: def __init__(self, name: str): self.name: str = name @@ -144,7 +322,16 @@ def solve( buckling factor. :return: (ResultObject) - Development **kwargs: + The results of the load cases are the results of every load case on its own; the + loads of the system itself are part of each of them, and a load of the case at the same + node or element replaces them. The 'combination' is the result of one calculation of the + system with the loads of all the load cases, each multiplied by its factor, added to the + loads of the system itself, which count once. This is the same as the sum of + the load cases for a linear calculation, and the only correct one if the calculation is + not linear (second order effects, or non linear nodes without `force_linear`): the + combination then has its own buckling factor, for the combined loads. + + Development **kwargs (passed to the solve of every load case and of the combination): :param naked: (bool) Whether or not to run the solve function without doing post processing. :param discretize_kwargs: When doing a geometric non linear analysis you can reduce or @@ -155,6 +342,7 @@ def solve( results = {} for lc, factor in self.spec.values(): ss = copy.deepcopy(system) + ss._invalidate_solution() # also when the system has been solved before ss.load_factor = factor ss.apply_load_case(lc) @@ -163,16 +351,24 @@ def solve( ) results[lc.name] = ss - ss_combination = copy.deepcopy(system) - ss_combination.post_processor.node_results_system() - for lc_ss in results.values(): - for k in ss_combination.element_map: - ss_combination.element_map[k] = ( - ss_combination.element_map[k] + lc_ss.element_map[k] - ) - for k in ss_combination.node_map: - ss_combination.node_map[k].add_results(lc_ss.node_map[k]) - ss_combination.post_processor.reaction_forces() - - results["combination"] = ss_combination + # the combination is one calculation with the loads of all the load cases: the + # results of non linear calculations can not be superposed, and for a linear one it + # is the same, while the loads of the system itself count once + ss_combined = copy.deepcopy(system) + ss_combined._invalidate_solution() + # every load case is applied to the system without its loads, so that the loads of the + # case are added to the loads of the system (in the result of a load case on its own + # they replace the loads of the system at the same node or element) + unloaded = copy.deepcopy(system) + unloaded._invalidate_solution() + unloaded.remove_loads(dead_load=True) + for lc, factor in self.spec.values(): + ss = copy.deepcopy(unloaded) + ss.load_factor = factor + ss.apply_load_case(lc) + _add_loads(ss_combined, ss, unloaded) + ss_combined.solve( + force_linear, verbosity, max_iter, geometrical_non_linear, **kwargs + ) + results["combination"] = ss_combined return results diff --git a/anastruct/vertex.py b/anastruct/vertex.py index 679efb5a..2e0ea834 100644 --- a/anastruct/vertex.py +++ b/anastruct/vertex.py @@ -1,7 +1,7 @@ from __future__ import annotations import math -from typing import TYPE_CHECKING, Sequence, Union +from typing import TYPE_CHECKING, Sequence, SupportsFloat, Union import numpy as np @@ -9,6 +9,23 @@ from anastruct._types import NumberLike, VertexLike +def _snap(value: SupportsFloat) -> float: + """Round a coordinate to 12 significant digits + + The coordinates are stored in double precision. Rounding to 12 digits removes the + rounding noise of computed coordinates (3.0000000000000004 for 3), so that points that + are the same location are the same Vertex (the nodes of a system are identified by the + Vertex), at any scale of the model. -0.0 becomes 0.0. + + Args: + value (SupportsFloat): Coordinate + + Returns: + float: The rounded coordinate + """ + return float(f"{float(value):.12g}") + 0.0 + + class Vertex: """ Utility point in 2D. @@ -27,18 +44,18 @@ def __init__( y (Union[NumberLike, None], optional): Y coordinate. Defaults to None. """ if isinstance(x, Vertex): - self.coordinates: np.ndarray = np.array(x.coordinates, dtype=np.float32) + self.coordinates: np.ndarray = np.array(x.coordinates, dtype=np.float64) elif ( isinstance(x, (Sequence, np.ndarray)) and len(x) == 2 and isinstance(x[0], (float, int, np.number)) and isinstance(x[1], (float, int, np.number)) ): - self.coordinates = np.array([x[0], x[1]], dtype=np.float32) + self.coordinates = np.array([_snap(x[0]), _snap(x[1])], dtype=np.float64) elif isinstance(x, (float, int, np.number)) and isinstance( y, (float, int, np.number) ): - self.coordinates = np.array([x, y], dtype=np.float32) + self.coordinates = np.array([_snap(x), _snap(y)], dtype=np.float64) else: raise TypeError( "Points must be convertable to a Vertex object: (x, y) or [x, y] or np.array([x, y]) or Vertex(x, y)" diff --git a/docs/source/calculation.rst b/docs/source/calculation.rst index c637d83f..f4433510 100644 --- a/docs/source/calculation.rst +++ b/docs/source/calculation.rst @@ -24,4 +24,60 @@ to pass a `discretize_kwargs` dictionary. With this dictionary you can set the amount of discretization elements generated during the geometrical non linear calculation. This calculation is an approximation and gets more accurate -with more discretization elements. \ No newline at end of file +with more discretization elements. + +Buckling factor +............... + +The calculation also determines the buckling factor, :code:`ss.buckling_factor`: the factor by which all the loads can +be increased until the structure buckles. It is the smallest positive :math:`\lambda` of the generalized eigenvalue +problem :math:`(K_0 + \lambda K_g) x = 0`, with :math:`K_0` the stiffness matrix of the first order analysis and +:math:`K_g` the geometric stiffness matrix for the normal forces of that analysis. Only compression gives a buckling +mode; if no compressive normal force acts on the free degrees of freedom the buckling factor is infinite +(:code:`float("inf")`). + +The geometric stiffness matrix of a cubic beam element is an approximation, so the factor is found from above and +converges with the number of elements (at the end of an element with a hinge or a rotational spring the stiffness is +condensed together with the geometric stiffness, so one element per member is within a few tenths of a percent): one element gives :math:`12 EI/L^2` for a column pinned at both ends, 20 elements +the Euler load :math:`\pi^2 EI/L^2` within 0.01 %. Hinges and rotational springs at the ends of an element (see +:ref:`End releases `) are accounted for. + +.. code-block:: python + + ss = SystemElements(EI=5e3, EA=1e6) + ss.add_element([[0, 0], [0, 10]]) # a column; its top node is at y = 10 + ss.add_support_hinged(1) + ss.add_support_roll(2, "y") + ss.point_load(2, Fy=-1) # a negative Fy pushes the top towards the base: compression + ss.solve(geometrical_non_linear=True, discretize_kwargs=dict(n=20)) + print(ss.buckling_factor) # 493.48, the Euler load of 1 * pi**2 * EI / L**2 + +Non linear nodes and second order effects +......................................... + +A second order calculation can be combined with non linear nodes (:code:`mp=`): every step of the iteration for the +plastic moments is a second order analysis, so the compression increases the moments and the displacements while the +moments at the plastic hinges stay at the plastic moment. The buckling factor is that of the elastic structure. + +A plastic hinge is a rotational spring in series with the element (and with a rotational spring given by the +user). Its stiffness is iterated with the secant :code:`k = k * mp / |M|`, so the end moment converges to the +plastic moment and the moment is redistributed exactly. A hinge that is unloaded below :code:`mp` becomes elastic +again. If the plastic hinges turn the structure into a mechanism a :code:`FEMException` is raised. + +Buckling of a bar of a truss +............................ + +A truss element has no bending stiffness, so a bar of a truss does not buckle between its nodes. To find the buckling +load of a bar, model it as an element with hinges at both ends. It then carries only an axial force, like a truss +element, and :code:`discretize` divides it with the hinges at its ends only, so that the bar can buckle between the +new nodes. + +.. code-block:: python + + ss = SystemElements(EA=1e6, EI=5e3) + ss.add_element([[0, 0], [2, 2]], spring={1: 0, 2: 0}) + ss.add_element([[2, 2], [4, 0]], spring={1: 0, 2: 0}) + ss.add_support_hinged([1, 3]) + ss.point_load(2, Fy=-1) + ss.solve(geometrical_non_linear=True, discretize_kwargs=dict(n=20)) + print(ss.buckling_factor) # the Euler load of a bar divided by its normal force: 8723.6 diff --git a/docs/source/elements.rst b/docs/source/elements.rst index e11b5a18..9aa939e8 100644 --- a/docs/source/elements.rst +++ b/docs/source/elements.rst @@ -93,10 +93,54 @@ add_truss_element .. automethod:: anastruct.fem.system.SystemElements.add_truss_element +.. _end-releases: + +End releases: hinges and rotational springs +------------------------------------------- + +The ends of a standard element can be released with the :code:`spring` argument of :code:`add_element`, +:code:`add_multiple_elements` and :code:`add_element_grid`. The keys are the element nodes (1 and 2), the values the +rotational stiffness :code:`k` of the connection (moment per radian). + +* :code:`k = 0` is a hinge. The end carries no bending moment. An element with one hinge has the rotational stiffness + :math:`3EI/l` instead of :math:`4EI/l`; the rotation of the hinge is eliminated by static condensation. +* :code:`k > 0` is a rotational spring in series with the element: the flexibilities add, + :math:`C = C_{element} + \mathrm{diag}(1/k_1, 1/k_2)`. A very large :code:`k` approaches a rigid connection. +* A node is an internal hinge when it is declared with :code:`add_internal_hinge`, or when every element that meets in + the node has a hinge there (:code:`{1: 0}` or :code:`{2: 0}`). All the elements are then released at the node. If one + or more elements are rigidly connected, they share the rotation of the node, which is solved like any other degree of + freedom (a moment load or a rotational support at the node is carried by the rigid elements); only the elements with + a hinge are released, through their own springs. The result does not depend on the order in which the elements were + added, and the :code:`spring` dictionaries given by the user are never modified. + +.. code-block:: python + + ss = SystemElements(EA=1e9, EI=1e4) + # fixed at node 1, hinge at the end of the element: M = q * L**2 / 8 + ss.add_element([[0, 0], [6, 0]], spring={2: 0}) + ss.add_support_fixed(1) + ss.add_support_hinged(2) + ss.q_load(-10, 1) + ss.solve() + + # end spring of 50 kNm/rad: tip deflection = P * L**3 / (3 * EI) + P * L**2 / k + ss = SystemElements(EA=1e9, EI=1e4) + ss.add_element([[0, 0], [4, 0]], spring={1: 50}) + ss.add_support_fixed(1) + ss.point_load(2, Fy=-10) + ss.solve() + +Mechanical loads, thermal loads and imposed displacements all use the same condensed stiffness, so releases are exact +for each of them. + Discretization -------------- -You can discretize an element in multiple smaller elements with the discretize method. +You can discretize an element in multiple smaller elements with the discretize method. The supports, loads, imposed +displacements and internal hinges are carried over. Hinges, rotational springs and plastic moments stay at the ends of +the original element. Truss elements are not divided, because the nodes between collinear truss elements would be +mechanisms. Note that the ids of the nodes and elements of the new mesh differ from the original ones; use +:code:`find_node_id` to find a node by its location. .. automethod:: anastruct.fem.system.SystemElements.discretize diff --git a/docs/source/loadcases.rst b/docs/source/loadcases.rst index b4d6a51a..942e69f1 100644 --- a/docs/source/loadcases.rst +++ b/docs/source/loadcases.rst @@ -85,6 +85,14 @@ by calling the `solve` method and passing our `SystemElements` model. The `solve the keys are the load cases and the values are the unique `SystemElement` objects for every load case. There is also a key `combination` in the results dictionary. +The `combination` is the result of one calculation of the system with the loads of all the load cases, each +multiplied by its factor. For a linear calculation this is the sum of the load cases, but the results of a non linear +calculation (second order effects with `geometrical_non_linear=True`, or non linear nodes with `mp=`) can not be +superposed, so this is the only correct way. The combination has its own `buckling_factor`, for the combined loads. +The loads that were applied to the system itself, such as self-weights, are part of the result of every load case (a +load of the case at the same node or element replaces them there) and count once in the combination, to which the loads +of all the load cases are added. + .. code-block:: python results = combination.solve(ss) diff --git a/docs/source/loads.rst b/docs/source/loads.rst index 350d13d6..55fa98be 100644 --- a/docs/source/loads.rst +++ b/docs/source/loads.rst @@ -67,6 +67,27 @@ Example .. image:: img/loads/q-load.png +thermal loads +############# + +A uniform temperature change gives a free axial strain ``alpha * delta_t``, a temperature gradient over the section +depth gives a free curvature ``alpha * delta_t_gradient / h``. A positive gradient means a warmer upper face of a +horizontal element. Thermal loads can also be used in a :class:`.LoadCase`. + +.. automethod:: anastruct.fem.system.SystemElements.thermal_load + +Example +....... + +.. code-block:: python + + ss = SystemElements(EA=1e6, EI=1e4) + ss.add_element([[0, 0], [10, 0]]) + ss.add_support_fixed([1, 2]) + ss.thermal_load(element_id=1, delta_t=20, alpha=1.2e-5, delta_t_gradient=15, h=0.5) + ss.solve() + + Remove loads ------------ diff --git a/docs/source/post_processing.rst b/docs/source/post_processing.rst index 3c499f74..f9d73710 100644 --- a/docs/source/post_processing.rst +++ b/docs/source/post_processing.rst @@ -47,6 +47,12 @@ Example We can use this method to query the reaction forces of the supports. +The support nodes in :code:`ss.reaction_forces` also hold the displacements of the node (:code:`ux`, :code:`uy`, +:code:`phi_z`). They are the real displacements, so they are not zero in a direction that the support leaves free (the +rotation of a hinged support, or the free direction of a roller). :code:`reaction_forces[i].Fx` is the force of the +support on the structure in the +x direction and :code:`reaction_forces[i].Fy` the same force counted positive +downwards. + .. code-block:: python print(ss.get_node_results_system(node_id=1)['Fy'], ss.get_node_results_system(node_id=-1)['Fy']) diff --git a/docs/source/supports.rst b/docs/source/supports.rst index 65df8c2d..bd05e11a 100644 --- a/docs/source/supports.rst +++ b/docs/source/supports.rst @@ -73,4 +73,54 @@ Example .. image:: img/supports/spring.png -.. automethod:: anastruct.fem.system.SystemElements.add_support_spring \ No newline at end of file +.. automethod:: anastruct.fem.system.SystemElements.add_support_spring + + +Imposed displacements +##################### + +A support settlement or an imposed rotation is prescribed to a degree of freedom that is restrained by a support. +Impose the displacements before the first :meth:`~anastruct.fem.system.SystemElements.solve`. In a +:class:`.LoadCombination` use :meth:`.LoadCase.imposed_displacement`, so that the settlement belongs to one load case. + +.. automethod:: anastruct.fem.system.SystemElements.imposed_displacement + +Like a load :code:`Fy`, a positive :code:`uy` is in the +y direction (upwards), so a settlement is negative; the +rotation :code:`phi_z` is positive like a moment load :code:`Tz`, and is reported with the opposite sign by +:code:`get_node_displacements`. + +Example +....... + +.. code-block:: python + + ss = SystemElements(EA=1e6, EI=1e4) + ss.add_element([[0, 0], [10, 0]]) + ss.add_support_fixed(1) + ss.add_support_roll(2) + ss.imposed_displacement(node_id=2, uy=-0.02) # 20 mm downwards (uy is positive upwards, like Fy) + ss.solve() + + +Inclined roller supports +######################## + +A roll support with an :code:`angle` is inclined: the support is free in the direction of the angle (relative to the +global x-axis) and restrains the translation normal to it. Loads can be placed at the node of an inclined roller. The +reaction of the support is normal to the free direction. + +An imposed displacement is possible only in a direction that a support restrains: in a free direction the node moves as +the structure requires, so its displacement is a result and can not be a condition. That is why a displacement can not +be imposed in the free direction of a roller, for the rotation of a hinged support, at a spring support (which yields), +or at a node without a support. An inclined roller restrains only the translation normal to its free direction, while +the imposed :code:`ux` and :code:`uy` are in the global directions and have a component along the free direction, so +imposing them on an inclined roller is not possible either. In all these cases :code:`solve` (or +:code:`imposed_displacement` for an inclined roller) raises a :code:`FEMException` whose message explains which support +restrains what. + +Changing the model after a calculation +###################################### + +Supports, elements and internal hinges can be added after a calculation (and :code:`insert_node` and +:code:`remove_element` can be used). The solution is then reset, so that the next :code:`solve` processes the changed +model. diff --git a/examples/ex_27_imposed_displacement.py b/examples/ex_27_imposed_displacement.py new file mode 100644 index 00000000..4cf07849 --- /dev/null +++ b/examples/ex_27_imposed_displacement.py @@ -0,0 +1,49 @@ +import math + +from anastruct.fem.system import SystemElements + +EI = 1e4 +L = 10.0 + +# Propped cantilever with a support settlement of 20 mm at the roller. Like a load Fy, uy +# is positive in the +y direction (upwards), so a settlement is a negative uy. +ss = SystemElements(EA=1e6, EI=EI) +ss.add_element(location=[(0, 0), (L, 0)]) +ss.add_support_fixed(node_id=1) +ss.add_support_roll(node_id=2) +ss.imposed_displacement(node_id=2, uy=-0.02) + +# Fixed-fixed beam with an imposed rotation of 0.01 rad at the right end. +ss2 = SystemElements(EA=1e6, EI=EI) +ss2.add_element(location=[(0, 0), (L, 0)]) +ss2.add_support_fixed(node_id=[1, 2]) +ss2.imposed_displacement(node_id=2, phi_z=0.01) + + +def check(name, value, expected): + """Print a result next to its analytical value and fail if they differ.""" + print(f"{name}: {value:.4f} (analytical: {expected:.4f})") + assert math.isclose(value, expected, rel_tol=1e-6, abs_tol=1e-9), name + + +if __name__ == "__main__": + delta = 0.02 # settlement + phi = 0.01 # imposed rotation + + ss.solve() + print("Settlement of 20 mm at node 2:") + # propped cantilever: R = 3 EI delta / L**3, M = 3 EI delta / L**2 + check("Roller reaction Fy", ss.reaction_forces[2].Fy, 3 * EI * delta / L**3) + check("Fixed end moment Tz", ss.reaction_forces[1].Tz, 3 * EI * delta / L**2) + ss.show_bending_moment() + + ss2.solve() + print("\nImposed rotation of 0.01 rad at node 2:") + # fixed-fixed beam: the far end gets 2 EI phi / L, the end that rotates 4 EI phi / L + check("Moment at the far end (node 1)", ss2.reaction_forces[1].Tz, 2 * EI * phi / L) + check( + "Moment at the rotated end (node 2)", + ss2.reaction_forces[2].Tz, + 4 * EI * phi / L, + ) + ss2.show_bending_moment() diff --git a/examples/ex_28_thermal_load.py b/examples/ex_28_thermal_load.py new file mode 100644 index 00000000..63f5ba43 --- /dev/null +++ b/examples/ex_28_thermal_load.py @@ -0,0 +1,66 @@ +import math + +from anastruct.fem.system import SystemElements + +EA = 1e6 +EI = 1e4 +L = 10.0 +ALPHA = 1.2e-5 + +# Fixed-fixed beam with a uniform temperature increase of 20 degrees. +# The restrained free expansion causes a constant compression force +# N = -EA * alpha * dT. +ss = SystemElements(EA=EA, EI=EI) +ss.add_element(location=[(0, 0), (L, 0)]) +ss.add_support_fixed(node_id=[1, 2]) +ss.thermal_load(element_id=1, delta_t=20, alpha=ALPHA) + +# Fixed-fixed beam with a linear temperature gradient of 15 degrees over a +# section depth of 0.5 m (upper face warmer). The restrained free curvature +# kappa = alpha * dT_gradient / h causes a constant bending moment +# M = EI * alpha * dT_gradient / h. +ss2 = SystemElements(EA=EA, EI=EI) +ss2.add_element(location=[(0, 0), (L, 0)]) +ss2.add_support_fixed(node_id=[1, 2]) +ss2.thermal_load(element_id=1, delta_t=0, alpha=ALPHA, delta_t_gradient=15, h=0.5) + +# Cantilever with the same gradient curves freely: the tip deflects by +# kappa * L**2 / 2 and no internal forces develop. +ss3 = SystemElements(EA=EA, EI=EI) +ss3.add_element(location=[(0, 0), (L, 0)]) +ss3.add_support_fixed(node_id=1) +ss3.thermal_load(element_id=1, delta_t=0, alpha=ALPHA, delta_t_gradient=15, h=0.5) + + +def check(name, value, expected): + """Print a result next to its analytical value and fail if they differ.""" + print(f"{name}: {value:.6f} (analytical: {expected:.6f})") + assert math.isclose(value, expected, rel_tol=1e-6, abs_tol=1e-9), name + + +if __name__ == "__main__": + delta_t = 20 + kappa = ALPHA * 15 / 0.5 # free curvature of the gradient + + ss.solve() + print("Uniform dT on fixed-fixed beam:") + # the supports push inwards with the compression force N = EA alpha dT + check("Axial reaction at node 1", ss.reaction_forces[1].Fx, EA * ALPHA * delta_t) + check("Axial reaction at node 2", ss.reaction_forces[2].Fx, -EA * ALPHA * delta_t) + ss.show_axial_force() + + ss2.solve() + print("\nTemperature gradient on fixed-fixed beam:") + # constant moment EI kappa (sagging is negative in anaStruct), no shear force + check("End moment at node 1", ss2.reaction_forces[1].Tz, -EI * kappa) + check("End moment at node 2", ss2.reaction_forces[2].Tz, EI * kappa) + ss2.show_bending_moment() + + ss3.solve() + print("\nTemperature gradient on cantilever:") + tip = ss3.get_node_displacements(2) + # the upper fibres are longer: the tip goes down by kappa L**2 / 2 and rotates by kappa L + check("Tip displacement uy", tip["uy"], -kappa * L**2 / 2) + check("Tip rotation phi_z", tip["phi_z"], kappa * L) + check("Reaction Fy (no internal forces)", ss3.reaction_forces[1].Fy, 0.0) + ss3.show_displacement() diff --git a/examples/ex_29_thermal_loadcombination.py b/examples/ex_29_thermal_loadcombination.py new file mode 100644 index 00000000..5de3884c --- /dev/null +++ b/examples/ex_29_thermal_loadcombination.py @@ -0,0 +1,68 @@ +import math + +import matplotlib.pyplot as plt + +from anastruct import LoadCase, LoadCombination +from anastruct.fem.system import SystemElements + +EI = 1e4 +L = 6.0 # length of each span +ALPHA = 1.2e-5 + +# Two-span continuous beam exposed to a uniform temperature change and a +# temperature gradient, combined with a q-load in a load combination. +ss = SystemElements(EA=1e6, EI=EI) +ss.add_element(location=[(0, 0), (L, 0)]) +ss.add_element(location=[(L, 0), (2 * L, 0)]) +ss.add_support_hinged(node_id=1) +ss.add_support_roll(node_id=2) +ss.add_support_roll(node_id=3) + +lc_thermal = LoadCase("thermal") +lc_thermal.thermal_load(element_id=[1, 2], delta_t=15, alpha=ALPHA) + +lc_gradient = LoadCase("gradient") +lc_gradient.thermal_load( + element_id=[1, 2], delta_t=0, alpha=ALPHA, delta_t_gradient=10, h=0.5 +) + +lc_traffic = LoadCase("traffic") +lc_traffic.q_load(q=-10, element_id=[1, 2]) # negative q acts downwards by default + +combination = LoadCombination("SLS") +combination.add_load_case(lc_thermal, factor=1.0) +combination.add_load_case(lc_gradient, factor=1.0) +combination.add_load_case(lc_traffic, factor=1.0) + + +def check(name, value, expected): + """Print a result next to its analytical value and fail if they differ.""" + print(f"{name}: {value:.4f} (analytical: {expected:.4f})") + assert math.isclose(value, expected, rel_tol=1e-6, abs_tol=1e-6), name + + +if __name__ == "__main__": + results = combination.solve(ss) + + # Analytical reactions of the middle support of a two-span beam with equal spans L: + kappa = ALPHA * 10 / 0.5 # free curvature of the gradient + expected = { + # a uniform temperature change expands the beam freely on the rollers + "thermal": 0.0, + # constant curvature kappa: R = 3 EI kappa / L (upwards) + "gradient": 3 * EI * kappa / L, + # uniform load q on both spans: R = 5 q L / 4 (q = -10 acts downwards) + "traffic": 5 * -10 * L / 4, + } + # the combination is the sum of the load cases (all factors are 1) + expected["combination"] = sum(expected.values()) + + for name, system in results.items(): + check( + f"{name} -> middle support reaction Fy", + system.reaction_forces[2].Fy, + expected[name], + ) + system.show_bending_moment(show=False) + plt.title(name) + plt.show() # type: ignore diff --git a/tests/test_buckling.py b/tests/test_buckling.py new file mode 100644 index 00000000..76bcdd97 --- /dev/null +++ b/tests/test_buckling.py @@ -0,0 +1,323 @@ +import copy + +import numpy as np +from pytest import approx + +from anastruct import SystemElements +from anastruct.fem.elements import geometric_stiffness_matrix +from anastruct.fem.system_components.solver import smallest_buckling_factor + +""" +NOTE: These tests validate the buckling factor of `solve(geometrical_non_linear=True)` +against the Euler buckling loads. General definitions: +- L = column length +- EI = bending stiffness +- P = 1 is the load on the column, so that the buckling factor equals the buckling load +- Pcr = pi**2 * EI / (mu * L)**2, with the effective length factor mu: 1 (pinned-pinned), + 2 (cantilever), 0.699 (fixed-pinned) and 0.5 (fixed-fixed) + +The geometric stiffness matrix of an element is exact for a prismatic beam with a constant +normal force only for a cubic displacement field, so a column needs to be discretized to +find the Euler load (the factor is found from above, and converges with the number of +elements). + +The tests are plain test functions (not nested describe/context blocks), so that every +assertion is guaranteed to be executed. +""" + +EI = 5.0e3 +EA = 1.0e6 +L = 10.0 +EULER = np.pi**2 * EI / L**2 # pinned-pinned +FIXED_PINNED = 20.190728556 * EI / L**2 # 2.0457 * pi**2 * EI / L**2 + + +def column(kind, load=-1.0, **element_kwargs): + system = SystemElements(EI=EI, EA=EA) + system.add_element([[0, 0], [0, L]], **element_kwargs) + if kind == "pinned": + system.add_support_hinged(1) + system.add_support_roll(2, "y") + elif kind == "cantilever": + system.add_support_fixed(1) + elif kind == "fixed-pinned": + system.add_support_fixed(1) + system.add_support_roll(2, "y") + elif kind == "fixed-fixed": + system.add_support_fixed(1) + system.add_support_roll(2, "y", rotate=False) + system.point_load(2, Fy=load) + return system + + +def buckling_factor(system, n=20): + system.solve(geometrical_non_linear=True, discretize_kwargs={"n": n}) + return system.buckling_factor + + +# --------------------------------------------------------------------------- +# Euler columns +# --------------------------------------------------------------------------- + + +def test_pinned_pinned_column(): + assert buckling_factor(column("pinned")) == approx(EULER, rel=1e-3) + + +def test_cantilever_column(): + assert buckling_factor(column("cantilever")) == approx(EULER / 4, rel=1e-3) + + +def test_fixed_pinned_column(): + assert buckling_factor(column("fixed-pinned")) == approx(FIXED_PINNED, rel=1e-3) + + +def test_fixed_fixed_column(): + assert buckling_factor(column("fixed-fixed")) == approx(4 * EULER, rel=1e-3) + + +def test_buckling_factor_converges_from_above_with_the_number_of_elements(): + coarse = buckling_factor(column("pinned"), n=4) + fine = buckling_factor(column("pinned"), n=16) + assert coarse > fine > EULER * (1 - 1e-6) + assert fine == approx(EULER, rel=2e-3) + + +def test_single_element_column_gives_the_buckling_load_of_one_element(): + # one cubic element: 12 * EI / L**2 instead of pi**2 * EI / L**2 + system = column("pinned") + system.solve(geometrical_non_linear=True) + assert system.buckling_factor == approx(12 * EI / L**2) + + +def test_buckling_factor_is_inversely_proportional_to_the_load(): + assert buckling_factor(column("pinned", load=-2.0)) == approx(EULER / 2, rel=1e-3) + + +def test_column_in_tension_has_no_buckling_factor(): + assert buckling_factor(column("cantilever", load=1.0)) == float("inf") + + +# --------------------------------------------------------------------------- +# frames +# --------------------------------------------------------------------------- + + +def test_sway_buckling_of_a_portal_frame_with_a_rigid_beam(): + # the rigid beam has no normal force, so the geometric stiffness matrix is + # singular; with hinged bases each column buckles as a cantilever + system = SystemElements(EI=EI, EA=EA) + system.add_element([[0, 0], [0, L]]) + system.add_element([[0, L], [6, L]], EI=1e9) + system.add_element([[6, L], [6, 0]]) + system.add_support_hinged([1, 4]) + system.point_load([2, 3], Fy=[-1, -1]) + + assert buckling_factor(system, n=10) == approx(EULER / 4, rel=2e-3) + + +# --------------------------------------------------------------------------- +# releases: hinges and springs +# --------------------------------------------------------------------------- + + +def test_hinge_at_the_end_of_an_element_does_not_change_the_buckling_factor(): + # the rotation of the roller is free, so a hinge at the end changes nothing; the + # geometric stiffness must be condensed like the elastic stiffness (965 without) + plain = buckling_factor(column("fixed-pinned"), n=8) + hinged = buckling_factor(column("fixed-pinned", spring={2: 0}), n=8) + assert hinged == approx(plain, rel=1e-4) + + +def test_spring_at_the_end_of_an_element_is_a_rotational_spring_support(): + for k in (500.0, 5.0e3, 5.0e4): + with_spring = SystemElements(EI=EI, EA=EA) + with_spring.add_element([[0, 0], [0, L]], spring={1: k}) + with_spring.add_support_fixed(1) + with_spring.point_load(2, Fy=-1) + + with_support = SystemElements(EI=EI, EA=EA) + with_support.add_element([[0, 0], [0, L]]) + with_support.add_support_hinged(1) + with_support.add_support_spring(1, translation=3, k=k) + with_support.point_load(2, Fy=-1) + + assert buckling_factor(with_spring) == approx( + buckling_factor(with_support), rel=1e-6 + ) + + +def test_cantilever_column_with_a_rotational_spring_at_the_base(): + # Beam-column theory: the moment at the base P * delta equals k * y'(0), which gives + # mu * L * tan(mu * L) = k * L / EI with P = mu**2 * EI. For k -> infinity this is + # the cantilever (mu * L = pi / 2). + for k in (500.0, 5.0e3, 5.0e4): + target = k * L / EI + low, high = 0.0, np.pi / 2 - 1e-12 + for _ in range(200): # bisection on the increasing function x * tan(x) + middle = (low + high) / 2 + if middle * np.tan(middle) < target: + low = middle + else: + high = middle + expected = low**2 * EI / L**2 + + system = SystemElements(EI=EI, EA=EA) + system.add_element([[0, 0], [0, L]], spring={1: k}) + system.add_support_fixed(1) + system.point_load(2, Fy=-1) + + assert buckling_factor(system) == approx(expected, rel=2e-3) + assert expected < EULER / 4 + + +# --------------------------------------------------------------------------- +# repeated calculations +# --------------------------------------------------------------------------- + + +def loaded_column(): + system = SystemElements(EI=EI, EA=EA) + system.add_element([[0, 0], [0, 4]]) + system.add_support_fixed(1) + system.point_load(2, Fy=-100, Fx=0.01) + return system + + +def test_repeated_second_order_calculations_give_the_same_buckling_factor(): + # the elements must not keep the geometric stiffness of the previous calculation + system = loaded_column() + factors = [] + for _ in range(3): + system.solve(geometrical_non_linear=True) + factors.append(system.buckling_factor) + assert factors == approx([factors[0]] * 3) + assert factors[0] == approx(np.pi**2 * EI / (4 * 4.0**2) / 100, rel=1e-2) + + copied = copy.deepcopy(system) + copied.solve(geometrical_non_linear=True) + assert copied.buckling_factor == approx(factors[0]) + + +def test_linear_calculation_after_a_second_order_calculation_is_linear(): + reference = loaded_column() + reference.solve() + + system = loaded_column() + system.solve(geometrical_non_linear=True) + second_order = system.get_node_displacements(2)["ux"] + system.solve() + + assert second_order > reference.get_node_displacements(2)["ux"] + assert system.get_node_displacements(2)["ux"] == approx( + reference.get_node_displacements(2)["ux"] + ) + + +def test_second_order_displacement_is_amplified_by_the_compression(): + # cantilever column with a horizontal load H and a compressive load P = Pcr / 2: the + # tip displacement is amplified by about 1 / (1 - P / Pcr) = 2 (one step of the + # second order analysis with the first order normal forces) + pcr = np.pi**2 * EI / (4 * L**2) + amplification = [] + for load in (-0.5 * pcr, 0.5 * pcr): # compression, tension + first = SystemElements(EI=EI, EA=EA) + first.add_element([[0, 0], [0, L]]) + first.add_support_fixed(1) + first.point_load(2, Fx=0.01, Fy=load) + first.solve() + + second = SystemElements(EI=EI, EA=EA) + second.add_element([[0, 0], [0, L]]) + second.add_support_fixed(1) + second.point_load(2, Fx=0.01, Fy=load) + second.solve(geometrical_non_linear=True, discretize_kwargs={"n": 20}) + amplification.append( + second.get_node_displacements(2)["ux"] + / first.get_node_displacements(2)["ux"] + ) + + assert amplification[0] == approx(2.0, rel=0.05) + assert amplification[1] < 1.0 # tension stiffens the column + + +def test_truss_geometric_stiffness_has_no_rotation_terms(): + # a truss element has no bending stiffness: the geometric stiffness is that of a string, + # N / l times the transverse translation, so the buckling factor is finite + matrix = geometric_stiffness_matrix(4.0, 2.0, 0.0, 0.0, 0.0, truss=True) + assert matrix[[2, 5], :] == approx(0.0) + assert matrix[:, [2, 5]] == approx(0.0) + # horizontal member: only the transverse (y) translations, with +-N / l + assert abs(matrix[1][1]) == approx(2.0 / 4.0) + assert matrix[1][4] == approx(-matrix[1][1]) + + system = SystemElements(EA=1.0e5) + system.add_truss_element([[0, 0], [3, 0]]) + system.add_truss_element([[3, 0], [1.5, 2]]) + system.add_truss_element([[0, 0], [1.5, 2]]) + system.add_support_hinged(1) + system.add_support_roll(2) + system.point_load(3, Fy=-1) + system.solve(geometrical_non_linear=True) + + assert np.isfinite(system.buckling_factor) + assert system.buckling_factor > 1.0e3 + + +# --------------------------------------------------------------------------- +# the eigenvalue problem +# --------------------------------------------------------------------------- + + +def test_smallest_buckling_factor_of_a_diagonal_problem(): + k0 = np.diag([2.0, 3.0]) + assert smallest_buckling_factor(k0, -np.eye(2)) == approx(2.0) + # tension (positive geometric stiffness) is no buckling mode + assert smallest_buckling_factor(k0, np.diag([-1.0, 1.0])) == approx(2.0) + assert smallest_buckling_factor(k0, np.eye(2)) == float("inf") + + +def test_smallest_buckling_factor_with_a_singular_geometric_stiffness(): + k0 = np.diag([2.0, 3.0]) + assert smallest_buckling_factor(k0, np.diag([-1.0, 0.0])) == approx(2.0) + + +def test_smallest_buckling_factor_without_a_positive_definite_stiffness(): + k0 = np.diag([2.0, -3.0]) + assert smallest_buckling_factor(k0, np.diag([-1.0, 0.0])) == approx(2.0) + + +# --------------------------------------------------------------------------- +# geometric stiffness matrix and repeated solves +# --------------------------------------------------------------------------- + + +def test_geometric_stiffness_matrix_is_symmetric_for_different_end_angles(): + # an inclined roller support changes the angle at one end of the element + matrix = geometric_stiffness_matrix(3.0, 2.0, 0.3, 0.7) + assert matrix == approx(matrix.T) + + +def test_solving_twice_gives_the_same_result_for_an_axially_loaded_column(): + # the transverse displacements are exactly 0 after the first solve; that must not + # make them restrained degrees of freedom in the second solve + system = column("cantilever") + first = np.array(system.solve()) + second = np.array(system.solve()) + assert second == approx(first) + # Fy = -1 pushes the top of the column towards its base: it shortens by P * L / EA + assert system.get_node_displacements(2)["uy"] == approx(-1.0 * L / EA) + + +def test_solving_twice_with_an_imposed_displacement(): + system = SystemElements(EA=EA, EI=1.0e4) + system.add_element([[0, 0], [10, 0]]) + system.add_support_fixed(1) + system.add_support_roll(2) + system.imposed_displacement(2, uy=0.02) + system.solve() + first = system.reaction_forces[2].Fy + system.solve() + + assert first == approx(-3 * 1.0e4 * 0.02 / 10**3) + assert system.reaction_forces[2].Fy == approx(first) diff --git a/tests/test_discretize_internal_hinges.py b/tests/test_discretize_internal_hinges.py new file mode 100644 index 00000000..f85d27d9 --- /dev/null +++ b/tests/test_discretize_internal_hinges.py @@ -0,0 +1,489 @@ +import itertools + +import numpy as np + +from pytest import approx, mark, raises + +from anastruct import SystemElements +from anastruct.basic import FEMException + +""" +NOTE: These tests cover the detection of internal hinges (`check_internal_hinges`) and +`SystemElements.discretize()`. The hinge status of a node follows from the springs given +by the user and does not depend on the order in which the elements were added; a +discretized system gives the same results as the original system. + +The tests are plain test functions (not nested describe/context blocks), so that every +assertion is guaranteed to be executed. +""" + +EA = 1.0e9 +EI = 1.0e4 +L = 3.0 + + +def reaction(system, point): + """Reaction forces at the node at the given location (the ids change in discretize)""" + return system.reaction_forces[system.find_node_id(point)] + + +# --------------------------------------------------------------------------- +# internal hinges +# --------------------------------------------------------------------------- + + +def tee(order, moment=10.0): + """Beam with a column and a beam whose start is a hinge, meeting in one node. + + The left beam and the column are rigidly connected, so they share the rotation of + the node and carry the moment; the right beam is released. + """ + system = SystemElements(EA=EA, EI=EI) + elements = { + "left": lambda: system.add_element([[0, 0], [L, 0]]), + "right": lambda: system.add_element([[L, 0], [2 * L, 0]], spring={1: 0}), + "column": lambda: system.add_element([[L, 0], [L, -L]]), + } + for name in order: + elements[name]() + junction = system.find_node_id([L, 0]) + system.add_support_fixed( + [system.find_node_id([0, 0]), system.find_node_id([L, -L])] + ) + system.add_support_hinged(system.find_node_id([2 * L, 0])) + system.moment_load(junction, Tz=moment) + system.solve() + return system, junction + + +@mark.parametrize("order", list(itertools.permutations(["left", "right", "column"]))) +def test_junction_with_two_rigid_elements_is_not_a_hinge_in_any_order(order): + # the rotation of the junction is shared by the left beam and the column, each + # fixed at the far end: phi = M / (4 * EI / L + 4 * EI / L) + moment = 10.0 + system, junction = tee(order, moment) + + assert system.internal_hinges == [] + assert not system.node_map[junction].hinge + assert abs(system.get_node_displacements(junction)["phi_z"]) == approx( + moment / (8 * EI / L), rel=1e-4 # EA is finite + ) + + +def test_internal_hinge_is_detected_when_all_elements_are_released(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]], spring={2: 0}) + system.add_element([[L, 0], [2 * L, 0]], spring={1: 0}) + junction = system.find_node_id([L, 0]) + assert [hinge.id for hinge in system.internal_hinges] == [junction] + assert system.node_map[junction].hinge + + # a rigid element takes the node out of the hinges, removing it again brings it back + column = system.add_element([[L, 0], [L, -L]]) + assert system.internal_hinges == [] + assert not system.node_map[junction].hinge + system.remove_element(column) + assert [hinge.id for hinge in system.internal_hinges] == [junction] + assert system.node_map[junction].hinge + + +def test_a_node_with_one_rigid_element_is_solved_with_its_own_rotation(): + # rigid cantilever + a released beam in one node: the node rotation is a normal + # degree of freedom, so a moment load is carried by the rigid element + # (it used to be dropped silently) + moment = 10.0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]], spring={1: 0}) + system.add_support_fixed(1) + system.add_support_hinged(3) + system.moment_load(2, Tz=moment) + system.solve() + + assert abs(reaction(system, [0, 0]).Tz) == approx(moment) + assert reaction(system, [2 * L, 0]).Fy == approx(0.0, abs=1e-9) + + +def test_a_fixed_support_before_a_released_element_stays_fixed(): + # cantilever (support at its right end) and a beam that is hinged to the support: + # q on the cantilever gives M = q * L**2 / 2 in the support + q = 10.0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed(2) + system.add_element([[L, 0], [2 * L, 0]], spring={1: 0}) + system.add_support_hinged(3) + system.q_load(-q, 1) + system.solve() + + assert abs(reaction(system, [L, 0]).Tz) == approx(q * L**2 / 2) + + +def test_hinges_stay_known_after_solving_more_than_once(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]], spring={2: 0}) + system.add_element([[L, 0], [2 * L, 0]], spring={1: 0}) + system.add_support_fixed(1) + system.add_support_roll(3) + junction = system.find_node_id([L, 0]) + for _ in range(2): + system.remove_loads() + system.q_load(-10, [1, 2]) + system.solve() + assert [hinge.id for hinge in system.internal_hinges] == [junction] + assert system.node_map[junction].hinge + assert len(system.node_map[junction].elements) == 2 + + # elements can be removed after solving; the remaining element is still released + # at the node, so it stays a hinge + system.remove_element(2) + assert [hinge.id for hinge in system.internal_hinges] == [junction] + system.remove_element(1) + assert system.internal_hinges == [] + + +def test_a_translational_spring_support_is_allowed_at_an_internal_hinge(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_internal_hinge(2) + system.add_support_spring(2, translation=2, k=500.0) # does not restrain rotation + with raises(FEMException): + system.add_support_spring(2, translation=3, k=500.0) + + +def test_springs_given_by_the_user_are_not_modified(): + spring = {1: 0} + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]], spring=spring) + system.add_element([[2 * L, 0], [3 * L, 0]], spring=spring) + + # the rigid element at the hinge node is released through the node, not by a spring + assert system.element_map[1].springs == {} + assert system.element_map[2].springs == {1: 0} + assert system.element_map[3].springs == {1: 0} + assert spring == {1: 0} + assert system.element_map[2].springs is not system.element_map[3].springs + + +def test_a_spring_dictionary_of_the_caller_is_not_changed_when_the_element_is_reversed(): + spring = {1: 500.0} + system = SystemElements(EA=EA, EI=EI) + system.add_element([[L, 0], [0, 0]], spring=spring) # drawn right to left + + assert spring == {1: 500.0} + assert system.element_map[1].springs == {2: 500.0} + + +def test_explicit_internal_hinge_is_a_hinge_immediately(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_internal_hinge(2) + + assert system.node_map[2].hinge + assert system.internal_hinges == [system.node_map[2]] + with raises(FEMException): + system.add_support_fixed(2) + + +def test_explicit_internal_hinge_with_a_third_rigid_element_stays_a_hinge(): + # a declared hinge releases all the elements, also when three are connected (a low EA, so + # that the load is not carried by the normal force of the column alone) + system = SystemElements(EA=1.0e3, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_element([[L, 0], [L, -L]]) + system.add_internal_hinge(2) + system.add_support_fixed([1, 3, 4]) + system.point_load(2, Fy=-10.0) + assert system.node_map[2].hinge + system.solve() + + # (the hinge flag is reset by the post-processing and set again by every solve) + assert [hinge.id for hinge in system.internal_hinges] == [2] + # the moment is zero at the hinge end of each of the three released elements; the two + # beams carry the load by shear into their supports (the column only by a normal force) + for element in system.element_map.values(): + moments = element.bending_moment + at_hinge = moments[0] if element.node_id1 == 2 else moments[-1] + assert at_hinge == approx(0.0, abs=1e-6) + beams = [system.element_map[1], system.element_map[2]] + assert all(np.max(np.abs(beam.bending_moment)) > 0.05 for beam in beams) + assert np.max(np.abs(system.element_map[3].bending_moment)) < 1e-3 + + +def test_moment_load_at_an_internal_hinge_is_an_error(): + # no element transfers a moment in a hinge: the load would vanish silently + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_support_fixed([1, 3]) + system.add_internal_hinge(2) + system.moment_load(2, Tz=10.0) + with raises(FEMException) as error: + system.solve() + assert "internal hinge" in error.value.message + + +def test_moment_load_at_a_node_with_only_truss_elements_is_an_error(): + system = SystemElements(EA=EA) + system.add_truss_element([[0, 0], [L, 0]]) + system.add_truss_element([[L, 0], [2 * L, 0]]) + system.add_support_hinged([1, 3]) + system.moment_load(2, Tz=10.0) + with raises(FEMException) as error: + system.solve() + assert "truss" in error.value.message + + +def test_insert_node_keeps_the_internal_hinge_of_a_released_node(): + def build(split): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [2 * L, 0]]) + system.add_element([[2 * L, 0], [4 * L, 0]], spring={1: 0}) + system.add_support_fixed(1) + system.add_support_roll(3) + if split: + system.insert_node(1, factor=0.5) + system.q_load(-10, [1, 2] if not split else [2, 3, 4]) + system.solve() + return system + + plain, split = build(False), build(True) + assert reaction(split, [0, 0]).Tz == approx(reaction(plain, [0, 0]).Tz, rel=1e-6) + assert reaction(split, [4 * L, 0]).Fy == approx( + reaction(plain, [4 * L, 0]).Fy, rel=1e-6 + ) + + +# --------------------------------------------------------------------------- +# discretize +# --------------------------------------------------------------------------- + + +def test_discretize_a_portal_frame_gives_the_same_results(): + # a model that is not a simple chain of elements (node ids do not follow the + # element ids) + def build(n=None): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [0, 4]]) + system.add_element([[0, 4], [6, 4]]) + system.add_element([[6, 4], [6, 0]]) + system.add_support_fixed(1) + system.add_support_hinged(4) + system.q_load(-10, 2) + system.point_load(2, Fx=5) + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(4) + for point in ([0, 0], [6, 0]): + for component in ("Fx", "Fy", "Tz"): + assert getattr(reaction(fine, point), component) == approx( + getattr(reaction(plain, point), component), abs=1e-4 + ) + assert len(fine.element_map) == 12 + + +def test_discretize_with_a_trapezoidal_q_load_dead_load_and_a_spring(): + def build(n=None): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [0, 4]]) + system.add_element([[0, 4], [6, 4]], spring={2: 800.0}, g=2.0) + system.add_element([[6, 4], [6, 0]]) + system.add_support_fixed([1, 4]) + system.q_load([-4, -12], 2) + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(5) + for point in ([0, 0], [6, 0]): + for component in ("Fx", "Fy", "Tz"): + assert getattr(reaction(fine, point), component) == approx( + getattr(reaction(plain, point), component), abs=1e-3 + ) + + +def test_discretize_gives_the_releases_to_the_outer_sub_elements_only(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]], spring={1: 0, 2: 500.0}, mp={1: 30.0, 2: 40.0}) + system.discretize(4) + + springs = [system.element_map[i].springs for i in sorted(system.element_map)] + assert springs == [{1: 0}, {}, {}, {2: 500.0}] + assert len({id(spring) for spring in springs}) == 4 # no shared dictionaries + assert [system.non_linear_elements.get(i) for i in sorted(system.element_map)] == [ + {1: 30.0}, + None, + None, + {2: 40.0}, + ] + + +def test_discretize_keeps_the_hinge_of_the_original_element_only(): + def build(n=None): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [0, 4]]) + system.add_element([[0, 4], [6, 4]], spring={1: 0}) + system.add_element([[6, 4], [6, 0]]) + system.add_support_fixed([1, 4]) + system.q_load(-10, 2) + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(4) + assert [ + element.springs for element in fine.element_map.values() if element.springs + ] == [{1: 0}] + assert reaction(fine, [0, 0]).Tz == approx(reaction(plain, [0, 0]).Tz, abs=1e-3) + assert reaction(fine, [6, 0]).Tz == approx(reaction(plain, [6, 0]).Tz, abs=1e-3) + + +def test_discretize_does_not_divide_truss_elements(): + # divided truss elements would leave mechanisms at the new nodes: the apex of + # this two-bar truss moves N * l / EA / sin(45 deg) = 0.02828 + def build(n=None): + system = SystemElements(EA=1000.0) + system.add_truss_element([[0, 0], [2, 2]]) + system.add_truss_element([[2, 2], [4, 0]]) + system.add_support_hinged(1) + system.add_support_hinged(3) + system.point_load(2, Fy=-10) + if n: + system.discretize(n) + system.solve() + return system + + fine = build(3) + assert len(fine.element_map) == 2 + apex = fine.find_node_id([2, 2]) + assert abs(fine.get_node_displacements(apex)["uy"]) == approx(0.028284, rel=1e-4) + assert abs(build().get_node_displacements(2)["uy"]) == approx(0.028284, rel=1e-4) + + +def test_discretize_with_a_spring_support_given_by_a_negative_node_id(): + # the negative id refers to the last node at the moment the support is added + def build(n=None): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [4, 0]]) + system.add_support_spring(-1, 2, 800.0) + system.add_element([[4, 0], [8, 0]]) + system.add_support_fixed(1) + system.q_load(-10, [1, 2]) + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(2) + assert reaction(fine, [0, 0]).Tz == approx(reaction(plain, [0, 0]).Tz, abs=1e-3) + assert reaction(fine, [0, 0]).Fy == approx(reaction(plain, [0, 0]).Fy, abs=1e-3) + assert fine.supports_spring_y[0][0].vertex.x == approx(4.0) + + +def test_geometrical_non_linear_solve_keeps_the_plotter_of_the_user_system(): + system = SystemElements(EI=5e3, EA=1e5) + system.add_element([0, 10]) + system.add_support_hinged(1) + system.add_support_roll(2, 1) + system.point_load(2, Fy=-1) + system.solve(geometrical_non_linear=True, discretize_kwargs={"n": 5}) + + assert len(system.element_map) == 1 + assert system.plotter.system is system + assert system.plot_values.system is system + + +def test_discretize_keeps_the_truss_elements(): + def build(n=None): + system = SystemElements(EA=1e5, EI=EI) + system.add_truss_element([[0, 0], [3, 0]]) + system.add_truss_element([[3, 0], [3, 4]]) + system.add_truss_element([[0, 0], [3, 4]]) + system.add_support_hinged(1) + system.add_support_roll(2) + system.point_load(3, Fx=10, Fy=-20) + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(3) + assert {element.type for element in fine.element_map.values()} == {"truss"} + for point in ([0, 0], [3, 0]): + for component in ("Fx", "Fy"): + # the bars have no bending stiffness (EI = 1e-14), so the transverse + # degrees of freedom of the inner nodes are almost singular + assert getattr(reaction(fine, point), component) == approx( + getattr(reaction(plain, point), component), abs=1e-4 + ) + + +def test_discretize_keeps_an_inclined_roller_support(): + def build(n=None): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_support_hinged(1) + system.add_support_roll(3, angle=30) + system.q_load(-10, [1, 2]) + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(3) + assert reaction(fine, [2 * L, 0]).Fx == approx( + reaction(plain, [2 * L, 0]).Fx, abs=1e-4 + ) + assert reaction(fine, [2 * L, 0]).Fy == approx( + reaction(plain, [2 * L, 0]).Fy, abs=1e-4 + ) + + +def test_discretize_keeps_an_explicit_internal_hinge_and_a_spring_support(): + def build(n=None): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_support_fixed(1) + system.add_support_spring(3, translation=2, k=500.0) + system.add_internal_hinge(2) + system.point_load(2, Fy=-100) + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(4) + assert len(fine.internal_hinges) == 1 + assert reaction(fine, [0, 0]).Fy == approx(reaction(plain, [0, 0]).Fy, abs=1e-4) + assert reaction(fine, [0, 0]).Tz == approx(reaction(plain, [0, 0]).Tz, abs=1e-4) + assert fine.get_node_displacements(fine.find_node_id([2 * L, 0]))["uy"] == approx( + plain.get_node_displacements(3)["uy"], abs=1e-9 + ) + + +def test_discretize_keeps_the_plotter_and_post_processor_bound_to_the_system(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed(1) + system.q_load(-10, 1) + system.point_load(2, Fy=-5) + max_q = system.plotter.max_q + system.discretize(3) + + assert system.plotter.system is system + assert system.plot_values.system is system + assert system.post_processor.system is system + assert system.plotter.max_q == max_q + system.solve() + assert system.get_element_results(1) is not None diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 4c5b3b24..798f745f 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -108,9 +108,9 @@ def context_example_4(): def it_results_in_correct_solution(): sol = np.fromstring( - """0.00000000e+00 0.00000000e+00 1.46957616e-25 2.00000000e-09 - -7.34788079e-25 0.00000000e+00 0.00000000e+00 0.00000000e+00 - 3.12500040e-03""", + """0.00000000e+00 0.00000000e+00 -4.89858720e-26 2.00000000e-09 + 2.44929360e-25 -2.08333293e-03 0.00000000e+00 0.00000000e+00 + 4.16666707e-03""", float, sep=" ", ) @@ -154,8 +154,8 @@ def context_example_7_rotational_spring(): def it_results_in_correct_solution(SS_7): sol = np.fromstring( - """0. 0. 0. 0. 0.23558645 -0.09665875 - 0. 0. 0.06433688""", + """0. 0. 0. 0. 0.25070634 -0.10443469 + 0. 0. 0.07363764""", float, sep=" ", ) diff --git a/tests/test_hinges_springs.py b/tests/test_hinges_springs.py new file mode 100644 index 00000000..e5e6ea83 --- /dev/null +++ b/tests/test_hinges_springs.py @@ -0,0 +1,295 @@ +import numpy as np +from pytest import approx + +from anastruct import SystemElements +from anastruct.fem.elements import constitutive_matrix + +""" +NOTE: These tests validate the element end releases (hinges and rotational springs, +`spring={node: k}` and internal hinges) against analytical results. A hinge is +modelled by static condensation of the end rotation (an element with one hinge has the +rotational stiffness 3EI/l instead of 4EI/l); a rotational spring k acts in series with +the element. General definitions: +- L = member length +- EA = axial stiffness +- EI = bending stiffness +- k = stiffness of the rotational spring at the element end + +The tests are plain test functions (not nested describe/context blocks), so that every +assertion is guaranteed to be executed. +""" + +EA = 1.0e9 +EI = 1.0e4 +L = 4.0 + + +# --------------------------------------------------------------------------- +# constitutive matrix +# --------------------------------------------------------------------------- + + +def test_constitutive_matrix_without_releases(): + matrix = constitutive_matrix(EA, EI, L, None, False, False) + expected = np.array( + [ + [EA / L, 0, 0], + [0, 4 * EI / L, -2 * EI / L], + [0, -2 * EI / L, 4 * EI / L], + ] + ) + assert matrix == approx(expected) + + +def test_constitutive_matrix_with_one_hinge_is_condensed(): + # fixed-hinge: 3EI/l, no coupling with the released rotation + for hinge_1, hinge_2, spring in ( + (False, True, None), + (False, False, {2: 0}), + (False, True, {2: 5.0}), # the hinge prevails over a spring + ): + matrix = constitutive_matrix(EA, EI, L, spring, hinge_1, hinge_2) + assert matrix[1][1] == approx(3 * EI / L) + assert matrix[1][2] == 0 and matrix[2][1] == 0 and matrix[2][2] == 0 + + matrix = constitutive_matrix(EA, EI, L, None, True, False) + assert matrix[2][2] == approx(3 * EI / L) + assert matrix[1][1] == 0 and matrix[1][2] == 0 and matrix[2][1] == 0 + + +def test_constitutive_matrix_with_two_hinges_has_no_bending_stiffness(): + matrix = constitutive_matrix(EA, EI, L, {1: 0, 2: 0}, False, False) + assert matrix[1:, 1:] == approx(np.zeros((2, 2))) + assert matrix[0][0] == approx(EA / L) + + +def test_constitutive_matrix_with_springs_is_finite_and_symmetric(): + # the series of two flexibilities used to give NaN/inf for a finite spring + matrix = constitutive_matrix(EA, EI, L, {1: 500.0, 2: 800.0}, False, False) + assert np.all(np.isfinite(matrix)) + assert matrix == approx(matrix.T) + flexibility = np.linalg.inv(matrix[1:, 1:]) + expected = np.linalg.inv(EI / L * np.array([[4.0, -2.0], [-2.0, 4.0]])) + assert flexibility == approx(expected + np.diag([1 / 500.0, 1 / 800.0])) + + +def test_constitutive_matrix_for_a_rigid_spring_is_the_rigid_element(): + matrix = constitutive_matrix(EA, EI, L, {1: 1e15, 2: 1e15}, False, False) + assert matrix[1][1] == approx(4 * EI / L) + assert matrix[1][2] == approx(-2 * EI / L) + + +# --------------------------------------------------------------------------- +# mechanical loads +# --------------------------------------------------------------------------- + + +def test_fixed_hinge_fixed_beam_with_point_load_at_the_hinge(): + # two propped cantilevers sharing the loaded hinge: u = P * l**3 / (6 * EI) + p = 100.0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_support_fixed([1, 3]) + system.add_internal_hinge(2) + system.point_load(2, Fy=-p) + system.solve() + + assert abs(system.get_node_displacements(2)["uy"]) == approx(p * L**3 / (6 * EI)) + assert system.reaction_forces[1].Fy == approx(system.reaction_forces[3].Fy) + + +def test_element_end_hinge_is_equivalent_to_a_hinged_support(): + # fixed-pinned beam under a q-load: M_fixed = q * L**2 / 8 + q = -10.0 + length = 6.0 + + def solve(spring): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [length, 0]], spring=spring) + system.add_support_fixed(1) + system.add_support_hinged(2) + system.q_load(q, 1) + system.solve() + return system + + plain = solve(None) + released = solve({2: 0}) + assert abs(plain.reaction_forces[1].Tz) == approx(abs(q) * length**2 / 8, rel=1e-4) + assert released.reaction_forces[1].Tz == approx(plain.reaction_forces[1].Tz) + assert released.reaction_forces[2].Fy == approx(plain.reaction_forces[2].Fy) + + +def test_cantilever_with_a_rotational_spring_at_the_fixed_end(): + # tip deflection: P * L**3 / (3 * EI) + P * L**2 / k (the spring rotates by M / k) + p = 10.0 + for k in (50.0, 1e3, 1e9): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]], spring={1: k}) + system.add_support_fixed(1) + system.point_load(2, Fy=-p) + system.solve() + + assert abs(system.get_node_displacements(2)["uy"]) == approx( + p * L**3 / (3 * EI) + p * L**2 / k + ) + + +def test_simply_supported_beam_with_a_rotational_spring_at_the_end(): + # end rotation under an end moment M: M * (L / (3 * EI) + 1 / k) + m = 10.0 + for k in (500.0, 1e3, 1e8): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]], spring={2: k}) + system.add_support_hinged(1) + system.add_support_roll(2) + system.moment_load(2, Tz=m) + system.solve() + + assert abs(system.get_node_displacements(2)["phi_z"]) == approx( + m * (L / (3 * EI) + 1 / k) + ) + + +def test_springs_at_both_ends_with_imposed_rotation(): + # fixed-fixed element with rotational springs at both ends: the end moment follows + # from the series of the element and the springs + k1, k2 = 300.0, 700.0 + phi = 0.01 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]], spring={1: k1, 2: k2}) + system.add_support_fixed([1, 2]) + system.imposed_displacement(2, phi_z=phi) + system.solve() + + element = EI / L * np.array([[4.0, -2.0], [-2.0, 4.0]]) + series = np.linalg.inv(np.linalg.inv(element) + np.diag([1 / k1, 1 / k2])) + assert system.reaction_forces[2].Tz == approx(series[1][1] * phi) + # the far-end moment is reported with the opposite sign of the coupling term + # (without springs: M_far = +2 * EI * phi / L) + assert system.reaction_forces[1].Tz == approx(-series[0][1] * phi) + + +def test_q_load_on_a_fixed_fixed_element_with_rotational_springs(): + # the fixed-end moment is reduced by the springs: the beam end rotation + # q * L**3 / (24 * EI) - M * L / (2 * EI) equals the spring rotation M / k, so + # M = q * L**3 / (24 * EI) / (L / (2 * EI) + 1 / k) + q = 10.0 + length = 6.0 + for k in (500.0, 50.0, 1e9): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [length, 0]], spring={1: k, 2: k}) + system.add_support_fixed([1, 2]) + system.q_load(-q, 1) + system.solve() + + expected = q * length**3 / (24 * EI) / (length / (2 * EI) + 1 / k) + assert abs(system.reaction_forces[1].Tz) == approx(expected) + assert abs(system.reaction_forces[2].Tz) == approx(expected) + assert system.get_element_results(1)["Mmax"] == approx(expected) + + +def test_q_load_on_an_element_with_a_start_hinge(): + # hinge at the start, fixed end: M_fixed = q * L**2 / 8, R_hinge = 3 * q * L / 8 + q = 10.0 + length = 6.0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [length, 0]], spring={1: 0}) + system.add_support_hinged(1) + system.add_support_fixed(2) + system.q_load(-q, 1) + system.solve() + + assert abs(system.reaction_forces[2].Tz) == approx(q * length**2 / 8, rel=1e-4) + assert abs(system.reaction_forces[1].Fy) == approx(3 * q * length / 8, rel=1e-4) + + +def test_q_load_on_a_beam_with_an_internal_hinge(): + # fixed - span - hinge - span - roller (statically determinate): + # R_roller = q * L / 2, M_fixed = q * L**2 (the shear at the hinge q * L / 2 acts + # on the cantilever) + q = 10.0 + length = 6.0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [length, 0]]) + system.add_element([[length, 0], [2 * length, 0]]) + system.add_support_fixed(1) + system.add_support_roll(3) + system.add_internal_hinge(2) + system.q_load(-q, [1, 2]) + system.solve() + + assert abs(system.reaction_forces[3].Fy) == approx(q * length / 2) + assert abs(system.reaction_forces[1].Tz) == approx(q * length**2) + + +def test_q_load_on_an_element_with_a_rotational_spring_and_a_plastic_hinge(): + # a spring and a plastic moment at the same end: the iteration converges and the + # end moment is limited to mp; the other end follows from equilibrium (75) + mp = 30.0 + system = SystemElements() + system.add_element([[0, 0], [6, 0]], EA=5e4, EI=2e3, spring={1: 1500.0}, mp={1: mp}) + system.add_support_fixed([1, 2]) + system.q_load(q=-20, element_id=1) + system.solve() + + assert system.element_map[1].bending_moment is not None + assert abs(system.reaction_forces[1].Tz) == approx(mp, rel=5e-3) + assert abs(system.reaction_forces[2].Tz) == approx(75.0, rel=5e-3) + + +def test_trapezoidal_q_load_on_a_truss_element(): + # a truss element carries no moment: simply supported reactions + # R1 = (2 * q1 + q2) * L / 6, R2 = (q1 + 2 * q2) * L / 6 + q1, q2, length = 6.0, 18.0, 5.0 + system = SystemElements() + system.add_truss_element([[0, 0], [length, 0]], EA=1e5) + system.add_support_hinged(1) + system.add_support_roll(2) + system.q_load(q=[-q1, -q2], element_id=1) + system.solve() + + assert abs(system.reaction_forces[1].Fy) == approx((2 * q1 + q2) * length / 6) + assert abs(system.reaction_forces[2].Fy) == approx((q1 + 2 * q2) * length / 6) + + +# --------------------------------------------------------------------------- +# thermal loads +# --------------------------------------------------------------------------- + + +def test_thermal_gradient_on_an_element_with_an_end_hinge(): + # fixed-pinned beam with a temperature gradient (warmer upper face): + # M_fixed = 3/2 * EI * kappa (sagging, so negative in anaStruct), also when the hinge + # is an element end release + kappa = 1.2e-5 * 15.0 / 0.5 + length = 10.0 + + def solve(spring): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [length, 0]], spring=spring) + system.add_support_fixed(1) + system.add_support_hinged(2) + system.thermal_load(1, delta_t=0, alpha=1.2e-5, delta_t_gradient=15, h=0.5) + system.solve() + return system + + for spring in (None, {2: 0}): + system = solve(spring) + assert system.reaction_forces[1].Tz == approx(-1.5 * EI * kappa) + assert system.reaction_forces[2].Fy == approx(-1.5 * EI * kappa / length) + + +def test_thermal_gradient_on_an_element_with_a_rotational_spring(): + # a spring on the fixed end of a cantilever does not carry a moment (the cantilever + # curves freely), so the spring does not change the free thermal response + kappa = 1.2e-5 * 15.0 / 0.5 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [10, 0]], spring={1: 500.0}) + system.add_support_fixed(1) + system.thermal_load(1, delta_t=0, alpha=1.2e-5, delta_t_gradient=15, h=0.5) + system.solve() + + # the tip moves down: the warmer face is the upper face + assert system.get_node_displacements(2)["uy"] == approx(-kappa * 10.0**2 / 2) + assert system.reaction_forces[1].Tz == approx(0.0, abs=1e-9) diff --git a/tests/test_imposed_thermal.py b/tests/test_imposed_thermal.py new file mode 100644 index 00000000..284d3d27 --- /dev/null +++ b/tests/test_imposed_thermal.py @@ -0,0 +1,552 @@ +from pytest import approx, raises + +from anastruct import LoadCase, LoadCombination, SystemElements +from anastruct.basic import FEMException + +""" +NOTE: These tests validate imposed displacements/rotations of supports (support +settlements) and thermal loads on elements against analytical results from +engineering theory, and cover their interplay with load combinations, model edits +(insert_node, discretize, remove_loads) and the sign conventions. General +definitions: +- L = member length +- EA = axial stiffness +- EI = bending stiffness +- alpha = coefficient of thermal expansion +- dT = uniform temperature change +- dT_grad = temperature difference over the section depth h +- kappa = alpha * dT_grad / h = free thermal curvature +- delta = imposed support settlement +- phi = imposed support rotation + +The tests are plain test functions (not nested describe/context blocks), so that every +assertion is guaranteed to be executed. +""" + +EA = 1.0e6 +EI = 1.0e4 +L = 10.0 +ALPHA = 1.2e-5 +DT = 20.0 +H = 0.5 +DT_GRAD = 15.0 +KAPPA = ALPHA * DT_GRAD / H + + +def propped_cantilever(**kwargs): + system = SystemElements(EA=EA, EI=EI, **kwargs) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed(1) + system.add_support_roll(2) + return system + + +def fixed_fixed(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed([1, 2]) + return system + + +def cantilever(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed(1) + return system + + +# --------------------------------------------------------------------------- +# imposed displacements +# --------------------------------------------------------------------------- + + +def test_propped_cantilever_settlement(): + # Propped cantilever with an imposed displacement delta of the prop: + # |R_prop| = 3 * EI * delta / L**3, |M_fixed| = 3 * EI * delta / L**2. + # uy is positive in the +y direction (upwards, like a load Fy): a settlement is a + # negative uy and gives the reactions of the opposite sign. + delta = 0.02 + for sign in (1, -1): # +1: the prop moves up, -1: the prop settles + system = propped_cantilever() + system.imposed_displacement(2, uy=sign * delta) + system.solve() + + assert system.reaction_forces[2].Fy == approx(-sign * 3 * EI * delta / L**3) + assert system.reaction_forces[1].Tz == approx(-sign * 3 * EI * delta / L**2) + # vertical equilibrium + assert system.reaction_forces[1].Fy + system.reaction_forces[2].Fy == approx(0) + # the imposed displacement is reported in the direction of +y + assert system.get_node_displacements(2)["uy"] == approx(sign * delta) + assert system.reaction_forces[2].uy == approx(sign * delta) + + +def test_positive_load_and_imposed_displacement_act_in_the_same_direction(): + # a positive Fy and a positive uy both act in the +y direction (upwards); with + # invert_y_loads=False they act in the -y direction + for invert, direction in ((True, 1), (False, -1)): + loaded = SystemElements(EA=EA, EI=EI, invert_y_loads=invert) + loaded.add_element([[0, 0], [L, 0]]) + loaded.add_support_fixed(1) + loaded.point_load(2, Fy=1.0) + loaded.solve() + assert direction * loaded.get_node_displacements(2)["uy"] > 0 + + moved = propped_cantilever(invert_y_loads=invert) + moved.imposed_displacement(2, uy=0.01) + moved.solve() + assert direction * moved.get_node_displacements(2)["uy"] > 0 + + +def test_positive_fy_acts_in_the_y_direction_of_the_structure(): + # a force along +y on the top node of a column (y = +L) pulls it: tension + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [0, L]]) + system.add_support_fixed(1) + system.point_load(2, Fy=1.0) + system.solve() + + assert system.element_map[1].N_1 == approx(1.0) + + +def test_fixed_fixed_imposed_rotation(): + # Fixed-fixed beam with an imposed rotation phi at node 2: + # M_near = 4 * EI * phi / L, M_far = 2 * EI * phi / L, R = 6 * EI * phi / L**2 + phi = 0.01 + system = fixed_fixed() + system.imposed_displacement(2, phi_z=phi) + system.solve() + + assert system.reaction_forces[2].Tz == approx(4 * EI * phi / L) + assert system.reaction_forces[1].Tz == approx(2 * EI * phi / L) + assert system.reaction_forces[1].Fy == approx(-6 * EI * phi / L**2) + assert system.reaction_forces[2].Fy == approx(6 * EI * phi / L**2) + # reported rotations have the opposite sign of the system displacement + # vector, consistent with the moment_load sign convention + assert system.get_node_displacements(2)["phi_z"] == approx(-phi) + + +def test_fixed_fixed_imposed_axial_displacement(): + # Fixed-fixed bar with an imposed axial displacement dx at node 2: + # N = EA * dx / L (tension) + dx = 0.01 + system = fixed_fixed() + system.imposed_displacement(2, ux=dx) + system.solve() + + assert system.reaction_forces[1].Fx == approx(-EA * dx / L) + assert system.reaction_forces[2].Fx == approx(EA * dx / L) + assert system.get_node_displacements(2)["ux"] == approx(dx) + + +def test_two_span_beam_middle_support_settlement(): + # Two equal spans (continuous beam), settlement delta of the middle support: + # the middle reaction is reduced by 6 * EI * delta / L**3 (L = span length) + delta = 0.01 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_support_hinged(1) + system.add_support_roll(2) + system.add_support_roll(3) + system.imposed_displacement(2, uy=delta) + system.solve() + + assert system.reaction_forces[2].Fy == approx(-6 * EI * delta / L**3) + assert system.reaction_forces[1].Fy == approx(3 * EI * delta / L**3) + assert system.reaction_forces[3].Fy == approx(3 * EI * delta / L**3) + + +def test_settlement_superposition_with_q_load(): + # Propped cantilever with a q-load and a settlement of the prop: + # R_prop = 3 * q * L / 8 - 3 * EI * delta / L**3 + q = 10.0 + delta = 0.02 + system = propped_cantilever() + system.q_load(q, 1) + system.imposed_displacement(2, uy=delta) + system.solve() + + assert system.reaction_forces[2].Fy == approx(3 * q * L / 8 - 3 * EI * delta / L**3) + + +def test_imposed_displacement_on_unrestrained_dof_raises_on_solve(): + system = cantilever() + system.imposed_displacement(2, uy=0.01) + with raises(FEMException): + system.solve() + + +def test_imposed_displacement_requires_a_value(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + with raises(FEMException): + system.imposed_displacement(1) + + +def test_imposed_displacement_after_solve_raises(): + system = propped_cantilever() + system.point_load(2, Fy=1.0) + system.solve() + with raises(FEMException): + system.imposed_displacement(2, uy=0.01) + + +def test_imposed_displacement_on_inclined_roller_raises(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_hinged(1) + system.add_support_roll(2, angle=45) + with raises(FEMException): + system.imposed_displacement(2, uy=0.01) + + +def test_imposed_rotation_on_internal_hinge_raises(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_support_fixed(1) + system.add_support_roll(3) + system.add_internal_hinge(2) + with raises(FEMException): + system.imposed_displacement(2, phi_z=0.01) + + +def test_imposed_displacement_is_equivalent_for_invert_y_loads_false(): + delta = 0.02 + system_inverted = propped_cantilever() + system_inverted.imposed_displacement(2, uy=delta) + system_inverted.solve() + system_plain = propped_cantilever(invert_y_loads=False) + system_plain.imposed_displacement(2, uy=-delta) + system_plain.solve() + + assert system_plain.reaction_forces[2].Fy == approx( + system_inverted.reaction_forces[2].Fy + ) + + +# --------------------------------------------------------------------------- +# thermal loads +# --------------------------------------------------------------------------- + + +def test_fixed_fixed_uniform_temperature(): + # Fixed-fixed beam with a uniform temperature increase: + # N = -EA * alpha * dT (compression), no bending + system = fixed_fixed() + system.thermal_load(1, delta_t=DT, alpha=ALPHA) + system.solve() + + assert system.reaction_forces[1].Fx == approx(EA * ALPHA * DT) + assert system.reaction_forces[2].Fx == approx(-EA * ALPHA * DT) + assert system.reaction_forces[1].Tz == approx(0) + assert system.reaction_forces[1].Fy == approx(0) + el = system.get_element_results(1) + assert el["Nmin"] == approx(-EA * ALPHA * DT) + assert el["Nmax"] == approx(-EA * ALPHA * DT) + assert el["Mmin"] == approx(0) + assert el["Mmax"] == approx(0) + + +def test_cantilever_uniform_temperature(): + # Cantilever with a uniform temperature increase expands freely: + # tip displacement = alpha * dT * L, no internal forces + system = cantilever() + system.thermal_load(1, delta_t=DT, alpha=ALPHA) + system.solve() + + assert system.get_node_displacements(2)["ux"] == approx(ALPHA * DT * L) + assert system.reaction_forces[1].Fx == approx(0) + el = system.get_element_results(1) + assert el["Nmin"] == approx(0) + assert el["Nmax"] == approx(0) + + +def test_fixed_fixed_temperature_gradient(): + # Fixed-fixed beam with a temperature gradient over the section depth (warmer upper + # face): the upper fibres are restrained in compression and the lower fibres in + # tension, a sagging moment of the constant value EI * kappa, no shear. Sagging + # moments are negative in anaStruct. + system = fixed_fixed() + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + system.solve() + + m = EI * KAPPA + assert system.reaction_forces[1].Tz == approx(-m) + assert system.reaction_forces[2].Tz == approx(m) + assert system.reaction_forces[1].Fy == approx(0) + assert system.reaction_forces[2].Fy == approx(0) + el = system.get_element_results(1) + assert el["Mmin"] == approx(-m) + assert el["Mmax"] == approx(-m) + assert el["Qmin"] == approx(0) + assert el["Qmax"] == approx(0) + + +def test_cantilever_temperature_gradient(): + # Cantilever with a temperature gradient curves freely with a constant curvature + # kappa: tip deflection = kappa * L**2 / 2, no internal forces. A positive gradient is + # a warmer upper face: the upper fibres are longer, so the tip moves down towards the + # colder lower face. get_node_displacements is positive in the direction of +y. + system = cantilever() + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + system.solve() + + assert system.get_node_displacements(2)["uy"] == approx(-KAPPA * L**2 / 2) + assert system.reaction_forces[1].Tz == approx(0) + assert system.reaction_forces[1].Fy == approx(0) + + +def test_propped_cantilever_temperature_gradient(): + # Fixed-pinned beam with a temperature gradient (warmer upper face): + # M_fixed = 3/2 * EI * kappa (sagging, so negative in anaStruct) + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed(1) + system.add_support_hinged(2) + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + system.solve() + + assert system.reaction_forces[1].Tz == approx(-1.5 * EI * KAPPA) + assert system.reaction_forces[1].Fy == approx(1.5 * EI * KAPPA / L) + assert system.reaction_forces[2].Fy == approx(-1.5 * EI * KAPPA / L) + + +def test_simply_supported_beam_with_a_warmer_upper_face_cambers_upwards(): + # an arch-shaped beam: the middle rises by kappa * L**2 / 8 relative to the supports + # (a sun-heated bridge girder) and there are no internal forces + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_hinged(1) + system.add_support_roll(2) + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + middle = system.insert_node(1, factor=0.5)["new_node_id"] + system.solve() + + assert system.get_node_displacements(middle)["uy"] == approx(KAPPA * L**2 / 8) + assert system.reaction_forces[1].Fy == approx(0.0, abs=1e-9) + + +def test_beam_with_a_warmer_lower_face_sags_downwards(): + # the same beam with a negative gradient (warmer lower face) hangs through + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_hinged(1) + system.add_support_roll(2) + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=-DT_GRAD, h=H) + middle = system.insert_node(1, factor=0.5)["new_node_id"] + system.solve() + + assert system.get_node_displacements(middle)["uy"] == approx(-KAPPA * L**2 / 8) + + +def test_truss_uniform_temperature(): + # Fully restrained truss bar with a uniform temperature increase: + # N = -EA * alpha * dT (compression) + system = SystemElements() + system.add_truss_element([[0, 0], [L, 0]], EA=EA) + system.add_support_hinged(1) + system.add_support_hinged(2) + system.thermal_load(1, delta_t=DT, alpha=ALPHA) + system.solve() + + assert system.reaction_forces[1].Fx == approx(EA * ALPHA * DT) + assert system.reaction_forces[2].Fx == approx(-EA * ALPHA * DT) + el = system.get_element_results(1) + assert el["Nmin"] == approx(-EA * ALPHA * DT) + assert el["Nmax"] == approx(-EA * ALPHA * DT) + + +def test_gradient_requires_section_depth(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + with raises(FEMException): + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD) + + +def test_thermal_load_with_element_lists(): + # two elements with different temperature changes, free expansion + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_element([[L, 0], [2 * L, 0]]) + system.add_support_fixed(1) + system.thermal_load([1, 2], delta_t=[DT, 2 * DT], alpha=ALPHA) + system.solve() + + assert system.get_node_displacements(3)["ux"] == approx(3 * ALPHA * DT * L) + + +def test_thermal_load_with_negative_ids(): + system = fixed_fixed() + system.thermal_load(-1, delta_t=DT, alpha=ALPHA) + system.solve() + + assert system.reaction_forces[1].Fx == approx(EA * ALPHA * DT) + + +def test_thermal_load_and_settlement_superposition(): + # propped cantilever, gradient and settlement of the prop: the prop reaction is + # the sum of the separate results + delta = 0.02 + thermal = propped_cantilever() + thermal.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + thermal.solve() + settlement = propped_cantilever() + settlement.imposed_displacement(2, uy=delta) + settlement.solve() + both = propped_cantilever() + both.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + both.imposed_displacement(2, uy=delta) + both.solve() + + assert both.reaction_forces[2].Fy == approx( + thermal.reaction_forces[2].Fy + settlement.reaction_forces[2].Fy + ) + assert both.reaction_forces[2].Fy != approx(0) + + +def test_gradient_warmer_face_on_the_left_of_a_vertical_element(): + # column fixed at the base, the face on the left of the direction from its first to + # its second node is warmer: the free end moves to the colder face. Drawn upwards the + # left face is the face towards -x, so the free end moves to +x; drawn downwards the + # left face is the face towards +x, so the free end moves to -x. + up = SystemElements(EA=EA, EI=EI) + up.add_element([[0, 0], [0, L]]) + up.add_support_fixed(1) + up.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + up.solve() + assert up.get_node_displacements(2)["ux"] == approx(KAPPA * L**2 / 2) + + down = SystemElements(EA=EA, EI=EI) + down.add_element([[0, L], [0, 0]]) + down.add_support_fixed(2) + down.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + down.solve() + assert down.get_node_displacements(1)["ux"] == approx(-KAPPA * L**2 / 2) + + +def test_gradient_warmer_face_up_for_a_right_to_left_element(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[L, 0], [0, 0]]) + system.add_support_fixed(2) + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + system.solve() + + # the warmer face is the upper face, whatever the order of the end points + assert system.get_node_displacements(1)["uy"] == approx(-KAPPA * L**2 / 2) + + +# --------------------------------------------------------------------------- +# load cases and load combinations +# --------------------------------------------------------------------------- + + +def test_thermal_load_in_load_case(): + lc = LoadCase("thermal") + lc.thermal_load(1, delta_t=DT, alpha=ALPHA) + system = fixed_fixed() + system.apply_load_case(lc) + system.solve() + + assert system.reaction_forces[1].Fx == approx(EA * ALPHA * DT) + + +def test_thermal_load_in_load_combination_applies_the_factor(): + lc = LoadCase("thermal") + lc.thermal_load(1, delta_t=DT, alpha=ALPHA) + comb = LoadCombination("ULS") + comb.add_load_case(lc, factor=1.5) + results = comb.solve(fixed_fixed()) + + assert results["combination"].reaction_forces[1].Fx == approx(1.5 * EA * ALPHA * DT) + + +def test_imposed_displacement_in_load_combination(): + # a settlement belongs to one load case: it must be counted once and be + # multiplied by the factor of its load case + delta = 0.02 + q = -10.0 + lc_settlement = LoadCase("settlement") + lc_settlement.imposed_displacement(2, uy=1.0) # unit settlement + lc_q = LoadCase("q") + lc_q.q_load(q, 1) + comb = LoadCombination("ULS") + comb.add_load_case(lc_settlement, factor=delta) + comb.add_load_case(lc_q, factor=1.5) + result = comb.solve(propped_cantilever())["combination"] + + # superposition of independent analyses + settlement_only = propped_cantilever() + settlement_only.imposed_displacement(2, uy=delta) + settlement_only.solve() + q_only = propped_cantilever(load_factor=1.5) + q_only.q_load(q, 1) + q_only.solve() + expected = settlement_only.reaction_forces[2].Fy + q_only.reaction_forces[2].Fy + assert result.reaction_forces[2].Fy == approx(expected) + assert result.get_node_displacements(2)["uy"] == approx(delta) + + +# --------------------------------------------------------------------------- +# model edits +# --------------------------------------------------------------------------- + + +def test_insert_node_carries_the_thermal_load_to_both_new_elements(): + system = cantilever() + system.thermal_load(1, delta_t=0, alpha=ALPHA, delta_t_gradient=DT_GRAD, h=H) + result = system.insert_node(1, factor=0.5) + system.solve() + + assert 1 not in system.loads_temperature + assert set(system.loads_temperature) == { + result["new_element_id1"], + result["new_element_id2"], + } + # free end of the cantilever: -kappa * L**2 / 2 (down), new middle node: + # -kappa * (L/2)**2 / 2 + assert system.get_node_displacements(2)["uy"] == approx(-KAPPA * L**2 / 2) + middle = result["new_node_id"] + assert system.get_node_displacements(middle)["uy"] == approx( + -KAPPA * (L / 2) ** 2 / 2 + ) + + +def test_discretize_keeps_the_thermal_load(): + system = fixed_fixed() + system.thermal_load(1, delta_t=DT, alpha=ALPHA) + system.discretize(4) + system.solve() + + assert system.reaction_forces[1].Fx == approx(EA * ALPHA * DT) + + +def test_discretize_keeps_the_imposed_displacement(): + delta = 0.02 + reference = propped_cantilever() + reference.imposed_displacement(2, uy=delta) + reference.solve() + + system = propped_cantilever() + system.imposed_displacement(2, uy=delta) + system.discretize(4) + system.solve() + + node_id = max(system.reaction_forces) + assert system.reaction_forces[node_id].Fy == approx(reference.reaction_forces[2].Fy) + + +def test_remove_loads_removes_thermal_loads_and_imposed_displacements(): + system = propped_cantilever() + system.thermal_load(1, delta_t=DT, alpha=ALPHA) + system.imposed_displacement(2, uy=0.02) + system.remove_loads() + + assert system.loads_temperature == {} + assert system.loads_displacement == {} + assert system.element_map[1].temperature_load == (0.0, 0.0) + + system.point_load(2, Fy=1.0) + system.solve() + assert system.reaction_forces[1].Fx == approx(0.0, abs=1e-9) + assert system.get_node_displacements(2)["uy"] == approx(0.0, abs=1e-12) diff --git a/tests/test_inherited_fixes.py b/tests/test_inherited_fixes.py new file mode 100644 index 00000000..aa13d517 --- /dev/null +++ b/tests/test_inherited_fixes.py @@ -0,0 +1,521 @@ +import numpy as np +from pytest import approx, mark, raises + +from anastruct import LoadCase, LoadCombination, SystemElements +from anastruct.basic import FEMException +from anastruct.vertex import Vertex + +""" +NOTE: These tests cover problems that anaStruct had before: the model of the plastic hinge, +the node ids after remove_element, LoadCase.dead_load, validate() before the first solve, the +precision of the coordinates, zero length elements and infinite springs, and the load +directions with invert_y_loads=False. + +The tests are plain test functions (not nested describe/context blocks), so that every +assertion is guaranteed to be executed. +""" + +EA = 1.0e6 +EI = 5.0e3 + + +# --------------------------------------------------------------------------- +# plastic hinges: a spring in series with the element, secant stiffness +# --------------------------------------------------------------------------- + + +def two_span_beam(q1, q2, mp): + # fixed at x = 0 with the plastic moment mp, rollers at x = 4 and x = 8 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [4, 0]], mp={1: mp}) + system.add_element([[4, 0], [8, 0]]) + system.add_support_fixed(1) + system.add_support_roll(2) + system.add_support_roll(3) + system.q_load(-q1, 1) + system.q_load(-q2, 2) + system.solve() + return system + + +@mark.parametrize("q1, q2", [(1.0, 1.0), (3.0, 1.0)]) +def test_plastic_hinge_at_a_fixed_end_redistributes_the_moments_exactly(q1, q2): + # a hinge with the moment mp at the fixed end: the three-moment equation with the end + # moment M_A = -mp gives M_B = (-(q1 L1**3 + q2 L2**3) / 4 + mp L1) / (2 (L1 + L2)) + mp = 1.0 + system = two_span_beam(q1, q2, mp) + + expected = (-(q1 * 4**3 + q2 * 4**3) / 4 + mp * 4) / 16 + assert abs(system.reaction_forces[1].Tz) == approx(mp, rel=3e-3) + assert system.element_map[1].bending_moment[-1] == approx(-expected, rel=2e-3) + + +def test_elastic_result_when_the_plastic_moment_is_not_reached(): + system = two_span_beam(2.0, 5.0, 100.0) + elastic = SystemElements(EA=EA, EI=EI) + elastic.add_element([[0, 0], [4, 0]]) + elastic.add_element([[4, 0], [8, 0]]) + elastic.add_support_fixed(1) + elastic.add_support_roll(2) + elastic.add_support_roll(3) + elastic.q_load(-2.0, 1) + elastic.q_load(-5.0, 2) + elastic.solve() + assert system.reaction_forces[1].Tz == approx(elastic.reaction_forces[1].Tz) + assert system.reaction_forces[2].Fy == approx(elastic.reaction_forces[2].Fy) + + +def test_rotation_of_a_propped_cantilever_with_a_plastic_hinge(): + # the hinge at the fixed end leaves a simply supported beam with the end moment mp: + # the rotation at the roller is q L**3 / (24 EI) - mp L / (6 EI) + length, q, mp = 4.0, 3.0, 1.0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [length, 0]], mp={1: mp}) + system.add_support_fixed(1) + system.add_support_roll(2) + system.q_load(-q, 1) + system.solve() + + expected = q * length**3 / (24 * EI) - mp * length / (6 * EI) + assert abs(system.get_node_displacements(2)["phi_z"]) == approx(expected, rel=2e-3) + + +def test_fixed_fixed_beam_with_plastic_hinges_at_both_ends(): + # M = mp at both ends, so the moment at mid-span is q L**2 / 8 - mp (statics) + length, q, mp = 6.0, 10.0, 20.0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [length / 2, 0]], mp={1: mp}) + system.add_element([[length / 2, 0], [length, 0]], mp={2: mp}) + system.add_support_fixed([1, 3]) + system.q_load(-q, [1, 2]) + system.solve() + + assert abs(system.reaction_forces[1].Tz) == approx(mp, rel=5e-3) + assert abs(system.reaction_forces[3].Tz) == approx(mp, rel=5e-3) + assert abs(system.element_map[1].bending_moment[-1]) == approx( + q * length**2 / 8 - mp, rel=5e-3 + ) + + +def test_plastic_hinge_with_a_spring_of_the_user_acts_in_series(): + # a plastic hinge and a rotational spring at the same end: the end carries mp + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [4, 0]], mp={1: 1.0}, spring={1: 800.0}) + system.add_support_fixed(1) + system.add_support_roll(2) + system.q_load(-3.0, 1) + system.solve() + assert abs(system.reaction_forces[1].Tz) == approx(1.0, rel=5e-3) + + +# --------------------------------------------------------------------------- +# remove_element: gaps in the node ids +# --------------------------------------------------------------------------- + + +def three_elements(): + system = SystemElements(EA=EA, EI=1.0e4) + system.add_element([[0, 0], [4, 0]]) + system.add_element([[4, 0], [8, 0]]) + system.add_element([[8, 0], [12, 0]]) + return system + + +def test_solve_after_removing_the_first_element(): + # the node 1 disappears: the ids 2, 3, 4 remain, and the degrees of freedom follow each other + system = three_elements() + system.remove_element(1) + assert sorted(system.node_map) == [2, 3, 4] + system.add_support_fixed(2) + system.add_support_roll(4) + system.q_load(-10, [2, 3]) + system.solve() + + reference = SystemElements(EA=EA, EI=1.0e4) + reference.add_element([[4, 0], [8, 0]]) + reference.add_element([[8, 0], [12, 0]]) + reference.add_support_fixed(1) + reference.add_support_roll(3) + reference.q_load(-10, [1, 2]) + reference.solve() + + assert system.reaction_forces[2].Fy == approx(reference.reaction_forces[1].Fy) + assert system.reaction_forces[2].Tz == approx(reference.reaction_forces[1].Tz) + assert system.get_node_displacements(3)["uy"] == approx( + reference.get_node_displacements(2)["uy"] + ) + + +def test_supports_springs_and_loads_with_gaps_in_the_node_ids(): + system = three_elements() + system.remove_element(1) + system.add_support_fixed(2) + system.add_support_spring(4, translation=2, k=2.0e3) + system.point_load(3, Fy=-5.0) + system.solve() + + reference = SystemElements(EA=EA, EI=1.0e4) + reference.add_element([[4, 0], [8, 0]]) + reference.add_element([[8, 0], [12, 0]]) + reference.add_support_fixed(1) + reference.add_support_spring(3, translation=2, k=2.0e3) + reference.point_load(2, Fy=-5.0) + reference.solve() + + assert system.reaction_forces[2].Tz == approx(reference.reaction_forces[1].Tz) + assert system.get_node_displacements(4)["uy"] == approx( + reference.get_node_displacements(3)["uy"] + ) + + +def test_solve_after_removing_a_middle_element_and_adding_one(): + system = three_elements() + system.remove_element(2) + system.add_element([[4, 0], [8, 0]]) # a new element between the same nodes + system.add_support_fixed(1) + system.add_support_roll(4) + system.q_load(-10, [1, 3, 4]) + system.solve() + + reference = three_elements() + reference.add_support_fixed(1) + reference.add_support_roll(4) + reference.q_load(-10, [1, 2, 3]) + reference.solve() + assert system.reaction_forces[1].Tz == approx(reference.reaction_forces[1].Tz) + + +# --------------------------------------------------------------------------- +# LoadCase.dead_load +# --------------------------------------------------------------------------- + + +def beam_with_supports(**element): + system = SystemElements(EA=EA, EI=1.0e4) + system.add_element([[0, 0], [6, 0]], **element) + system.add_support_fixed(1) + system.add_support_roll(2) + return system + + +def test_dead_load_of_a_load_case(): + reference = beam_with_supports(g=3.0) + reference.solve() + + system = beam_with_supports() + case = LoadCase("self-weight") + case.dead_load(element_id=1, g=3.0) + system.apply_load_case(case) + system.solve() + + assert system.reaction_forces[2].Fy == approx(reference.reaction_forces[2].Fy) + assert system.reaction_forces[1].Tz == approx(reference.reaction_forces[1].Tz) + + +def test_dead_load_method_uses_the_load_factor(): + system = beam_with_supports() + system.load_factor = 1.5 + system.dead_load(1, 2.0) + system.solve() + + reference = beam_with_supports(g=3.0) + reference.solve() + assert system.reaction_forces[2].Fy == approx(reference.reaction_forces[2].Fy) + + +def test_dead_load_in_a_load_combination(): + wind = LoadCase("wind") + wind.point_load(2, Fy=-1.0) + weight = LoadCase("weight") + weight.dead_load(1, 1.0) + combination = LoadCombination("c") + combination.add_load_case(wind, 2.0) + combination.add_load_case(weight, 3.0) + combined = combination.solve(beam_with_supports(g=0.5))["combination"] + + direct = beam_with_supports(g=0.5 + 3.0 * 1.0) + direct.point_load(2, Fy=-2.0) + direct.solve() + assert combined.reaction_forces[1].Tz == approx(direct.reaction_forces[1].Tz) + assert combined.reaction_forces[2].Fy == approx(direct.reaction_forces[2].Fy) + + +def test_q_load_after_removing_the_dead_load(): + # the q-loads of an element are processed also after remove_loads(dead_load=True) + system = beam_with_supports(g=2.0) + system.remove_loads(dead_load=True) + system.q_load(-3.0, 1) + system.solve() + assert abs(system.reaction_forces[1].Tz) == approx(3.0 * 6**2 / 8) + + +# --------------------------------------------------------------------------- +# validate() before the first solve, and errors for unusual input +# --------------------------------------------------------------------------- + + +def test_validate_before_the_first_solve(): + supported = beam_with_supports() + supported.q_load(-1.0, 1) + assert supported.validate() is True + supported.solve() # and the solve still works afterwards + assert abs(supported.reaction_forces[1].Tz) == approx(1.0 * 6**2 / 8) + + unsupported = SystemElements(EA=EA, EI=EI) + unsupported.add_element([[0, 0], [4, 0]]) + unsupported.point_load(2, Fy=-1.0) + assert unsupported.validate() is False + with raises(FEMException) as error: + unsupported.solve() + assert error.value.type == "StabilityError" + + +def test_zero_length_element_is_an_error(): + system = SystemElements() + with raises(FEMException) as error: + system.add_element([[1, 1], [1, 1]]) + assert "two different locations" in error.value.message + assert system.element_map == {} # nothing was added + + +@mark.parametrize("k", [float("inf"), -1.0, float("nan")]) +def test_spring_support_needs_a_finite_stiffness(k): + system = SystemElements() + system.add_element([[0, 0], [1, 0]]) + with raises(FEMException) as error: + system.add_support_spring(1, translation=2, k=k) + assert "finite" in error.value.message + + +# --------------------------------------------------------------------------- +# coordinates in double precision +# --------------------------------------------------------------------------- + + +def test_coordinates_are_stored_in_double_precision(): + # (rounded to 12 significant digits, so that computed coordinates match) + vertex = Vertex(1000.123456789, 0.1) + assert vertex.x == approx(1000.123456789, rel=1e-11) + assert vertex.y == 0.1 # float32 would give 0.10000000149011612 + + system = SystemElements() + system.add_element([[0, 0], [1000.123456789, 0]]) + assert system.element_map[1].l == approx(1000.123456789, rel=1e-11) + + +def test_computed_and_given_coordinates_are_the_same_node(): + # 0.1 + 0.2 is 0.30000000000000004: still the node at 0.3 + system = SystemElements() + system.add_element([[0, 0], [0.1 + 0.2, 0]]) + system.add_element([[0.3, 0], [0.6, 0]]) + assert len(system.node_map) == 3 + assert Vertex(0.1 + 0.2, -0.0) == Vertex(0.3, 0) + assert str(Vertex(-0.0, 1)) == "Vertex(0.0, 1.0)" + + +# --------------------------------------------------------------------------- +# invert_y_loads=False: the x-direction does not change +# --------------------------------------------------------------------------- + + +def cantilever_displacement(invert_y_loads, apply_load): + system = SystemElements(EA=EA, EI=1.0e4, invert_y_loads=invert_y_loads) + system.add_element([[0, 0], [4, 0]]) + system.add_support_fixed(1) + apply_load(system) + system.solve() + displacement = system.get_node_displacements(2) + return displacement["ux"], displacement["uy"] + + +@mark.parametrize("direction", ["x", "parallel"]) +def test_q_load_in_the_x_direction_is_the_same_in_both_modes(direction): + default = cantilever_displacement( + True, lambda s: s.q_load(1.0, 1, direction=direction) + ) + inverted = cantilever_displacement( + False, lambda s: s.q_load(1.0, 1, direction=direction) + ) + assert default[0] > 0 + assert inverted == approx(default) + + +@mark.parametrize("direction", ["y", "element", "perpendicular"]) +def test_q_load_in_the_y_direction_is_reversed_with_invert_y_loads_false(direction): + default = cantilever_displacement( + True, lambda s: s.q_load(1.0, 1, direction=direction) + ) + inverted = cantilever_displacement( + False, lambda s: s.q_load(1.0, 1, direction=direction) + ) + assert default[1] > 0 + assert inverted[1] == approx(-default[1]) + + +def test_q_perp_of_an_x_load_is_a_y_load(): + default = cantilever_displacement( + True, lambda s: s.q_load(1.0, 1, direction="x", q_perp=1.0) + ) + inverted = cantilever_displacement( + False, lambda s: s.q_load(1.0, 1, direction="x", q_perp=1.0) + ) + assert inverted[0] == approx(default[0]) + assert inverted[1] == approx(-default[1]) + + +def test_point_load_rotation_in_both_modes(): + # clockwise rotation: with the default (y up) Fy = 1 (up) turns to +x and Fx = 1 to -y; with + # invert_y_loads=False the y-axis points down: Fy = 1 (down) turns to -x + rotated_fy = { + mode: cantilever_displacement( + mode, lambda s: s.point_load(2, Fy=1.0, rotation=90.0) + ) + for mode in (True, False) + } + assert rotated_fy[True][0] > 0 + assert rotated_fy[False][0] == approx(-rotated_fy[True][0]) + for mode in (True, False): + rotated_fx = cantilever_displacement( + mode, lambda s: s.point_load(2, Fx=1.0, rotation=90.0) + ) + assert rotated_fx[1] < 0 # down + assert np.isclose(rotated_fx[0], 0.0, atol=1e-12) + + +# --------------------------------------------------------------------------- +# findings of the review: ids after a gap, stale supports, order of load cases +# --------------------------------------------------------------------------- + + +def test_new_element_after_a_gap_gets_new_node_ids(): + system = three_elements() + system.remove_element(1) # the ids 2, 3, 4 remain + system.add_element([[12, 0], [16, 0]]) + assert sorted(system.node_map) == [2, 3, 4, 5] + assert system.element_map[4].node_id1 == 4 + assert system.element_map[4].node_id2 == 5 + + system.add_support_fixed(2) + system.add_support_roll(5) + system.q_load(-10, [2, 3, 4]) + system.solve() + + reference = SystemElements(EA=EA, EI=1.0e4) + for i in range(3): + reference.add_element([[4 + 4 * i, 0], [8 + 4 * i, 0]]) + reference.add_support_fixed(1) + reference.add_support_roll(4) + reference.q_load(-10, [1, 2, 3]) + reference.solve() + assert system.reaction_forces[2].Tz == approx(reference.reaction_forces[1].Tz) + + +def test_solve_remove_element_solve_again(): + # the supports of the removed node are removed also after a solve (new node objects) + system = three_elements() + system.add_support_fixed(1) + system.add_support_roll(4) + system.q_load(-10, [1, 2, 3]) + system.solve() + system.remove_element(1) + system.add_support_fixed(2) + system.q_load(-10, [2, 3]) + system.solve() + + reference = SystemElements(EA=EA, EI=1.0e4) + reference.add_element([[4, 0], [8, 0]]) + reference.add_element([[8, 0], [12, 0]]) + reference.add_support_fixed(1) + reference.add_support_roll(3) + reference.q_load(-10, [1, 2]) + reference.solve() + assert system.reaction_forces[2].Tz == approx(reference.reaction_forces[1].Tz) + + +def test_spring_support_and_imposed_displacement_of_a_removed_node_are_removed(): + system = three_elements() + system.add_support_spring(1, translation=2, k=100.0) + system.add_support_fixed(1) + system.imposed_displacement(1, uy=0.01) + system.remove_element(1) + system.add_support_fixed(2) + system.add_support_roll(4) + system.q_load(-10, [2, 3]) + system.solve() + assert sorted(system.reaction_forces) == [2, 4] + + +def test_dead_load_case_after_a_q_load_case_in_a_combination(): + q_case = LoadCase("q") + q_case.q_load(-2.0, 1) + dead_case = LoadCase("g") + dead_case.dead_load(1, 1.5) + combination = LoadCombination("c") + combination.add_load_case(q_case, 1.0) + combination.add_load_case(dead_case, 2.0) + combined = combination.solve(beam_with_supports())["combination"] + + direct = beam_with_supports(g=3.0) + direct.q_load(-2.0, 1) + direct.solve() + assert combined.reaction_forces[1].Tz == approx(direct.reaction_forces[1].Tz) + assert combined.reaction_forces[2].Fy == approx(direct.reaction_forces[2].Fy) + + +@mark.parametrize("mp", [5.99, 5.95]) +def test_plastic_moment_just_below_the_elastic_moment_converges(mp): + # the elastic fixed-end moment is q L**2 / 8 = 6 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [4, 0]], mp={1: mp}) + system.add_support_fixed(1) + system.add_support_roll(2) + system.q_load(-3.0, 1) + system.solve() + assert abs(system.reaction_forces[1].Tz) == approx(mp, rel=2e-3) + + +def test_failed_zero_length_element_keeps_the_previous_point(): + system = SystemElements() + system.add_element([[0, 0], [1, 0]]) + with raises(FEMException): + system.add_element([1, 0]) + system.add_element([2, 0]) # continues from the previous point (1, 0) + assert system.element_map[2].vertex_1 == Vertex(1, 0) + + +@mark.parametrize("rotation, direction", [(0, "x"), (90, "y")]) +@mark.parametrize("perpendicular", [False, True]) +def test_q_load_rotation_is_the_same_as_the_direction_with_invert_y_loads_false( + rotation, direction, perpendicular +): + def displacement(**load): + system = SystemElements(EA=EA, EI=1.0e4, invert_y_loads=False) + system.add_element([[0, 0], [4, 3]]) + system.add_support_fixed(1) + system.q_load( + q=0.0 if perpendicular else 1.0, + element_id=1, + **load, + **({"q_perp": 1.0} if perpendicular else {}), + ) + system.solve() + return system.get_node_displacements(2) + + by_rotation = displacement(rotation=rotation) + by_direction = displacement(direction=direction) + assert by_rotation["ux"] == approx(by_direction["ux"]) + assert by_rotation["uy"] == approx(by_direction["uy"]) + + +def test_plastic_frame_beyond_the_collapse_load_is_a_mechanism(): + mps = [[14.67, 17.98], [10.95, 16.87], [12.48, 13.77], [24.51, 14.17]] + points = [[0, 0], [0, 4], [3, 4], [6, 4], [6, 0]] + system = SystemElements(EA=1.0e8, EI=EI) + for i, (start, end) in enumerate(zip(points[:-1], points[1:])): + system.add_element([start, end], mp={1: mps[i][0], 2: mps[i][1]}) + system.add_support_fixed([1, 5]) + system.point_load(2, Fx=1.526) + system.point_load(3, Fy=-9.892) + system.q_load(-4.731, [2, 3]) + with raises(FEMException, match="mechanism"): + system.solve() diff --git a/tests/test_limitations.py b/tests/test_limitations.py new file mode 100644 index 00000000..fe5941c8 --- /dev/null +++ b/tests/test_limitations.py @@ -0,0 +1,961 @@ +import numpy as np +from pytest import approx, mark, raises + +from anastruct import LoadCase, LoadCombination, SystemElements +from anastruct.basic import FEMException + +""" +NOTE: These tests cover former limitations of anaStruct: loads on nodes with an inclined +roller support, member buckling of bars, plastic hinges in a second order analysis, load +combinations of non linear calculations and changes of the model after a solve. General +definitions: +- L = member length +- EA = axial stiffness +- EI = bending stiffness +- Pcr = Euler buckling load of a column +- reaction_forces[i].Fx is the force of the support on the structure in the +x direction + and reaction_forces[i].Fy the same force counted positive downwards + +The tests are plain test functions (not nested describe/context blocks), so that every +assertion is guaranteed to be executed. +""" + +EA = 1.0e6 +EI = 1.0e4 +L = 4.0 + + +# --------------------------------------------------------------------------- +# point loads on a node with an inclined roller support +# --------------------------------------------------------------------------- + + +@mark.parametrize("angle", [30, 60, 100, 135, 180, 225, -40]) +@mark.parametrize("load", [(0.0, -10.0), (6.0, -10.0), (6.0, 0.0)]) +def test_point_load_on_an_inclined_roller_satisfies_equilibrium(angle, load): + # beam hinged at x = 0, roller at x = L whose free direction has the angle `angle`: + # the reaction R of the roller is normal to the free direction, and the moment about + # the hinge gives R * n_y * L + F_y * L = 0 + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_hinged(1) + system.add_support_roll(2, angle=angle) + system.point_load(2, Fx=load[0], Fy=load[1]) + system.solve() + + radians = np.radians(angle) + normal = np.array([-np.sin(radians), np.cos(radians)]) + force = np.array(load) + roller = -force[1] / normal[1] * normal + hinge = -(force + roller) + + reaction_roller = system.reaction_forces[2] + reaction_hinge = system.reaction_forces[1] + assert [reaction_roller.Fx, -reaction_roller.Fy] == approx(list(roller), abs=1e-6) + assert [reaction_hinge.Fx, -reaction_hinge.Fy] == approx(list(hinge), abs=1e-6) + + +@mark.parametrize( + "beam, plain, angle, load", + [ + ([[0, 0], [L, 0]], "x", 0, (3.0, -10.0)), + ([[0, 0], [L, 0]], "x", 180, (7.0, -10.0)), + ([[0, 0], [0, L]], "y", 90, (5.0, 3.0)), + ], +) +def test_point_load_on_an_inclined_roller_equals_a_plain_roller( + beam, plain, angle, load +): + # inclined rollers of 0, 90 and 180 degrees are the plain rollers + results = [] + for kind in (plain, angle): + system = SystemElements(EA=EA, EI=EI) + system.add_element(beam) + system.add_support_hinged(1) + if isinstance(kind, str): + system.add_support_roll(2, kind) + else: + system.add_support_roll(2, angle=kind) + system.point_load(2, Fx=load[0], Fy=load[1]) + system.solve() + results.append( + [ + system.reaction_forces[1].Fx, + system.reaction_forces[1].Fy, + system.reaction_forces[2].Fx, + system.reaction_forces[2].Fy, + *system.get_node_displacements(2).values(), + ] + ) + assert results[0] == approx(results[1], abs=1e-9) + + +# --------------------------------------------------------------------------- +# member buckling of bars +# --------------------------------------------------------------------------- + + +def test_bar_with_hinges_at_both_ends_buckles_like_an_euler_column(): + # a bar is an element with hinges at both ends: discretize puts the hinges at the + # ends of the bar only, so the bar can buckle between the new nodes + ei, length = 5.0e3, 10.0 + system = SystemElements(EI=ei, EA=EA) + system.add_element([[0, 0], [0, length]], spring={1: 0, 2: 0}) + system.add_support_hinged(1) + system.add_support_roll(2, "y") + system.point_load(2, Fy=-1) + system.solve(geometrical_non_linear=True, discretize_kwargs={"n": 20}) + + assert system.buckling_factor == approx(np.pi**2 * ei / length**2, rel=1e-3) + + +def test_member_buckling_of_a_truss_bar(): + # symmetric two-bar truss with an apex load of 1: N = 1 / (2 sin 45 deg) in each bar, + # the bars (l = 2 sqrt 2) buckle at Pcr / N = pi**2 EI / l**2 / N + ei = 5.0e3 + length = np.hypot(2, 2) + expected = np.pi**2 * ei / length**2 / (1 / (2 * np.sin(np.pi / 4))) + + system = SystemElements(EA=EA, EI=ei) + system.add_element([[0, 0], [2, 2]], spring={1: 0, 2: 0}) + system.add_element([[2, 2], [4, 0]], spring={1: 0, 2: 0}) + system.add_support_hinged(1) + system.add_support_hinged(3) + system.point_load(2, Fy=-1) + system.solve(geometrical_non_linear=True, discretize_kwargs={"n": 20}) + + assert system.buckling_factor == approx(expected, rel=1e-3) + + +def test_truss_elements_have_no_member_buckling(): + # truss elements have no bending stiffness: only the geometry of the whole truss + system = SystemElements(EA=EA) + system.add_truss_element([[0, 0], [2, 2]]) + system.add_truss_element([[2, 2], [4, 0]]) + system.add_support_hinged(1) + system.add_support_hinged(3) + system.point_load(2, Fy=-1) + system.solve(geometrical_non_linear=True) + + assert system.buckling_factor > 1.0e5 + + +# --------------------------------------------------------------------------- +# plastic hinges in a second order analysis +# --------------------------------------------------------------------------- + + +def plastic_column(horizontal, axial, mp, **solve_kwargs): + # fixed base (plastic moment mp), lateral support at the top, a horizontal load at + # mid-height and an axial compression at the top + system = SystemElements(EI=5.0e3, EA=EA) + system.add_element([[0, 0], [0, 2]], mp={1: mp}) + system.add_element([[0, 2], [0, 4]]) + system.add_support_fixed(1) + system.add_support_roll(3, "y") + system.point_load(2, Fx=horizontal) + system.point_load(3, Fy=-axial) + system.solve(**solve_kwargs) + return system + + +def test_second_order_analysis_without_axial_force_is_first_order(): + first = plastic_column(60.0, 0.0, 30.0) + second = plastic_column(60.0, 0.0, 30.0, geometrical_non_linear=True) + assert second.get_node_displacements(2)["ux"] == approx( + first.get_node_displacements(2)["ux"] + ) + + +def test_plastic_hinge_in_a_second_order_analysis(): + # the base moment is limited by mp, the compression amplifies the displacement + first = plastic_column(60.0, 150.0, 30.0) + second = plastic_column(60.0, 150.0, 30.0, geometrical_non_linear=True) + elastic_second = plastic_column(60.0, 150.0, 1.0e9, geometrical_non_linear=True) + + assert abs(first.reaction_forces[1].Tz) == approx(30.0, rel=5e-3) + assert abs(second.reaction_forces[1].Tz) == approx(30.0, rel=5e-3) + assert abs(elastic_second.reaction_forces[1].Tz) > 45.0 # not limited + assert abs(second.get_node_displacements(2)["ux"]) > abs( + first.get_node_displacements(2)["ux"] + ) + + +def test_buckling_factor_with_plastic_hinges_is_the_elastic_one(): + # the elastic cantilever column, one element: the load of 0.3 Pcr + ei, length = 5.0e3, 4.0 + pcr = np.pi**2 * ei / (4 * length**2) + system = SystemElements(EI=ei, EA=EA) + system.add_element([[0, 0], [0, length]], mp={1: 30.0}) + system.add_support_fixed(1) + system.point_load(2, Fx=4.0, Fy=-0.3 * pcr) + system.solve(geometrical_non_linear=True, discretize_kwargs={"n": 20}) + + assert system.buckling_factor == approx(1 / 0.3, rel=1e-3) + # (the moment of 4 * 4 + the second order part stays below mp: elastic result) + elastic = SystemElements(EI=ei, EA=EA) + elastic.add_element([[0, 0], [0, length]]) + elastic.add_support_fixed(1) + elastic.point_load(2, Fx=4.0, Fy=-0.3 * pcr) + elastic.solve(geometrical_non_linear=True) + assert system.get_node_displacements(2)["ux"] == approx( + elastic.get_node_displacements(2)["ux"] + ) + + +# --------------------------------------------------------------------------- +# load combinations of non linear calculations +# --------------------------------------------------------------------------- + + +def two_element_column(): + system = SystemElements(EI=5.0e3, EA=EA) + system.add_element([[0, 0], [0, 2]]) + system.add_element([[0, 2], [0, 4]]) + system.add_support_fixed(1) + return system + + +def test_second_order_combination_is_one_calculation_with_all_the_loads(): + pcr = np.pi**2 * 5.0e3 / (4 * 4.0**2) + horizontal, axial = 5.0, 0.3 * pcr + wind = LoadCase("wind") + wind.point_load(2, Fx=1.0) + wind.q_load(-2.0, 2) + gravity = LoadCase("gravity") + gravity.point_load(3, Fy=-1.0) + combination = LoadCombination("ULS") + combination.add_load_case(wind, horizontal) + combination.add_load_case(gravity, axial) + results = combination.solve(two_element_column(), geometrical_non_linear=True) + + direct = two_element_column() + direct.point_load(2, Fx=horizontal) + direct.point_load(3, Fy=-axial) + direct.q_load(-2.0 * horizontal, 2) + direct.solve(geometrical_non_linear=True) + + combined = results["combination"] + for node_id in (1,): + assert combined.reaction_forces[node_id].Fx == approx( + direct.reaction_forces[node_id].Fx + ) + assert combined.reaction_forces[node_id].Fy == approx( + direct.reaction_forces[node_id].Fy + ) + assert combined.reaction_forces[node_id].Tz == approx( + direct.reaction_forces[node_id].Tz + ) + assert combined.get_node_displacements(3)["ux"] == approx( + direct.get_node_displacements(3)["ux"] + ) + assert combined.buckling_factor == approx(direct.buckling_factor) + + # superposing the second order results of the load cases would not be second order + superposed = sum( + results[name].get_node_displacements(3)["ux"] for name in ("wind", "gravity") + ) + assert abs(combined.get_node_displacements(3)["ux"]) > abs(superposed) * 1.05 + + +def test_second_order_combination_with_thermal_loads_and_factors(): + def build(): + system = SystemElements(EI=5.0e3, EA=EA) + system.add_element([[0, 0], [0, 2]]) + system.add_element([[0, 2], [0, 4]]) + system.add_support_fixed(1) + return system + + q_case = LoadCase("q") + q_case.q_load(-3.0, 1) + thermal_case = LoadCase("thermal") + thermal_case.thermal_load(2, delta_t=15, alpha=1.2e-5, delta_t_gradient=10, h=0.4) + point_case = LoadCase("point") + point_case.point_load(3, Fx=2.0, Fy=-50.0) + combination = LoadCombination("c") + combination.add_load_case(q_case, 1.5) + combination.add_load_case(thermal_case, 1.2) + combination.add_load_case(point_case, 1.1) + combined = combination.solve(build(), geometrical_non_linear=True)["combination"] + + direct = build() + direct.q_load(-3.0 * 1.5, 1) + direct.thermal_load( + 2, delta_t=15 * 1.2, alpha=1.2e-5, delta_t_gradient=10 * 1.2, h=0.4 + ) + direct.point_load(3, Fx=2.0 * 1.1, Fy=-50.0 * 1.1) + direct.solve(geometrical_non_linear=True) + + assert combined.reaction_forces[1].Tz == approx(direct.reaction_forces[1].Tz) + assert combined.get_node_displacements(3)["ux"] == approx( + direct.get_node_displacements(3)["ux"] + ) + + +def test_linear_combination_is_still_superposed(): + wind = LoadCase("wind") + wind.point_load(3, Fx=1.0) + gravity = LoadCase("gravity") + gravity.point_load(3, Fy=-1.0) + combination = LoadCombination("c") + combination.add_load_case(wind, 5.0) + combination.add_load_case(gravity, 40.0) + results = combination.solve(two_element_column()) + + expected = sum( + results[name].get_node_displacements(3)["ux"] for name in ("wind", "gravity") + ) + assert results["combination"].get_node_displacements(3)["ux"] == approx(expected) + assert results["combination"].buckling_factor is None + + +def test_combination_with_plastic_hinges_is_one_calculation(): + def build(): + system = SystemElements(EI=5.0e3, EA=EA) + system.add_element([[0, 0], [0, 2]], mp={1: 30.0}) + system.add_element([[0, 2], [0, 4]]) + system.add_support_fixed(1) + system.add_support_roll(3, "y") + return system + + first = LoadCase("first") + first.point_load(2, Fx=1.0) + combination = LoadCombination("c") + combination.add_load_case(first, 60.0) + combined = combination.solve(build())["combination"] + + direct = build() + direct.point_load(2, Fx=60.0) + direct.solve() + + assert abs(combined.reaction_forces[1].Tz) == approx(30.0, rel=5e-3) + assert combined.reaction_forces[1].Tz == approx(direct.reaction_forces[1].Tz) + assert combined.get_node_displacements(2)["ux"] == approx( + direct.get_node_displacements(2)["ux"] + ) + + +# --------------------------------------------------------------------------- +# changes of the model after a solve +# --------------------------------------------------------------------------- + + +def chain(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [4, 0]]) + system.add_element([[4, 0], [8, 0]]) + system.add_element([[8, 0], [12, 0]]) + system.add_support_fixed(1) + system.add_support_roll(4) + system.q_load(-10, [1, 2, 3]) + return system + + +def test_support_added_after_a_solve_is_used(): + expected = chain() + expected.add_support_hinged(3) + expected.solve() + + system = chain() + system.solve() + system.add_support_hinged(3) + system.solve() + + assert system.reaction_forces[3].Fy == approx(expected.reaction_forces[3].Fy) + assert system.reaction_forces[1].Tz == approx(expected.reaction_forces[1].Tz) + + +def test_insert_node_after_a_solve(): + def build(solve_first): + system = chain() + if solve_first: + system.solve() + ids = system.insert_node(2, factor=0.5) + system.q_load(-10, [ids["new_element_id1"], ids["new_element_id2"]]) + system.solve() + return system + + after, before = build(True), build(False) + assert after.reaction_forces[1].Fy == approx(before.reaction_forces[1].Fy) + assert after.reaction_forces[1].Tz == approx(before.reaction_forces[1].Tz) + + +def test_element_added_after_a_solve(): + def build(solve_first): + system = chain() + if solve_first: + system.solve() + system.add_element([[12, 0], [16, 0]]) + system.add_support_roll(5) + system.q_load(-10, 4) + system.solve() + return system + + after, before = build(True), build(False) + assert after.reaction_forces[1].Fy == approx(before.reaction_forces[1].Fy) + + +def test_imposed_displacement_after_a_change_of_the_model(): + system = chain() + system.solve() + system.add_support_hinged(3) # the solution is reset, so a displacement can follow + system.imposed_displacement(3, uy=-0.01) + system.solve() + + expected = chain() + expected.add_support_hinged(3) + expected.imposed_displacement(3, uy=-0.01) + expected.solve() + assert system.reaction_forces[3].Fy == approx(expected.reaction_forces[3].Fy) + + +def test_spring_dictionaries_are_not_shared_between_elements(): + spring = {1: 0} + multiple = SystemElements(EA=EA, EI=EI) + multiple.add_multiple_elements([[0, 0], [8, 0]], n=2, spring=spring) + grid = SystemElements(EA=EA, EI=EI) + grid.add_element_grid([0, 3, 6], [0, 0, 0], spring=spring) + + elements = list(multiple.element_map.values()) + list(grid.element_map.values()) + assert len({id(element.springs) for element in elements}) == len(elements) + assert spring == {1: 0} + + +# --------------------------------------------------------------------------- +# review findings: hinges added after a solve, repeated and forced linear calculations +# --------------------------------------------------------------------------- + + +def test_internal_hinge_added_after_a_solve(): + # fixed - 4 m - hinge - 4 m - fixed with a load P = 10 at the hinge: two cantilevers + # with M = P / 2 * l = 20 and u = P / 2 * l**3 / (3 EI) + def build(): + system = SystemElements() + system.add_element([[0, 0], [4, 0]]) + system.add_element([[4, 0], [8, 0]]) + system.add_support_fixed([1, 3]) + system.point_load(2, Fy=-10) + return system + + after = build() + after.solve() + after.add_internal_hinge(2) + after.solve() + + assert abs(after.reaction_forces[1].Tz) == approx(20.0) + assert abs(after.get_node_displacements(2)["uy"]) == approx( + 5.0 * 4.0**3 / (3 * 5.0e3) + ) + + +def plastic_beam_column(mp, **solve_kwargs): + # fixed base (plastic moment mp), lateral support at the top, a horizontal load at + # mid-height and an axial compression at the top + system = SystemElements(EI=2.0e3, EA=5.0e4) + system.add_element([[0, 0], [0, 2]], mp={1: mp}) + system.add_element([[0, 2], [0, 4]]) + system.add_support_fixed(1) + system.add_support_roll(3, "y") + system.point_load(2, Fx=10.0) + system.point_load(3, Fy=-80.0) + system.solve(**solve_kwargs) + return system + + +def test_forced_linear_second_order_analysis_ignores_the_plastic_moments(): + plastic = plastic_beam_column(4.0, geometrical_non_linear=True, force_linear=True) + elastic = plastic_beam_column(1.0e9, geometrical_non_linear=True, force_linear=True) + + assert plastic.reaction_forces[1].Tz == approx(elastic.reaction_forces[1].Tz) + assert plastic.get_node_displacements(2)["ux"] == approx( + elastic.get_node_displacements(2)["ux"] + ) + assert abs(plastic.reaction_forces[1].Tz) > 4.0 # the elastic moment, not mp + + +def test_repeated_second_order_calculations_with_plastic_hinges_are_identical(): + system = plastic_beam_column(4.0, geometrical_non_linear=True) + elastic = plastic_beam_column(1.0e9, geometrical_non_linear=True) + first = ( + system.buckling_factor, + system.reaction_forces[1].Tz, + system.get_node_displacements(2)["ux"], + ) + for _ in range(2): + system.solve(geometrical_non_linear=True) + again = ( + system.buckling_factor, + system.reaction_forces[1].Tz, + system.get_node_displacements(2)["ux"], + ) + assert again == approx(first, rel=1e-9) + + # the buckling factor is that of the elastic structure + assert first[0] == approx(elastic.buckling_factor) + assert abs(first[1]) == approx(4.0, rel=5e-3) # limited by mp + + +def test_repeated_plastic_calculations_start_from_the_elastic_stiffness(): + system = SystemElements(EI=5.0e3, EA=1.0e6) + system.add_element([[0, 0], [0, 2]], mp={1: 30.0}) + system.add_element([[0, 2], [0, 4]]) + system.add_support_fixed(1) + system.add_support_roll(3, "y") + system.point_load(2, Fx=60.0) + results = [] + for _ in range(3): + system.solve() + results.append( + (system.reaction_forces[1].Tz, system.get_node_displacements(2)["ux"]) + ) + assert results[1] == approx(results[0], rel=1e-9) + assert results[2] == approx(results[0], rel=1e-9) + + +def test_plastic_iteration_that_does_not_converge_is_an_error(): + # a cantilever with a plastic hinge at the base that carries less than the load: + # a mechanism, there is no solution + system = SystemElements(EI=5.0e3, EA=1.0e6) + system.add_element([[0, 0], [0, 4]], mp={1: 30.0}) + system.add_support_fixed(1) + system.point_load(2, Fx=10.0) + with raises(FEMException): + system.solve(max_iter=30) + + +def test_combination_counts_the_loads_of_the_system_once(): + # the self-weight and a load of the system itself are part of every load case result, + # but only once of the combination (linear as well as non linear) + def build(): + system = SystemElements(EI=EI, EA=EA) + system.add_element([[0, 0], [4, 0]], g=1.5) + system.add_element([[4, 0], [8, 0]], g=1.5) + system.add_support_fixed(1) + system.add_support_roll(3) + system.point_load(2, Fy=-3.0) + return system + + first = LoadCase("first") + first.q_load(-2.0, 1) + second = LoadCase("second") + second.point_load(3, Fy=-4.0) + combination = LoadCombination("c") + combination.add_load_case(first, 1.5) + combination.add_load_case(second, 1.2) + combined = combination.solve(build())["combination"] + + direct = build() + direct.q_load(-2.0 * 1.5, 1) + direct.point_load(3, Fy=-4.0 * 1.2) + direct.solve() + + assert combined.reaction_forces[1].Fy == approx(direct.reaction_forces[1].Fy) + assert combined.reaction_forces[1].Tz == approx(direct.reaction_forces[1].Tz) + assert combined.get_node_displacements(2)["uy"] == approx( + direct.get_node_displacements(2)["uy"] + ) + + +# --------------------------------------------------------------------------- +# imposed displacements in a direction that no support restrains +# --------------------------------------------------------------------------- + + +def fixed_beam(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [10, 0]]) + system.add_support_fixed(1) + return system + + +def message_of(action): + with raises(FEMException) as error: + action() + return error.value.message + + +def test_imposed_displacement_in_the_free_direction_of_a_roller_explains_why(): + def action(): + system = fixed_beam() + system.add_support_roll(2, "x") + system.imposed_displacement(2, ux=0.01) + system.solve() + + message = message_of(action) + assert "imposed ux at node 2" in message + assert "roller support that is free to move in the x direction" in message + assert "restrains the y translation" in message + + +def test_imposed_rotation_at_a_hinged_support_explains_why(): + def action(): + system = fixed_beam() + system.add_support_hinged(2) + system.imposed_displacement(2, phi_z=0.01) + system.solve() + + message = message_of(action) + assert "imposed phi_z at node 2" in message + assert "hinged support" in message and "not the rotation" in message + + +def test_imposed_displacement_on_an_inclined_roller_explains_the_restrained_direction(): + def action(): + system = fixed_beam() + system.add_support_roll(2, angle=30) + system.imposed_displacement(2, uy=0.01) + + message = message_of(action) + assert "imposed uy at node 2" in message + assert "inclined roller support" in message + assert "direction of 30 degrees" in message # the free direction + assert ( + "direction of 120 degrees" in message + ) # the restrained direction, normal to it + + +def test_inclined_roller_added_after_the_imposed_displacement_is_reported_when_solving(): + def action(): + system = fixed_beam() + system.imposed_displacement(2, uy=0.01) + system.add_support_roll(2, angle=45) + system.solve() + + message = message_of(action) + assert "imposed uy at node 2" in message + assert "inclined roller support" in message + + +def test_imposed_displacement_without_a_support_and_on_a_spring_support(): + def without_support(): + system = fixed_beam() + system.imposed_displacement(2, uy=0.01) + system.solve() + + def with_spring(): + system = fixed_beam() + system.add_support_spring(2, translation=2, k=500.0) + system.imposed_displacement(2, uy=0.01) + system.solve() + + assert "no support restrains" in message_of(without_support) + assert "spring support, which yields" in message_of(with_spring) + + +# --------------------------------------------------------------------------- +# findings of the second review +# --------------------------------------------------------------------------- + + +def test_second_order_solves_of_a_horizontal_column_are_repeatable(): + # the transverse displacements of a horizontal column are exactly 0: they must not + # become restrained degrees of freedom in the second solve + def build(): + system = SystemElements(EI=5.0e3, EA=1.0e5) + system.add_multiple_elements([[0, 0], [10, 0]], 10) + system.add_support_hinged(1) + system.add_support_roll(11, "x") + system.point_load(11, Fx=-1) + return system + + system = build() + factors = [] + for _ in range(3): + system.solve(geometrical_non_linear=True) + factors.append(system.buckling_factor) + assert np.isfinite(factors[0]) + assert factors == approx([factors[0]] * 3) + assert factors[0] == approx(np.pi**2 * 5.0e3 / 10.0**2, rel=2e-3) + + +def test_linear_calculation_after_a_plastic_one_is_elastic(): + def build(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [3, 0]], mp={1: 20.0}) + system.add_element([[3, 0], [6, 0]], mp={2: 20.0}) + system.add_support_fixed([1, 3]) + system.q_load(-10, [1, 2]) + return system + + plastic = build() + plastic.solve() + assert abs(plastic.reaction_forces[1].Tz) == approx(20.0, rel=5e-3) + plastic.solve(force_linear=True) + + elastic = build() + elastic.solve(force_linear=True) + assert abs(elastic.reaction_forces[1].Tz) == approx(10 * 6**2 / 12) + assert plastic.reaction_forces[1].Tz == approx(elastic.reaction_forces[1].Tz) + + +def test_combination_with_an_imposed_displacement_when_the_system_was_solved(): + def build(): + system = chain() + system.q_load(-10, [1, 2, 3]) + return system + + solved = build() + solved.solve() + settlement = LoadCase("settlement") + settlement.imposed_displacement(4, uy=-0.01) + combination = LoadCombination("c") + combination.add_load_case(settlement, 1.0) + combined = combination.solve(solved)["combination"] + + fresh = build() + fresh.imposed_displacement(4, uy=-0.01) + fresh.solve() + assert combined.reaction_forces[1].Fy == approx(fresh.reaction_forces[1].Fy) + assert combined.reaction_forces[1].Tz == approx(fresh.reaction_forces[1].Tz) + + +def test_buckling_factor_without_free_degrees_of_freedom_is_infinite(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed([1, 2]) + system.q_load(-1, 1) + system.solve(geometrical_non_linear=True) + assert system.buckling_factor == float("inf") + + +@mark.parametrize("k", [500.0, 5.0e3, 5.0e4]) +def test_buckling_of_one_element_with_a_spring_is_close_to_the_rotational_support(k): + # the geometric stiffness of a released end is condensed with the elastic stiffness: one + # element per member is within 0.5 % (it was several times too high before) + with_spring = SystemElements(EI=5.0e3, EA=EA) + with_spring.add_element([[0, 0], [0, 10]], spring={1: k}) + with_spring.add_support_fixed(1) + with_spring.point_load(2, Fy=-1) + with_spring.solve(geometrical_non_linear=True) + + with_support = SystemElements(EI=5.0e3, EA=EA) + with_support.add_element([[0, 0], [0, 10]]) + with_support.add_support_hinged(1) + with_support.add_support_spring(1, translation=3, k=k) + with_support.point_load(2, Fy=-1) + with_support.solve(geometrical_non_linear=True) + + assert with_spring.buckling_factor == approx(with_support.buckling_factor, rel=5e-3) + + +def test_plastic_moment_of_zero_is_an_error(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]], mp={1: 0.0}) + system.add_support_fixed(1) + system.add_support_roll(2) + system.point_load(2, Fy=-1.0) + with raises(AssertionError, match="mp = 0"): + system.solve() + + +@mark.parametrize("g", [2.0, -2.0]) +def test_second_order_self_weight_column_does_not_depend_on_the_drawing_direction(g): + # the normal force varies along the element: the geometric stiffness uses its mean + def build(drawn_up): + system = SystemElements(EI=5.0e3, EA=1.0e6) + if drawn_up: + system.add_element([[0, 0], [0, 10]], g=g) + system.add_support_fixed(1) + else: + system.add_element([[0, 10], [0, 0]], g=g) + system.add_support_fixed(2) + system.solve(geometrical_non_linear=True, discretize_kwargs={"n": 8}) + return system.buckling_factor + + up, down = build(True), build(False) + assert up == approx(down, rel=1e-6) + + +@mark.parametrize("options", [{}, {"load_factor": 2.0}, {"invert_y_loads": False}]) +def test_insert_node_copies_the_q_load_with_factor_and_orientation(options): + def build(split): + system = SystemElements(EA=EA, EI=EI, **options) + system.add_element([[0, 0], [4, 0]]) + system.add_support_fixed(1) + system.add_support_roll(2) + system.q_load([-4, -8], 1) + if split: + system.insert_node(1, factor=0.3) + system.solve() + return system + + plain, split = build(False), build(True) + for node_id in (1, 2): + assert split.reaction_forces[node_id].Fy == approx( + plain.reaction_forces[node_id].Fy, rel=1e-5 + ) + assert split.reaction_forces[1].Tz == approx(plain.reaction_forces[1].Tz, rel=1e-5) + + +def test_insert_node_keeps_a_truss_element_a_truss(): + system = SystemElements(EA=1.0e5) + system.add_truss_element([[0, 0], [3, 0]]) + system.add_support_hinged(1) + system.add_support_roll(2) + system.insert_node(1, factor=0.5) + assert {element.type for element in system.element_map.values()} == {"truss"} + + +def test_internal_hinges_stay_consistent_when_hinges_are_added_and_removed(): + system = SystemElements(EA=EA, EI=EI) + for x in range(5): + system.add_element([[x * 3, 0], [(x + 1) * 3, 0]]) + for node_id in (4, 2, 5, 3): + system.add_internal_hinge(node_id) + assert sorted(h.id for h in system.internal_hinges) == [2, 3, 4, 5] + index = system._internal_hinge_index + assert all(system.internal_hinges[i].id == node_id for node_id, i in index.items()) + + system.remove_element(5) # the node 6 is removed, the hinge at node 5 stays + system.remove_element(4) # the node 5 is removed with its hinge + assert sorted(h.id for h in system.internal_hinges) == [2, 3, 4] + index = system._internal_hinge_index + assert sorted(index) == [2, 3, 4] + assert all(system.internal_hinges[i].id == node_id for node_id, i in index.items()) + + +def test_remove_loads_removes_the_perpendicular_q_load(): + def build(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [L, 0]]) + system.add_support_fixed(1) + return system + + system = build() + system.q_load(q=-5, element_id=1, direction="x", q_perp=-3) + system.remove_loads() + system.point_load(2, Fy=-1.0) + system.solve() + + fresh = build() + fresh.point_load(2, Fy=-1.0) + fresh.solve() + assert system.get_node_displacements(2)["uy"] == approx( + fresh.get_node_displacements(2)["uy"] + ) + + +def test_combination_adds_the_loads_of_the_cases_to_the_loads_of_the_system(): + def build(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [4, 0]]) + system.add_element([[4, 0], [8, 0]]) + system.add_support_fixed(1) + system.add_support_roll(3) + system.point_load(2, Fy=-3.0) + system.moment_load(2, Tz=2.0) + system.imposed_displacement(3, uy=-0.01) + return system + + first = LoadCase("first") + first.point_load(2, Fy=-1.0) + first.moment_load(2, Tz=1.0) + first.imposed_displacement(3, uy=-0.005) + second = LoadCase("second") + second.point_load(2, Fy=-1.0) + second.moment_load(2, Tz=1.0) + second.imposed_displacement(3, uy=-0.005) + combination = LoadCombination("c") + combination.add_load_case(first, 1.0) + combination.add_load_case(second, 2.0) + combined = combination.solve(build())["combination"] + + # the system itself counts once: -3 - 1 - 2, 2 + 1 + 2, -0.01 - 0.005 - 0.01 + direct = SystemElements(EA=EA, EI=EI) + direct.add_element([[0, 0], [4, 0]]) + direct.add_element([[4, 0], [8, 0]]) + direct.add_support_fixed(1) + direct.add_support_roll(3) + direct.point_load(2, Fy=-6.0) + direct.moment_load(2, Tz=5.0) + direct.imposed_displacement(3, uy=-0.025) + direct.solve() + + assert combined.loads_point[2] == approx(direct.loads_point[2]) + assert combined.reaction_forces[1].Fy == approx(direct.reaction_forces[1].Fy) + assert combined.reaction_forces[1].Tz == approx(direct.reaction_forces[1].Tz) + assert combined.get_node_displacements(2)["uy"] == approx( + direct.get_node_displacements(2)["uy"] + ) + + +def test_combination_does_not_show_rounding_noise_in_the_q_load(): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [0, 4]]) + system.add_support_fixed(1) + case = LoadCase("q") + case.q_load(-1.5, 1) + combination = LoadCombination("c") + combination.add_load_case(case, 1.0) + results = combination.solve(system) + + values = [ + *results["combination"].get_element_results(1)["q"], + *results["combination"].element_map[1].q_load, + *results["combination"].element_map[1].q_perp_load, + ] + assert all(value == 0 or abs(value) > 1e-9 for value in values) + assert results["combination"].get_element_results(1)["q"] == approx( + results["q"].get_element_results(1)["q"] + ) + + +@mark.parametrize("support", ["fixed", "spring"]) +def test_supports_added_after_a_solve_are_used(support): + def add(system): + if support == "fixed": + system.add_support_fixed(3) + else: + system.add_support_spring(3, translation=2, k=500.0) + + expected = chain() + add(expected) + expected.solve() + + system = chain() + system.solve() + add(system) + system.solve() + assert system.reaction_forces[1].Tz == approx(expected.reaction_forces[1].Tz) + assert system.reaction_forces[1].Fy == approx(expected.reaction_forces[1].Fy) + + +def test_element_with_a_hinge_added_after_a_solve(): + def build(solve_first): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [4, 0]], spring={2: 0}) + system.add_support_fixed(1) + if solve_first: + system.point_load(2, Fy=-1.0) + system.solve() + system.add_element([[4, 0], [8, 0]], spring={1: 0}) + system.add_support_hinged(3) + system.remove_loads() + system.q_load(-10, [1, 2]) + system.solve() + return system + + after, before = build(True), build(False) + assert after.reaction_forces[1].Fy == approx(before.reaction_forces[1].Fy) + assert after.reaction_forces[1].Tz == approx(before.reaction_forces[1].Tz) + assert [hinge.id for hinge in after.internal_hinges] == [2] + + +def test_discretize_keeps_the_direction_of_a_q_load_on_an_inclined_element(): + def build(n=None): + system = SystemElements(EA=EA, EI=EI) + system.add_element([[0, 0], [5, 3]]) + system.add_support_fixed(1) + system.add_support_hinged(2) + system.q_load(-4, 1, direction="x") + if n: + system.discretize(n) + system.solve() + return system + + plain, fine = build(), build(4) + for point in ([0, 0], [5, 3]): + reaction_plain = plain.reaction_forces[plain.find_node_id(point)] + reaction_fine = fine.reaction_forces[fine.find_node_id(point)] + assert reaction_fine.Fx == approx(reaction_plain.Fx, abs=1e-3) + assert reaction_fine.Fy == approx(reaction_plain.Fy, abs=1e-3) diff --git a/tests/test_upstream_examples.py b/tests/test_upstream_examples.py new file mode 100644 index 00000000..8712def8 --- /dev/null +++ b/tests/test_upstream_examples.py @@ -0,0 +1,132 @@ +import numpy as np +from pytest import approx + +from anastruct import SystemElements + +""" +NOTE: The upstream tests of these examples (tests/test_e2e.py) are nested describe/context/it +blocks, which pytest-describe does not run in this environment. These plain tests execute +them. The expectations for the hinge in example 4 and the rotational spring in example 7 +follow from the condensation of hinges and springs (the older values, 3.125e-3 and +0.2356/0.0967/0.0643, used 4EI/l for an element with a hinge, and a wrong series of the +spring), and are verified independently here. +""" + + +def test_example_4_column_pinned_at_both_ends(): + # a moment M at the top of a column that is pinned at both ends (the beam, with a hinge + # at the column, only gives a horizontal support): the rotation is M * l / (3 EI) + system = SystemElements() + system.add_element(location=[[0, 0], [5, 0]], EA=5e9, EI=8000, spring={2: 0}) + system.add_element(location=[[5, 0], [5, 5]], EA=5e9, EI=4000) + system.moment_load(Tz=10, node_id=3) + system.add_support_hinged(node_id=1) + system.add_support_hinged(node_id=3) + solution = system.solve() + + assert solution[8] == approx(10 * 5 / (3 * 4000), rel=1e-6) + assert solution[5] == approx( + -10 * 5 / (6 * 4000), rel=1e-6 + ) # the column end at the hinge + + +def test_example_7_rotational_spring(): + # beam elements with the degrees of freedom (v up, theta counter-clockwise): the free + # degrees of freedom are v2, theta2, the rotation r of the end of the beam behind the + # spring, and theta3; P = 100 down at node 2, spring k = 100 between theta2 and r + ei, length, load, k = 5.0e3, 3.5, 100.0, 100.0 + + def beam(): + return ( + ei + / length**3 + * np.array( + [ + [12, 6 * length, -12, 6 * length], + [6 * length, 4 * length**2, -6 * length, 2 * length**2], + [-12, -6 * length, 12, -6 * length], + [6 * length, 2 * length**2, -6 * length, 4 * length**2], + ] + ) + ) + + stiffness = np.zeros((4, 4)) + stiffness[0:2, 0:2] += beam()[2:4, 2:4] # the end of the left element is node 2 + right = beam() # (v2, r, v3, theta3), v3 is restrained + index = [0, 2, None, 3] + for a in range(4): + for b in range(4): + if index[a] is not None and index[b] is not None: + stiffness[index[a], index[b]] += right[a, b] + stiffness[1, 1] += k + stiffness[2, 2] += k + stiffness[1, 2] -= k + stiffness[2, 1] -= k + v2, theta2, _, theta3 = np.linalg.solve(stiffness, np.array([-load, 0, 0, 0])) + + system = SystemElements() + system.add_element([[0.0, 0.0], [3.5, 0.0]]) + system.add_element([7, 0], spring={1: 100}) + system.add_support_fixed([1]) + system.add_support_hinged(3) + system.point_load(2, Fy=-100) + solution = system.solve() + + assert abs(solution[4]) == approx(abs(v2), rel=1e-6) + assert abs(solution[5]) == approx(abs(theta2), rel=1e-6) + assert abs(solution[8]) == approx(abs(theta3), rel=1e-6) + + +def test_inclined_roller_of_0_degrees_is_the_plain_roller(): + results = [] + for roller in ({"direction": "x"}, {"angle": 0}): + system = SystemElements() + system.add_element_grid([0, 1, 2], [0, 1, 0]) + system.add_support_hinged(1) + system.add_support_roll(3, **roller) + system.point_load(2, Fy=-100) + system.solve() + results.append(system.get_node_results_system(3)) + assert results[0]["Fx"] == approx(results[1]["Fx"]) + assert results[0]["Fy"] == approx(results[1]["Fy"]) + assert results[0]["Tz"] == approx(results[1]["Tz"]) + + +def test_inclined_roller_of_45_degrees_reactions(): + # the roller reaction is normal to its free direction (45 degrees): equal components + system = SystemElements() + system.add_element_grid([0, 1, 2], [0, 0, 0]) + system.add_support_hinged(1) + system.add_support_roll(3, angle=45) + system.point_load(2, Fy=-100) + system.solve() + + assert system.get_node_results_system(3)["Fx"] == approx(50) + assert system.get_node_results_system(3)["Fy"] == approx(-50) + assert system.reaction_forces[3].Fx == approx(-50) + assert system.reaction_forces[3].Fy == approx(-50) + + +def test_inclined_roller_with_a_q_load(): + system = SystemElements(EA=356000, EI=1330) + system.add_element(location=[[0, 0], [10, 0]]) + system.add_support_hinged(node_id=1) + system.add_support_roll(node_id=-1, angle=45) + system.q_load(q=-1, element_id=1, direction="element") + system.solve() + + assert system.get_node_results_system(1)["Fx"] == approx(-5) + assert system.get_node_results_system(1)["Fy"] == approx(-5) + assert system.get_element_results(1)["Nmax"] == approx(-5) + assert system.get_element_results(1)["Nmin"] == approx(-5) + + +def test_buckling_factor_of_example_18_with_one_element(): + # one cubic element: 12 EI / L**2 for a column that is pinned at both ends + system = SystemElements(EI=5e3, EA=1e5) + system.add_element([0, 10]) + system.add_support_hinged(1) + system.add_support_roll(2, 1) + system.point_load(2, Fy=-1) + system.solve(geometrical_non_linear=True) + assert system.buckling_factor == approx(600)