-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathe2k_reader.py
More file actions
281 lines (234 loc) · 9.92 KB
/
e2k_reader.py
File metadata and controls
281 lines (234 loc) · 9.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
import re
import pandas as pd
_QUOTED_TOKEN_RE = re.compile(r'"(?:[^"]|"")*"')
def _unquote_etabs(token: str) -> str:
token = token.strip()
if len(token) >= 2 and token[0] == '"' and token[-1] == '"':
inner = token[1:-1]
# ETABS doubles quotes inside strings: "" -> "
return inner.replace('""', '"')
return token
def tokenize_e2k_line(line: str) -> List[str]:
"""Tokenize a single E2K line.
Handles quoted strings that may contain escaped quotes via doubled quotes.
Examples:
MATERIAL "C30" TYPE "Concrete" WEIGHTPERVOLUME 2500
TITLE1 "{\"\"key\"\": 1}" (very long JSON-like text)
"""
s = line.strip()
if not s or s.startswith('$'):
return []
out: List[str] = []
i = 0
n = len(s)
while i < n:
# skip spaces
while i < n and s[i].isspace():
i += 1
if i >= n:
break
if s[i] == '"':
m = _QUOTED_TOKEN_RE.match(s, i)
if not m:
# fall back: take until next quote
j = i + 1
while j < n and s[j] != '"':
j += 1
out.append(s[i:j + 1] if j < n else s[i:])
i = j + 1
else:
out.append(m.group(0))
i = m.end()
else:
j = i
while j < n and not s[j].isspace():
j += 1
out.append(s[i:j])
i = j
return out
def _try_float(s: str) -> Any:
try:
if s.lower() in {'nan', '+nan', '-nan'}:
return float('nan')
return float(s)
except Exception:
return s
def parse_key_value_tokens(tokens: List[str], start_index: int) -> Dict[str, Any]:
"""Parse tokens of the form KEY VALUE KEY VALUE ... into a dict.
If an odd token remains at the end, it is interpreted as a boolean flag set to True.
"""
d: Dict[str, Any] = {}
i = start_index
while i < len(tokens):
key = tokens[i]
if i + 1 >= len(tokens):
d[key] = True
break
val = _unquote_etabs(tokens[i + 1])
d[key] = _try_float(val)
i += 2
return d
@dataclass
class E2KModel:
"""Lightweight reader for ETABS .e2k text exports.
This is NOT a full semantic ETABS model. It is a structured view of key
tables (stories, points, lines, frame sections, materials) that is useful
for offline QA and geometry/metadata queries.
Limitations:
- Design/analysis results are not in .e2k in a way that replaces running ETABS.
- Some advanced tables are not parsed (yet).
"""
e2k_path: Path
# parsed outputs
units: Optional[Tuple[str, str, str]] = None
stories: pd.DataFrame = field(default_factory=pd.DataFrame)
points: pd.DataFrame = field(default_factory=pd.DataFrame)
point_assigns: pd.DataFrame = field(default_factory=pd.DataFrame)
lines: pd.DataFrame = field(default_factory=pd.DataFrame)
line_assigns: pd.DataFrame = field(default_factory=pd.DataFrame)
areas: pd.DataFrame = field(default_factory=pd.DataFrame)
frame_sections: pd.DataFrame = field(default_factory=pd.DataFrame)
materials: pd.DataFrame = field(default_factory=pd.DataFrame)
def __post_init__(self) -> None:
self.e2k_path = Path(self.e2k_path)
self._parse()
def _parse(self) -> None:
stories: List[Dict[str, Any]] = []
points: List[Dict[str, Any]] = []
point_assigns: List[Dict[str, Any]] = []
lines: List[Dict[str, Any]] = []
line_assigns: List[Dict[str, Any]] = []
areas: List[Dict[str, Any]] = []
frame_sections: List[Dict[str, Any]] = []
materials: List[Dict[str, Any]] = []
current_block: Optional[str] = None
with self.e2k_path.open('r', encoding='utf-8', errors='replace') as f:
for raw in f:
line = raw.rstrip('\n')
if not line.strip():
continue
if line.lstrip().startswith('$'):
current_block = line.strip().lstrip('$').strip()
continue
tokens = tokenize_e2k_line(line)
if not tokens:
continue
rec = tokens[0].upper()
# Controls / units
if rec == 'UNITS' and len(tokens) >= 4:
self.units = (
_unquote_etabs(tokens[1]),
_unquote_etabs(tokens[2]),
_unquote_etabs(tokens[3]),
)
continue
# Stories
if rec == 'STORY' and len(tokens) >= 2:
name = _unquote_etabs(tokens[1])
row: Dict[str, Any] = {'Story': name}
row.update(parse_key_value_tokens(tokens, 2))
stories.append(row)
continue
# Points
if rec == 'POINT' and len(tokens) >= 4:
# POINT "id" x y [z]
pid = _unquote_etabs(tokens[1])
x = _try_float(_unquote_etabs(tokens[2]))
y = _try_float(_unquote_etabs(tokens[3]))
z = _try_float(_unquote_etabs(tokens[4])) if len(tokens) >= 5 else 0.0
points.append({'Point': pid, 'X': x, 'Y': y, 'Z': z})
continue
# Point assigns (per story)
if rec == 'POINTASSIGN' and len(tokens) >= 3:
# POINTASSIGN "1" "Roof" USERJOINT "Yes" ...
pid = _unquote_etabs(tokens[1])
story = _unquote_etabs(tokens[2])
row = {'Point': pid, 'Story': story}
row.update(parse_key_value_tokens(tokens, 3))
point_assigns.append(row)
continue
# Line connectivities
if rec == 'LINE' and len(tokens) >= 6:
# LINE "B1" BEAM "2" "7" 0
lname = _unquote_etabs(tokens[1])
ltype = tokens[2].upper() # BEAM/COLUMN/BRACE/etc.
pi = _unquote_etabs(tokens[3])
pj = _unquote_etabs(tokens[4])
try:
extra = int(float(tokens[5]))
except Exception:
extra = tokens[5]
lines.append({'Line': lname, 'Type': ltype, 'PointI': pi, 'PointJ': pj, 'Extra': extra})
continue
# Line assigns (per story)
if rec == 'LINEASSIGN' and len(tokens) >= 3:
# LINEASSIGN "B2" "Roof" SECTION "B40X40" PROPMODI22 0.35 ...
lname = _unquote_etabs(tokens[1])
story = _unquote_etabs(tokens[2])
row = {'Line': lname, 'Story': story}
row.update(parse_key_value_tokens(tokens, 3))
line_assigns.append(row)
continue
# Area connectivities
if rec == 'AREA' and len(tokens) >= 5:
# AREA "F1" FLOOR 5 "2" "10" ...
aname = _unquote_etabs(tokens[1])
atype = tokens[2].upper()
# the rest is variable-length; store as raw tokens
areas.append({'Area': aname, 'Type': atype, 'Tokens': [ _unquote_etabs(t) for t in tokens[3:] ]})
continue
# Frame sections
if rec == 'FRAMESECTION' and len(tokens) >= 2:
sec = _unquote_etabs(tokens[1])
row = {'Section': sec}
row.update(parse_key_value_tokens(tokens, 2))
frame_sections.append(row)
continue
# Materials
if rec == 'MATERIAL' and len(tokens) >= 2:
mname = _unquote_etabs(tokens[1])
row = {'Material': mname}
row.update(parse_key_value_tokens(tokens, 2))
materials.append(row)
continue
# Everything else: ignore.
_ = current_block
self.stories = pd.DataFrame(stories)
self.points = pd.DataFrame(points)
self.point_assigns = pd.DataFrame(point_assigns)
self.lines = pd.DataFrame(lines)
self.line_assigns = pd.DataFrame(line_assigns)
self.areas = pd.DataFrame(areas)
self.frame_sections = pd.DataFrame(frame_sections)
self.materials = pd.DataFrame(materials)
# Convenience APIs -------------------------------------------------
def get_point(self, point_id: str) -> Tuple[float, float, float]:
df = self.points
if df.empty:
raise KeyError(f'No points parsed: {point_id}')
row = df.loc[df['Point'] == str(point_id)]
if row.empty:
raise KeyError(f'Point not found: {point_id}')
r0 = row.iloc[0]
return float(r0['X']), float(r0['Y']), float(r0['Z'])
def get_line_endpoints(self, line_name: str) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
df = self.lines
row = df.loc[df['Line'] == str(line_name)]
if row.empty:
raise KeyError(f'Line not found: {line_name}')
r0 = row.iloc[0]
p1 = self.get_point(str(r0['PointI']))
p2 = self.get_point(str(r0['PointJ']))
return p1, p2
def iter_beams(self) -> Iterable[str]:
if self.lines.empty:
return iter(())
return (str(x) for x in self.lines.loc[self.lines['Type'] == 'BEAM', 'Line'].tolist())
def iter_columns(self) -> Iterable[str]:
if self.lines.empty:
return iter(())
return (str(x) for x in self.lines.loc[self.lines['Type'] == 'COLUMN', 'Line'].tolist())