Skip to content

Commit

Permalink
ruff formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
rpakishore committed Jan 14, 2025
1 parent 6c7229f commit 22912f4
Show file tree
Hide file tree
Showing 25 changed files with 330 additions and 289 deletions.
334 changes: 176 additions & 158 deletions documentation/Usage.ipynb

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions pages/2_Tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
from ak_sap import Sap2000Wrapper
from ak_sap.gui.streamlit import st_initialize

st.write('## Tables')
st.write("## Tables")
st_initialize()

if not st.session_state.get('attached'):
st.warning('[Attach to existing](/) SAP model first to use this tab')
if not st.session_state.get("attached"):
st.warning("[Attach to existing](/) SAP model first to use this tab")
st.stop()

sap:Sap2000Wrapper = st.session_state['SAP']
sap: Sap2000Wrapper = st.session_state["SAP"]
st.divider()
with st.expander('Tables Tables'):
_all = st.checkbox('Show All')
with st.expander("Tables Tables"):
_all = st.checkbox("Show All")
if _all:
st.table(sap.Table.list_all())
else:
st.table(sap.Table.list_available())
st.divider()
st.divider()
134 changes: 76 additions & 58 deletions pages/Export/hilti_export.py
Original file line number Diff line number Diff line change
@@ -1,123 +1,141 @@
from hilti_profis import PE
import streamlit as st

from datetime import datetime
import os
import tempfile
from datetime import datetime

import streamlit as st
from hilti_profis import PE

from ak_sap import Sap2000Wrapper


def main():
sap:Sap2000Wrapper = st.session_state['SAP']
sap: Sap2000Wrapper = st.session_state["SAP"]
_steps = """
Steps to follow:
1. Run the Analysis on SAP2000.
2. Select the frame and attached support for export in the 3D model.
3. Click the `Extract Values` button below.
"""
st.info(_steps, icon='ℹ️')
if st.session_state.get('_hilti_values_extracted') is None:
st.session_state['_hilti_values_extracted'] = False
st.info(_steps, icon="ℹ️")

if st.session_state.get("_hilti_values_extracted") is None:
st.session_state["_hilti_values_extracted"] = False

def _hilti_extract_values():
try:
st.session_state['_hilti_values_extracted'] = sap.Object.Point.selected().__next__()
st.session_state["_hilti_values_extracted"] = (
sap.Object.Point.selected().__next__()
)
except StopIteration:
st.session_state['_hilti_values_extracted'] = None
st.warning('Make sure the node is selected.')
st.button('Extract Values', on_click=_hilti_extract_values)
st.session_state["_hilti_values_extracted"] = None
st.warning("Make sure the node is selected.")

st.button("Extract Values", on_click=_hilti_extract_values)

@st.cache_data
def load_hilti_class(basefile):
return PE(basefile=basefile)
if st.session_state['_hilti_values_extracted']:

if st.session_state["_hilti_values_extracted"]:
try:
selected_section = sap.Object.Frame.get_section(frame_name=sap.Object.Frame.selected().__next__())
selected_section = sap.Object.Frame.get_section(
frame_name=sap.Object.Frame.selected().__next__()
)
except StopIteration:
selected_section = None

st.divider()
st.markdown('##### Selections')
st.markdown("##### Selections")
_lcases = sap.Load.Case.list_all()
_lcombos = sap.Load.Combo.list_all()

col1, col2, col3 = st.columns(3)
cases = col1.multiselect(label='Load Cases for Export', default=_lcases, options=_lcases)
combos = col2.multiselect(label='Load Combos for Export', default=_lcombos, options=_lcombos)
#col3.write(f'##### Selected Section: \n###### {selected_section}')
col3.table(data = {'Selected Section':selected_section, 'Selected Node #':st.session_state['_hilti_values_extracted']})

col1, col2 = st.columns([3,1])
cases = col1.multiselect(
label="Load Cases for Export", default=_lcases, options=_lcases
)
combos = col2.multiselect(
label="Load Combos for Export", default=_lcombos, options=_lcombos
)
# col3.write(f'##### Selected Section: \n###### {selected_section}')
col3.table(
data={
"Selected Section": selected_section,
"Selected Node #": st.session_state["_hilti_values_extracted"],
}
)

col1, col2 = st.columns([3, 1])
uploaded_file = col2.file_uploader(
label = 'Upload a base `.pe` file (Optional)',
label="Upload a base `.pe` file (Optional)",
accept_multiple_files=False,
help='You can optionally provide a `.pe` file as reference. All other design values will be imported from supplied file',
key = 'pe_basefile',
type='pe'
help="You can optionally provide a `.pe` file as reference. All other design values will be imported from supplied file",
key="pe_basefile",
type="pe",
)

