{"repo": "JWock82/Pynite", "n_pairs": 118, "version": "v2_function_scoped", "contexts": {"Testing/test_material_section_coverage.py::93": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["Section"], "enclosing_function": "test_section_creation", "extracted_code": "# Source: Pynite/Section.py\nclass Section():\n \"\"\"\n A class representing a section assigned to a Member3D element in a finite element model.\n\n This class stores all properties related to the geometry of the member\n \"\"\"\n def __init__(self, model: 'FEModel3D', name: str, A: float, Iy: float, Iz: float, J: float) -> None:\n \"\"\"\n :param model: The finite element model to which this section belongs\n :type model: FEModel3D\n :param name: Name of the section\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\" \n self.model: 'FEModel3D' = model\n self.name: str = name\n self.A: float = A\n self.Iy: float = Iy\n self.Iz: float = Iz\n self.J: float = J\n \n def Phi(self, fx: float = 0, my: float = 0, mz: float = 0):\n \"\"\"\n Method to be overridden by subclasses for determining whether the cross section is\n elastic or plastic.\n \n :param fx: Axial force\n :type fx: float\n :param my: y-axis (weak) moment\n :type my: float\n :param mz: z-axis (strong) moment\n :type mz: float\n :return: The stress ratio\n :rtype: float\n \"\"\"\n raise NotImplementedError(\"Phi method must be implemented in subclasses.\")\n\n def G(self, fx: float, my: float, mz: float) -> NDArray:\n \"\"\"\n Returns the gradient to the yield surface at a given point using numerical differentiation. This is a default solution. For a better solution, overwrite this method with a more precise one in the material/shape specific child class that inherits from this class.\n\n :param fx: Axial force at the cross-section\n :type fx: float\n :param my: y-axis (weak) moment at the cross-section\n :type my: float\n :param mz: z-axis (strong) moment at the cross-section\n :type mz: float\n :return: The gradient to the yield surface at the cross-section\n :rtype: NDArray\n \"\"\"\n\n # Small increment for numerical differentiation\n epsilon = 1e-6\n\n # Calculate the central differences for each parameter\n dPhi_dfx = (self.Phi(fx + epsilon, my, mz) - self.Phi(fx - epsilon, my, mz)) / (2 * epsilon)\n dPhi_dmy = (self.Phi(fx, my + epsilon, mz) - self.Phi(fx, my - epsilon, mz)) / (2 * epsilon)\n dPhi_dmz = (self.Phi(fx, my, mz + epsilon) - self.Phi(fx, my, mz - epsilon)) / (2 * epsilon)\n\n # Return the gradient\n return np.array([[dPhi_dfx],\n [dPhi_dmy],\n [dPhi_dmz]])", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2920}, "Testing/test_mesh_regen_simple.py::99": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_mesh_regeneration_with_shared_nodes", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_modal_analysis.py::156": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_mass_increase", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::94": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["Section"], "enclosing_function": "test_section_creation", "extracted_code": "# Source: Pynite/Section.py\nclass Section():\n \"\"\"\n A class representing a section assigned to a Member3D element in a finite element model.\n\n This class stores all properties related to the geometry of the member\n \"\"\"\n def __init__(self, model: 'FEModel3D', name: str, A: float, Iy: float, Iz: float, J: float) -> None:\n \"\"\"\n :param model: The finite element model to which this section belongs\n :type model: FEModel3D\n :param name: Name of the section\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\" \n self.model: 'FEModel3D' = model\n self.name: str = name\n self.A: float = A\n self.Iy: float = Iy\n self.Iz: float = Iz\n self.J: float = J\n \n def Phi(self, fx: float = 0, my: float = 0, mz: float = 0):\n \"\"\"\n Method to be overridden by subclasses for determining whether the cross section is\n elastic or plastic.\n \n :param fx: Axial force\n :type fx: float\n :param my: y-axis (weak) moment\n :type my: float\n :param mz: z-axis (strong) moment\n :type mz: float\n :return: The stress ratio\n :rtype: float\n \"\"\"\n raise NotImplementedError(\"Phi method must be implemented in subclasses.\")\n\n def G(self, fx: float, my: float, mz: float) -> NDArray:\n \"\"\"\n Returns the gradient to the yield surface at a given point using numerical differentiation. This is a default solution. For a better solution, overwrite this method with a more precise one in the material/shape specific child class that inherits from this class.\n\n :param fx: Axial force at the cross-section\n :type fx: float\n :param my: y-axis (weak) moment at the cross-section\n :type my: float\n :param mz: z-axis (strong) moment at the cross-section\n :type mz: float\n :return: The gradient to the yield surface at the cross-section\n :rtype: NDArray\n \"\"\"\n\n # Small increment for numerical differentiation\n epsilon = 1e-6\n\n # Calculate the central differences for each parameter\n dPhi_dfx = (self.Phi(fx + epsilon, my, mz) - self.Phi(fx - epsilon, my, mz)) / (2 * epsilon)\n dPhi_dmy = (self.Phi(fx, my + epsilon, mz) - self.Phi(fx, my - epsilon, mz)) / (2 * epsilon)\n dPhi_dmz = (self.Phi(fx, my, mz + epsilon) - self.Phi(fx, my, mz - epsilon)) / (2 * epsilon)\n\n # Return the gradient\n return np.array([[dPhi_dfx],\n [dPhi_dmy],\n [dPhi_dmz]])", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2920}, "Testing/test_node_spring_coverage.py::30": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": [], "enclosing_function": "test_node_coordinates", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "Testing/test_support_settlement.py::92": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_support_settlement", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::142": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["SteelSection"], "enclosing_function": "test_steel_section_creation", "extracted_code": "# Source: Pynite/Section.py\nclass SteelSection(Section):\n\n def __init__(self, model: 'FEModel3D', name: str, A: float, Iy: float, Iz: float, J: float, \n Zy: float, Zz: float, material_name: str) -> None:\n \"\"\"\n Initialize a steel section\n\n :param model: The finite element model to which this section belongs\n :type model: FEModel3D\n :param name: Name of the section\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: Plastic section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: Plastic section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: Name of the material used for this section\n :type material_name: str\n \"\"\"\n\n # Basic section properties\n super().__init__(model, name, A, Iy, Iz, J)\n\n # Additional section properties for steel\n self.ry: float = (Iy/A)**0.5\n self.rz: float = (Iz/A)**0.5\n self.Zy: float = Zy\n self.Zz: float = Zz\n\n self.material = model.materials[material_name]\n\n def Phi(self, fx: float = 0, my: float = 0, mz: float = 0) -> float:\n \"\"\"\n A method used to determine whether the cross section is elastic or plastic.\n Values less than 1 indicate the section is elastic.\n\n :param fx: Axial force divided by axial strength.\n :type fx: float\n :param my: Weak axis moment divided by weak axis strength.\n :type my: float\n :param mz: Strong axis moment divided by strong axis strength.\n :type mz: float\n :return: The total stress ratio for the cross section.\n :rtype: float\n \"\"\"\n\n # Plastic strengths for material nonlinearity\n Py = self.material.fy*self.A\n Mpy = self.material.fy*self.Zy\n Mpz = self.material.fy*self.Zz\n\n # Values for p, my, and mz based on actual loads\n p = fx/Py\n m_y = my/Mpy\n m_z = mz/Mpz\n\n # \"Matrix Structural Analysis, 2nd Edition\", Equation 10.18\n return p**2 + m_z**2 + m_y**4 + 3.5*p**2*m_z**2 + 3*p**6*m_y**2 + 4.5*m_z**4*m_y**2\n\n def G(self, fx: float, my: float, mz: float) -> NDArray[float64]:\n \"\"\"Returns the gradient to the material's yield surface for the given load. Used to construct the plastic reduction matrix for nonlinear behavior.\n\n :param fx: Axial force at the cross-section.\n :type fx: float\n :param my: y-axis (weak) moment at the cross-section.\n :type my: float\n :param mz: z-axis (strong) moment at the cross-section.\n :type mz: float\n :return: The gradient to the material's yield surface at the cross-section.\n :rtype: NDArray\n \"\"\"\n\n # Calculate `Phi` which is essentially a stress check indicating how close to yield we are\n Phi = self.Phi(fx, my, mz)\n\n # If Phi is less than 1.0 the member is still elastic and there is no gradient to the yield surface\n if Phi < 1.0:\n\n # G = zero vector\n return np.array([[0],\n [0],\n [0],\n [0],\n [0],\n [0]])\n\n # Plastic action is occuring\n else:\n\n # Plastic strengths for material nonlinearity\n Py = self.material.fy*self.A\n Mpy = self.material.fy*self.Zy\n Mpz = self.material.fy*self.Zz\n\n # Partial derivatives of Phi\n dPhi_dfx = 18*fx**5*my**2/(Mpy**2*Py**6) + 2*fx/Py**2 + 7.0*fx*mz**2/(Mpz**2*Py**2)\n dPhi_dmy = 6*fx**6*my/(Mpy**2*Py**6) + 2*my/Mpy**2 + 9.0*my*mz**4/(Mpy**2*Mpz**4)\n dPhi_dmz = 7.0*fx**2*mz/(Mpz**2*Py**2) + 2*mz/Mpz**2 + 18.0*my**2*mz**3/(Mpy**2*Mpz**4)\n\n # Return the gradient\n return np.array([[dPhi_dfx],\n [0],\n [0],\n [0],\n [dPhi_dmy],\n [dPhi_dmz]])", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 4412}, "Testing/test_spring_support.py::73": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_beam_on_elastic_foundation", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_TC_analysis.py::62": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_TC_members", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_merge.py::100": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_support_and_spring_support_merge", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_material_section_coverage.py::80": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["LoadCombo"], "enclosing_function": "test_overwrite_load_case", "extracted_code": "# Source: Pynite/LoadCombo.py\nclass LoadCombo():\n \"\"\"A class that stores all the information necessary to define a load combination.\n \"\"\"\n\n def __init__(self, name: str, combo_tags: List[str] | None = None, factors: Dict[str, float] = {}) -> None:\n \"\"\"Initializes a new load combination.\n\n :param name: A unique name for the load combination.\n :type name: str\n :param combo_tags: A list of tags for the load combination. This is a list of any strings you would like to use to categorize your load combinations. It is useful for separating load combinations into strength, service, or overstrength combinations as often required by building codes. This parameter has no effect on the analysis, but it can be used to restrict analysis to only the load combinations with the tags you specify.\n :type combo_tags: list, optional\n :param factors: A dictionary of load case names (`keys`) followed by their load factors (`items`). For example, the load combination 1.2D+1.6L would be represented as follows: `{'D': 1.2, 'L': 1.6}`. Defaults to {}.\n :type factors: dict, optional\n \"\"\"\n \n self.name: str = name # A unique user-defined name for the load combination\n self.combo_tags: List[str] | None = combo_tags # Used to categorize the load combination (e.g. strength or serviceability)\n self.factors: Dict[str, float] = factors # A dictionary containing each load case name and associated load factor\n \n def AddLoadCase(self, case_name: str, factor: float) -> None:\n '''\n Adds a load case with its associated load factor\n\n :param case_name: The name of the load case\n :type case_name: str\n :param factor: The load factor to apply to the load case\n :type factor: float\n '''\n\n self.factors[case_name] = factor\n \n def DeleteLoadCase(self, case_name: str) -> None:\n '''\n Deletes a load case with its associated load factor\n\n :param case_name: The name of the load case to delete\n :type case_name: str\n '''\n\n del self.factors[case_name]", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2148}, "Testing/test_plates&quads.py::66": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_plate_displacement", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::162": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["SteelSection"], "enclosing_function": "test_steel_section_phi_elastic", "extracted_code": "# Source: Pynite/Section.py\nclass SteelSection(Section):\n\n def __init__(self, model: 'FEModel3D', name: str, A: float, Iy: float, Iz: float, J: float, \n Zy: float, Zz: float, material_name: str) -> None:\n \"\"\"\n Initialize a steel section\n\n :param model: The finite element model to which this section belongs\n :type model: FEModel3D\n :param name: Name of the section\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: Plastic section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: Plastic section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: Name of the material used for this section\n :type material_name: str\n \"\"\"\n\n # Basic section properties\n super().__init__(model, name, A, Iy, Iz, J)\n\n # Additional section properties for steel\n self.ry: float = (Iy/A)**0.5\n self.rz: float = (Iz/A)**0.5\n self.Zy: float = Zy\n self.Zz: float = Zz\n\n self.material = model.materials[material_name]\n\n def Phi(self, fx: float = 0, my: float = 0, mz: float = 0) -> float:\n \"\"\"\n A method used to determine whether the cross section is elastic or plastic.\n Values less than 1 indicate the section is elastic.\n\n :param fx: Axial force divided by axial strength.\n :type fx: float\n :param my: Weak axis moment divided by weak axis strength.\n :type my: float\n :param mz: Strong axis moment divided by strong axis strength.\n :type mz: float\n :return: The total stress ratio for the cross section.\n :rtype: float\n \"\"\"\n\n # Plastic strengths for material nonlinearity\n Py = self.material.fy*self.A\n Mpy = self.material.fy*self.Zy\n Mpz = self.material.fy*self.Zz\n\n # Values for p, my, and mz based on actual loads\n p = fx/Py\n m_y = my/Mpy\n m_z = mz/Mpz\n\n # \"Matrix Structural Analysis, 2nd Edition\", Equation 10.18\n return p**2 + m_z**2 + m_y**4 + 3.5*p**2*m_z**2 + 3*p**6*m_y**2 + 4.5*m_z**4*m_y**2\n\n def G(self, fx: float, my: float, mz: float) -> NDArray[float64]:\n \"\"\"Returns the gradient to the material's yield surface for the given load. Used to construct the plastic reduction matrix for nonlinear behavior.\n\n :param fx: Axial force at the cross-section.\n :type fx: float\n :param my: y-axis (weak) moment at the cross-section.\n :type my: float\n :param mz: z-axis (strong) moment at the cross-section.\n :type mz: float\n :return: The gradient to the material's yield surface at the cross-section.\n :rtype: NDArray\n \"\"\"\n\n # Calculate `Phi` which is essentially a stress check indicating how close to yield we are\n Phi = self.Phi(fx, my, mz)\n\n # If Phi is less than 1.0 the member is still elastic and there is no gradient to the yield surface\n if Phi < 1.0:\n\n # G = zero vector\n return np.array([[0],\n [0],\n [0],\n [0],\n [0],\n [0]])\n\n # Plastic action is occuring\n else:\n\n # Plastic strengths for material nonlinearity\n Py = self.material.fy*self.A\n Mpy = self.material.fy*self.Zy\n Mpz = self.material.fy*self.Zz\n\n # Partial derivatives of Phi\n dPhi_dfx = 18*fx**5*my**2/(Mpy**2*Py**6) + 2*fx/Py**2 + 7.0*fx*mz**2/(Mpz**2*Py**2)\n dPhi_dmy = 6*fx**6*my/(Mpy**2*Py**6) + 2*my/Mpy**2 + 9.0*my*mz**4/(Mpy**2*Mpz**4)\n dPhi_dmz = 7.0*fx**2*mz/(Mpz**2*Py**2) + 2*mz/Mpz**2 + 18.0*my**2*mz**3/(Mpy**2*Mpz**4)\n\n # Return the gradient\n return np.array([[dPhi_dfx],\n [0],\n [0],\n [0],\n [dPhi_dmy],\n [dPhi_dmz]])", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 4412}, "Testing/test_shear_wall.py::135": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_piers_and_coupling_beams", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_member_rotation.py::40": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_beam_rotation", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_Visualization.py::265": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_case_combo_mutual_exclusion", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_delete_mesh.py::51": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_basic", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_merge.py::42": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_simple_pair_merge_canonical_first_added", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_shear_wall.py::261": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_cracked_rect_shear_wall", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_node_merge.py::28": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_no_merge_unique_nodes", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_node_spring_coverage.py::28": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": [], "enclosing_function": "test_node_coordinates", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "Testing/test_node_merge.py::43": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_simple_pair_merge_canonical_first_added", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_modal_analysis.py::215": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_lumped_vs_consistent_mass", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_delete_mesh.py::48": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_basic", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_spring_coverage.py::73": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": [], "enclosing_function": "test_node_distance_simple", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "Testing/test_meshes.py::207": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_PCA_7_rect", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_member_rotation.py::39": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_beam_rotation", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_meshes.py::47": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D", "isclose"], "enclosing_function": "test_rect_mesh_in_plane_stiffness", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_delete_mesh.py::108": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_with_attached_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_spring_coverage.py::29": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": [], "enclosing_function": "test_node_coordinates", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "Testing/test_modal_analysis.py::233": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D", "pytest"], "enclosing_function": "test_different_mode_counts", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regen_simple.py::51": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::46": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["LoadCombo"], "enclosing_function": "test_loadcombo_creation_empty", "extracted_code": "# Source: Pynite/LoadCombo.py\nclass LoadCombo():\n \"\"\"A class that stores all the information necessary to define a load combination.\n \"\"\"\n\n def __init__(self, name: str, combo_tags: List[str] | None = None, factors: Dict[str, float] = {}) -> None:\n \"\"\"Initializes a new load combination.\n\n :param name: A unique name for the load combination.\n :type name: str\n :param combo_tags: A list of tags for the load combination. This is a list of any strings you would like to use to categorize your load combinations. It is useful for separating load combinations into strength, service, or overstrength combinations as often required by building codes. This parameter has no effect on the analysis, but it can be used to restrict analysis to only the load combinations with the tags you specify.\n :type combo_tags: list, optional\n :param factors: A dictionary of load case names (`keys`) followed by their load factors (`items`). For example, the load combination 1.2D+1.6L would be represented as follows: `{'D': 1.2, 'L': 1.6}`. Defaults to {}.\n :type factors: dict, optional\n \"\"\"\n \n self.name: str = name # A unique user-defined name for the load combination\n self.combo_tags: List[str] | None = combo_tags # Used to categorize the load combination (e.g. strength or serviceability)\n self.factors: Dict[str, float] = factors # A dictionary containing each load case name and associated load factor\n \n def AddLoadCase(self, case_name: str, factor: float) -> None:\n '''\n Adds a load case with its associated load factor\n\n :param case_name: The name of the load case\n :type case_name: str\n :param factor: The load factor to apply to the load case\n :type factor: float\n '''\n\n self.factors[case_name] = factor\n \n def DeleteLoadCase(self, case_name: str) -> None:\n '''\n Deletes a load case with its associated load factor\n\n :param case_name: The name of the load case to delete\n :type case_name: str\n '''\n\n del self.factors[case_name]", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2148}, "Testing/test_Visualization.py::151": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_toggle_visual_properties", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_springs.py::48": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_spring_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_TC_analysis.py::65": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_TC_members", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_meshes.py::210": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_PCA_7_rect", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_Visualization.py::262": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_case_combo_mutual_exclusion", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_Visualization.py::385": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D", "vtk"], "enclosing_function": "test_render_nodal_loads", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 375}, "Testing/test_reactions.py::16": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_spring_reactions", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 1, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_modal_analysis.py::208": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_lumped_vs_consistent_mass", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_AISC_PDelta_benchmarks.py::93": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D", "math"], "enclosing_function": "test_AISC_benchmark_old", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_reanalysis.py::72": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_reanalysis", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regen_simple.py::95": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_mesh_regeneration_with_shared_nodes", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_loads.py::58": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Section.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_member_self_weight_local_direction", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_AISC_PDelta_benchmarks.py::226": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_AISC_benchmark_case2", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regeneration.py::194": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_multiple_meshes_independent_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regeneration.py::87": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_mesh_regeneration_with_shared_nodes", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_spring_coverage.py::20": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": [], "enclosing_function": "test_node_creation", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "Testing/test_node_merge.py::30": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_no_merge_unique_nodes", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_springs.py::45": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_spring_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_Visualization.py::351": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_member_end_release_visuals", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 375}, "Testing/test_mesh_regen_simple.py::46": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_Visualization.py::229": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": ["pytest"], "enclosing_function": "test_annotation_size_auto_two_nodes", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_2D_frames.py::289": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_Kassimali_3_35", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_merge.py::74": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_cluster_merge_and_element_rewire", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_node_merge.py::56": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_pair_not_merged_when_beyond_tolerance", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_2D_frames.py::121": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_XY_member_ptload", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_torsion.py::47": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_member_torque_load", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_member_rotation.py::41": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_beam_rotation", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regeneration.py::192": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_multiple_meshes_independent_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_unstable_structure.py::63": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_unstable_supports", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_delete_mesh.py::302": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_flags_unsolved", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_shear_wall.py::134": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_piers_and_coupling_beams", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_Visualization.py::311": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_visnode_support_fixed_and_pinned", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::54": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["LoadCombo"], "enclosing_function": "test_loadcombo_creation_with_factors", "extracted_code": "# Source: Pynite/LoadCombo.py\nclass LoadCombo():\n \"\"\"A class that stores all the information necessary to define a load combination.\n \"\"\"\n\n def __init__(self, name: str, combo_tags: List[str] | None = None, factors: Dict[str, float] = {}) -> None:\n \"\"\"Initializes a new load combination.\n\n :param name: A unique name for the load combination.\n :type name: str\n :param combo_tags: A list of tags for the load combination. This is a list of any strings you would like to use to categorize your load combinations. It is useful for separating load combinations into strength, service, or overstrength combinations as often required by building codes. This parameter has no effect on the analysis, but it can be used to restrict analysis to only the load combinations with the tags you specify.\n :type combo_tags: list, optional\n :param factors: A dictionary of load case names (`keys`) followed by their load factors (`items`). For example, the load combination 1.2D+1.6L would be represented as follows: `{'D': 1.2, 'L': 1.6}`. Defaults to {}.\n :type factors: dict, optional\n \"\"\"\n \n self.name: str = name # A unique user-defined name for the load combination\n self.combo_tags: List[str] | None = combo_tags # Used to categorize the load combination (e.g. strength or serviceability)\n self.factors: Dict[str, float] = factors # A dictionary containing each load case name and associated load factor\n \n def AddLoadCase(self, case_name: str, factor: float) -> None:\n '''\n Adds a load case with its associated load factor\n\n :param case_name: The name of the load case\n :type case_name: str\n :param factor: The load factor to apply to the load case\n :type factor: float\n '''\n\n self.factors[case_name] = factor\n \n def DeleteLoadCase(self, case_name: str) -> None:\n '''\n Deletes a load case with its associated load factor\n\n :param case_name: The name of the load case to delete\n :type case_name: str\n '''\n\n del self.factors[case_name]", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2148}, "Testing/test_delete_mesh.py::264": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_multiple_meshes", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_shear_wall.py::175": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D", "Renderer"], "enclosing_function": "test_quad_shear_wall", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version\n\n\n# Source: Pynite/Rendering.py\nclass Renderer:\n \"\"\"Render finite element models using PyVista.\n\n This class provides methods for rendering 3D models (nodes, members, springs,\n plates, quads) with deformed shapes, loads, contours, and diagrams.\n \"\"\"\n\n scalar: Optional[str] = None\n\n def __init__(self, model: FEModel3D) -> None:\n \"\"\"Initialize the renderer with a finite element model.\n\n :param FEModel3D model: Finite element model to render.\n \"\"\"\n self.model: FEModel3D = model\n\n # Default settings for rendering\n self._annotation_size: Optional[float] = None # None means auto-calculate\n self._annotation_size_manual: bool = False # Track if user manually set the size\n self._annotation_size_cached: Optional[float] = None # Cache to avoid recalculating 2600+ times per render\n self._deformed_shape: bool = False\n self._deformed_scale: float = 30.0\n self._render_nodes: bool = True\n self._render_loads: bool = True\n self._color_map: Optional[str] = None\n self._combo_name: Optional[str] = 'Combo 1'\n self._case: Optional[str] = None\n self._labels: bool = True\n self._scalar_bar: bool = False\n self._scalar_bar_text_size: int = 24\n self._member_diagrams: Optional[str] = None # Options: None, 'Fy', 'Fz', 'My', 'Mz', 'Fx', 'Tx'\n self._diagram_scale: float = 30.0\n self.theme: str = 'default'\n\n # Callback list for post-update customization:\n # This is added because `self.update()` clears the plotter, removing user self.plotter configurations.\n # Functions in this list run after Pynite adds actors, allowing further PyVista customizations\n # (e.g., grid, axes) before render. Each func in this list must accept a `pyvista.Plotter` argument.\n self.post_update_callbacks: List[Callable[[pv.Plotter], None]] = []\n\n # Create plotter with off_screen mode if pyvista is set globally to OFF_SCREEN\n # This is important for headless CI/testing environments\n self.plotter: pv.Plotter = pv.Plotter(off_screen=pv.OFF_SCREEN)\n self.plotter.set_background('white') # Setting background color\n # self.plotter.add_logo_widget('./Resources/Full Logo No Buffer - Transparent.png')\n\n # Only set view and axes in interactive mode (renderer must exist for these calls)\n # In off-screen/headless mode, these will be set when update() is called\n if not pv.OFF_SCREEN:\n # self.plotter.view_isometric()\n self.plotter.view_xy()\n self.plotter.show_axes()\n self.plotter.set_viewup((0, 1, 0)) # Set the Y axis to vertical for 3D plots\n\n # Make X button behave like 'q' key - properly exit without destroying plotter\n # Why: By default, PyVista's X button forcefully destroys the render window,\n # causing warnings and preventing clean shutdown. This observer intercepts\n # the window close event.\n # How: When ExitEvent fires (X button clicked), we call TerminateApp() on the\n # interactor, which cleanly exits the event loop just like pressing 'q'.\n self.plotter.iren.add_observer('ExitEvent', lambda obj, event: obj.TerminateApp())\n\n # Initialize load labels\n self._load_label_points: List[List[float]] = []\n self._load_labels: List[Union[str, float, int]] = []\n\n # Initialize spring labels\n self._spring_label_points: List[List[float]] = []\n self._spring_labels: List[str] = []\n\n @property\n def window_width(self) -> int:\n return self.plotter.window_size[0]\n\n @window_width.setter\n def window_width(self, width: int) -> None:\n height = self.plotter.window_size[1]\n self.plotter.window_size = (width, height)\n\n @property\n def window_height(self) -> int:\n return self.plotter.window_size[1]\n\n @window_height.setter\n def window_height(self, height: int) -> None:\n width = self.plotter.window_size[0]\n self.plotter.window_size = (width, height)\n\n @property\n def annotation_size(self) -> float:\n \"\"\"Size of text annotations and visual elements in model units.\n\n Auto-calculated as 5% of shortest distance between nodes if not\n manually set.\n \"\"\"\n if self._annotation_size is None or not self._annotation_size_manual:\n # Return cached value if available; calculate once on first access\n if self._annotation_size_cached is None:\n self._annotation_size_cached = self._calculate_auto_annotation_size()\n return self._annotation_size_cached\n return self._annotation_size\n\n @annotation_size.setter\n def annotation_size(self, size: float) -> None:\n self._annotation_size = size\n self._annotation_size_manual = True # Mark as manually set\n\n @property\n def deformed_shape(self) -> bool:\n return self._deformed_shape\n\n @deformed_shape.setter\n def deformed_shape(self, deformed_shape: bool) -> None:\n self._deformed_shape = deformed_shape\n\n @property\n def deformed_scale(self) -> float:\n return self._deformed_scale\n\n @deformed_scale.setter\n def deformed_scale(self, scale: float) -> None:\n self._deformed_scale = scale\n\n @property\n def render_nodes(self) -> bool:\n return self._render_nodes\n\n @render_nodes.setter\n def render_nodes(self, render_nodes: bool) -> None:\n self._render_nodes = render_nodes\n\n @property\n def render_loads(self) -> bool:\n return self._render_loads\n\n @render_loads.setter\n def render_loads(self, render_loads: bool) -> None:\n self._render_loads = render_loads\n\n @property\n def color_map(self) -> Optional[str]:\n return self._color_map\n\n @color_map.setter\n def color_map(self, color_map: Optional[str]) -> None:\n self._color_map = color_map\n\n @property\n def combo_name(self) -> Optional[str]:\n return self._combo_name\n\n @combo_name.setter\n def combo_name(self, combo_name: Optional[str]) -> None:\n self._combo_name = combo_name\n self._case = None\n\n @property\n def case(self) -> Optional[str]:\n return self._case\n\n @case.setter\n def case(self, case: Optional[str]) -> None:\n self._case = case\n self._combo_name = None\n\n @property\n def show_labels(self) -> bool:\n return self._labels\n\n @show_labels.setter\n def show_labels(self, show_labels: bool) -> None:\n self._labels = show_labels\n\n @property\n def scalar_bar(self) -> bool:\n return self._scalar_bar\n\n @scalar_bar.setter\n def scalar_bar(self, scalar_bar: bool) -> None:\n self._scalar_bar = scalar_bar\n\n @property\n def scalar_bar_text_size(self) -> int:\n return self._scalar_bar_text_size\n\n @scalar_bar_text_size.setter\n def scalar_bar_text_size(self, text_size: int) -> None:\n self._scalar_bar_text_size = text_size\n\n @property\n def member_diagrams(self) -> Optional[str]:\n \"\"\"Member diagram type to display.\n\n Options: ``None``, ``'Fy'``, ``'Fz'``, ``'My'``, ``'Mz'``, ``'Fx'``, ``'Tx'``.\n \"\"\"\n return self._member_diagrams\n\n @member_diagrams.setter\n def member_diagrams(self, diagram_type: Optional[str]) -> None:\n valid_options = [None, 'Fy', 'Fz', 'My', 'Mz', 'Fx', 'Tx']\n if diagram_type not in valid_options:\n raise ValueError(f\"member_diagrams must be one of {valid_options}, got '{diagram_type}'\")\n self._member_diagrams = diagram_type\n\n @property\n def diagram_scale(self) -> float:\n \"\"\"Scale factor for member diagram visualization.\"\"\"\n return self._diagram_scale\n\n @diagram_scale.setter\n def diagram_scale(self, scale: float) -> None:\n self._diagram_scale = scale\n\n def _calculate_auto_annotation_size(self) -> float:\n \"\"\"Calculate automatic annotation size as 5% of shortest node distance.\n\n Uses vectorized NumPy operations for fast computation on large meshes.\n Result is cached by the annotation_size property to avoid recalculation.\n\n :returns: Annotation size in model units (``5.0`` fallback if <2 nodes).\n :rtype: float\n \"\"\"\n from numpy import asarray\n \n nodes = list(self.model.nodes.values())\n\n # Need at least 2 nodes to calculate distance\n if len(nodes) < 2:\n return 5.0 # Default fallback\n\n # Extract node coordinates as numpy array (much faster than nested loops)\n coords = asarray([[node.X, node.Y, node.Z] for node in nodes])\n \n # Calculate pairwise distances using vectorized operations\n # For each node, compute distance to all other nodes, then find minimum\n min_distance = float('inf')\n for i in range(len(coords)):\n # Vectorized distance calculation for node i to all others\n diffs = coords[i+1:] - coords[i]\n distances = (diffs**2).sum(axis=1)**0.5\n \n # Find minimum distance from this node to subsequent nodes\n valid_distances = distances[distances > 0]\n if len(valid_distances) > 0:\n local_min = valid_distances.min()\n if local_min < min_distance:\n min_distance = local_min\n\n # If all nodes are at same location, use default\n if min_distance == float('inf') or min_distance == 0:\n return 5.0\n\n # Return 5% of shortest distance\n return min_distance * 0.05\n\n def render_model(self, reset_camera: bool = True, off_screen: bool = False) -> None:\n \"\"\"Render the model in a window.\n\n :param bool reset_camera: Reset the camera before rendering (default ``True``).\n :param bool off_screen: Render off-screen without displaying a window\n (useful for headless environments, default ``False``).\n \"\"\"\n\n # Set off-screen mode if requested (for testing/headless environments)\n # This must be done BEFORE calling update() so the plotter is in off-screen mode\n # when adding meshes, preventing PyVista camera initialization issues\n if off_screen:\n self.plotter.off_screen = True\n\n # Update the plotter with the latest geometry\n self.update(reset_camera)\n\n # Render the model (code execution will pause here until the user closes the window)\n try:\n self.plotter.show(title='Pynite - Simple Finite Element Analysis for Python', auto_close=False)\n finally:\n # Explicitly deep clean the plotter to prevent garbage collection issues\n # Why: PyVista/VTK objects can have circular references that cause AttributeErrors\n # during Python's garbage collection phase when the program exits.\n # How: deep_clean() forces immediate cleanup of all VTK objects, meshes, and actors\n # before Python's garbage collector runs, preventing the \"'NoneType' object has\n # no attribute 'check_attribute'\" exception that would otherwise appear.\n self.plotter.deep_clean()\n\n def screenshot(self, filepath: str = './Pynite_Image.png', interact: bool = True, reset_camera: bool = False) -> None:\n \"\"\"Save a screenshot of the rendered model.\n\n In non-Jupyter environments, if ``interact=True`` the user can adjust\n the view before taking the screenshot (press ``'q'`` to proceed).\n For Jupyter, use ``render_model`` to set the scene before ``screenshot``.\n\n :param str filepath: File path to write PNG image (default ``'./Pynite_Image.png'``).\n :param bool interact: Allow user interaction before screenshot (default ``True``).\n :param bool reset_camera: Reset camera to original view (default ``False``).\n \"\"\"\n\n # Update the plotter with the latest geometry\n self.update(reset_camera)\n\n # In a Jupyter notebook pyvista will always take the screenshot prior to allowing user interaction. In order to get interaction before taking the screenshot, `render_model` must be called in a cell before `screenshot`. Since `render_model` will show the plotter, there is no need to show it again when using `screenshot`. This next line prevents showing the plotter twice.\n self.plotter.notebook = False\n\n # For non-Jupyter environments, determine if the user should interact with the window before capturing the screenshot\n if interact == False: self.plotter.off_screen = True\n\n # Save the screenshot to the specified filepath. Note that `auto_close` shuts down the entire plotter after the screenshot is taken, rather than just closing the window. We'll set `auto_close=False` to allow the plotter to remain active. Note that the window must be closed by pressing `q`. Closing it with the 'X' button in the window's corner will close the whole plotter down.\n self.plotter.show(\n title='Pynite - Simple Finite Element Anlaysis for Python',\n screenshot=filepath,\n auto_close=False\n )\n\n def update(self, reset_camera: bool = True) -> None:\n \"\"\"Rebuild the PyVista plotter with current settings.\n\n Updates all visual elements (geometry, loads, labels, contours, diagrams)\n and calls post-update callbacks.\n\n :param bool reset_camera: Reset camera to fit model (default ``True``).\n \"\"\"\n\n # Clear annotation size cache to recalculate if model has changed\n self._annotation_size_cached = None\n\n # Input validation\n if self.deformed_shape and self.case != None:\n raise Exception('Deformed shape is only available for load combinations,'\n ' not load cases.')\n if self.model.load_combos == {} and self.render_loads == True and self.case == None:\n self.render_loads = False\n warnings.warn('Unable to render load combination. No load combinations defined.', UserWarning)\n\n # Clear out the old plot (if any)\n self.plotter.clear()\n\n # Set up view and axes (works for both interactive and off-screen modes)\n try:\n self.plotter.view_xy()\n self.plotter.show_axes()\n self.plotter.set_viewup((0, 1, 0))\n except:\n # Silently fail if not supported in this context\n pass\n\n # Clear out internally stored labels (if any)\n self._load_label_points = []\n self._load_labels = []\n\n self._spring_label_points = []\n self._spring_labels = []\n\n # Build visual helper objects. These classes encapsulate geometry and label bookkeeping\n # so that the renderer logic stays readable while still leveraging PyVista efficiently.\n vis_nodes: List[VisNode] = []\n vis_springs: List[VisSpring] = []\n vis_members: List[VisMember] = []\n\n if self.render_nodes:\n node_color = 'black' if self.theme == 'print' else 'grey'\n vis_nodes = [VisNode(node, self.annotation_size, node_color) for node in self.model.nodes.values()]\n for vis_node in vis_nodes:\n vis_node.add_to_plotter(self.plotter)\n\n if self.model.springs:\n # Undeformed springs are added here; deformed ones come later if requested.\n vis_springs = [VisSpring(spring, self.annotation_size, 'grey', False, self.deformed_scale, self.combo_name) for spring in self.model.springs.values()]\n for vis_spring in vis_springs:\n vis_spring.add_to_plotter(self.plotter)\n\n if self.model.members:\n vis_members = [VisMember(member, self.theme, self.annotation_size) for member in self.model.members.values()]\n for vis_member in vis_members:\n vis_member.add_to_plotter(self.plotter)\n\n # Render the deformed shape if requested. Deformed visuals are built separately so the\n # undeformed geometry remains visible alongside deformed overlays when desired.\n if self.deformed_shape:\n for member in self.model.members.values():\n vis_def_member = VisDeformedMember(member, self.deformed_scale, self.combo_name)\n vis_def_member.add_to_plotter(self.plotter)\n\n for spring in self.model.springs.values():\n vis_def_spring = VisSpring(spring, self.annotation_size, 'red', True, self.deformed_scale, self.combo_name)\n vis_def_spring.add_to_plotter(self.plotter)\n\n # Render labels if requested. We gather label locations from the visual helper classes to\n # avoid duplicating coordinate math here.\n if self.show_labels and vis_nodes:\n label_points = [vis_node.label_point for vis_node in vis_nodes]\n labels = [vis_node.label for vis_node in vis_nodes]\n label_points = np.asarray(label_points, dtype=float)\n self.plotter.add_point_labels(label_points, labels, bold=False, text_color='black', show_points=True, point_color='grey', point_size=5, shape=None, render_points_as_spheres=True)\n\n if self.show_labels and vis_springs:\n self._spring_label_points = [vis_spring.label_point for vis_spring in vis_springs]\n self._spring_labels = [vis_spring.label for vis_spring in vis_springs]\n spring_label_points = np.asarray(self._spring_label_points, dtype=float)\n self.plotter.add_point_labels(spring_label_points, self._spring_labels, text_color='black', bold=False, shape=None, render_points_as_spheres=False)\n\n if self.show_labels and vis_members:\n label_points = [vis_member.label_point for vis_member in vis_members]\n labels = [vis_member.label for vis_member in vis_members]\n label_points = np.asarray(label_points, dtype=float)\n self.plotter.add_point_labels(label_points, labels, bold=False, text_color='black', show_points=False, shape=None, render_points_as_spheres=False)\n\n # Render the loads if requested\n if (self.combo_name != None or self.case != None) and self.render_loads != False:\n\n # Plot the loads\n self.plot_loads()\n\n # Plot the load labels\n load_label_points = np.asarray(self._load_label_points, dtype=float)\n self.plotter.add_point_labels(load_label_points, self._load_labels, bold=False, text_color='green', show_points=False, shape=None, render_points_as_spheres=False)\n\n # Render the plates and quads, if present\n if self.model.quads or self.model.plates:\n self.plot_plates(self.deformed_shape, self.deformed_scale, self.color_map, self.combo_name)\n\n # Render member diagrams if requested\n if self.member_diagrams and (self.combo_name is not None or self.case is not None):\n self.plot_member_diagrams()\n\n # Determine whether to show or hide the scalar bar\n # if self._scalar_bar == False:\n # self.plotter.scalar_bar.VisibilityOff()\n\n # Execute user-defined post-update callbacks.\n # Allows plotter customization after internal Pynite updates. See __init__.\n if hasattr(self, 'post_update_callbacks') and self.post_update_callbacks:\n for func in self.post_update_callbacks:\n if callable(func):\n try:\n # Pass the plotter instance to the user's function\n func(self.plotter)\n except Exception as e:\n warnings.warn(f\"Error executing post-update callback {func.__name__}: {e}\")\n else:\n warnings.warn(f\"Item in post_update_callbacks is not callable: {func}\")\n\n # Reset the camera if requested by the user\n if reset_camera:\n self.plotter.reset_camera()\n\n\n def plot_node(self, node: Node3D, color: str = 'grey') -> None:\n \"\"\"Add a node and its support geometry to the plotter.\n\n :param Node3D node: Node to visualize (support conditions displayed).\n :param str color: Color for nodes/supports (default ``'grey'``).\n \"\"\"\n\n # Get the node's position\n X = node.X # Global X coordinate\n Y = node.Y # Global Y coordinate\n Z = node.Z # Global Z coordinate\n\n # Generate any supports that occur at the node\n # Check for a fixed suppport\n if node.support_DX and node.support_DY and node.support_DZ and node.support_RX and node.support_RY and node.support_RZ:\n\n # Create a cube using PyVista\n self.plotter.add_mesh(pv.Cube(center=(node.X, node.Y, node.Z),\n x_length=self.annotation_size*2,\n y_length=self.annotation_size*2,\n z_length=self.annotation_size*2),\n color=color)\n\n # Check for a pinned support\n elif node.support_DX and node.support_DY and node.support_DZ and not node.support_RX and not node.support_RY and not node.support_RZ:\n\n # Create a cone using PyVista's Cone function\n self.plotter.add_mesh(pv.Cone(center=(node.X, node.Y - self.annotation_size, node.Z),\n direction=(0, 1, 0),\n height=self.annotation_size*2,\n radius=self.annotation_size*2),\n color=color)\n\n # Other support conditions\n else:\n\n # Generate a sphere for the node\n # sphere = pv.Sphere(center=(X, Y, Z), radius=0.4*self.annotation_size)\n # self.plotter.add_mesh(sphere, name='Node: '+ node.name, color=color)\n\n # Restrained against X translation\n if node.support_DX:\n\n # Line showing support direction\n self.plotter.add_mesh(pv.Line((node.X - self.annotation_size, node.Y, node.Z),\n (node.X + self.annotation_size, node.Y, node.Z)),\n color=color)\n\n # Cones at both ends\n self.plotter.add_mesh(pv.Cone(center=(node.X - self.annotation_size, node.Y,\n node.Z),\n direction=(1, 0, 0), height=self.annotation_size*0.6,\n radius=self.annotation_size*0.3),\n color=color)\n self.plotter.add_mesh(pv.Cone(center=(node.X + self.annotation_size, node.Y,\n node.Z),\n direction=(-1, 0, 0),\n height=self.annotation_size*0.6,\n radius=self.annotation_size*0.3),\n color=color)\n\n # Restrained against Y translation\n if node.support_DY:\n\n # Line showing support direction\n self.plotter.add_mesh(pv.Line((node.X, node.Y - self.annotation_size, node.Z),\n (node.X, node.Y + self.annotation_size, node.Z)),\n color=color)\n\n # Cones at both ends\n self.plotter.add_mesh(pv.Cone(center=(node.X, node.Y - self.annotation_size,\n node.Z), direction=(0, 1, 0),\n height=self.annotation_size*0.6,\n radius=self.annotation_size*0.3),\n color=color)\n self.plotter.add_mesh(pv.Cone(center=(node.X, node.Y + self.annotation_size,\n node.Z),\n direction=(0, -1, 0),\n height=self.annotation_size*0.6,\n radius=self.annotation_size*0.3),\n color=color)\n\n # Restrained against Z translation\n if node.support_DZ:\n\n # Line showing support direction\n self.plotter.add_mesh(pv.Line((node.X, node.Y, node.Z-self.annotation_size),\n (node.X, node.Y, node.Z+self.annotation_size)),\n color=color)\n\n # Cones at both ends\n self.plotter.add_mesh(pv.Cone(center=(node.X, node.Y, node.Z-self.annotation_size),\n direction=(0, 0, 1),\n height=self.annotation_size*0.6,\n radius=self.annotation_size*0.3),\n color=color)\n self.plotter.add_mesh(pv.Cone(center=(node.X, node.Y, node.Z+self.annotation_size),\n direction=(0, 0, -1),\n height=self.annotation_size*0.6,\n radius=self.annotation_size*0.3),\n color=color)\n\n # Restrained against X rotation\n if node.support_RX:\n\n # Line showing support direction\n self.plotter.add_mesh(pv.Line((node.X-1.6*self.annotation_size, node.Y, node.Z),\n (node.X+1.6*self.annotation_size, node.Y, node.Z)),\n color=color)\n\n # Cubes at both ends\n self.plotter.add_mesh(pv.Cube(center=(node.X-1.9*self.annotation_size, node.Y,\n node.Z),\n x_length=self.annotation_size*0.6,\n y_length=self.annotation_size*0.6,\n z_length=self.annotation_size*0.6),\n color=color)\n self.plotter.add_mesh(pv.Cube(center=(node.X+1.9 *self.annotation_size, node.Y,\n node.Z),\n x_length=self.annotation_size*0.6,\n y_length=self.annotation_size*0.6,\n z_length=self.annotation_size*0.6),\n color=color)\n\n # Restrained against rotation about the Y-axis\n if node.support_RY:\n\n # Line showing support direction\n self.plotter.add_mesh(pv.Line((node.X, node.Y-1.6*self.annotation_size, node.Z),\n (node.X, node.Y+1.6*self.annotation_size, node.Z)),\n color=color)\n\n # Cubes at both ends\n self.plotter.add_mesh(pv.Cube(center=(node.X, node.Y-1.9*self.annotation_size,\n node.Z),\n x_length=self.annotation_size*0.6,\n y_length=self.annotation_size*0.6,\n z_length=self.annotation_size*0.6),\n color=color)\n self.plotter.add_mesh(pv.Cube(center=(node.X, node.Y+1.9*self.annotation_size,\n node.Z),\n x_length=self.annotation_size*0.6,\n y_length=self.annotation_size*0.6,\n z_length=self.annotation_size*0.6),\n color=color)\n\n # Restrained against rotation about the Z-axis\n if node.support_RZ:\n\n # Line showing support direction\n self.plotter.add_mesh(pv.Line((node.X, node.Y, node.Z-1.6*self.annotation_size),\n (node.X, node.Y, node.Z+1.6*self.annotation_size)),\n color=color)\n\n # Cubes at both ends\n self.plotter.add_mesh(pv.Cube(center=(node.X, node.Y,\n node.Z-1.9*self.annotation_size),\n x_length=self.annotation_size*0.6,\n y_length=self.annotation_size*0.6,\n z_length=self.annotation_size*0.6),\n color=color)\n self.plotter.add_mesh(pv.Cube(center=(node.X, node.Y,\n node.Z+1.9*self.annotation_size),\n x_length=self.annotation_size*0.6,\n y_length=self.annotation_size*0.6,\n z_length=self.annotation_size*0.6),\n color=color)\n\n def plot_member(self, member: Member3D, theme: str = 'default') -> None:\n \"\"\"Add a member to the plotter.\n\n Generates a line representing the structural member between its end nodes.\n\n :param Member3D member: Structural member to plot.\n :param str theme: Rendering theme (default ``'default'``).\n \"\"\"\n\n # Generate a line for the member\n line = pv.Line()\n\n Xi = member.i_node.X\n Yi = member.i_node.Y\n Zi = member.i_node.Z\n line.points[0] = [Xi, Yi, Zi]\n\n Xj = member.j_node.X\n Yj = member.j_node.Y\n Zj = member.j_node.Z\n line.points[1] = [Xj, Yj, Zj]\n\n self.plotter.add_mesh(line, color='black', line_width=2)\n\n def plot_spring(self, spring: Spring3D, color: str = 'grey', deformed: bool = False) -> None:\n \"\"\"Add a spring to the plotter.\n\n Generates a zig-zag line representing the spring between its end nodes.\n\n :param Spring3D spring: Spring to visualize.\n :param str color: Line color (default ``'grey'``).\n :param bool deformed: Plot deformed shape if ``True`` (default ``False``).\n \"\"\"\n\n # Scale the spring's zigzags\n size = self.annotation_size\n\n # Find the spring's i-node and j-node\n i_node = spring.i_node\n j_node = spring.j_node\n\n # Find the spring's node coordinates\n Xi, Yi, Zi = i_node.X, i_node.Y, i_node.Z\n Xj, Yj, Zj = j_node.X, j_node.Y, j_node.Z\n\n # Determine if the spring should be plotted in its deformed shape\n if deformed:\n Xi = Xi + i_node.DX[self.combo_name]*self.deformed_scale\n Yi = Yi + i_node.DY[self.combo_name]*self.deformed_scale\n Zi = Zi + i_node.DZ[self.combo_name]*self.deformed_scale\n Xj = Xj + j_node.DX[self.combo_name]*self.deformed_scale\n Yj = Yj + j_node.DY[self.combo_name]*self.deformed_scale\n Zj = Zj + j_node.DZ[self.combo_name]*self.deformed_scale\n\n # Calculate the spring direction vector and length\n direction = np.array([Xj, Yj, Zj]) - np.array([Xi, Yi, Zi])\n length = np.linalg.norm(direction)\n\n # Normalize the direction vector\n direction = direction / length\n\n # Calculate perpendicular vectors for zig-zag plane\n arbitrary_vector = np.array([1, 0, 0])\n if np.allclose(direction, arbitrary_vector) or np.allclose(direction, -arbitrary_vector):\n arbitrary_vector = np.array([0, 1, 0])\n perp_vector1 = np.cross(direction, arbitrary_vector)\n perp_vector1 /= np.linalg.norm(perp_vector1)\n perp_vector2 = np.cross(direction, perp_vector1)\n perp_vector2 /= np.linalg.norm(perp_vector2)\n\n # Define the length of the straight segments\n straight_segment_length = length / 10\n zigzag_length = length - 2 * straight_segment_length\n\n # Generate points for the zig-zag line\n num_zigs = 4\n num_points = num_zigs * 2\n amplitude = size\n t = np.linspace(0, zigzag_length, num_points)\n zigzag_pattern = amplitude * np.tile([1, -1], num_zigs)\n zigzag_points = np.outer(t, direction) + np.outer(zigzag_pattern, perp_vector1)\n\n # Add the straight segments to the start and end\n start_point = np.array([Xi, Yi, Zi])\n end_point = np.array([Xj, Yj, Zj])\n start_segment = start_point + direction * straight_segment_length\n end_segment = end_point - direction * straight_segment_length\n\n # Adjust the zigzag points to the correct position\n zigzag_points += start_segment\n\n # Combine the points\n points = np.vstack([start_point, start_segment, zigzag_points, end_segment, end_point])\n\n # Add lines connecting the points\n num_points = len(points)\n lines = np.zeros((num_points - 1, 3), dtype=int)\n lines[:, 0] = 2\n lines[:, 1] = np.arange(num_points - 1, dtype=int)\n lines[:, 2] = np.arange(1, num_points, dtype=int)\n\n # Create a PolyData object for the zig-zag line\n zigzag_line = pv.PolyData(points, lines=lines)\n\n # Create a plotter and add the zig-zag line\n self.plotter.add_mesh(zigzag_line, color=color, line_width=2)\n\n # Add the spring label to the list of labels\n self._spring_labels.append(spring.name)\n self._spring_label_points.append([(Xi + Xj) / 2, (Yi + Yj) / 2, (Zi + Zj) / 2])\n\n\n def plot_plates(self, deformed_shape: bool, deformed_scale: float, color_map: Optional[str], combo_name: Optional[str]) -> None:\n \"\"\"Add plate/quad elements to the plotter with optional contours.\n\n :param bool deformed_shape: Plot deformed geometry if ``True``.\n :param float deformed_scale: Scale factor for deformations.\n :param str | None color_map: Contour result type (``None`` disables contours).\n :param str | None combo_name: Load combination name for results.\n \"\"\"\n\n # Start a list of vertices\n plate_vertices = []\n\n # Start a list of plates (faces) for the mesh.\n plate_faces = []\n\n # `plate_results` will store the results in a list for PyVista\n plate_results = []\n\n # Each element will be assigned a unique element number `i` beginning at 0\n i = 0\n\n # Calculate the smoothed contour results at each node\n _PrepContour(self.model, color_map, combo_name)\n\n # Add each plate and quad in the model to the PyVista dataset\n for item in list(self.model.plates.values()) + list(self.model.quads.values()):\n\n # Create a point for each corner (must be in counter clockwise order)\n if deformed_shape:\n p0 = [item.i_node.X + item.i_node.DX[combo_name]*deformed_scale,\n item.i_node.Y + item.i_node.DY[combo_name]*deformed_scale,\n item.i_node.Z + item.i_node.DZ[combo_name]*deformed_scale]\n p1 = [item.j_node.X + item.j_node.DX[combo_name]*deformed_scale,\n item.j_node.Y + item.j_node.DY[combo_name]*deformed_scale,\n item.j_node.Z + item.j_node.DZ[combo_name]*deformed_scale]\n p2 = [item.m_node.X + item.m_node.DX[combo_name]*deformed_scale,\n item.m_node.Y + item.m_node.DY[combo_name]*deformed_scale,\n item.m_node.Z + item.m_node.DZ[combo_name]*deformed_scale]\n p3 = [item.n_node.X + item.n_node.DX[combo_name]*deformed_scale,\n item.n_node.Y + item.n_node.DY[combo_name]*deformed_scale,\n item.n_node.Z + item.n_node.DZ[combo_name]*deformed_scale]\n else:\n p0 = [item.i_node.X, item.i_node.Y, item.i_node.Z]\n p1 = [item.j_node.X, item.j_node.Y, item.j_node.Z]\n p2 = [item.m_node.X, item.m_node.Y, item.m_node.Z]\n p3 = [item.n_node.X, item.n_node.Y, item.n_node.Z]\n\n # Add the points to the PyVista dataset\n plate_vertices.append(p0)\n plate_vertices.append(p1)\n plate_vertices.append(p2)\n plate_vertices.append(p3)\n plate_faces.append([4, i*4, i*4 + 1, i*4 + 2, i*4 + 3])\n\n # Get the contour value for each node\n r0 = item.i_node.contour\n r1 = item.j_node.contour\n r2 = item.m_node.contour\n r3 = item.n_node.contour\n\n # Add plate results to the results list if the user has requested them\n if color_map:\n\n # Save the results for each corner of the plate - one entry for each corner\n plate_results.append(r0)\n plate_results.append(r1)\n plate_results.append(r2)\n plate_results.append(r3)\n\n # Move on to the next plate in our lists to repeat the process\n i+=1\n\n # Add the vertices and the faces to our lists\n plate_vertices = np.array(plate_vertices, dtype=float)\n plate_faces = np.array(plate_faces)\n\n # Create a new PyVista dataset to store plate data\n plate_polydata = pv.PolyData(plate_vertices, plate_faces)\n\n # Add the results as point data to the PyVista dataset\n if color_map:\n\n plate_polydata = plate_polydata.separate_cells()\n plate_polydata['Contours'] = np.array(plate_results)\n\n # Add the scalar bar for the contours\n if self._scalar_bar == True:\n self.plotter.add_mesh(plate_polydata, scalars='Contours', show_edges=True)\n else:\n self.plotter.add_mesh(plate_polydata)\n\n else:\n self.plotter.add_mesh(plate_polydata)\n\n def plot_deformed_node(self, node: Node3D, scale_factor: float, color: str = 'grey') -> None:\n \"\"\"Add a node in its deformed position to the plotter.\n\n :param Node3D node: Node to visualize in deformed state.\n :param float scale_factor: Scale factor for displacements.\n :param str color: Sphere color (default ``'grey'``).\n \"\"\"\n\n # Calculate the node's deformed position\n newX = node.X + scale_factor * (node.DX[self.combo_name])\n newY = node.Y + scale_factor * (node.DY[self.combo_name])\n newZ = node.Z + scale_factor * (node.DZ[self.combo_name])\n\n # Generate a sphere source for the node in its deformed position\n sphere = pv.Sphere(radius=0.4*self.annotation_size, center=[newX, newY, newZ])\n\n # Add the mesh to the plotter\n self.plotter.add_mesh(sphere, color=color)\n\n def plot_deformed_member(self, member: Member3D, scale_factor: float) -> None:\n \"\"\"Add a member in its deformed configuration to the plotter.\n\n :param Member3D member: Member to visualize in deformed state.\n :param float scale_factor: Scale factor for displacements.\n \"\"\"\n\n # Determine if this member is active for each load combination\n if member.active:\n\n L = member.L() # Member length\n T = member.T() # Member local transformation matrix\n\n cos_x = np.array([T[0, 0:3]]) # Direction cosines of local x-axis\n cos_y = np.array([T[1, 0:3]]) # Direction cosines of local y-axis\n cos_z = np.array([T[2, 0:3]]) # Direction cosines of local z-axis\n\n # Find the initial position of the local i-node\n Xi = member.i_node.X\n Yi = member.i_node.Y\n Zi = member.i_node.Z\n\n # Calculate the local y-axis displacements at 20 points along the member's length\n DY_plot = np.empty((0, 3))\n for i in range(20):\n\n # Calculate the local y-direction displacement\n dy_tot = member.deflection('dy', L / 19 * i, self.combo_name)\n\n # Calculate the scaled displacement in global coordinates\n DY_plot = np.append(DY_plot, dy_tot * cos_y * scale_factor, axis=0)\n\n # Calculate the local z-axis displacements at 20 points along the member's length\n DZ_plot = np.empty((0, 3))\n for i in range(20):\n\n # Calculate the local z-direction displacement\n dz_tot = member.deflection('dz', L / 19 * i, self.combo_name)\n\n # Calculate the scaled displacement in global coordinates\n DZ_plot = np.append(DZ_plot, dz_tot * cos_z * scale_factor, axis=0)\n\n # Calculate the local x-axis displacements at 20 points along the member's length\n DX_plot = np.empty((0, 3))\n for i in range(20):\n\n # Displacements in local coordinates\n dx_tot = [[Xi, Yi, Zi]] + (L / 19 * i + member.deflection('dx', L / 19 * i, self.combo_name) * scale_factor) * cos_x\n\n # Magnified displacements in global coordinates\n DX_plot = np.append(DX_plot, dx_tot, axis=0)\n\n # Sum the component displacements to obtain overall displacement\n D_plot = DY_plot + DZ_plot + DX_plot\n\n # Create lines connecting the points\n for i in range(len(D_plot)-1):\n line = pv.Line(D_plot[i], D_plot[i+1])\n self.plotter.add_mesh(line, color='red', line_width=2)\n\n def plot_pt_load(self, position: Tuple[float, float, float], direction: Union[Tuple[float, float, float], np.ndarray],\n length: float, label_text: Optional[Union[str, float, int]] = None, color: str = 'green') -> None:\n \"\"\"Add a point-load arrow to the plotter.\n\n :param tuple position: Arrow tip coordinates ``(X, Y, Z)``.\n :param tuple|ndarray direction: Direction vector (normalized).\n :param float length: Arrow length; sign determines direction.\n :param str|float|int|None label_text: Label text (optional).\n :param str color: Arrow color (default ``'green'``).\n \"\"\"\n\n # Create a unit vector in the direction of the 'direction' vector\n unitVector = direction/np.linalg.norm(direction)\n\n # Determine if the load is positive or negative\n if length == 0:\n sign = 1\n else:\n sign = abs(length)/length\n\n # Generate the tip of the load arrow\n tip_length = abs(length) / 4\n radius = abs(length) / 16\n tip = pv.Cone(center=(position[0] - tip_length*sign*unitVector[0]/2,\n position[1] - tip_length*sign*unitVector[1]/2,\n position[2] - tip_length*sign*unitVector[2]/2),\n direction=(direction[0]*sign, direction[1]*sign, direction[2]*sign),\n height=tip_length, radius=radius)\n\n # Plot the tip\n self.plotter.add_mesh(tip, color=color)\n\n # Create the shaft (you'll need to specify the second point)\n X_tail = position[0] - unitVector[0]*length\n Y_tail = position[1] - unitVector[1]*length\n Z_tail = position[2] - unitVector[2]*length\n shaft = pv.Line(pointa=position, pointb=(X_tail, Y_tail, Z_tail))\n\n # Save the data necessary to create the load's label\n if label_text is not None:\n self._load_labels.append(sig_fig_round(label_text, 3))\n self._load_label_points.append([X_tail, Y_tail, Z_tail])\n\n # Plot the shaft\n self.plotter.add_mesh(shaft, line_width=2, color=color)\n\n def plot_dist_load(self, position1: Tuple[float, float, float], position2: Tuple[float, float, float],\n direction: Union[np.ndarray, Tuple[float, float, float]], length1: float, length2: float,\n label_text1: Optional[Union[str, float, int]], label_text2: Optional[Union[str, float, int]],\n color: str = 'green') -> None:\n \"\"\"Add a linearly varying distributed load to the plotter.\n\n :param tuple position1: Start point of the load.\n :param tuple position2: End point of the load.\n :param ndarray|tuple direction: Load direction vector (normalized).\n :param float length1: Arrow length at start (sign indicates direction).\n :param float length2: Arrow length at end (sign indicates direction).\n :param str|float|int|None label_text1: Label at start.\n :param str|float|int|None label_text2: Label at end.\n :param str color: Arrow color (default ``'green'``).\n \"\"\"\n\n # Calculate the length of the distributed load\n load_length = ((position2[0] - position1[0])**2 + (position2[1] - position1[1])**2 + (position2[2] - position1[2])**2)**0.5\n\n # Find the direction cosines for the line the load acts on\n line_dir_cos = [(position2[0] - position1[0])/load_length,\n (position2[1] - position1[1])/load_length,\n (position2[2] - position1[2])/load_length]\n\n # Find the direction cosines for the direction the load acts in\n dir_dir_cos = direction/np.linalg.norm(direction)\n\n # Create point loads at intervals roughly equal to 75% of the load's largest length\n # Add text labels to the first and last load arrow\n if load_length > 0:\n num_steps = int(round(0.75 * load_length/max(abs(length1), abs(length2)), 0))\n else:\n num_steps = 0\n\n num_steps = max(num_steps, 1)\n step = load_length/num_steps\n\n for i in range(num_steps + 1):\n\n # Calculate the position (X, Y, Z) of this load arrow's point\n position = (position1[0] + i*step*line_dir_cos[0],\n position1[1] + i*step*line_dir_cos[1],\n position1[2] + i*step*line_dir_cos[2])\n\n # Determine the length of this load arrow\n length = length1 + (length2 - length1)/load_length*i*step\n\n # Determine the label's text\n if i == 0:\n label_text = label_text1\n elif i == num_steps:\n label_text = label_text2\n else:\n label_text = None\n\n # Plot the load arrow\n self.plot_pt_load(position, dir_dir_cos, length, label_text, color)\n\n # Draw a line between the first and last load arrow's tails (using cylinder here for better visualization)\n tail_line = pv.Line(position1 - dir_dir_cos*length1, position2 - dir_dir_cos*length2)\n\n # Combine all geometry into a single PolyData object\n self.plotter.add_mesh(tail_line, color=color)\n\n def plot_moment(self, center: Tuple[float, float, float], direction: Union[Tuple[float, float, float], np.ndarray],\n radius: float, label_text: Optional[Union[str, float, int]] = None, color: str = 'green') -> None:\n \"\"\"Add a concentrated moment to the plotter.\n\n :param tuple center: Center point of the moment arc.\n :param tuple|ndarray direction: Direction vector for the moment axis.\n :param float radius: Arc radius.\n :param str|float|int|None label_text: Label text (optional).\n :param str color: Arc and arrow color (default ``'green'``).\n \"\"\"\n\n # Convert the direction vector into a unit vector\n v1 = direction/np.linalg.norm(direction)\n\n # Find any vector perpendicular to the moment direction vector. This will serve as a\n # vector from the center of the arc pointing to the tail of the moment arc.\n v2 = _PerpVector(v1)\n\n # Generate the arc for the moment\n arc = pv.CircularArcFromNormal(center=center, resolution=20, normal=v1, angle=215, polar=v2*radius)\n\n # Add the arc to the plot\n self.plotter.add_mesh(arc, line_width=2, color=color)\n\n # Generate the arrow tip at the end of the arc\n tip_length = radius/4\n cone_radius = radius/16\n cone_direction = -np.cross(v1, arc.center - arc.points[-1])\n tip = pv.Cone(center=arc.points[-1], direction=cone_direction, height=tip_length,\n radius=cone_radius)\n\n # Add the tip to the plot\n self.plotter.add_mesh(tip, color=color)\n\n # Create the text label\n if label_text:\n text_pos = center + (radius + 0.25*self.annotation_size)*v2\n self._load_label_points.append(text_pos)\n self._load_labels.append(label_text)\n\n def plot_area_load(self, position0, position1, position2, position3, direction, length, label_text, color='green'):\n \"\"\"Add an area load (quad with arrows) to the plotter.\n\n :param tuple position0: First corner of the loaded area.\n :param tuple position1: Second corner of the loaded area.\n :param tuple position2: Third corner of the loaded area.\n :param tuple position3: Fourth corner of the loaded area.\n :param tuple|ndarray direction: Load direction vector (normalized).\n :param float length: Arrow length; sign determines orientation.\n :param str label_text: Label text shown at one corner.\n :param str color: Polygon and arrow color (default ``'green'``).\n \"\"\"\n\n # Find the direction cosines for the direction the load acts in\n dir_dir_cos = direction / np.linalg.norm(direction)\n\n # Find the positions of the tails of all the arrows at the corners\n self.p0 = position0 - dir_dir_cos * length\n self.p1 = position1 - dir_dir_cos * length\n self.p2 = position2 - dir_dir_cos * length\n self.p3 = position3 - dir_dir_cos * length\n\n # Plot the area load arrows\n self.plot_pt_load(position0, dir_dir_cos, length, label_text, color)\n self.plot_pt_load(position1, dir_dir_cos, length, color=color)\n self.plot_pt_load(position2, dir_dir_cos, length, color=color)\n self.plot_pt_load(position3, dir_dir_cos, length, color=color)\n\n # Create the area load polygon (quad)\n quad = pv.Quadrilateral([self.p0, self.p1, self.p2, self.p3])\n\n self.plotter.add_mesh(quad, color=color)\n\n def _calc_max_loads(self):\n \"\"\"Calculate maximum load magnitudes for normalization.\n\n :returns: Tuple of (max_pt_load, max_moment, max_dist_load, max_area_load)\n with zero values replaced by 1 to avoid division errors.\n :rtype: tuple[float, float, float, float]\n \"\"\"\n\n max_pt_load = 0\n max_moment = 0\n max_dist_load = 0\n max_area_load = 0\n\n # Find the requested load combination or load case\n if self.case == None:\n\n # Step through each node\n for node in self.model.nodes.values():\n\n # Step through each nodal load to find the largest one\n for load in node.NodeLoads:\n\n # Find the largest loads in the load combination\n if load[2] in self.model.load_combos[self.combo_name].factors:\n if load[0] == 'FX' or load[0] == 'FY' or load[0] == 'FZ':\n if abs(load[1]*self.model.load_combos[self.combo_name].factors[load[2]]) > max_pt_load:\n max_pt_load = abs(load[1]*self.model.load_combos[self.combo_name].factors[load[2]])\n else:\n if abs(load[1]*self.model.load_combos[self.combo_name].factors[load[2]]) > max_moment:\n max_moment = abs(load[1]*self.model.load_combos[self.combo_name].factors[load[2]])\n\n # Step through each member\n for member in self.model.members.values():\n\n # Step through each member point load\n for load in member.PtLoads:\n\n # Find and store the largest point load and moment in the load combination\n if load[3] in self.model.load_combos[self.combo_name].factors:\n\n if (load[0] == 'Fx' or load[0] == 'Fy' or load[0] == 'Fz'\n or load[0] == 'FX' or load[0] == 'FY' or load[0] == 'FZ'):\n if abs(load[1]*self.model.load_combos[self.combo_name].factors[load[3]]) > max_pt_load:\n max_pt_load = abs(load[1]*self.model.load_combos[self.combo_name].factors[load[3]])\n else:\n if abs(load[1]*self.model.load_combos[self.combo_name].factors[load[3]]) > max_moment:\n max_moment = abs(load[1]*self.model.load_combos[self.combo_name].factors[load[3]])\n\n # Step through each member distributed load\n for load in member.DistLoads:\n\n #Find and store the largest distributed load in the load combination\n if load[5] in self.model.load_combos[self.combo_name].factors:\n\n if abs(load[1]*self.model.load_combos[self.combo_name].factors[load[5]]) > max_dist_load:\n max_dist_load = abs(load[1]*self.model.load_combos[self.combo_name].factors[load[5]])\n if abs(load[2]*self.model.load_combos[self.combo_name].factors[load[5]]) > max_dist_load:\n max_dist_load = abs(load[2]*self.model.load_combos[self.combo_name].factors[load[5]])\n\n # Step through each plate\n for plate in self.model.plates.values():\n\n # Step through each plate load\n for load in plate.pressures:\n\n if load[1] in self.model.load_combos[self.combo_name].factors:\n if abs(load[0]*self.model.load_combos[self.combo_name].factors[load[1]]) > max_area_load:\n max_area_load = abs(load[0]*self.model.load_combos[self.combo_name].factors[load[1]])\n\n # Step through each quad\n for quad in self.model.quads.values():\n\n # Step through each plate load\n for load in quad.pressures:\n\n # Check to see if the load case is in the requested load combination\n if load[1] in self.model.load_combos[self.combo_name].factors:\n if abs(load[0]*self.model.load_combos[self.combo_name].factors[load[1]]) > max_area_load:\n max_area_load = abs(load[0]*self.model.load_combos[self.combo_name].factors[load[1]])\n\n # Behavior if case has been specified\n else:\n\n # Step through each node\n for node in self.model.nodes.values():\n\n # Step through each nodal load to find the largest one\n for load in node.NodeLoads:\n\n # Find the largest loads in the load case\n if load[2] == self.case:\n if load[0] == 'FX' or load[0] == 'FY' or load[0] == 'FZ':\n if abs(load[1]) > max_pt_load:\n max_pt_load = abs(load[1])\n else:\n if abs(load[1]) > max_moment:\n max_moment = abs(load[1])\n\n # Step through each member\n for member in self.model.members.values():\n\n # Step through each member point load\n for load in member.PtLoads:\n\n # Find and store the largest point load and moment in the load case\n if load[3] == self.case:\n\n if (load[0] == 'Fx' or load[0] == 'Fy' or load[0] == 'Fz'\n or load[0] == 'FX' or load[0] == 'FY' or load[0] == 'FZ'):\n if abs(load[1]) > max_pt_load:\n max_pt_load = abs(load[1])\n else:\n if abs(load[1]) > max_moment:\n max_moment = abs(load[1])\n\n # Step through each member distributed load\n for load in member.DistLoads:\n\n # Find and store the largest distributed load in the load case\n if load[5] == self.case:\n\n if abs(load[1]) > max_dist_load:\n max_dist_load = abs(load[1])\n if abs(load[2]) > max_dist_load:\n max_dist_load = abs(load[2])\n\n # Step through each plate\n for plate in self.model.plates.values():\n\n # Step through each plate load\n for load in plate.pressures:\n\n if load[1] == self.case:\n\n if abs(load[0]) > max_area_load:\n max_area_load = abs(load[0])\n\n # Step through each quad\n for quad in self.model.quads.values():\n\n # Step through each plate load\n for load in quad.pressures:\n\n if load[1] == self.case:\n\n if abs(load[0]) > max_area_load:\n max_area_load = abs(load[0])\n\n # Prevent division by zero errors by ensuring max values are never zero\n # If a load type has no loads, set it to 1 to avoid crashes during normalization\n if max_pt_load == 0:\n max_pt_load = 1\n if max_moment == 0:\n max_moment = 1\n if max_dist_load == 0:\n max_dist_load = 1\n if max_area_load == 0:\n max_area_load = 1\n\n # Return the maximum loads for the load combo or load case\n return max_pt_load, max_moment, max_dist_load, max_area_load\n\n def plot_loads(self):\n \"\"\"Add all loads (nodal, member, plate) to the plotter.\n\n Renders point loads, moments, distributed loads, and area loads\n with appropriate glyphs and labels.\n \"\"\"\n\n # Get the maximum load magnitudes that will be used to normalize the display scale\n max_pt_load, max_moment, max_dist_load, max_area_load = self._calc_max_loads()\n\n # Display the requested load combination, or 'Combo 1' if no load combo or case has been\n # specified\n if self.case is None:\n # Store model.load_combos[combo].factors under a simpler name for use below\n load_factors = self.model.load_combos[self.combo_name].factors\n else:\n # Set up a load combination dictionary that represents the load case\n load_factors = {self.case: 1}\n\n # Step through each node\n for node in self.model.nodes.values():\n\n # Step through and display each nodal load\n for load in node.NodeLoads:\n\n # Determine if this load is part of the requested LoadCombo or case\n if load[2] in load_factors:\n\n # Calculate the factored value for this load and it's sign (positive or\n # negative)\n load_value = load[1]*load_factors[load[2]]\n if load_value != 0:\n sign = load_value/abs(load_value)\n else:\n sign = 1\n\n # Determine the direction of this load\n if load[0] == 'FX' or load[0] == 'MX': direction = (sign, 0, 0)\n elif load[0] == 'FY' or load[0] == 'MY': direction = (0, sign, 0)\n elif load[0] == 'FZ' or load[0] == 'MZ': direction = (0, 0, sign)\n\n # Display the load\n if load[0] in {'FX', 'FY', 'FZ'}:\n self.plot_pt_load((node.X, node.Y, node.Z), direction,\n abs(load_value/max_pt_load)*5*self.annotation_size,\n load_value, 'green')\n elif load[0] in {'MX', 'MY', 'MZ'}:\n self.plot_moment((node.X, node.Y, node.Z), direction, abs(load_value/max_moment)*2.5*self.annotation_size, str(load_value), 'green')\n\n # Step through each member\n for member in self.model.members.values():\n\n # Get the direction cosines for the member's local axes\n dir_cos = member.T()[0:3, 0:3]\n\n # Get the starting point for the member\n x_start, y_start, z_start = member.i_node.X, member.i_node.Y, member.i_node.Z\n\n # Step through each member point load\n for load in member.PtLoads:\n\n # Determine if this load is part of the requested load combination\n if load[3] in load_factors:\n\n # Calculate the factored value for this load and it's sign (positive or negative)\n load_value = load[1]*load_factors[load[3]]\n sign = load_value/abs(load_value)\n\n # Calculate the load's location in 3D space\n x = load[2]\n position = [x_start + dir_cos[0, 0]*x, y_start + dir_cos[0, 1]*x, z_start + dir_cos[0, 2]*x]\n\n # Display the load\n if load[0] == 'Fx':\n self.plot_pt_load(position, dir_cos[0, :], load_value/max_pt_load*5*self.annotation_size, load_value)\n elif load[0] == 'Fy':\n self.plot_pt_load(position, dir_cos[1, :], load_value/max_pt_load*5*self.annotation_size, load_value)\n elif load[0] == 'Fz':\n self.plot_pt_load(position, dir_cos[2, :], load_value/max_pt_load*5*self.annotation_size, load_value)\n elif load[0] == 'Mx':\n self.plot_moment(position, dir_cos[0, :]*sign, abs(load_value)/max_moment*2.5*self.annotation_size, str(load_value))\n elif load[0] == 'My':\n self.plot_moment(position, dir_cos[1, :]*sign, abs(load_value)/max_moment*2.5*self.annotation_size, str(load_value))\n elif load[0] == 'Mz':\n self.plot_moment(position, dir_cos[2, :]*sign, abs(load_value)/max_moment*2.5*self.annotation_size, str(load_value))\n elif load[0] == 'FX':\n self.plot_pt_load(position, [1, 0, 0], load_value/max_pt_load*5*self.annotation_size, load_value)\n elif load[0] == 'FY':\n self.plot_pt_load(position, [0, 1, 0], load_value/max_pt_load*5*self.annotation_size, load_value)\n elif load[0] == 'FZ':\n self.plot_pt_load(position, [0, 0, 1], load_value/max_pt_load*5*self.annotation_size, load_value)\n elif load[0] == 'MX':\n self.plot_moment(position, [1*sign, 0, 0], abs(load_value)/max_moment*2.5*self.annotation_size, str(load_value))\n elif load[0] == 'MY':\n self.plot_moment(position, [0, 1*sign, 0], abs(load_value)/max_moment*2.5*self.annotation_size, str(load_value))\n elif load[0] == 'MZ':\n self.plot_moment(position, [0, 0, 1*sign], abs(load_value)/max_moment*2.5*self.annotation_size, str(load_value))\n\n # Step through each member distributed load\n for load in member.DistLoads:\n\n # Determine if this load is part of the requested load combination\n if load[5] in load_factors:\n\n # Calculate the factored value for this load and it's sign (positive or negative)\n w1 = load[1]*load_factors[load[5]]\n w2 = load[2]*load_factors[load[5]]\n\n # Calculate the loads location in 3D space\n x1 = load[3]\n x2 = load[4]\n position1 = [x_start + dir_cos[0, 0]*x1, y_start + dir_cos[0, 1]*x1, z_start + dir_cos[0, 2]*x1]\n position2 = [x_start + dir_cos[0, 0]*x2, y_start + dir_cos[0, 1]*x2, z_start + dir_cos[0, 2]*x2]\n\n # Display the load\n if load[0] in {'Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'}:\n\n # Determine the load direction\n if load[0] == 'Fx': direction = dir_cos[0, :]\n elif load[0] == 'Fy': direction = dir_cos[1, :]\n elif load[0] == 'Fz': direction = dir_cos[2, :]\n elif load[0] == 'FX': direction = [1, 0, 0]\n elif load[0] == 'FY': direction = [0, 1, 0]\n elif load[0] == 'FZ': direction = [0, 0, 1]\n\n # Plot the distributed load\n self.plot_dist_load(position1, position2, direction, w1/max_dist_load*5*self.annotation_size, w2/max_dist_load*5*self.annotation_size, str(sig_fig_round(w1, 3)), str(sig_fig_round(w2, 3)), 'green')\n\n # Step through each plate\n for plate in list(self.model.plates.values()) + list(self.model.quads.values()):\n\n # Get the direction cosines for the plate's local z-axis\n dir_cos = plate.T()[0:3, 0:3]\n dir_cos = dir_cos[2]\n\n # Step through each plate load\n for load in plate.pressures:\n\n # Determine if this load is part of the requested load combination\n if load[1] in load_factors:\n\n # Calculate the factored value for this load\n load_value = load[0]*load_factors[load[1]]\n\n # Find the sign for this load. Intercept any divide by zero errors\n if load[0] == 0:\n sign = 1\n else:\n sign = abs(load[0])/load[0]\n\n # Find the position of the load's 4 corners\n position0 = [plate.i_node.X, plate.i_node.Y, plate.i_node.Z]\n position1 = [plate.j_node.X, plate.j_node.Y, plate.j_node.Z]\n position2 = [plate.m_node.X, plate.m_node.Y, plate.m_node.Z]\n position3 = [plate.n_node.X, plate.n_node.Y, plate.n_node.Z]\n\n # Create an area load and get its data\n self.plot_area_load(position0, position1, position2, position3, dir_cos*sign, load_value/max_area_load*5*self.annotation_size, str(sig_fig_round(load_value, 3)), color='green')\n\n def _get_max_internal_forces(self, diagram_type: str, combo_name: str) -> float:\n \"\"\"Calculate maximum internal force/moment magnitudes across all members for consistent scaling.\n\n :param str diagram_type: Diagram type (``'Fy'``, ``'Fz'``, ``'My'``, ``'Mz'``, ``'Fx'``, ``'Tx'``).\n :param str combo_name: Load combination name.\n :returns: Maximum absolute value of the internal force/moment.\n :rtype: float\n \"\"\"\n \n max_value = 0\n \n # Iterate through all members to find the global maximum\n for member in self.model.members.values():\n \n # Skip inactive members for this combo\n if combo_name not in member.active or not member.active[combo_name]:\n continue\n \n try:\n # Get the maximum value for this member based on diagram type\n if diagram_type == 'Fy':\n member_max = member.max_shear('Fy', combo_name)\n member_min = member.min_shear('Fy', combo_name)\n elif diagram_type == 'Fz':\n member_max = member.max_shear('Fz', combo_name)\n member_min = member.min_shear('Fz', combo_name)\n elif diagram_type == 'My':\n member_max = member.max_moment('My', combo_name)\n member_min = member.min_moment('My', combo_name)\n elif diagram_type == 'Mz':\n member_max = member.max_moment('Mz', combo_name)\n member_min = member.min_moment('Mz', combo_name)\n elif diagram_type == 'Fx':\n member_max = member.max_axial(combo_name)\n member_min = member.min_axial(combo_name)\n elif diagram_type == 'Tx':\n member_max = member.max_torque(combo_name)\n member_min = member.min_torque(combo_name)\n else:\n continue\n \n # Track the global maximum absolute value\n max_value = max(max_value, abs(member_max), abs(member_min))\n \n except Exception:\n # Skip members that don't have the requested results\n continue\n \n # Prevent division by zero\n if max_value == 0:\n max_value = 1\n \n return max_value\n\n def plot_member_diagrams(self) -> None:\n \"\"\"Add internal force/moment diagrams to members.\n\n Displays member diagrams (Fy, Fz, My, Mz, Fx, Tx) based on the\n current ``member_diagrams`` setting.\n \"\"\"\n \n # Determine which combo/case to use\n combo_name = self.combo_name if self.combo_name is not None else self.case\n \n # Calculate global maximum internal force/moment for consistent scaling across all members\n global_max = self._get_max_internal_forces(self.member_diagrams, combo_name)\n \n # Create diagrams for each active member\n for member in self.model.members.values():\n \n # Check if member is active for the specified combo\n if combo_name not in member.active or not member.active[combo_name]:\n continue\n \n try:\n # Get member information\n i_node = member.i_node\n j_node = member.j_node\n Xi, Yi, Zi = i_node.X, i_node.Y, i_node.Z\n Xj, Yj, Zj = j_node.X, j_node.Y, j_node.Z\n L = member.L()\n \n # Get transformation matrix for local coordinates\n T = member.T()\n cos_x = np.array([T[0, 0:3]]) # Local x-axis (along member)\n cos_y = np.array([T[1, 0:3]]) # Local y-axis\n cos_z = np.array([T[2, 0:3]]) # Local z-axis\n \n # Member base line\n member_start = np.array([Xi, Yi, Zi])\n member_dir = np.array([Xj - Xi, Yj - Yi, Zj - Zi])\n \n # Determine perpendicular direction for diagram offset\n if self.member_diagrams in ['Fy', 'Mz']:\n perp_dir = cos_y[0] # Use y direction for offset\n elif self.member_diagrams in ['Fz', 'My']:\n perp_dir = cos_z[0] # Use z direction for offset\n else:\n perp_dir = cos_y[0] # Default to y direction\n \n # Get result values at points along member\n n_points = 20\n x_array = np.linspace(0, L, n_points)\n \n if self.member_diagrams == 'Fy':\n results = member.shear_array('Fy', n_points, combo_name, x_array)\n y_values = results[1]\n max_value = member.max_shear('Fy', combo_name)\n min_value = member.min_shear('Fy', combo_name)\n elif self.member_diagrams == 'Fz':\n results = member.shear_array('Fz', n_points, combo_name, x_array)\n y_values = results[1]\n max_value = member.max_shear('Fz', combo_name)\n min_value = member.min_shear('Fz', combo_name)\n elif self.member_diagrams == 'My':\n results = member.moment_array('My', n_points, combo_name, x_array)\n y_values = results[1]\n max_value = member.max_moment('My', combo_name)\n min_value = member.min_moment('My', combo_name)\n elif self.member_diagrams == 'Mz':\n results = member.moment_array('Mz', n_points, combo_name, x_array)\n y_values = results[1]\n max_value = member.max_moment('Mz', combo_name)\n min_value = member.min_moment('Mz', combo_name)\n elif self.member_diagrams == 'Fx':\n results = member.axial_array(n_points, combo_name, x_array)\n y_values = results[1]\n max_value = member.max_axial(combo_name)\n min_value = member.min_axial(combo_name)\n elif self.member_diagrams == 'Tx':\n results = member.torque_array(n_points, combo_name, x_array)\n y_values = results[1]\n max_value = member.max_torque(combo_name)\n min_value = member.min_torque(combo_name)\n else:\n continue\n \n # Normalize values for better visualization\n # Use global_max for consistent scaling across all members\n if global_max > 0:\n normalized_values = y_values / global_max\n else:\n normalized_values = y_values\n \n # Create baseline points\n baseline_points = []\n for i, x in enumerate(x_array):\n pos_along_member = member_start + (x / L) * member_dir\n baseline_points.append(pos_along_member)\n \n # Create diagram points (displaced from member axis)\n diagram_points = []\n for i, x in enumerate(x_array):\n pos_along_member = member_start + (x / L) * member_dir\n diag_displacement = (normalized_values[i] * self.diagram_scale * 0.5) * perp_dir\n diagram_pt = pos_along_member + diag_displacement\n diagram_points.append(diagram_pt)\n \n # Create baseline line\n baseline_pts = np.array(baseline_points)\n baseline_lines = np.zeros((len(baseline_pts)-1, 3), dtype=int)\n baseline_lines[:, 0] = 2\n baseline_lines[:, 1] = np.arange(len(baseline_pts)-1, dtype=int)\n baseline_lines[:, 2] = np.arange(1, len(baseline_pts), dtype=int)\n baseline_polydata = pv.PolyData(baseline_pts, lines=baseline_lines)\n \n # Create diagram line\n diagram_pts = np.array(diagram_points)\n diagram_lines = np.zeros((len(diagram_pts)-1, 3), dtype=int)\n diagram_lines[:, 0] = 2\n diagram_lines[:, 1] = np.arange(len(diagram_pts)-1, dtype=int)\n diagram_lines[:, 2] = np.arange(1, len(diagram_pts), dtype=int)\n diagram_polydata = pv.PolyData(diagram_pts, lines=diagram_lines)\n \n # Create connector lines (vertical lines from baseline to diagram)\n connector_pts_list = []\n connector_lines_list = []\n pt_idx = 0\n for i in range(len(x_array)):\n connector_pts_list.append(baseline_points[i])\n connector_pts_list.append(diagram_points[i])\n connector_lines_list.append([2, pt_idx, pt_idx + 1])\n pt_idx += 2\n \n if connector_pts_list:\n connector_pts = np.array(connector_pts_list)\n connector_lines = np.array(connector_lines_list)\n connector_polydata = pv.PolyData(connector_pts, lines=connector_lines)\n \n # Set color based on theme\n if self.theme == 'default':\n color = (0, 1, 1) # Cyan\n else:\n color = (0, 0, 0) # Black for print\n \n # Add all diagram components to plotter\n self.plotter.add_mesh(baseline_polydata, color=color, line_width=1)\n self.plotter.add_mesh(diagram_polydata, color=color, line_width=1)\n self.plotter.add_mesh(connector_polydata, color=color, line_width=1)\n \n # Add value labels at max and min points\n if self.show_labels:\n max_idx = int(y_values.argmax())\n min_idx = int(y_values.argmin())\n \n # Place labels with offset proportional to annotation_size\n label_offset = 0.1 * self.annotation_size\n max_pos = np.array(diagram_points[max_idx]) + label_offset * perp_dir\n min_pos = np.array(diagram_points[min_idx]) + label_offset * perp_dir\n \n max_str = f\"{max_value:.3g}\"\n min_str = f\"{min_value:.3g}\"\n \n # Add text labels (show_points defaults to True)\n self.plotter.add_point_labels([max_pos], [max_str], text_color=color, point_color=color, bold=False, shape=None, render_points_as_spheres=False)\n self.plotter.add_point_labels([min_pos], [min_str], text_color=color, point_color=color, bold=False, shape=None, render_points_as_spheres=False)\n \n except Exception:\n # Silently skip members that fail to render diagrams\n pass", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 78095}, "Testing/test_material_section_coverage.py::141": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["SteelSection"], "enclosing_function": "test_steel_section_creation", "extracted_code": "# Source: Pynite/Section.py\nclass SteelSection(Section):\n\n def __init__(self, model: 'FEModel3D', name: str, A: float, Iy: float, Iz: float, J: float, \n Zy: float, Zz: float, material_name: str) -> None:\n \"\"\"\n Initialize a steel section\n\n :param model: The finite element model to which this section belongs\n :type model: FEModel3D\n :param name: Name of the section\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: Plastic section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: Plastic section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: Name of the material used for this section\n :type material_name: str\n \"\"\"\n\n # Basic section properties\n super().__init__(model, name, A, Iy, Iz, J)\n\n # Additional section properties for steel\n self.ry: float = (Iy/A)**0.5\n self.rz: float = (Iz/A)**0.5\n self.Zy: float = Zy\n self.Zz: float = Zz\n\n self.material = model.materials[material_name]\n\n def Phi(self, fx: float = 0, my: float = 0, mz: float = 0) -> float:\n \"\"\"\n A method used to determine whether the cross section is elastic or plastic.\n Values less than 1 indicate the section is elastic.\n\n :param fx: Axial force divided by axial strength.\n :type fx: float\n :param my: Weak axis moment divided by weak axis strength.\n :type my: float\n :param mz: Strong axis moment divided by strong axis strength.\n :type mz: float\n :return: The total stress ratio for the cross section.\n :rtype: float\n \"\"\"\n\n # Plastic strengths for material nonlinearity\n Py = self.material.fy*self.A\n Mpy = self.material.fy*self.Zy\n Mpz = self.material.fy*self.Zz\n\n # Values for p, my, and mz based on actual loads\n p = fx/Py\n m_y = my/Mpy\n m_z = mz/Mpz\n\n # \"Matrix Structural Analysis, 2nd Edition\", Equation 10.18\n return p**2 + m_z**2 + m_y**4 + 3.5*p**2*m_z**2 + 3*p**6*m_y**2 + 4.5*m_z**4*m_y**2\n\n def G(self, fx: float, my: float, mz: float) -> NDArray[float64]:\n \"\"\"Returns the gradient to the material's yield surface for the given load. Used to construct the plastic reduction matrix for nonlinear behavior.\n\n :param fx: Axial force at the cross-section.\n :type fx: float\n :param my: y-axis (weak) moment at the cross-section.\n :type my: float\n :param mz: z-axis (strong) moment at the cross-section.\n :type mz: float\n :return: The gradient to the material's yield surface at the cross-section.\n :rtype: NDArray\n \"\"\"\n\n # Calculate `Phi` which is essentially a stress check indicating how close to yield we are\n Phi = self.Phi(fx, my, mz)\n\n # If Phi is less than 1.0 the member is still elastic and there is no gradient to the yield surface\n if Phi < 1.0:\n\n # G = zero vector\n return np.array([[0],\n [0],\n [0],\n [0],\n [0],\n [0]])\n\n # Plastic action is occuring\n else:\n\n # Plastic strengths for material nonlinearity\n Py = self.material.fy*self.A\n Mpy = self.material.fy*self.Zy\n Mpz = self.material.fy*self.Zz\n\n # Partial derivatives of Phi\n dPhi_dfx = 18*fx**5*my**2/(Mpy**2*Py**6) + 2*fx/Py**2 + 7.0*fx*mz**2/(Mpz**2*Py**2)\n dPhi_dmy = 6*fx**6*my/(Mpy**2*Py**6) + 2*my/Mpy**2 + 9.0*my*mz**4/(Mpy**2*Mpz**4)\n dPhi_dmz = 7.0*fx**2*mz/(Mpz**2*Py**2) + 2*mz/Mpz**2 + 18.0*my**2*mz**3/(Mpy**2*Mpz**4)\n\n # Return the gradient\n return np.array([[dPhi_dfx],\n [0],\n [0],\n [0],\n [dPhi_dmy],\n [dPhi_dmz]])", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 4412}, "Testing/test_2D_frames.py::287": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_Kassimali_3_35", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regen_simple.py::175": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_multiple_meshes_independent_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regen_simple.py::44": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_springs.py::51": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_spring_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_Visualization.py::237": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_annotation_size_auto_single_node", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_mesh_regeneration.py::44": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::124": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["Section"], "enclosing_function": "test_section_gradient_calculation", "extracted_code": "# Source: Pynite/Section.py\nclass Section():\n \"\"\"\n A class representing a section assigned to a Member3D element in a finite element model.\n\n This class stores all properties related to the geometry of the member\n \"\"\"\n def __init__(self, model: 'FEModel3D', name: str, A: float, Iy: float, Iz: float, J: float) -> None:\n \"\"\"\n :param model: The finite element model to which this section belongs\n :type model: FEModel3D\n :param name: Name of the section\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\" \n self.model: 'FEModel3D' = model\n self.name: str = name\n self.A: float = A\n self.Iy: float = Iy\n self.Iz: float = Iz\n self.J: float = J\n \n def Phi(self, fx: float = 0, my: float = 0, mz: float = 0):\n \"\"\"\n Method to be overridden by subclasses for determining whether the cross section is\n elastic or plastic.\n \n :param fx: Axial force\n :type fx: float\n :param my: y-axis (weak) moment\n :type my: float\n :param mz: z-axis (strong) moment\n :type mz: float\n :return: The stress ratio\n :rtype: float\n \"\"\"\n raise NotImplementedError(\"Phi method must be implemented in subclasses.\")\n\n def G(self, fx: float, my: float, mz: float) -> NDArray:\n \"\"\"\n Returns the gradient to the yield surface at a given point using numerical differentiation. This is a default solution. For a better solution, overwrite this method with a more precise one in the material/shape specific child class that inherits from this class.\n\n :param fx: Axial force at the cross-section\n :type fx: float\n :param my: y-axis (weak) moment at the cross-section\n :type my: float\n :param mz: z-axis (strong) moment at the cross-section\n :type mz: float\n :return: The gradient to the yield surface at the cross-section\n :rtype: NDArray\n \"\"\"\n\n # Small increment for numerical differentiation\n epsilon = 1e-6\n\n # Calculate the central differences for each parameter\n dPhi_dfx = (self.Phi(fx + epsilon, my, mz) - self.Phi(fx - epsilon, my, mz)) / (2 * epsilon)\n dPhi_dmy = (self.Phi(fx, my + epsilon, mz) - self.Phi(fx, my - epsilon, mz)) / (2 * epsilon)\n dPhi_dmz = (self.Phi(fx, my, mz + epsilon) - self.Phi(fx, my, mz - epsilon)) / (2 * epsilon)\n\n # Return the gradient\n return np.array([[dPhi_dfx],\n [dPhi_dmy],\n [dPhi_dmz]])", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2920}, "Testing/test_mesh_regeneration.py::46": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regen_simple.py::173": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_multiple_meshes_independent_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_delete_mesh.py::150": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_with_attached_members", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regeneration.py::40": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_Visualization.py::253": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_annotation_size_manual_override", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_plates&quads.py::120": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D", "math"], "enclosing_function": "test_hydrostatic_plate", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_AISC_PDelta_benchmarks.py::160": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_AISC_benchmark_case1", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regeneration.py::38": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_loads.py::111": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Section.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_axial_distributed_load", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_node_merge.py::76": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_cluster_merge_and_element_rewire", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_2D_frames.py::288": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_Kassimali_3_35", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_springs.py::54": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_spring_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_spring_coverage.py::85": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": [], "enclosing_function": "test_node_load_lists_initialized", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "Testing/test_node_merge.py::29": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_no_merge_unique_nodes", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_springs.py::78": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_nodal_springs", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_Visualization.py::363": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_member_end_release_none", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 375}, "Testing/test_Visualization.py::184": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_toggle_deformed_shape", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_meshes.py::129": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_PCA_7_quad", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::25": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["Material"], "enclosing_function": "test_material_creation", "extracted_code": "# Source: Pynite/Material.py\nclass Material():\n \"\"\"\n A class representing a material assigned to a Member3D, Plate or Quad in a finite element model.\n\n This class stores all properties related to the physical material of the element\n \"\"\"\n def __init__(self, model: FEModel3D, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> None:\n \"\"\"Initialize a material object.\n\n :param model: The finite element model this material belongs to\n :type model: FEModel3D\n :param name: A unique name for the material\n :type name: str\n :param E: Modulus of elasticity\n :type E: float\n :param G: Shear modulus\n :type G: float\n :param nu: Poisson's ratio\n :type nu: float\n :param rho: Density of the material\n :type rho: float\n :param fy: Yield strength of the material, defaults to None\n :type fy: float, optional\n \"\"\"\n\n self.model: FEModel3D = model\n self.name: str = name\n self.E: float = E\n self.G: float = G\n self.nu: float = nu\n self.rho: float = rho\n self.fy: float | None = fy", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 1173}, "Testing/test_delete_mesh.py::107": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_with_attached_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::32": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["Material"], "enclosing_function": "test_material_with_yield_strength", "extracted_code": "# Source: Pynite/Material.py\nclass Material():\n \"\"\"\n A class representing a material assigned to a Member3D, Plate or Quad in a finite element model.\n\n This class stores all properties related to the physical material of the element\n \"\"\"\n def __init__(self, model: FEModel3D, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> None:\n \"\"\"Initialize a material object.\n\n :param model: The finite element model this material belongs to\n :type model: FEModel3D\n :param name: A unique name for the material\n :type name: str\n :param E: Modulus of elasticity\n :type E: float\n :param G: Shear modulus\n :type G: float\n :param nu: Poisson's ratio\n :type nu: float\n :param rho: Density of the material\n :type rho: float\n :param fy: Yield strength of the material, defaults to None\n :type fy: float, optional\n \"\"\"\n\n self.model: FEModel3D = model\n self.name: str = name\n self.E: float = E\n self.G: float = G\n self.nu: float = nu\n self.rho: float = rho\n self.fy: float | None = fy", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 1173}, "Testing/test_Visualization.py::149": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_toggle_visual_properties", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_delete_mesh.py::103": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_with_attached_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_loads.py::40": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Section.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_member_self_weight", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_end_releases.py::57": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_end_release_Rz", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_merge.py::96": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_support_and_spring_support_merge", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_member_rotation.py::101": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_column_rotation", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_mesh_regeneration.py::83": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_mesh_regeneration_with_shared_nodes", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_merge.py::44": {"resolved_imports": ["Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_simple_pair_merge_canonical_first_added", "extracted_code": "# Source: Pynite/FEModel3D.py\nclass FEModel3D():\n \"\"\"A 3D finite element model object. This object has methods and dictionaries to create, store,\n and retrieve results from a finite element model.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Creates a new 3D finite element model.\n \"\"\"\n\n # Initialize the model's various dictionaries. The dictionaries will be prepopulated with\n # the data types they store, and then those types will be removed. This will give us the\n # ability to get type-based hints when using the dictionaries.\n\n self.nodes: Dict[str, Node3D] = {} # A dictionary of the model's nodes\n self.materials: Dict[str, Material] = {} # A dictionary of the model's materials\n self.sections: Dict[str, Section] = {} # A dictonary of the model's cross-sections\n self.springs: Dict[str, Spring3D] = {} # A dictionary of the model's springs\n self.members: Dict[str, PhysMember] = {} # A dictionary of the model's physical members\n self.quads: Dict[str, Quad3D] = {} # A dictionary of the model's quadiralterals\n self.plates: Dict[str, Plate3D] = {} # A dictionary of the model's rectangular plates\n self.meshes: Dict[str, Mesh] = {} # A dictionary of the model's meshes\n self.shear_walls: Dict[str, ShearWall] = {} # A dictionary of the model's shear walls\n self.mats: Dict[str, MatFoundation] = {} # A dictionary of the model's mat foundations\n self.load_combos: Dict[str, LoadCombo] = {} # A dictionary of the model's load combinations\n self._D: Dict[str, NDArray[float64]] = {} # A dictionary of the model's nodal displacements by load combination\n\n self.solution: str | None = None # Indicates the solution type for the latest run of the model\n\n # Decorator marks this helper as not needing class/instance state.\n @staticmethod\n # Define helper that flattens node DOFs into a single index vector.\n def _build_dof_vector(*nodes: Node3D) -> NDArray[np.int64]:\n \"\"\"Returns the flattened list of global DOF indices for the supplied nodes.\n\n Example for a 2-node member:\n\n [i_node*6 + (0..5), j_node*6 + (0..5)] -> 12 indices total.\n\n Once this vector is created we can operate on entire element sub-matrices via\n numpy broadcasting, instead of repeating the ``node.ID*6 + local_dof`` math in\n Python loops.\n \"\"\"\n\n # Preallocate the DOF array (nodes * 6 DOFs each) as 64-bit ints.\n dofs = np.empty(len(nodes)*6, dtype=np.int64)\n\n # Build a template 0..5 array to shift per node.\n local = np.arange(6, dtype=np.int64)\n\n # Iterate through each supplied node with its ordinal index.\n for i, node in enumerate(nodes):\n\n # Compute the slice start for this node's 6 DOFs.\n start = i*6\n\n # Fill the slice with the node's base DOF plus the 0..5 offsets.\n dofs[start:start+6] = node.ID*6 + local\n \n # Hand back the populated DOF vector for downstream use.\n return dofs\n\n # Decorator again indicates no self access is needed for sparse conversion helper.\n @staticmethod\n # Define helper that converts a dense element block into coo-format row/col/data arrays.\n def _append_sparse_block(dofs: NDArray[np.int64], block: np.ndarray,\n row_parts: list[np.ndarray], col_parts: list[np.ndarray],\n data_parts: list[np.ndarray]) -> None:\n \"\"\"Converts an element sub-matrix into row/col/data arrays for COO assembly.\n\n Compared to the former nested loops, this function handles the conversion in\n three numpy statements:\n 1. ``rows = repeat(dofs, size)``\n 2. ``cols = tile(dofs, size)``\n 3. ``data = block.reshape(-1)``\n\n Optional zero filtering keeps the sparse storage compact.\n \"\"\"\n\n # Ensure we are working with a float ndarray copy of the element block.\n block = np.asarray(block, dtype=float)\n\n # Cache the number of DOFs so we know how many row/column pairs we need; the sparse\n # COO builder needs every (row, col) pair formed by combining each DOF with\n # every other DOF because each element term contributes to one of those pairs.\n size = dofs.size\n\n # Flatten the element block into a 1-D vector matching the row/column pairing order so\n # ``flat[k]`` lines up with the kth (row, col) pair produced by the repeat/tile step;\n # this guarantees each coefficient from the local matrix lands on the\n # matching global DOF pair when we append into COO format.\n flat = block.reshape(-1)\n\n # Skip work entirely if this block contains only zeros; many elements (like nodal mass\n # shells) hand back zero-filled matrices, and filtering them here avoids appending\n # useless entries into the sparse accumulator.\n nonzero_mask = flat != 0.0\n\n # Return immediately when there is nothing to contribute to the sparse matrix.\n if not np.any(nonzero_mask):\n return\n\n # Build the repeated row indices for the full set of row/column combinations; repeating\n # each DOF ``size`` times yields the row portion of every (row, col) pair needed for COO insertion.\n rows = np.repeat(dofs, size)\n \n # Build the tiled column indices for that same set of combinations; tiling the DOF vector\n # produces the matching column portion for those same (row, col) pairs.\n cols = np.tile(dofs, size)\n\n # Append the nonzero row vector to the running parts list.\n row_parts.append(rows[nonzero_mask])\n\n # Append the nonzero column vector to the running parts list.\n col_parts.append(cols[nonzero_mask])\n \n # Append the nonzero data values to the running parts list.\n data_parts.append(flat[nonzero_mask])\n\n # Decorator marks this helper as purely functional for dense updates.\n @staticmethod\n # Define helper that adds an element block to the dense global matrix via vectorized indices.\n def _add_dense_block(global_matrix: np.ndarray, dofs: NDArray[np.int64], block: np.ndarray) -> None:\n \"\"\"Adds an element block to the dense global matrix using vectorized indexing.\n\n ``np.ix_(dofs, dofs)`` builds every row/column combination of those DOFs, letting the\n 12x12 or 24x24 block be summed in a single vectorized add.\n \"\"\"\n\n # Convert the block to a float ndarray so dtype math aligns with the global matrix.\n block = np.asarray(block, dtype=float)\n\n # Use numpy advanced indexing to add the entire block in one statement.\n global_matrix[np.ix_(dofs, dofs)] += block\n\n @property\n def load_cases(self) -> List[str]:\n \"\"\"Returns a list of all the load cases in the model (in alphabetical order).\n \"\"\"\n\n # Create an empty list of load cases\n cases: List[str] = []\n\n # Step through each node\n for node in self.nodes.values():\n # Step through each nodal load\n for load in node.NodeLoads:\n # Get the load case for each nodal laod\n cases.append(load[2])\n\n # Step through each member\n for member in self.members.values():\n # Step through each member point load\n for load in member.PtLoads:\n # Get the load case for each member point load\n cases.append(load[3])\n # Step through each member distributed load\n for load in member.DistLoads:\n # Get the load case for each member distributed load\n cases.append(load[5])\n\n # Step through each plate/quad\n for plate in list(self.plates.values()) + list(self.quads.values()):\n # Step through each surface load\n for load in plate.pressures:\n # Get the load case for each plate/quad pressure\n cases.append(load[1])\n\n # Remove duplicates and return the list (sorted ascending)\n return sorted(list(dict.fromkeys(cases)))\n\n def add_node(self, name: str, X: float, Y: float, Z: float) -> str:\n \"\"\"Adds a new node to the model.\n\n :param name: A unique user-defined name for the node. If set to None or \"\" a name will be\n automatically assigned.\n :type name: str\n :param X: The node's global X-coordinate.\n :type X: float\n :param Y: The node's global Y-coordinate.\n :type Y: float\n :param Z: The node's global Z-coordinate.\n :type Z: float\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the node added to the model.\n :rtype: str\n \"\"\"\n\n # Name the node or check it doesn't already exist\n if name:\n if name in self.nodes:\n raise NameError(f\"Node name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"N\" + str(len(self.nodes))\n count = 1\n while name in self.nodes:\n name = \"N\" + str(len(self.nodes) + count)\n count += 1\n\n # Create a new node\n new_node = Node3D(self, name, X, Y, Z)\n\n # Add the new node to the model\n self.nodes[name] = new_node\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the node name\n return name\n\n def add_material(self, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> str:\n \"\"\"Adds a new material to the model.\n\n :param name: A unique user-defined name for the material.\n :type name: str\n :param E: The modulus of elasticity of the material.\n :type E: float\n :param G: The shear modulus of elasticity of the material.\n :type G: float\n :param nu: Poisson's ratio of the material.\n :type nu: float\n :param rho: The density of the material\n :type rho: float\n :return: The name of the material added to the model.\n :rtype: str\n :raises NameError: Occurs when the specified name already exists in the model.\n \"\"\"\n\n # Name the material or check it doesn't already exist\n if name:\n if name in self.materials:\n raise NameError(f\"Material name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.materials))\n count = 1\n while name in self.materials:\n name = \"M\" + str(len(self.materials) + count)\n count += 1\n\n # Create a new material\n new_material = Material(self, name, E, G, nu, rho, fy)\n\n # Add the new material to the model\n self.materials[name] = new_material\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the materal name\n return name\n\n def add_section(self, name: str, A: float, Iy: float, Iz: float, J: float) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = Section(self, name, A, Iy, Iz, J)\n\n # Return the section name\n return name\n\n def add_steel_section(self, name: str, A: float, Iy: float, Iz: float, J: float, Zy: float, Zz: float, material_name: str) -> str:\n \"\"\"Adds a cross-section to the model.\n\n :param name: A unique name for the cross-section.\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n :param Zy: The section modulus about the Y (minor) axis\n :type Zy: float\n :param Zz: The section modulus about the Z (major) axis\n :type Zz: float\n :param material_name: The name of the steel material\n :type material_name: str\n \"\"\"\n\n # Name the section or check it doesn't already exist\n if name:\n if name in self.sections:\n raise NameError(f\"Section name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"SC\" + str(len(self.sections))\n count = 1\n while name in self.sections:\n name = \"SC\" + str(len(self.sections) + count)\n count += 1\n\n # Add the new section to the model\n self.sections[name] = SteelSection(self, name, A, Iy, Iz, J, Zy, Zz, material_name)\n\n # Return the section name\n return name\n\n def add_spring(self, name: str, i_node: str, j_node: str, ks: float, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new spring to the model.\n\n :param name: A unique user-defined name for the spring. If ``None`` or ``\"\"``, a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param ks: The spring constant (force/displacement).\n :type ks: float\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the spring that was added to the model.\n :rtype: str\n \"\"\"\n\n # Name the spring or check it doesn't already exist\n if name:\n if name in self.springs:\n raise NameError(f\"Spring name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"S\" + str(len(self.springs))\n count = 1\n while name in self.springs:\n name = \"S\" + str(len(self.springs) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new spring\n new_spring = Spring3D(name, pn_nodes[0], pn_nodes[1],\n ks, self.load_combos, tension_only=tension_only,\n comp_only=comp_only)\n\n # Add the new spring to the model\n self.springs[name] = new_spring\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the spring name\n return name\n\n def add_member(self, name: str, i_node: str, j_node: str, material_name: str, section_name: str, rotation: float = 0.0, tension_only: bool = False, comp_only: bool = False) -> str:\n \"\"\"Adds a new physical member to the model.\n\n :param name: A unique user-defined name for the member. If ``None`` or ``\"\"``, a name will be automatically assigned\n :type name: str\n :param i_node: The name of the i-node (start node).\n :type i_node: str\n :param j_node: The name of the j-node (end node).\n :type j_node: str\n :param material_name: The name of the material of the member.\n :type material_name: str\n :param section_name: The name of the cross section to use for section properties.\n :type section_name: str\n :param rotation: The angle of rotation (degrees) of the member cross-section about its longitudinal (local x) axis. Default is 0.\n :type rotation: float, optional\n :param tension_only: Indicates if the member is tension-only, defaults to False\n :type tension_only: bool, optional\n :param comp_only: Indicates if the member is compression-only, defaults to False\n :type comp_only: bool, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the member added to the model.\n :rtype: str\n \"\"\"\n\n # Name the member or check it doesn't already exist\n if name:\n if name in self.members:\n raise NameError(f\"Member name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"M\" + str(len(self.members))\n count = 1\n while name in self.members:\n name = \"M\" + str(len(self.members)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_member = PhysMember(self, name, pn_nodes[0], pn_nodes[1], material_name, section_name, rotation=rotation, tension_only=tension_only, comp_only=comp_only)\n\n # Add the new member to the model\n self.members[name] = new_member\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the member name\n return name\n\n def add_plate(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str, t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new rectangular plate to the model. The plate formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on a 12-term\n polynomial formulation. This element must be rectangular, and must not be used where a\n thick plate formulation is needed. For a more versatile plate element that can handle\n distortion and thick plate conditions, consider using the `add_quad` method instead.\n\n :param name: A unique user-defined name for the plate. If None or \"\", a name will be\n automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the plate or check it doesn't already exist\n if name:\n if name in self.plates:\n raise NameError(f\"Plate name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"P\" + str(len(self.plates))\n count = 1\n while name in self.plates:\n name = \"P\" + str(len(self.plates)+count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new plate\n new_plate = Plate3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new plate to the model\n self.plates[name] = new_plate\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the plate name\n return name\n\n def add_quad(self, name: str, i_node: str, j_node: str, m_node: str, n_node: str,\n t: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0) -> str:\n \"\"\"Adds a new quadrilateral to the model. The quad formulation for in-plane (membrane)\n stiffness is based on an isoparametric formulation. For bending, it is based on an MITC4\n formulation. This element handles distortion relatively well, and is appropriate for thick\n and thin plates. One limitation with this element is that it does a poor job of reporting\n corner stresses. Corner forces, however are very accurate. Center stresses are very\n accurate as well. For cases where corner stress results are important, consider using the\n `add_plate` method instead.\n\n :param name: A unique user-defined name for the quadrilateral. If None or \"\", a name will\n be automatically assigned.\n :type name: str\n :param i_node: The name of the i-node.\n :type i_node: str\n :param j_node: The name of the j-node.\n :type j_node: str\n :param m_node: The name of the m-node.\n :type m_node: str\n :param n_node: The name of the n-node.\n :type n_node: str\n :param t: The thickness of the element.\n :type t: float\n :param material_name: The name of the material for the element.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local\n x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local\n y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the element added to the model.\n :rtype: str\n \"\"\"\n\n # Name the quad or check it doesn't already exist\n if name:\n if name in self.quads:\n raise NameError(f\"Quad name '{name}' already exists\")\n else:\n # As a guess, start with the length of the dictionary\n name = \"Q\" + str(len(self.quads))\n count = 1\n while name in self.quads:\n name = \"Q\" + str(len(self.quads) + count)\n count += 1\n\n # Lookup node names and safely handle exceptions\n try:\n pn_nodes = [self.nodes[node_name] for node_name in (i_node, j_node, m_node, n_node)]\n except KeyError as e:\n raise NameError(f\"Node '{e.args[0]}' does not exist in the model\")\n\n # Create a new member\n new_quad = Quad3D(name, pn_nodes[0], pn_nodes[1], pn_nodes[2], pn_nodes[3],\n t, material_name, self, kx_mod, ky_mod)\n\n # Add the new member to the model\n self.quads[name] = new_quad\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the quad name\n return name\n\n def add_rectangle_mesh(self, name: str, mesh_size: float, width: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), plane: str = 'XY', x_control: list | None = None, y_control: list | None = None, start_node: str | None = None, start_element: str | None = None, element_type: str = 'Quad') -> str:\n \"\"\"Adds a rectangular mesh of elements to the model.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The desired mesh size.\n :type mesh_size: float\n :param width: The overall width of the rectangular mesh measured along its local x-axis.\n :type width: float\n :param height: The overall height of the rectangular mesh measured along its local y-axis.\n :type height: float\n :param thickness: The thickness of each element in the mesh.\n :type thickness: float\n :param material_name: The name of the material for elements in the mesh.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for in-plane stiffness in the element's local x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for in-plane stiffness in the element's local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the regtangular mesh's local coordinate system. Defaults to [0, 0, 0]\n :type origin: list, optional\n :param plane: The plane the mesh will be parallel to. Options are 'XY', 'YZ', and 'XZ'. Defaults to 'XY'.\n :type plane: str, optional\n :param x_control: A list of control points along the mesh's local x-axis to work into the mesh. Defaults to `None`.\n :type x_control: list, optional\n :param y_control: A list of control points along the mesh's local y-axis to work into the mesh. Defaults to None.\n :type y_control: list, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :param element_type: They type of element to make the mesh out of. Either 'Quad' or 'Rect'. Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name isn't already being used\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Rename the mesh if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create the mesh\n new_mesh = RectangleMesh(mesh_size, width, height, thickness, material_name, self, kx_mod,\n ky_mod, origin, plane, x_control, y_control, start_node,\n start_element, element_type=element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_annulus_mesh(self, name: str, mesh_size: float, outer_radius: float, inner_radius: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming an annulus (a donut).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param outer_radius: The radius to the outside of the annulus.\n :type outer_radius: float\n :param inner_radius: The radius to the inside of the annulus.\n :type inner_radius: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in the element's local\n x-direction. Default is 1.0 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in the element's\n local y-direction. Default is 1.0 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh. The default is [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. The default is 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Default is `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Default is `None`.\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists in the model.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a mesh name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = AnnulusMesh(mesh_size, outer_radius, inner_radius, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_frustrum_mesh(self, name: str, mesh_size: float, large_radius: float, small_radius: float, height: float, thickness: float, material_name: str, kx_mod: float = 1.0, ky_mod: float = 1.0, origin: list | tuple = (0, 0, 0), axis: str = 'Y', start_node: str | None = None, start_element: str | None = None) -> str:\n \"\"\"Adds a mesh of quadrilaterals forming a frustrum (a cone intersected by a horizontal plane).\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size\n :type mesh_size: float\n :param large_radius: The larger of the two end radii.\n :type large_radius: float\n :param small_radius: The smaller of the two end radii.\n :type small_radius: float\n :param height: The height of the frustrum.\n :type height: float\n :param thickness: The thickness of the elements.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for radial stiffness in each element's local x-direction, defaults to 1 (no modification).\n :type kx_mod: float, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's local y-direction, defaults to 1 (no modification).\n :type ky_mod: float, optional\n :param origin: The origin of the mesh, defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated, defaults to 'Y'.\n :type axis: str, optional\n :param start_node: The name of the first node in the mesh. If set to None the program will use the next available node name, defaults to None.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name, defaults to None\n :type start_element: str, optional\n :raises NameError: Occurs if the specified name already exists.\n :return: The name of the mesh added to the model.\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = FrustrumMesh(mesh_size, large_radius, small_radius, height, thickness, material_name,\n self, kx_mod, ky_mod, origin, axis, start_node, start_element)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_cylinder_mesh(self, name:str, mesh_size:float, radius:float, height:float,\n thickness:float, material_name:str, kx_mod:float = 1,\n ky_mod:float = 1, origin:list | tuple = (0, 0, 0),\n axis:str = 'Y', num_elements:int | None = None,\n start_node: str | None = None, start_element:str | None = None,\n element_type:str = 'Quad') -> str:\n \"\"\"Adds a mesh of elements forming a cylinder.\n\n :param name: A unique name for the mesh.\n :type name: str\n :param mesh_size: The target mesh size.\n :type mesh_size: float\n :param radius: The radius of the cylinder.\n :type radius: float\n :param height: The height of the cylinder.\n :type height: float\n :param thickness: Element thickness.\n :type thickness: float\n :param material_name: The name of the element material.\n :type material_name: str\n :param kx_mod: Stiffness modification factor for hoop stiffness in each element's local\n x-direction. Defaults to 1.0 (no modification).\n :type kx_mod: int, optional\n :param ky_mod: Stiffness modification factor for meridional stiffness in each element's\n local y-direction. Defaults to 1.0 (no modification).\n :type ky_mod: int, optional\n :param origin: The origin [X, Y, Z] of the mesh. Defaults to [0, 0, 0].\n :type origin: list, optional\n :param axis: The global axis about which the mesh will be generated. Defaults to 'Y'.\n :type axis: str, optional\n :param num_elements: The number of elements to use to form each course of elements. This\n is typically only used if you are trying to match the nodes to another\n mesh's nodes. If set to `None` the program will automatically\n calculate the number of elements to use based on the mesh size.\n Defaults to None.\n :type num_elements: int, optional\n :param start_node: The name of the first node in the mesh. If set to `None` the program\n will use the next available node name. Defaults to `None`.\n :type start_node: str, optional\n :param start_element: The name of the first element in the mesh. If set to `None` the\n program will use the next available element name. Defaults to `None`.\n :type start_element: str, optional\n :param element_type: The type of element to make the mesh out of. Either 'Quad' or 'Rect'.\n Defaults to 'Quad'.\n :type element_type: str, optional\n :raises NameError: Occurs when the specified mesh name is already being used in the model.\n :return: The name of the mesh added to the model\n :rtype: str\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the mesh name doesn't already exist\n if name in self.meshes: raise NameError(f\"Mesh name '{name}' already exists\")\n # Give the mesh a new name if necessary\n else:\n name = self.unique_name(self.meshes, 'MSH')\n\n # Identify the starting node and element\n if start_node is None:\n start_node = self.unique_name(self.nodes, 'N')\n if element_type == 'Rect' and start_element is None:\n start_element = self.unique_name(self.plates, 'R')\n elif element_type == 'Quad' and start_element is None:\n start_element = self.unique_name(self.quads, 'Q')\n\n # Create a new mesh\n new_mesh = CylinderMesh(mesh_size, radius, height, thickness, material_name, self,\n kx_mod, ky_mod, origin, axis, start_node, start_element,\n num_elements, element_type)\n\n # Add the new mesh to the `Meshes` dictionary\n self.meshes[name] = new_mesh\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the mesh's name\n return name\n\n def add_shear_wall(self, name: str, mesh_size: float, length: float, height: float, thickness: float, material_name: str, ky_mod: float = 0.35, plane: Literal['XY', 'YZ'] = 'XY', origin: List[float] = [0, 0, 0]):\n \"\"\"Adds a meshed shear wall helper to the model.\n\n The shear wall utility generates a regular mesh for a rectangular wall panel and\n keeps references to the created nodes and elements for convenience.\n\n :param name: Unique name for the shear wall.\n :type name: str\n :param mesh_size: Target element size for the mesh generator.\n :type mesh_size: float\n :param length: Wall length along the local x-direction.\n :type length: float\n :param height: Wall height along the local y-direction.\n :type height: float\n :param thickness: Element thickness for the wall mesh.\n :type thickness: float\n :param material_name: Name of the material to assign to elements.\n :type material_name: str\n :param ky_mod: In-plane stiffness modifier in local y; default 0.35.\n :type ky_mod: float, optional\n :param plane: Global plane for the wall: ``'XY'`` or ``'YZ'``; default ``'XY'``.\n :type plane: Literal['XY','YZ'], optional\n :param origin: Global origin [X, Y, Z] of the wall; default ``[0,0,0]``.\n :type origin: list[float], optional\n :return: None\n :rtype: NoneType\n \"\"\"\n\n # Check if a name has been provided\n if name:\n # Check that the shear wall name doesn't already exist\n if name in self.shear_walls: raise NameError(f\"Shear wall name '{name}' already exists\")\n # Give the shear wall a new name if necessary\n else:\n name = self.unique_name(self.shear_walls, 'SW')\n\n # Create a new shear wall\n new_shear_wall = ShearWall(self, name, mesh_size, length, height, thickness, material_name, ky_mod, origin, plane)\n\n # Add the wall to the model\n self.shear_walls[name] = new_shear_wall\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_mat_foundation(self, name, mesh_size, length_X, length_Z, thickness, material_name, ks, origin=[0, 0, 0], x_control=[], y_control=[]):\n\n # Check if a name has been provided\n if name:\n # Check that the mat foundation name doesn't already exist\n if name in self.mats: raise NameError(f\"Mat foundation name '{name}' already exists\")\n # Give the mat a new name if necessary\n else:\n name = self.unique_name(self.mats, 'MAT')\n\n new_mat = MatFoundation(name, mesh_size, length_X, length_Z, thickness, material_name, self, ks, origin, x_control, y_control)\n\n # Add the mat foundation to the model\n self.mats[name] = new_mat\n\n # Flag the model as unsolved\n self.solution = None\n\n def merge_duplicate_nodes(self, tolerance: float = 0.001) -> list:\n \"\"\"Removes duplicate nodes from the model and returns a list of the removed node names.\n\n :param tolerance: The maximum distance between two nodes in order to consider them duplicates. Defaults to 0.001.\n :type tolerance: float, optional\n :return: A list of the names of the nodes that were removed from the model.\n \"\"\"\n\n # Initialize a dictionary marking where each node is used\n node_lookup = {node_name: [] for node_name in self.nodes.keys()}\n element_dicts = ('springs', 'members', 'plates', 'quads')\n node_types = ('i_node', 'j_node', 'm_node', 'n_node')\n\n # Step through each dictionary of elements in the model (springs, members, plates, quads)\n for element_dict in element_dicts:\n\n # Step through each element in the dictionary\n for element in getattr(self, element_dict).values():\n\n # Step through each possible node type in the element (i-node, j-node, m-node, n-node)\n for node_type in node_types:\n\n # Get the current element's node having the current type\n # Return `None` if the element doesn't have this node type\n node = getattr(element, node_type, None)\n\n # Determine if the node exists on the element\n if node is not None:\n # Add the element to the list of elements attached to the node\n node_lookup[node.name].append((element, node_type))\n\n # Make a list of the names of each node in the model\n node_names = list(self.nodes.keys())\n\n # Make a list of nodes to be removed from the model\n remove_list = []\n\n # Step through each node in the copy of the `Nodes` dictionary\n for i, node_1_name in enumerate(node_names):\n\n # Skip iteration if `node_1` has already been removed\n if node_lookup[node_1_name] is None:\n continue\n\n # There is no need to check `node_1` against itself\n for node_2_name in node_names[i + 1:]:\n\n # Skip iteration if node_2 has already been removed\n if node_lookup[node_2_name] is None:\n continue\n\n # Calculate the distance between nodes\n if self.nodes[node_1_name].distance(self.nodes[node_2_name]) > tolerance:\n continue\n\n # Replace references to `node_2` in each element with references to `node_1`\n for element, node_type in node_lookup[node_2_name]:\n setattr(element, node_type, self.nodes[node_1_name])\n\n # Flag `node_2` as no longer used\n node_lookup[node_2_name] = None\n\n # Merge any boundary conditions\n support_cond = ('support_DX', 'support_DY', 'support_DZ', 'support_RX', 'support_RY', 'support_RZ')\n for dof in support_cond:\n if getattr(self.nodes[node_2_name], dof) == True:\n setattr(self.nodes[node_1_name], dof, True)\n\n # Merge any spring supports\n spring_cond = ('spring_DX', 'spring_DY', 'spring_DZ', 'spring_RX', 'spring_RY', 'spring_RZ')\n for dof in spring_cond:\n value = getattr(self.nodes[node_2_name], dof)\n if value != [None, None, None]:\n setattr(self.nodes[node_1_name], dof, value)\n\n # Fix the mesh labels\n for mesh in self.meshes.values():\n\n # Fix the nodes in the mesh\n if node_2_name in mesh.nodes.keys():\n\n # Attach the correct node to the mesh\n mesh.nodes[node_2_name] = self.nodes[node_1_name]\n\n # Fix the dictionary key\n mesh.nodes[node_1_name] = mesh.nodes.pop(node_2_name)\n\n # Fix the elements in the mesh\n for element in mesh.elements.values():\n if node_2_name == element.i_node.name: element.i_node = self.nodes[node_1_name]\n if node_2_name == element.j_node.name: element.j_node = self.nodes[node_1_name]\n if node_2_name == element.m_node.name: element.m_node = self.nodes[node_1_name]\n if node_2_name == element.n_node.name: element.n_node = self.nodes[node_1_name]\n\n # Add the node to the `remove` list\n remove_list.append(node_2_name)\n\n # Remove `node_2` from the model's `Nodes` dictionary\n for node_name in remove_list:\n self.nodes.pop(node_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n # Return the list of removed nodes\n return remove_list\n\n def delete_node(self, node_name: str):\n \"\"\"Removes a node from the model. All nodal loads associated with the node and elements attached to the node will also be removed.\n\n :param node_name: The name of the node to be removed.\n :type node_name: str\n \"\"\"\n\n # Remove the node. Nodal loads are stored within the node, so they\n # will be deleted automatically when the node is deleted.\n self.nodes.pop(node_name)\n\n # Find any elements attached to the node and remove them\n self.members = {name: member for name, member in self.members.items() if member.i_node.name != node_name and member.j_node.name != node_name}\n self.plates = {name: plate for name, plate in self.plates.items() if plate.i_node.name != node_name and plate.j_node.name != node_name and plate.m_node.name != node_name and plate.n_node.name != node_name}\n self.quads = {name: quad for name, quad in self.quads.items() if quad.i_node.name != node_name and quad.j_node.name != node_name and quad.m_node.name != node_name and quad.n_node.name != node_name}\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_spring(self, spring_name: str):\n \"\"\"Removes a spring from the model.\n\n :param spring_name: The name of the spring to be removed.\n :type spring_name: str\n \"\"\"\n\n # Remove the spring\n self.springs.pop(spring_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_member(self, member_name:str):\n \"\"\"Removes a member from the model. All member loads associated with the member will also\n be removed.\n\n :param member_name: The name of the member to be removed.\n :type member_name: str\n \"\"\"\n\n # Remove the member. Member loads are stored within the member, so they\n # will be deleted automatically when the member is deleted.\n self.members.pop(member_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_mesh(self, mesh_name: str) -> None:\n \"\"\"Removes a mesh from the model. The mesh's elements are removed, but nodes that are\n shared with elements outside the mesh are preserved.\n\n :param mesh_name: The name of the mesh to be removed.\n :type mesh_name: str\n :raises KeyError: Occurs when the specified mesh does not exist in the model.\n \"\"\"\n\n # Check if the mesh exists\n if mesh_name not in self.meshes:\n raise KeyError(f\"Mesh '{mesh_name}' does not exist in the model.\")\n\n # Get the mesh\n mesh = self.meshes[mesh_name]\n\n # Remove the mesh's nodes and elements from the model (preserving shared nodes)\n mesh._remove_from_model()\n\n # Remove the mesh from the model's mesh dictionary\n self.meshes.pop(mesh_name)\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support(self, node_name: str, support_DX: bool = False, support_DY: bool = False,\n support_DZ: bool = False, support_RX: bool = False, support_RY: bool = False,\n support_RZ: bool = False):\n \"\"\"Defines the support conditions at a node. Nodes will default to fully unsupported\n unless specified otherwise.\n\n :param node_name: The name of the node where the support is being defined.\n :type node_name: str\n :param support_DX: Indicates whether the node is supported against translation in the\n global X-direction. Defaults to False.\n :type support_DX: bool, optional\n :param support_DY: Indicates whether the node is supported against translation in the\n global Y-direction. Defaults to False.\n :type support_DY: bool, optional\n :param support_DZ: Indicates whether the node is supported against translation in the\n global Z-direction. Defaults to False.\n :type support_DZ: bool, optional\n :param support_RX: Indicates whether the node is supported against rotation about the\n global X-axis. Defaults to False.\n :type support_RX: bool, optional\n :param support_RY: Indicates whether the node is supported against rotation about the\n global Y-axis. Defaults to False.\n :type support_RY: bool, optional\n :param support_RZ: Indicates whether the node is supported against rotation about the\n global Z-axis. Defaults to False.\n :type support_RZ: bool, optional\n \"\"\"\n\n # Get the node to be supported\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Set the node's support conditions\n node.support_DX = support_DX\n node.support_DY = support_DY\n node.support_DZ = support_DZ\n node.support_RX = support_RX\n node.support_RY = support_RY\n node.support_RZ = support_RZ\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_support_spring(self, node_name: str, dof: str, stiffness: float, direction: str | None = None):\n \"\"\"Defines a spring support at a node.\n\n :param node_name: The name of the node to apply the spring support to.\n :type node_name: str\n :param dof: The degree of freedom to apply the spring support to.\n :type dof: str ('DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ')\n :param stiffness: The translational or rotational stiffness of the spring support.\n :type stiffness: float\n :param direction: The direction in which the spring can act. '+' allows the spring to resist positive displacements. '-' allows the spring to resist negative displacements. None allows the spring to act in both directions. Default is None.\n :type direction: str or None ('+', '-', None), optional\n :raises ValueError: Occurs when an invalid support spring direction has been specified.\n :raises ValueError: Occurs when an invalid support spring degree of freedom has been specified.\n \"\"\"\n\n if dof in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n if direction in ('+', '-', None):\n try:\n if dof == 'DX':\n self.nodes[node_name].spring_DX = [stiffness, direction, True]\n elif dof == 'DY':\n self.nodes[node_name].spring_DY = [stiffness, direction, True]\n elif dof == 'DZ':\n self.nodes[node_name].spring_DZ = [stiffness, direction, True]\n elif dof == 'RX':\n self.nodes[node_name].spring_RX = [stiffness, direction, True]\n elif dof == 'RY':\n self.nodes[node_name].spring_RY = [stiffness, direction, True]\n elif dof == 'RZ':\n self.nodes[node_name].spring_RZ = [stiffness, direction, True]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n else:\n raise ValueError('Invalid support spring direction. Specify \\'+\\', \\'-\\', or None.')\n else:\n raise ValueError('Invalid support spring degree of freedom. Specify \\'DX\\', \\'DY\\', \\'DZ\\', \\'RX\\', \\'RY\\', or \\'RZ\\'')\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_node_disp(self, node_name:str, direction:str, magnitude:float):\n \"\"\"Defines a nodal displacement at a node.\n\n :param node_name: The name of the node where the nodal displacement is being applied.\n :type node_name: str\n :param direction: The global direction the nodal displacement is being applied in. Displacements are 'DX', 'DY', and 'DZ'. Rotations are 'RX', 'RY', and 'RZ'.\n :type direction: str\n :param magnitude: The magnitude of the displacement.\n :type magnitude: float\n :raises ValueError: If an invalid displacement/rotation direction is provided.\n :raises NameError: If the specified node does not exist in the model.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('DX', 'DY', 'DZ', 'RX', 'RY', 'RZ'):\n raise ValueError(f\"direction must be 'DX', 'DY', 'DZ', 'RX', 'RY', or 'RZ'. {direction} was given.\")\n\n # Get the node\n try:\n node = self.nodes[node_name]\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n if direction == 'DX':\n node.EnforcedDX = magnitude\n if direction == 'DY':\n node.EnforcedDY = magnitude\n if direction == 'DZ':\n node.EnforcedDZ = magnitude\n if direction == 'RX':\n node.EnforcedRX = magnitude\n if direction == 'RY':\n node.EnforcedRY = magnitude\n if direction == 'RZ':\n node.EnforcedRZ = magnitude\n\n # Flag the model as unsolved\n self.solution = None\n\n def def_releases(self, member_name:str, Dxi:bool=False, Dyi:bool=False, Dzi:bool=False,\n Rxi:bool=False, Ryi:bool=False, Rzi:bool=False,\n Dxj:bool=False, Dyj:bool=False, Dzj:bool=False,\n Rxj:bool=False, Ryj:bool=False, Rzj:bool=False):\n \"\"\"Defines member end releases for a member. All member end releases will default to unreleased unless specified otherwise.\n\n :param member_name: The name of the member to have its releases modified.\n :type member_name: str\n :param Dxi: Indicates whether the member is released axially at its start. Defaults to False.\n :type Dxi: bool, optional\n :param Dyi: Indicates whether the member is released for shear in the local y-axis at its start. Defaults to False.\n :type Dyi: bool, optional\n :param Dzi: Indicates whether the member is released for shear in the local z-axis at its start. Defaults to False.\n :type Dzi: bool, optional\n :param Rxi: Indicates whether the member is released for torsion at its start. Defaults to False.\n :type Rxi: bool, optional\n :param Ryi: Indicates whether the member is released for moment about the local y-axis at its start. Defaults to False.\n :type Ryi: bool, optional\n :param Rzi: Indicates whether the member is released for moment about the local z-axis at its start. Defaults to False.\n :type Rzi: bool, optional\n :param Dxj: Indicates whether the member is released axially at its end. Defaults to False.\n :type Dxj: bool, optional\n :param Dyj: Indicates whether the member is released for shear in the local y-axis at its end. Defaults to False.\n :type Dyj: bool, optional\n :param Dzj: Indicates whether the member is released for shear in the local z-axis. Defaults to False.\n :type Dzj: bool, optional\n :param Rxj: Indicates whether the member is released for torsion at its end. Defaults to False.\n :type Rxj: bool, optional\n :param Ryj: Indicates whether the member is released for moment about the local y-axis at its end. Defaults to False.\n :type Ryj: bool, optional\n :param Rzj: Indicates whether the member is released for moment about the local z-axis at its end. Defaults to False.\n :type Rzj: bool, optional\n \"\"\"\n\n # Apply the end releases to the member\n try:\n self.members[member_name].Releases = [Dxi, Dyi, Dzi, Rxi, Ryi, Rzi, Dxj, Dyj, Dzj, Rxj, Ryj, Rzj]\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_load_combo(self, name:str, factors:dict, combo_tags:list | None = None):\n \"\"\"Adds a load combination to the model.\n\n :param name: A unique name for the load combination (e.g. '1.2D+1.6L+0.5S' or 'Gravity Combo').\n :type name: str\n :param factors: A dictionary containing load cases and their corresponding factors (e.g. {'D':1.2, 'L':1.6, 'S':0.5}).\n :type factors: dict\n :param combo_tags: A list of tags used to categorize load combinations. Default is `None`. This can be useful for filtering results later on, or for limiting analysis to only those combinations with certain tags. This feature is provided for convenience. It is not necessary to use tags.\n :type combo_tags: list, optional\n \"\"\"\n\n # Create a new load combination object\n new_combo = LoadCombo(name, combo_tags, factors)\n\n # Add the load combination to the dictionary of load combinations\n self.load_combos[name] = new_combo\n\n # Flag the model as solved\n self.solution = None\n\n def add_node_load(self, node_name:str, direction:str, P:float, case:str = 'Case 1'):\n \"\"\"Adds a nodal load to the model.\n\n :param node_name: The name of the node where the load is being applied.\n :type node_name: str\n :param direction: The global direction the load is being applied in. Forces are `'FX'`, `'FY'`, and `'FZ'`. Moments are `'MX'`, `'MY'`, and `'MZ'`.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param case: The name of the load case the load belongs to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction was specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('FX', 'FY', 'FZ', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'FX', 'FY', 'FZ', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the node load to the model\n try:\n self.nodes[node_name].NodeLoads.append((direction, P, case))\n except KeyError:\n raise NameError(f\"Node '{node_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_pt_load(self, member_name:str, direction:str, P:float, x:float, case:str = 'Case 1'):\n \"\"\"Adds a member point load to the model.\n\n :param member_name: The name of the member the load is being applied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'Mx'`, `'My'`, `'Mz'`, `'FX'`, `'FY'`, `'FZ'`, `'MX'`, `'MY'`, or `'MZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param P: The numeric value (magnitude) of the load.\n :type P: float\n :param x: The load's location along the member's local x-axis.\n :type x: float\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', 'MZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', FZ', 'Mx', 'My', 'Mz', 'MX', 'MY', or 'MZ'. {direction} was given.\")\n\n # Add the point load to the member\n try:\n self.members[member_name].PtLoads.append((direction, P, x, case))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_dist_load(self, member_name: str, direction: str, w1: float, w2: float,\n x1: float | None = None, x2: float | None = None,\n case: str = 'Case 1', self_weight: bool = False):\n \"\"\"Adds a member distributed load to the model.\n\n :param member_name: The name of the member the load is being appied to.\n :type member_name: str\n :param direction: The direction in which the load is to be applied. Valid values are `'Fx'`,\n `'Fy'`, `'Fz'`, `'FX'`, `'FY'`, or `'FZ'`.\n Note that lower-case notation indicates use of the beam's local\n coordinate system, while upper-case indicates use of the model's global\n coordinate system.\n :type direction: str\n :param w1: The starting value (magnitude) of the load.\n :type w1: float\n :param w2: The ending value (magnitude) of the load.\n :type w2: float\n :param x1: The load's start location along the member's local x-axis. If this argument is\n not specified, the start of the member will be used. Defaults to `None`\n :type x1: float, optional\n :param x2: The load's end location along the member's local x-axis. If this argument is not\n specified, the end of the member will be used. Defaults to `None`.\n :type x2: float, optional\n :param case: The load case to categorize the load under. Defaults to 'Case 1'.\n :type case: str, optional\n :param self_weight: Indicates whether this load is a self-weight load. Only set this to True if you are entering member self weight manually instead of using the `add_member_self_weight` method. This parameter is used by the modal analysis engine to determine whether to create a lumped mass for the load. Self-weight loads are already accounted for in modal analysis using a consistent mass matrix, so creating an additional lumped mass incorrect. Typically you will leave this value at the default value of `False`.\n :type self_weight: bool, optional\n :raises ValueError: Occurs when an invalid load direction has been specified.\n \"\"\"\n\n # Validate the value of direction\n if direction not in ('Fx', 'Fy', 'Fz', 'FX', 'FY', 'FZ'):\n raise ValueError(f\"direction must be 'Fx', 'Fy', 'Fz', 'FX', 'FY', or 'FZ'. {direction} was given.\")\n # Determine if a starting and ending points for the load have been specified.\n # If not, use the member start and end as defaults\n if x1 == None:\n start = 0\n else:\n start = x1\n\n if x2 == None:\n end = self.members[member_name].L()\n else:\n end = x2\n\n # Add the distributed load to the member\n try:\n self.members[member_name].DistLoads.append((direction, w1, w2, start, end, case, self_weight))\n except KeyError:\n raise NameError(f\"Member '{member_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_member_self_weight(self, global_direction: str, factor: float, case: str = 'Case 1'):\n \"\"\"Adds self weight to all members in the model. Note that this only works for members. Plate, quad, and spring elements will be ignored by this command.\n\n :param global_direction: The global direction to apply the member load in: 'FX', 'FY', or 'FZ'.\n :type global_direction: str\n :param factor: A factor to apply to the member self-weight. Can be used to account for items like connections, or to switch the direction of the self-weight load.\n :type factor: float\n :param case: The load case to apply the self-weight to. Defaults to 'Case 1'\n :type case: str, optional\n :raises ValueError: IF a local direction ('Fx', 'Fy', or 'Fz') is used instead of a global direction.\n \"\"\"\n\n # Validate that a global direction was provided, not a local direction\n if global_direction in ('Fx', 'Fy', 'Fz'):\n raise ValueError(\n f\"Local direction '{global_direction}' is not allowed for self-weight. \\\n Use global directions 'FX', 'FY', or 'FZ' instead.\"\n )\n\n # Validate the value of direction\n if global_direction not in ('FX', 'FY', 'FZ'):\n raise ValueError(f\"Direction must be 'FX', 'FY', or 'FZ'. {global_direction} was given.\")\n\n # Step through each member in the model\n for member in self.members.values():\n\n # Calculate the self weight of the member\n self_weight = factor*member.material.rho*member.section.A\n\n # Add the self-weight load to the member\n self.add_member_dist_load(member.name, global_direction, self_weight, self_weight, case=case, self_weight=True)\n\n # No need to flag the model as unsolved. That has already been taken care of by our call to `add_member_dist_load`\n\n def add_plate_surface_pressure(self, plate_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the rectangular plate element.\n\n :param plate_name: The name for the rectangular plate to add the surface pressure to.\n :type plate_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid plate name has been specified.\n \"\"\"\n\n # Add the surface pressure to the rectangle\n try:\n self.plates[plate_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Plate '{plate_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def add_quad_surface_pressure(self, quad_name: str, pressure: float, case: str = 'Case 1'):\n \"\"\"Adds a surface pressure to the quadrilateral element.\n\n :param quad_name: The name for the quad to add the surface pressure to.\n :type quad_name: str\n :param pressure: The value (magnitude) for the surface pressure.\n :type pressure: float\n :param case: The load case to add the surface pressure to. Defaults to 'Case 1'.\n :type case: str, optional\n :raises Exception: Occurs when an invalid quad name has been specified.\n \"\"\"\n\n # Add the surface pressure to the quadrilateral\n try:\n self.quads[quad_name].pressures.append([pressure, case])\n except KeyError:\n raise NameError(f\"Quad '{quad_name}' does not exist in the model\")\n\n # Flag the model as unsolved\n self.solution = None\n\n def delete_loads(self):\n \"\"\"Deletes all loads from the model along with any results based on the loads.\n \"\"\"\n\n # Delete the member loads and the calculated internal forces\n for member in self.members.values():\n member.DistLoads = []\n member.PtLoads = []\n member.SegmentsZ = []\n member.SegmentsY = []\n member.SegmentsX = []\n\n # Delete the plate loads\n for plate in self.plates.values():\n plate.pressures = []\n\n # Delete the quadrilateral loads\n for quad in self.quads.values():\n quad.pressures = []\n\n # Delete the nodal loads, calculated displacements, and calculated reactions\n for node in self.nodes.values():\n\n node.NodeLoads = []\n\n node.DX = {}\n node.DY = {}\n node.DZ = {}\n node.RX = {}\n node.RY = {}\n node.RZ = {}\n\n node.RxnFX = {}\n node.RxnFY = {}\n node.RxnFZ = {}\n node.RxnMX = {}\n node.RxnMY = {}\n node.RxnMZ = {}\n\n # Flag the model as unsolved\n self.solution = None\n\n def K(self, combo_name='Combo 1', log=False, check_stability=True, sparse=True):\n \"\"\"Returns the model's global stiffness matrix. The stiffness matrix will be returned in\n scipy's sparse coo format, which reduces memory usage and can be easily converted to\n other formats.\n\n :param combo_name: The load combination to get the stiffness matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to True. Defaults to False.\n :type log: bool, optional\n :param check_stability: Causes Pynite to check for instabilities if set to True. Defaults\n to True. Set to False if you want the model to run faster.\n :type check_stability: bool, optional\n :param sparse: Returns a sparse matrix if set to True, and a dense matrix otherwise.\n Defaults to True.\n :type sparse: bool, optional\n :return: The global stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # Instead of pushing one entry at a time, we keep batched row/col/data arrays\n # per element and concatenate once. This drastically cuts Python overhead.\n # Initialize the list of per-element row vectors for later concatenation.\n row_parts: list[np.ndarray] = []\n # Initialize the list of per-element column vectors for later concatenation.\n col_parts: list[np.ndarray] = []\n # Initialize the list of per-element data vectors for later concatenation.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n K = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each nodal spring in the model\n if log: print('- Adding nodal spring support stiffness terms to global stiffness matrix')\n for node in self.nodes.values():\n\n # Determine if the node has any spring supports\n if node.spring_DX[0] is not None:\n\n # Check for an active spring support\n if node.spring_DX[2] == True:\n m, n = node.ID*6, node.ID*6\n # Cache the spring stiffness value once for reuse below.\n val = float(node.spring_DX[0])\n if sparse == True:\n # Record the row index associated with the restrained DOF.\n row_parts.append(np.array([m], dtype=np.int64))\n # Record the column index associated with the same DOF.\n col_parts.append(np.array([n], dtype=np.int64))\n # Record the spring stiffness contribution for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DY[0] is not None:\n\n # Check for an active spring support\n if node.spring_DY[2] == True:\n m, n = node.ID*6 + 1, node.ID*6 + 1\n # Capture the Y-direction spring stiffness once per DOF.\n val = float(node.spring_DY[0])\n if sparse == True:\n # Store the row index for the Y spring term.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Y spring term.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness coefficient for this DOF.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_DZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_DZ[2] == True:\n m, n = node.ID*6 + 2, node.ID*6 + 2\n # Capture the Z-direction spring stiffness once per DOF.\n val = float(node.spring_DZ[0])\n if sparse == True:\n # Store the row index for the Z spring contribution.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the Z spring contribution.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the spring stiffness magnitude itself.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RX[0] is not None:\n\n # Check for an active spring support\n if node.spring_RX[2] == True:\n m, n = node.ID*6 + 3, node.ID*6 + 3\n # Capture the rotational X-direction spring stiffness.\n val = float(node.spring_RX[0])\n if sparse == True:\n # Store the row index for the RX spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RX spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RX.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RY[0] is not None:\n\n # Check for an active spring support\n if node.spring_RY[2] == True:\n m, n = node.ID*6 + 4, node.ID*6 + 4\n # Capture the rotational Y-direction spring stiffness.\n val = float(node.spring_RY[0])\n if sparse == True:\n # Store the row index for the RY spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RY spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RY.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n if node.spring_RZ[0] is not None:\n\n # Check for an active spring support\n if node.spring_RZ[2] == True:\n m, n = node.ID*6 + 5, node.ID*6 + 5\n # Capture the rotational Z-direction spring stiffness.\n val = float(node.spring_RZ[0])\n if sparse == True:\n # Store the row index for the RZ spring.\n row_parts.append(np.array([m], dtype=np.int64))\n # Store the column index for the RZ spring.\n col_parts.append(np.array([n], dtype=np.int64))\n # Store the rotational stiffness value for RZ.\n data_parts.append(np.array([val], dtype=float))\n else:\n K[m, n] += val\n\n # Add stiffness terms for each spring in the model\n if log: print('- Adding spring stiffness terms to global stiffness matrix')\n for spring in self.springs.values():\n\n if spring.active[combo_name] == True:\n\n # Build the DOF index vector once and add the whole 12x12 block in one shot.\n # This mirrors the old nested loops but pushes the work into numpy.\n # Capture the full set of i/j DOF indices for this spring element.\n dofs = self._build_dof_vector(spring.i_node, spring.j_node)\n # Grab the spring's already-transformed global stiffness matrix.\n spring_K = spring.K()\n\n if sparse == True:\n # Convert the spring block into sparse row/col/data pieces.\n self._append_sparse_block(dofs, spring_K, row_parts, col_parts, data_parts)\n else:\n # Add the spring block directly to the dense global matrix.\n self._add_dense_block(K, dofs, spring_K)\n\n # Add stiffness terms for each physical member in the model\n if log: print('- Adding member stiffness terms to global stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Build the member DOF vector once so we can add the entire 12x12 block,\n # keeping parity with the previous (i,j) nested summation.\n # Capture the member's i/j DOFs for subsequent block placement.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n # Grab the member's global stiffness matrix.\n member_K = member.K()\n\n if sparse == True:\n # Append the member block into the sparse assembly lists.\n self._append_sparse_block(dofs, member_K, row_parts, col_parts, data_parts)\n else:\n # Inject the member block into the dense matrix via vectorized indexing.\n self._add_dense_block(K, dofs, member_K)\n\n # Add stiffness terms for each quadrilateral in the model\n if log: print('- Adding quadrilateral stiffness terms to global stiffness matrix')\n for quad in self.quads.values():\n\n # Get the quadrilateral's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n quad_K = quad.K()\n # Four nodes -> 24 DOFs. The helper keeps those indices contiguous so the\n # full block can be added without manual bookkeeping.\n # Build the 24-entry DOF vector for the quadrilateral element.\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n\n if sparse == True:\n # Append the quad block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, quad_K, row_parts, col_parts, data_parts)\n else:\n # Add the quad block directly to the dense matrix.\n self._add_dense_block(K, dofs, quad_K)\n\n # Add stiffness terms for each plate in the model\n if log: print('- Adding plate stiffness terms to global stiffness matrix')\n for plate in self.plates.values():\n\n # Get the plate's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n plate_K = plate.K()\n # Same concept as the quad above, but for the rectangular plate element.\n # Build the DOF vector for the plate's four nodes.\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n\n if sparse == True:\n # Append the plate block contributions to the sparse assembly lists.\n self._append_sparse_block(dofs, plate_K, row_parts, col_parts, data_parts)\n else:\n # Add the plate block directly to the dense matrix.\n self._add_dense_block(K, dofs, plate_K)\n\n if sparse:\n # Concatenate the per-element contributions into the vectors scipy expects.\n if row_parts:\n # Collapse all stored row chunks into one contiguous vector.\n row = np.concatenate(row_parts)\n # Collapse all stored column chunks into one contiguous vector.\n col = np.concatenate(col_parts)\n # Collapse all stored data chunks into one contiguous vector.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no elements contributed (edge case).\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no elements contributed (edge case).\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no elements contributed (edge case).\n data = np.array([], dtype=float)\n\n # Build the sparse COO matrix from the assembled vectors.\n K = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n if check_stability:\n if log: print('- Checking nodal stability')\n if sparse: Analysis._check_stability(self, K.tocsr())\n else: Analysis._check_stability(self, K)\n\n # Return the global stiffness matrix\n return K\n\n def Kg(self, combo_name='Combo 1', log=False, sparse=True, first_step=True):\n \"\"\"Returns the model's global geometric stiffness matrix. Geometric stiffness of plates is not considered.\n\n :param combo_name: The name of the load combination to derive the matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param log: Prints updates to the console if set to `True`. Defaults to `False`.\n :type log: bool, optional\n :param sparse: Returns a sparse matrix if set to `True`, and a dense matrix otherwise. Defaults to `True`.\n :type sparse: bool, optional\n :param first_step: Used to indicate if the analysis is occuring at the first load step. Used in nonlinear analysis where the load is broken into multiple steps. Default is `True`.\n :type first_step: bool, optional\n :return: The global geometric stiffness matrix for the structure.\n :rtype: ndarray or coo_matrix\n \"\"\"\n\n if sparse == True:\n # The geometric stiffness matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row, col, data = [], [], []\n else:\n Kg = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n if log:\n print('- Adding member geometric stiffness terms to global geometric stiffness matrix')\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Calculate the axial force in the member\n E = member.material.E\n A = member.section.A\n L = member.L()\n\n # Calculate the axial force acting on the member\n if first_step:\n # For the first load step take P = 0\n P = 0\n else:\n # Calculate the member axial force due to axial strain\n d = member.d(combo_name)\n P = E*A/L*(d[6, 0] - d[0, 0])\n\n # Get the member's global stiffness matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Kg = member.Kg(P)\n\n # Step through each term in the member's stiffness matrix\n # 'a' & 'b' below are row/column indices in the member's stiffness matrix\n # 'm' & 'n' are corresponding row/column indices in the global stiffness matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global stiffness matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global stiffness matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global stiffness matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Kg[(a, b)])\n else:\n Kg[m, n] += member_Kg[(a, b)]\n\n if sparse:\n # Convert the row, col, data lists to numpy arrays and create the COO matrix\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Kg = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Return the global geometric stiffness matrix\n return Kg\n\n def Km(self, combo_name='Combo 1', push_combo='Push', step_num=1, log=False, sparse=True):\n \"\"\"Calculates the structure's global plastic reduction matrix, which is used for nonlinear inelastic analysis.\n\n :param combo_name: The name of the load combination to get the plastic reduction matrix for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :param push_combo: The name of the load combination that contains the pushover load definition. Defaults to 'Push'.\n :type push_combo: str, optional\n :param step_num: The load step used to generate the plastic reduction matrix. Defaults to 1.\n :type step_num: int, optional\n :param log: Determines whether this method writes output to the console as it runs. Defaults to False.\n :type log: bool, optional\n :param sparse: Indicates whether the sparse solver should be used. Defaults to True.\n :type sparse: bool, optional\n :return: The global plastic reduction matrix.\n :rtype: np.array\n \"\"\"\n\n # Determine if a sparse matrix has been requested\n if sparse == True:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index. We'll build the matrix from three lists.\n row = []\n col = []\n data = []\n else:\n # Initialize a dense matrix of zeros\n Km = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n # Add stiffness terms for each physical member in the model\n for phys_member in self.members.values():\n\n # Check to see if the physical member is active for the given load combination\n if phys_member.active[combo_name] == True:\n\n # Step through each sub-member in the physical member and add terms\n for member in phys_member.sub_members.values():\n\n # Get the member's global plastic reduction matrix\n # Storing it as a local variable eliminates the need to rebuild it every time a term is needed\n member_Km = member.Km(combo_name)\n\n # Step through each term in the member's plastic reduction matrix\n # 'a' & 'b' below are row/column indices in the member's matrix\n # 'm' & 'n' are corresponding row/column indices in the structure's global matrix\n for a in range(12):\n\n # Determine if index 'a' is related to the i-node or j-node\n if a < 6:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.i_node.ID*6 + a\n else:\n # Find the corresponding index 'm' in the global plastic reduction matrix\n m = member.j_node.ID*6 + (a-6)\n\n for b in range(12):\n\n # Determine if index 'b' is related to the i-node or j-node\n if b < 6:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.i_node.ID*6 + b\n else:\n # Find the corresponding index 'n' in the global plastic reduction matrix\n n = member.j_node.ID*6 + (b-6)\n\n # Now that 'm' and 'n' are known, place the term in the global plastic reduction matrix\n if sparse == True:\n row.append(m)\n col.append(n)\n data.append(member_Km[a, b])\n else:\n Km[m, n] += member_Km[a, b]\n\n if sparse:\n # The plastic reduction matrix will be stored as a scipy `coo_matrix`. Scipy's documentation states that this type of matrix is ideal for efficient construction of finite element matrices. When converted to another format, the `coo_matrix` sums values at the same (i, j) index.\n row = np.array(row)\n col = np.array(col)\n data = np.array(data)\n Km = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # Check that there are no nodal instabilities\n # if check_stability:\n # if log: print('- Checking nodal stability')\n # if sparse: Analysis._check_stability(self, Km.tocsr())\n # else: Analysis._check_stability(self, Km)\n\n # Return the global plastic reduction matrix\n return Km\n\n def _calculate_characteristic_length(self) -> float:\n \"\"\"\n Calculates a characteristic length for the model.\n Uses average member length, or bounding box dimensions as fallback.\n \"\"\"\n if self.members:\n # Use average member length\n total_length = sum(member.L() for member in self.members.values())\n return total_length / len(self.members)\n else:\n # Fallback: use bounding box diagonal\n if self.nodes:\n coords = [(node.X, node.Y, node.Z) for node in self.nodes.values()]\n min_coords = [min(coord[i] for coord in coords) for i in range(3)]\n max_coords = [max(coord[i] for coord in coords) for i in range(3)]\n bbox_diag = sum((max_coords[i] - min_coords[i])**2 for i in range(3))**0.5\n return bbox_diag\n else:\n return 1.0 # Default fallback\n\n def M(self, mass_combo_name: str | None = None, mass_direction: str = 'Y', gravity: float = 1.0, log: bool = False, sparse: bool = True):\n \"\"\"\n Returns the model's global mass matrix for dynamic analysis. This implementation follows a separation of responsibilities approach, where members handle both translational and rotational mass/inertia, while nodes provide translational mass only (to prevent double-counting). Rotational stability terms are only added to free DOFs considering member releases and node supports.\n\n :param mass_combo_name: Load combination name defining mass (via force loads). Forces are converted to mass using m = F/g. If `None` is specified, masses from loads will be ignored during modal analysis. Defaults to `None`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (positive or negative) will be converted to mass. Default is 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Whether to print progress messages, defaults to `False`.\n :type log: bool, optional\n :param sparse: Whether to return a sparse matrix, defaults to `True`.\n :type sparse: bool, optional\n :return: Global mass matrix of shape (n_dof, n_dof)\n :rtype: scipy.sparse.coo_matrix or numpy.ndarray\n \"\"\"\n\n # TODO: Change gravity direction inputs to accept X, Y and Z instead of 0, 1, and 2.\n\n # Check if a sparse matrix has been requested\n if sparse == True:\n # Reuse the same block-based storage approach used for the stiffness matrix.\n # Initialize list to collect row index vectors per element for mass assembly.\n row_parts: list[np.ndarray] = []\n # Initialize list to collect column index vectors per element for mass assembly.\n col_parts: list[np.ndarray] = []\n # Initialize list to collect data vectors per element for mass assembly.\n data_parts: list[np.ndarray] = []\n else:\n # Initialize a dense matrix of zeros\n M = np.zeros((len(self.nodes)*6, len(self.nodes)*6))\n\n if log:\n print(f' - Converting member loads from combo: {mass_combo_name} into masses.')\n\n # Step through each physical member in the model\n for phys_member in self.members.values():\n\n # Determine if this physical member is active\n if phys_member.active[mass_combo_name] == True:\n\n # Step through each submember in this physical member\n for member in phys_member.sub_members.values():\n\n member_M = member.M(mass_combo_name, mass_direction, gravity)\n # Reuse the same DOF layout as stiffness assembly so mass and stiffness\n # stay aligned term-by-term.\n # Build the DOF vector shared with stiffness for consistency.\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n\n if sparse:\n # Append the member mass block into the sparse lists.\n self._append_sparse_block(dofs, member_M, row_parts, col_parts, data_parts)\n else:\n # Inject the member mass block into the dense matrix.\n self._add_dense_block(M, dofs, member_M)\n\n if log:\n print(f' - Converting nodal loads from combo: {mass_combo_name} to mass (translation only)')\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n # Get node's mass matrix (translation only, so set characteristic length to `None`)\n node_m = node.M(mass_combo_name, mass_direction, gravity, characteristic_length=None)\n\n # Node-only mass contributes translational DOFs. The helper still works even\n # though only one node is supplied.\n # Build the DOF vector for this single node's translational DOFs.\n dofs = self._build_dof_vector(node)\n\n if sparse:\n # Append the nodal mass block into the sparse lists.\n self._append_sparse_block(dofs, node_m, row_parts, col_parts, data_parts)\n else:\n # Add the nodal mass block directly into the dense matrix.\n self._add_dense_block(M, dofs, node_m)\n\n # Add sparse option\n if sparse:\n if row_parts:\n # Concatenate all row vectors contributed by members and nodes.\n row = np.concatenate(row_parts)\n # Concatenate all column vectors contributed by members and nodes.\n col = np.concatenate(col_parts)\n # Concatenate all data vectors contributed by members and nodes.\n data = np.concatenate(data_parts)\n else:\n # Provide empty row vector when no mass contributions exist.\n row = np.array([], dtype=np.int64)\n # Provide empty column vector when no mass contributions exist.\n col = np.array([], dtype=np.int64)\n # Provide empty data vector when no mass contributions exist.\n data = np.array([], dtype=float)\n\n # Build the sparse COO mass matrix from the assembled vectors.\n M = sp.sparse.coo_matrix((data, (row, col)), shape=(len(self.nodes)*6, len(self.nodes)*6))\n\n # At this point, we have M, but there could be zero terms along the diagonal indicating DOFs without mass. We'll add an insignificant mass to those terms to get the matrix to solve.\n\n # Get all the diagonal terms from the mass matrix\n if sparse:\n Mdiag = M.diagonal()\n else:\n Mdiag = np.diag(M)\n\n # Get all the diagonal terms that are greater than zero\n positive = Mdiag[Mdiag > 0]\n\n # Calculate a mass that will be insignificant to the overall solution\n if positive.size > 0:\n eps = positive.min()*1e-6 # tiny stabilization mass\n else:\n raise Exception('Unable to perform modal analysis. Model is massless.') # Fallback for truly massless models\n\n # Identify which terms on the diagonal have zero mass\n zero_diag = (Mdiag == 0)\n\n # Add our tiny stabilization mass to these terms\n if sparse:\n # Add eps to zero-mass DOFs\n M = M + sp.sparse.diags(eps*zero_diag.astype(float), 0, shape=M.shape)\n else:\n idx = np.where(zero_diag)[0]\n M[idx, idx] += eps\n\n if log:\n print('- Global mass matrix complete')\n\n return M\n\n def FER(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global fixed end reaction vector for any given load combo.\n\n :param combo_name: The name of the load combination to get the fixed end reaction vector\n for. Defaults to 'Combo 1'.\n :type combo_name: str, optional\n :return: The fixed end reaction vector\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n FER = np.zeros((len(self.nodes) * 6, 1))\n\n # Step through each physical member in the model; each sub-member reports a 12x1 block\n # that already lives in global coordinates, so we can drop it straight onto the matching\n # DOFs without touching individual entries.\n for phys_member in self.members.values():\n\n # Step through each sub-member and add terms\n for member in phys_member.sub_members.values():\n\n # Grab the member's fixed-end reactions and add the entire 12x1 block\n # directly at the matching DOF locations. Casting/reshaping makes sure we have\n # a flat float vector that aligns with the DOF helper ordering.\n member_FER = np.asarray(member.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(member.i_node, member.j_node)\n FER[dofs, 0] += member_FER\n\n # Repeat the same block-based add for rectangular plates (24x1 reaction blocks).\n for plate in self.plates.values():\n\n # Add the 24x1 plate reactions with the same DOF helper used for stiffness/mass so\n # the indexing stays consistent across every assembler.\n plate_FER = np.asarray(plate.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(plate.i_node, plate.j_node, plate.m_node, plate.n_node)\n FER[dofs, 0] += plate_FER\n\n # Quadrilaterals follow the same pattern: 24x1 block dropped in via the DOF helper.\n for quad in self.quads.values():\n\n # Add the 24x1 quad reactions in a single vectorized write via the DOF helper.\n quad_FER = np.asarray(quad.FER(combo_name), dtype=float).reshape(-1)\n dofs = self._build_dof_vector(quad.i_node, quad.j_node, quad.m_node, quad.n_node)\n FER[dofs, 0] += quad_FER\n\n # Return the global fixed end reaction vector\n return FER\n\n def P(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Assembles and returns the global nodal force vector.\n\n :param combo_name: The name of the load combination to get the force vector for. Defaults\n to 'Combo 1'.\n :type combo_name: str, optional\n :return: The global nodal force vector.\n :rtype: NDArray[float64]\n \"\"\"\n\n # Initialize a zero vector to hold all the terms\n P = np.zeros((len(self.nodes)*6, 1))\n\n # Get the load combination for the given 'combo_name'\n combo = self.load_combos[combo_name]\n\n # Map load direction strings to their DOF offsets once so we do not re-run the\n # if/elif ladder for every single nodal load.\n dof_lookup = {'FX': 0, 'FY': 1, 'FZ': 2, 'MX': 3, 'MY': 4, 'MZ': 5}\n\n # Add terms for each node in the model\n for node in self.nodes.values():\n\n # Accumulate this node's six DOF loads locally before writing to the global vector.\n # This keeps the code vectorized and avoids hammering the global array for every\n # individual load tuple.\n local = np.zeros(6, dtype=float)\n\n for direction, magnitude, case in node.NodeLoads:\n # Look up the combo factor once per load; loads from unrelated cases are skipped\n # immediately instead of falling through nested conditionals.\n factor = combo.factors.get(case)\n if factor is None:\n continue\n\n # Normalize the direction string and map it to the correct DOF slot. Unknown\n # direction labels are ignored to match the previous behavior.\n idx = dof_lookup.get(direction.upper())\n if idx is None:\n continue # Ignore load types outside the standard 6 DOFs\n\n # Add the scaled load into the local 6-entry accumulator.\n local[idx] += factor * magnitude\n\n # Once all loads for this node are tallied, drop the 6x1 block into the global\n # vector via the DOF helper. Empty accumulators are skipped to avoid pointless writes.\n if np.any(local):\n dofs = self._build_dof_vector(node)\n P[dofs, 0] += local\n\n # Return the global nodal force vector\n return P\n\n def D(self, combo_name='Combo 1') -> NDArray[float64]:\n \"\"\"Returns the global displacement vector for the model.\n\n :param combo_name: The name of the load combination to get the results for. Defaults to\n 'Combo 1'.\n :type combo_name: str, optional\n :return: The global displacement vector for the model\n :rtype: NDArray[float64]\n \"\"\"\n\n # Return the global displacement vector\n return self._D[combo_name]\n\n def analyze_linear(self, log=False, check_stability=True, check_statics=False, sparse=True, combo_tags=None):\n \"\"\"Performs first-order static analysis. This analysis procedure is much faster since it only assembles the global stiffness matrix once, rather than once for each load combination. It is not appropriate when non-linear behavior such as tension/compression only analysis or P-Delta analysis are required.\n\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param check_statics: When set to True, causes a statics check to be performed. Defaults to False.\n :type check_statics: bool, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises Exception: Occurs when a singular stiffness matrix is found. This indicates an unstable structure has been modeled.\n \"\"\"\n\n if log:\n print('+-------------------+')\n print('| Analyzing: Linear |')\n print('+-------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n # Note that for linear analysis the stiffness matrix can be obtained for any load combination, as it's the same for all of them\n combo_name = list(self.load_combos.keys())[0]\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo_name, log, check_stability, sparse), D1_indices, D2_indices)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the global displacement vector\n if log:\n print('- Calculating global displacement vector')\n if K11.shape == (0, 0):\n # All displacements are known, so D1 is an empty vector\n D1 = []\n else:\n try:\n # Calculate the unknown displacements D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted\n # to `csr` format for mathematical operations. The `@` operator performs\n # matrix multiplication on sparse matrices.\n D1 = spsolve(K11.tocsr(), np.subtract(np.subtract(P1, FER1), K12.tocsr() @ D2))\n D1 = D1.reshape(len(D1), 1)\n else:\n D1 = solve(K11, np.subtract(np.subtract(P1, FER1), np.matmul(K12, D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store the calculated displacements to the model and the nodes in the model\n Analysis._store_displacements(self, D1, D2, D1_indices, D2_indices, combo)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Linear'\n\n def analyze(self, log=False, check_stability=True, check_statics=False, max_iter=30, sparse=True, combo_tags=None, spring_tolerance=0, member_tolerance=0, num_steps=1):\n \"\"\"Performs a first-order elastic analysis of the model.\n\n Allows sparse solvers for larger models, handles tension/compression-only\n behavior for nodal springs and members via iteration, and supports load\n stepping for improved convergence.\n\n :param log: If ``True``, prints progress messages during analysis. Defaults to ``False``.\n :type log: bool, optional\n :param check_stability: If ``True``, checks model stability at each analysis step. Defaults to ``True``.\n :type check_stability: bool, optional\n :param check_statics: If ``True``, performs a statics check after analysis. Defaults to ``False``.\n :type check_statics: bool, optional\n :param max_iter: Maximum number of tension/compression-only iterations allowed per load step before assuming divergence. Defaults to ``30``.\n :type max_iter: int, optional\n :param sparse: If ``True``, uses sparse matrix solvers for improved efficiency on large models. Defaults to ``True``.\n :type sparse: bool, optional\n :param combo_tags: Tags used to select which load combinations to analyze. If ``None``, all combinations are analyzed. Defaults to ``None``.\n :type combo_tags: list[str] | None, optional\n :param spring_tolerance: Convergence tolerance for springs in tension/compression-only analysis. Defaults to ``0``.\n :type spring_tolerance: float, optional\n :param member_tolerance: Convergence tolerance for members in tension/compression-only analysis. Defaults to ``0``.\n :type member_tolerance: float, optional\n :param num_steps: Number of load increments for applying load combinations. Use more steps for better convergence in highly nonlinear cases. Defaults to ``1``.\n :type num_steps: int, optional\n :raises Exception: If the stiffness matrix is singular (indicating instability) or if the model fails to converge within the maximum allowed iterations.\n \"\"\"\n\n if log:\n print('+-----------+')\n print('| Analyzing |')\n print('+-----------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Calculate the incremental enforced displacement vector\n Delta_D2 = D2/num_steps\n\n # Step through each load combination\n for combo in combo_list:\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Get the partitioned total global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global fixed end reaction vector\n Delta_FER1 = FER1/num_steps\n\n # Get the partitioned total global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Calculate the incremental global nodal force vector\n Delta_P1 = P1/num_steps\n\n # Apply the load incrementally\n load_step = 1\n while load_step <= num_steps:\n\n # Keep track of the number of iterations in this load step\n iter_count = 1\n convergence = False\n divergence = False\n\n # Iterate until convergence or divergence occurs\n while convergence == False and divergence == False:\n\n # Check for tension/compression-only divergence\n if iter_count > max_iter:\n divergence = True\n raise Exception('Model diverged during tension/compression-only analysis')\n\n # Report which load step we are on\n if log:\n print(f'- Analyzing load step #{str(load_step)}')\n\n # Get the partitioned global stiffness matrix K11, K12, K21, K22\n if sparse == True:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse).tocsr(), D1_indices, D2_indices)\n else:\n K11, K12, K21, K22 = Analysis._partition(self, self.K(combo.name, log, check_stability, sparse), D1_indices, D2_indices)\n\n if K11.shape == (0, 0):\n # All displacements are known, so Delta_D1 is an empty vector\n Delta_D1 = []\n else:\n try:\n # Calculate the unknown displacements Delta_D1\n if sparse == True:\n # The partitioned stiffness matrix originates as `coo` and is converted to `csr`\n # format for mathematical operations. The `@` operator performs matrix multiplication\n # on sparse matrices.\n Delta_D1 = spsolve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), K12 @ Delta_D2))\n Delta_D1 = Delta_D1.reshape(len(Delta_D1), 1)\n else:\n Delta_D1 = solve(K11, np.subtract(np.subtract(Delta_P1, Delta_FER1), np.matmul(K12, Delta_D2)))\n except:\n # Return out of the method if 'K' is singular and provide an error message\n raise Exception('The stiffness matrix is singular, which implies rigid body motion. The structure is unstable. Aborting analysis.')\n\n # Store or sum the calculated displacements to the model and the nodes in the model\n if load_step == 1:\n Analysis._store_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n else:\n Analysis._sum_displacements(self, Delta_D1, Delta_D2, D1_indices, D2_indices, combo)\n\n # Check for tension/compression-only convergence at this load step\n convergence = Analysis._check_TC_convergence(self, combo.name, log=log, spring_tolerance=spring_tolerance, member_tolerance=member_tolerance)\n\n if convergence == False:\n\n if log:\n print(f'- Undoing load step #{load_step} due to failed convergence.')\n\n # Undo the latest analysis step to prepare for re-analysis of the load step\n Analysis._sum_displacements(self, -Delta_D1, -Delta_D2, D1_indices, D2_indices, combo)\n\n else:\n # Move on to the next load step\n load_step += 1\n\n # Keep track of the number of tension/compression only iterations\n iter_count += 1\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Check statics if requested\n if check_statics == True:\n Analysis._check_statics(self, combo_tags)\n\n # Flag the model as solved\n self.solution = 'Nonlinear TC'\n\n def analyze_PDelta(self, log=False, check_stability=True, max_iter=30, sparse=True, combo_tags=None):\n \"\"\"Performs second order (P-Delta) analysis. This type of analysis is appropriate for most models using beams, columns and braces. Second order analysis is usually required by material specific codes. The analysis is iterative and takes longer to solve. Models with slender members and/or members with combined bending and axial loads will generally have more significant P-Delta effects. P-Delta effects in plates/quads are not considered.\n\n :param log: Prints updates to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for any unstable degrees of freedom and reports them back to the console. This does add to the solution time. Defaults to True.\n :type check_stability: bool, optional\n :param max_iter: The maximum number of iterations permitted. If this value is exceeded the program will report divergence. Defaults to 30.\n :type max_iter: int, optional\n :param sparse: Indicates whether the sparse matrix solver should be used. A matrix can be considered sparse or dense depening on how many zero terms there are. Structural stiffness matrices often contain many zero terms. The sparse solver can offer faster solutions for such matrices. Using the sparse solver on dense matrices may lead to slower solution times. Be sure ``scipy`` is installed to use the sparse solver. Default is True.\n :type sparse: bool, optional\n :raises ValueError: Occurs when there is a singularity in the stiffness matrix, which indicates an unstable structure.\n :raises Exception: Occurs when a model fails to converge.\n \"\"\"\n\n if log:\n print('+--------------------+')\n print('| Analyzing: P-Delta |')\n print('+--------------------+')\n\n # Import `scipy` features if the sparse solver is being used\n if sparse == True:\n from scipy.sparse.linalg import spsolve\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify which load combinations have the tags the user has given\n combo_list = Analysis._identify_combos(self, combo_tags)\n\n # Step through each load combination\n for combo in combo_list:\n\n # Get the partitioned global fixed end reaction vector\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run the P-Delta analysis for this load combination\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, log, sparse, check_stability, max_iter)\n\n # Calculate reactions\n Analysis._calc_reactions(self, log, combo_tags)\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'P-Delta'\n\n def analyze_modal(self, num_modes: int = 12, mass_combo_name: str = 'Combo 1', mass_direction: str = 'Y', gravity: float = 1.0, log=False, check_stability=True):\n \"\"\"\n Performs modal analysis to determine natural frequencies and mode shapes.\n\n A sparse solution based on `num_modes` is always used to help filter out irrelevant frequencies from unimportant modes.\n\n :param num_modes: Number of modes to calculate. Defaults to 12.\n :type num_modes: int, optional\n :param mass_combo_name: Load combination name to use to convert loads to masses. Defaults to `Combo 1`.\n :type mass_combo_name: str, optional\n :param mass_direction: Direction for load-to-mass conversion ('X', 'Y', or 'Z'). Any loads applied in this direction (postive or negative) will be converted to mass. Defaults to 'Y'.\n :type mass_direction: str, optional\n :param gravity: The acceleration due to gravity. Defaults to 1.0. In most cases you'll want to change this to be in units consistent with your model.\n :type gravity: float\n :param log: Prints the analysis log to the console if set to True. Default is False.\n :type log: bool, optional\n :param check_stability: When set to True, checks the stiffness matrix for unstable DOFs. Defaults to True.\n :type check_stability: bool, optional\n :return: A list containing frequencies (Hz)\n :rtype: List\n :raises Exception: Occurs when a singular stiffness matrix is found.\n \"\"\"\n\n if log:\n print('+------------------+')\n print('| Analyzing: Modal |')\n print('+------------------+')\n\n # Prepare the model for analysis (same as other analysis methods)\n # This will generate the default load case ('Case 1') and load combo ('Combo 1') if none are present.\n Analysis._prepare_model(self, num_modes)\n\n # Get the auxiliary list used for matrix partitioning\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n if log:\n print('- Assembling global stiffness matrix')\n\n # Assemble and partition the global stiffness matrix\n K_global = self.K(mass_combo_name, log, check_stability, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n K11, K12, K21, K22 = Analysis._partition(self, K_global, D1_indices, D2_indices)\n\n if log:\n print('- Assembling global mass matrix')\n\n # Assemble and partition the global mass matrix\n M_global = self.M(mass_combo_name, mass_direction, gravity, log, sparse=True).tocsr()\n\n # Partition to remove supported DOFs\n M11, M12, M21, M22 = Analysis._partition(self, M_global, D1_indices, D2_indices)\n\n # Check that we have mass terms\n if M11.nnz == 0:\n raise Exception('No mass terms found. Ensure materials have density or provide mass_combo_name.')\n\n if log:\n print('- Solving eigenvalue problem')\n\n try:\n # Solve the generalized eigenvalue problem: [K11]{φ} = λ[M11]{φ}, where λ = ω²\n # Or rewritten: (-[M11]ω² + [K11]){φ} = 0\n # (See \"Structural Dynamics for Structural Engineers\" by Hart & Wong Equation 4.96)\n eigenvalues, eigenvectors = sp.sparse.linalg.eigsh(A=K11, k=num_modes, M=M11, sigma=0.0, which='LM')\n\n except sp.linalg.LinAlgError as e:\n raise Exception(f'Eigenvalue solution failed: {str(e)}. Check matrix conditioning.')\n\n # Calculate frequencies in Hz from eigenvalues (λ = ω²)\n frequencies = np.sqrt(eigenvalues) / (2 * np.pi)\n\n if log:\n print('- Processing mode shapes')\n\n # Process eigenvectors (mode shapes) to expand back to full DOF set\n for i in range(len(frequencies)):\n\n # Get the load combo for this mode\n mode_combo = self.load_combos[f'Mode {i + 1}']\n\n # Reshape the SciPy eigenvector (mode shape) into a column array that is compatible with Pynite\n D1_mode = eigenvectors[:, i].reshape(-1, 1)\n\n Analysis._store_displacements(self, D1_mode, D2, D1_indices, D2_indices, mode_combo)\n\n # Store results in the model\n self.frequencies = frequencies\n\n if log:\n print('- Modal analysis complete')\n\n # Flag the model as having modal results\n self.solution = 'Modal'\n\n if log:\n print(f'- Found {len(frequencies)} modes')\n for i, freq in enumerate(frequencies):\n print(f' Mode {i + 1}: {freq:.3f} Hz')\n print('- Modal analysis complete')\n\n def _not_ready_yet_analyze_pushover(self, log=False, check_stability=True, push_combo='Push', max_iter=30, tol=0.01, sparse=True, combo_tags=None):\n\n if log:\n print('+---------------------+')\n print('| Analyzing: Pushover |')\n print('+---------------------+')\n\n # Prepare the model for analysis\n Analysis._prepare_model(self)\n\n # Get the auxiliary list used to determine how the matrices will be partitioned\n D1_indices, D2_indices, D2 = Analysis._partition_D(self)\n\n # Identify and tag the primary load combinations the pushover load will be added to\n for combo in self.load_combos.values():\n\n # No need to tag the pushover combo\n if combo.name != push_combo:\n\n # Add 'primary' to the combo's tags if it's not already there\n if combo.combo_tags is None:\n combo.combo_tags = ['primary']\n elif 'primary' not in combo.combo_tags:\n combo.combo_tags.append('primary')\n\n # Identify which load combinations have the tags the user has given\n # TODO: Remove the pushover combo istelf from `combo_list`\n combo_list = Analysis._identify_combos(self, combo_tags)\n combo_list = [combo for combo in combo_list if combo.name != push_combo]\n\n # Step through each load combination\n for combo in combo_list:\n\n # Skip the pushover combo\n if combo.name == push_combo:\n continue\n\n if log:\n print('')\n print('- Analyzing load combination ' + combo.name)\n\n # Reset nonlinear material member end forces to zero\n for phys_member in self.members.values():\n for sub_member in phys_member.sub_members.values():\n sub_member._fxi, sub_member._myi, sub_member._mzi = 0, 0, 0\n sub_member._fxj, sub_member._myj, sub_member._mzj = 0, 0, 0\n\n # Get the partitioned global fixed end reaction vector for the load combination\n FER1, FER2 = Analysis._partition(self, self.FER(combo.name), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for the load combination\n P1, P2 = Analysis._partition(self, self.P(combo.name), D1_indices, D2_indices)\n\n # Run an elastic P-Delta analysis for the load combination (w/o pushover loads)\n # This will be used to preload the member with non-pushover loads prior to pushover anlaysis\n Analysis._PDelta(self, combo.name, P1, FER1, D1_indices, D2_indices, D2, False, sparse, check_stability, 30)\n\n # The previous step flagged the solution as a P-Delta solution, but we need to indicate that this is actually a Pushover solution so that the calls to Member3D.f() are excecuted considering nonlinear behavior\n self.solution = 'Pushover'\n\n # Get the partitioned global fixed end reaction vector for a pushover load increment\n FER1_push, FER2_push = Analysis._partition(self, self.FER(push_combo), D1_indices, D2_indices)\n\n # Get the partitioned global nodal force vector for a pushover load increment\n P1_push, P2_push = Analysis._partition(self, self.P(push_combo), D1_indices, D2_indices)\n\n # Get the pushover load step and initialize the load factor\n load_step = list(self.load_combos[push_combo].factors.values())[0] # TODO: This line can probably live outside the loop\n load_factor = load_step\n step_num = 1\n\n # Apply the pushover load in steps, summing deformations as we go, until the full pushover load has been analyzed\n while round(load_factor, 8) <= 1.0:\n\n # Inform the user which pushover load step we're on\n if log:\n print('- Beginning pushover load step #' + str(step_num))\n print(f'- Load_factor = {load_factor}')\n\n # Run the next pushover load step\n Analysis._pushover_step(self, combo.name, push_combo, step_num, P1_push, FER1_push, D1_indices, D2_indices, D2, log, sparse, check_stability)\n\n # Update nonlinear material member end forces for each member\n for phys_member in self.members.values():\n\n for member in phys_member.sub_members.values():\n\n # Calculate the local member end force vector (once)\n f = member.f(combo.name, push_combo, step_num)\n\n # Store the end forces in the member\n member._fxi = f[0, 0]\n member._myi = f[4, 0]\n member._mzi = f[5, 0]\n member._fxj = f[6, 0]\n member._myj = f[10, 0]\n member._mzj = f[11, 0]\n\n # Move on to the next load step\n step_num += 1\n load_factor += load_step\n\n # Calculate reactions for every primary load combination\n Analysis._calc_reactions(self, log, combo_tags=['primary'])\n\n if log:\n print('')\n print('- Analysis complete')\n print('')\n\n # Flag the model as solved\n self.solution = 'Pushover'\n\n def unique_name(self, dictionary, prefix):\n \"\"\"Returns the next available unique name for a dictionary of objects.\n\n :param dictionary: The dictionary to get a unique name for.\n :type dictionary: dict\n :param prefix: The prefix to use for the unique name.\n :type prefix: str\n :return: A unique name for the dictionary.\n :rtype: str\n \"\"\"\n\n # Select a trial value for the next available name\n name = prefix + str(len(dictionary) + 1)\n i = 2\n while name in dictionary.keys():\n name = prefix + str(len(dictionary) + i)\n i += 1\n\n # Return the next available name\n return name\n\n\n def rename(self):\n \"\"\"\n Renames all the nodes and elements in the model.\n \"\"\"\n\n # Rename each node in the model\n temp = self.nodes.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'N' + str(id)\n self.nodes[new_key] = self.nodes.pop(old_key)\n self.nodes[new_key].name = new_key\n id += 1\n\n # Rename each spring in the model\n temp = self.springs.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'S' + str(id)\n self.springs[new_key] = self.springs.pop(old_key)\n self.springs[new_key].name = new_key\n id += 1\n\n # Rename each member in the model\n temp = self.members.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'M' + str(id)\n self.members[new_key] = self.members.pop(old_key)\n self.members[new_key].name = new_key\n id += 1\n\n # Rename each plate in the model\n temp = self.plates.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'P' + str(id)\n self.plates[new_key] = self.plates.pop(old_key)\n self.plates[new_key].name = new_key\n id += 1\n\n # Rename each quad in the model\n temp = self.quads.copy()\n id = 1\n for old_key in temp.keys():\n new_key = 'Q' + str(id)\n self.quads[new_key] = self.quads.pop(old_key)\n self.quads[new_key].name = new_key\n id += 1\n\n def orphaned_nodes(self):\n \"\"\"\n Returns a list of the names of nodes that are not attached to any elements.\n \"\"\"\n\n # Initialize a list of orphaned nodes\n orphans = []\n\n # Step through each node in the model\n for node in self.nodes.values():\n\n orphaned = False\n\n # Check to see if the node is attached to any elements\n quads = [quad.name for quad in self.quads.values() if quad.i_node == node or quad.j_node == node or quad.m_node == node or quad.n_node == node]\n plates = [plate.name for plate in self.plates.values() if plate.i_node == node or plate.j_node == node or plate.m_node == node or plate.n_node == node]\n members = [member.name for member in self.members.values() if member.i_node == node or member.j_node == node]\n springs = [spring.name for spring in self.springs.values() if spring.i_node == node or spring.j_node == node]\n\n # Determine if the node is orphaned\n if quads == [] and plates == [] and members == [] and springs == []:\n orphaned = True\n\n # Add the orphaned nodes to the list of orphaned nodes\n if orphaned == True:\n orphans.append(node.name)\n\n return orphans", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 137234}, "Testing/test_mesh_regen_simple.py::50": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_rectangle_mesh_regeneration", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_node_spring_coverage.py::89": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": [], "enclosing_function": "test_node_displacement_dicts_initialized", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 0}, "Testing/test_delete_mesh.py::198": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_with_attached_springs", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::95": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["Section"], "enclosing_function": "test_section_creation", "extracted_code": "# Source: Pynite/Section.py\nclass Section():\n \"\"\"\n A class representing a section assigned to a Member3D element in a finite element model.\n\n This class stores all properties related to the geometry of the member\n \"\"\"\n def __init__(self, model: 'FEModel3D', name: str, A: float, Iy: float, Iz: float, J: float) -> None:\n \"\"\"\n :param model: The finite element model to which this section belongs\n :type model: FEModel3D\n :param name: Name of the section\n :type name: str\n :param A: Cross-sectional area of the section\n :type A: float\n :param Iy: The second moment of area the section about the Y (minor) axis\n :type Iy: float\n :param Iz: The second moment of area the section about the Z (major) axis\n :type Iz: float\n :param J: The torsion constant of the section\n :type J: float\n \"\"\" \n self.model: 'FEModel3D' = model\n self.name: str = name\n self.A: float = A\n self.Iy: float = Iy\n self.Iz: float = Iz\n self.J: float = J\n \n def Phi(self, fx: float = 0, my: float = 0, mz: float = 0):\n \"\"\"\n Method to be overridden by subclasses for determining whether the cross section is\n elastic or plastic.\n \n :param fx: Axial force\n :type fx: float\n :param my: y-axis (weak) moment\n :type my: float\n :param mz: z-axis (strong) moment\n :type mz: float\n :return: The stress ratio\n :rtype: float\n \"\"\"\n raise NotImplementedError(\"Phi method must be implemented in subclasses.\")\n\n def G(self, fx: float, my: float, mz: float) -> NDArray:\n \"\"\"\n Returns the gradient to the yield surface at a given point using numerical differentiation. This is a default solution. For a better solution, overwrite this method with a more precise one in the material/shape specific child class that inherits from this class.\n\n :param fx: Axial force at the cross-section\n :type fx: float\n :param my: y-axis (weak) moment at the cross-section\n :type my: float\n :param mz: z-axis (strong) moment at the cross-section\n :type mz: float\n :return: The gradient to the yield surface at the cross-section\n :rtype: NDArray\n \"\"\"\n\n # Small increment for numerical differentiation\n epsilon = 1e-6\n\n # Calculate the central differences for each parameter\n dPhi_dfx = (self.Phi(fx + epsilon, my, mz) - self.Phi(fx - epsilon, my, mz)) / (2 * epsilon)\n dPhi_dmy = (self.Phi(fx, my + epsilon, mz) - self.Phi(fx, my - epsilon, mz)) / (2 * epsilon)\n dPhi_dmz = (self.Phi(fx, my, mz + epsilon) - self.Phi(fx, my, mz - epsilon)) / (2 * epsilon)\n\n # Return the gradient\n return np.array([[dPhi_dfx],\n [dPhi_dmy],\n [dPhi_dmz]])", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2920}, "Testing/test_sloped_beam.py::76": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_sloped_beam", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_meshes.py::124": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Rendering.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_PCA_7_quad", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::47": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["LoadCombo"], "enclosing_function": "test_loadcombo_creation_empty", "extracted_code": "# Source: Pynite/LoadCombo.py\nclass LoadCombo():\n \"\"\"A class that stores all the information necessary to define a load combination.\n \"\"\"\n\n def __init__(self, name: str, combo_tags: List[str] | None = None, factors: Dict[str, float] = {}) -> None:\n \"\"\"Initializes a new load combination.\n\n :param name: A unique name for the load combination.\n :type name: str\n :param combo_tags: A list of tags for the load combination. This is a list of any strings you would like to use to categorize your load combinations. It is useful for separating load combinations into strength, service, or overstrength combinations as often required by building codes. This parameter has no effect on the analysis, but it can be used to restrict analysis to only the load combinations with the tags you specify.\n :type combo_tags: list, optional\n :param factors: A dictionary of load case names (`keys`) followed by their load factors (`items`). For example, the load combination 1.2D+1.6L would be represented as follows: `{'D': 1.2, 'L': 1.6}`. Defaults to {}.\n :type factors: dict, optional\n \"\"\"\n \n self.name: str = name # A unique user-defined name for the load combination\n self.combo_tags: List[str] | None = combo_tags # Used to categorize the load combination (e.g. strength or serviceability)\n self.factors: Dict[str, float] = factors # A dictionary containing each load case name and associated load factor\n \n def AddLoadCase(self, case_name: str, factor: float) -> None:\n '''\n Adds a load case with its associated load factor\n\n :param case_name: The name of the load case\n :type case_name: str\n :param factor: The load factor to apply to the load case\n :type factor: float\n '''\n\n self.factors[case_name] = factor\n \n def DeleteLoadCase(self, case_name: str) -> None:\n '''\n Deletes a load case with its associated load factor\n\n :param case_name: The name of the load case to delete\n :type case_name: str\n '''\n\n del self.factors[case_name]", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2148}, "Testing/test_material_section_coverage.py::23": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["Material"], "enclosing_function": "test_material_creation", "extracted_code": "# Source: Pynite/Material.py\nclass Material():\n \"\"\"\n A class representing a material assigned to a Member3D, Plate or Quad in a finite element model.\n\n This class stores all properties related to the physical material of the element\n \"\"\"\n def __init__(self, model: FEModel3D, name: str, E: float, G: float, nu: float, rho: float, fy: float | None = None) -> None:\n \"\"\"Initialize a material object.\n\n :param model: The finite element model this material belongs to\n :type model: FEModel3D\n :param name: A unique name for the material\n :type name: str\n :param E: Modulus of elasticity\n :type E: float\n :param G: Shear modulus\n :type G: float\n :param nu: Poisson's ratio\n :type nu: float\n :param rho: Density of the material\n :type rho: float\n :param fy: Yield strength of the material, defaults to None\n :type fy: float, optional\n \"\"\"\n\n self.model: FEModel3D = model\n self.name: str = name\n self.E: float = E\n self.G: float = G\n self.nu: float = nu\n self.rho: float = rho\n self.fy: float | None = fy", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 1173}, "Testing/test_delete_mesh.py::99": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_delete_mesh_with_attached_elements", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_material_section_coverage.py::53": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Material.py", "Pynite/Section.py", "Pynite/LoadCombo.py"], "used_names": ["LoadCombo"], "enclosing_function": "test_loadcombo_creation_with_factors", "extracted_code": "# Source: Pynite/LoadCombo.py\nclass LoadCombo():\n \"\"\"A class that stores all the information necessary to define a load combination.\n \"\"\"\n\n def __init__(self, name: str, combo_tags: List[str] | None = None, factors: Dict[str, float] = {}) -> None:\n \"\"\"Initializes a new load combination.\n\n :param name: A unique name for the load combination.\n :type name: str\n :param combo_tags: A list of tags for the load combination. This is a list of any strings you would like to use to categorize your load combinations. It is useful for separating load combinations into strength, service, or overstrength combinations as often required by building codes. This parameter has no effect on the analysis, but it can be used to restrict analysis to only the load combinations with the tags you specify.\n :type combo_tags: list, optional\n :param factors: A dictionary of load case names (`keys`) followed by their load factors (`items`). For example, the load combination 1.2D+1.6L would be represented as follows: `{'D': 1.2, 'L': 1.6}`. Defaults to {}.\n :type factors: dict, optional\n \"\"\"\n \n self.name: str = name # A unique user-defined name for the load combination\n self.combo_tags: List[str] | None = combo_tags # Used to categorize the load combination (e.g. strength or serviceability)\n self.factors: Dict[str, float] = factors # A dictionary containing each load case name and associated load factor\n \n def AddLoadCase(self, case_name: str, factor: float) -> None:\n '''\n Adds a load case with its associated load factor\n\n :param case_name: The name of the load case\n :type case_name: str\n :param factor: The load factor to apply to the load case\n :type factor: float\n '''\n\n self.factors[case_name] = factor\n \n def DeleteLoadCase(self, case_name: str) -> None:\n '''\n Deletes a load case with its associated load factor\n\n :param case_name: The name of the load case to delete\n :type case_name: str\n '''\n\n del self.factors[case_name]", "n_imports_parsed": 6, "n_files_resolved": 5, "n_chars_extracted": 2148}, "Testing/test_Visualization.py::153": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py", "Pynite/Visualization.py", "Pynite/Rendering.py"], "used_names": [], "enclosing_function": "test_toggle_visual_properties", "extracted_code": "", "n_imports_parsed": 10, "n_files_resolved": 4, "n_chars_extracted": 0}, "Testing/test_member_rotation.py::95": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_column_rotation", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 375}, "Testing/test_AISC_PDelta_benchmarks.py::227": {"resolved_imports": ["Pynite/__init__.py", "Pynite/FEModel3D.py"], "used_names": ["FEModel3D"], "enclosing_function": "test_AISC_benchmark_case2", "extracted_code": "# Source: Pynite/__init__.py\n# Select libraries that will be imported into Pynite for the user\nfrom Pynite.FEModel3D import FEModel3D\nfrom Pynite.ShearWall import ShearWall\nimport Pynite\n\nfrom importlib.metadata import version, PackageNotFoundError\n\ntry:\n __version__ = version(\"PyniteFEA\")\nexcept PackageNotFoundError:\n # Package not installed, use development version", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 375}}}