col1, col2, col3 = col1.columns(3)
_axis = [1,2,3]
x_axis = col2.selectbox(label='X-axis', options=_axis, index=0)
y_axis = col3.selectbox(label='Y-axis', options=_axis, index=1)
z_axis = col1.selectbox(label='Z-axis', options=_axis, index=2)
_axis = [1, 2, 3]
x_axis = col2.selectbox(label="X-axis", options=_axis, index=0)
y_axis = col3.selectbox(label="Y-axis", options=_axis, index=1)
z_axis = col1.selectbox(label="Z-axis", options=_axis, index=2)

def generate_pe() -> str:
sap:Sap2000Wrapper = st.session_state['SAP']
sap: Sap2000Wrapper = st.session_state["SAP"]
if not x_axis != y_axis != z_axis:
st.error('^ Make sure X, Y, Z axis are mutually exclusive from each other')
st.error(
"^ Make sure X, Y, Z axis are mutually exclusive from each other"
)
if uploaded_file is not None:
basefile = os.path.join(tempfile.mkdtemp(), uploaded_file.name)
with open(basefile, "wb") as f:
f.write(uploaded_file.getvalue())
else:
basefile = None
anchor = load_hilti_class(basefile=basefile)

sap.Results.Setup.clear_casecombo()

for case in cases:
sap.Results.Setup.select_case(casename=case)

for combo in combos:
sap.Results.Setup.select_combo(comboname=combo)

_current_units = sap.Model.units
sap.Model.set_units(value="N_mm_C")

#Delete Existing Load Combinations
anchor.Model.Loads.Combos.data['LoadCombinationEntity'] = None

for rxn in sap.Results.joint_reactions(jointname=st.session_state['_hilti_values_extracted']):

# Delete Existing Load Combinations
anchor.Model.Loads.Combos.data["LoadCombinationEntity"] = None

for rxn in sap.Results.joint_reactions(
jointname=st.session_state["_hilti_values_extracted"]
):
anchor.Model.Loads.Combos.add(
Fx=-rxn[f"F{x_axis}"],
Fy=-rxn[f"F{y_axis}"],
Fz=-rxn[f"F{z_axis}"],
Mx=-rxn[f"M{x_axis}"],
My=-rxn[f"M{y_axis}"],
Mz=-rxn[f"M{z_axis}"],
LoadType='Seismic',
Comment=rxn["LoadCase"]
LoadType="Seismic",
Comment=rxn["LoadCase"],
)
sap.Model.set_units(value=_current_units)

anchor.Model.apply()
_xml=anchor.xml_content()
_xml = anchor.xml_content()
assert isinstance(_xml, str)
return anchor.xml_content() # type: ignore
return anchor.xml_content() # type: ignore

st.divider()

# Todo
# Defer the `generate_pe` function run until the button is clicked.
# Currently on [streamlit roadmap](https://roadmap.streamlit.app) for May-July ("Deferred data load for st.download_button")
st.download_button(
label='Export `.pe` file',
label="Export `.pe` file",
data=generate_pe(),
file_name=f"{sap.Model.filepath.stem}-{st.session_state['_hilti_values_extracted']}{'-'+selected_section if selected_section else ''}-AK-{datetime.now():%m%d_%H%M}.pe",
type='primary',
mime = 'text/plain'
file_name=f"{sap.Model.filepath.stem}-{st.session_state['_hilti_values_extracted']}{'-' + selected_section if selected_section else ''}-AK-{datetime.now():%m%d_%H%M}.pe",
type="primary",
mime="text/plain",
)
11 changes: 6 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
[build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"

[project]
name = "ak_sap"
version = "0.0.1"
requires-python = ">=3.12.0"
authors = [{name = "Arun Kishore", email = "[email protected]"}]
readme = "README.md"
license = {file = "LICENSE"}
classifiers = ["License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"]
dynamic = ["version", "description"]
dependencies = [
"comtypes>=1.4.8",
"forallpeople>=2.7.1",
Expand All @@ -31,6 +27,10 @@ update-doc="ak_sap.cli.update_doc:app"

[tool.uv]
default-groups = ["gui"]
package = true

[tool.setuptools.dynamic]
description = {file = "README.md"}

[dependency-groups]
cli = [
Expand All @@ -41,6 +41,7 @@ dev = [
"ipykernel>=6.29.5",
"ipywidgets>=8.1.5",
"line-profiler>=4.2.0",
"ruff>=0.9.1",
]
gui = [
"streamlit>=1.40.1",
Expand Down
41 changes: 26 additions & 15 deletions scripts/code_coverage.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
import subprocess
import tempfile
from pathlib import Path
import webbrowser
import subprocess
import shutil
from pathlib import Path

# Run Pytest Coverage Report
code_coverage_path = Path(tempfile.gettempdir()) / "code_coverage_report"


cmd = [
"uv",
"run",
"--group",
"test",
"pytest",
"--cov=ak_sap",
f"--cov-report=html:{code_coverage_path}",
]
print(" ".join(cmd))
subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait()
def run_cmd(cmd: list[str]):
print(" ".join(cmd))
subprocess.Popen(
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
).wait()


run_cmd(cmd=["uv", "run", "ruff", "format"])
run_cmd(cmd=["uv", "run", "ruff", "check", "--select", "I", "-e", "--fix"])
run_cmd(cmd=["uv", "run", "ruff", "check", "--fix", ">&1"])

run_cmd(
cmd=[
"uv",
"run",
"--group",
"test",
"pytest",
"--cov=template_python",
f"--cov-report=html:{code_coverage_path}",
]
)
webbrowser.open(f"file://{code_coverage_path}/index.html")

webbrowser.open(f"file://{code_coverage_path}/index.html")
run_cmd(cmd=["uv", "run", "--group", "test", "pytest"])
2 changes: 1 addition & 1 deletion src/ak_sap/Analyze/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Literal

from ak_sap.utils import MasterClass, log
from ak_sap.utils import MasterClass
from ak_sap.utils.decorators import smooth_sap_do


Expand Down
12 changes: 6 additions & 6 deletions src/ak_sap/Database/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,9 @@ def _array_to_pandas(headers: tuple, array: tuple) -> pd.DataFrame:
"""Given the table headers as tuple and table data as a single tuple;
Returns table as a dataframe."""
num_fields = len(headers)
assert (
len(array) % num_fields == 0
), f"Array length ({len(array)}) is not divisible by header length ({num_fields})"
assert len(array) % num_fields == 0, (
f"Array length ({len(array)}) is not divisible by header length ({num_fields})"
)

df_data: dict[str, list] = {header: [] for header in headers}
for array_idx, value in enumerate(array):
Expand All @@ -212,9 +212,9 @@ def _array_to_list_of_dicts(headers: tuple, array: tuple) -> list[dict[str, Any]
"""Given the table headers as tuple and table data as a single tuple;
Returns table as a list of dictionaries."""
num_fields = len(headers)
assert (
len(array) % num_fields == 0
), f"Array length ({len(array)}) is not divisible by header length ({num_fields})"
assert len(array) % num_fields == 0, (
f"Array length ({len(array)}) is not divisible by header length ({num_fields})"
)

list_of_dicts = []
for i in range(len(array) // num_fields):
Expand Down
20 changes: 10 additions & 10 deletions src/ak_sap/Loads/LoadCases.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import typing

from ak_sap.utils import MasterClass, log
from ak_sap.utils import MasterClass
from ak_sap.utils.decorators import smooth_sap_do

from .constants import LoadCaseType, LoadPatternType
Expand Down Expand Up @@ -33,9 +33,9 @@ def total(self, casetype: LoadCaseType | None = None):
@smooth_sap_do
def rename(self, old_name: str, new_name: str):
"""changes the name of an existing load case."""
assert (
old_name in self.list_all()
), f'"{old_name}" is not in list of defined load cases {self.list_all()}'
assert old_name in self.list_all(), (
f'"{old_name}" is not in list of defined load cases {self.list_all()}'
)
return self.__LoadCases.ChangeName(old_name, new_name)

@smooth_sap_do
Expand All @@ -46,9 +46,9 @@ def list_all(self) -> tuple[str]:

@smooth_sap_do
def delete(self, name: str):
assert (
name in self.list_all()
), f'"{name}" is not in list of defined load cases {self.list_all()}'
assert name in self.list_all(), (
f'"{name}" is not in list of defined load cases {self.list_all()}'
)
return self.__LoadCases.Delete(name)

@smooth_sap_do
Expand All @@ -73,8 +73,8 @@ def case_info(self, name: str) -> dict:

@smooth_sap_do
def set_type(self, name: str, casetype: LoadCaseType):
assert (
name in self.list_all()
), f'"{name}" is not in list of defined load cases {self.list_all()}'
assert name in self.list_all(), (
f'"{name}" is not in list of defined load cases {self.list_all()}'
)
_value = typing.get_args(LoadCaseType).index(casetype) + 1
return self.__LoadCases.SetDesignType(name, 1, _value)
Loading

0 comments on commit 22912f4

Please sign in to comment.