Skip to content

Commit 84561e7

Browse files
committed
Clean up code
1 parent 3aa2962 commit 84561e7

File tree

2 files changed

+29
-69
lines changed

2 files changed

+29
-69
lines changed

mpldxf/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
import mpldxf.backend_dxf
22
from .backend_dxf import FigureCanvasDxf
3-
from .backend_dxf import FigureCanvasDxfNGI
3+
from .backend_dxf import FigureCanvasDxfFM

mpldxf/backend_dxf.py

Lines changed: 28 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -83,16 +83,16 @@ def rgb_to_dxf(rgb_val):
8383
class RendererDxf(RendererBase):
8484
"""
8585
The renderer handles drawing/rendering operations.
86-
Renders the drawing using the ``ezdxf`` package with NGI layer support.
86+
Renders the drawing using the ``ezdxf`` package with Field Manager layer support.
8787
"""
8888

89-
def __init__(self, width, height, dpi, dxfversion, use_ngi_layers=False):
89+
def __init__(self, width, height, dpi, dxfversion, use_fm_layers=False):
9090
RendererBase.__init__(self)
9191
self.height = height
9292
self.width = width
9393
self.dpi = dpi
9494
self.dxfversion = dxfversion
95-
self.use_ngi_layers = use_ngi_layers
95+
self.use_fm_layers = use_fm_layers
9696
self._init_drawing()
9797
self._groupd = []
9898
self._method_context = False
@@ -108,25 +108,25 @@ def _init_drawing(self):
108108
drawing.header["$EXTMIN"] = (0, 0, 0)
109109
drawing.header["$EXTMAX"] = (self.width, self.height, 0)
110110

111-
if self.use_ngi_layers:
112-
self._create_ngi_layers(drawing)
111+
if self.use_fm_layers:
112+
self._create_fm_layers(drawing)
113113

114114
self.drawing = drawing
115115
self.modelspace = modelspace
116116

117-
def _create_ngi_layers(self, drawing):
118-
"""Create NGI-specific layers with specific colors"""
119-
ngi_layers = {
120-
"FM-Frame": 7, # White/Black - frames, ticks, gridlines
121-
"FM-Graph": 1, # Red - data graphs/lines
122-
"FM-Location": 2, # Yellow - location name text
123-
"FM-Method": 3, # Green - method icons and names
124-
"FM-Depth": 4, # Cyan - Y-axis values (depth/elevation)
125-
"FM-Value": 5, # Blue - X-axis values
126-
"FM-Text": 6, # Magenta - axis labels and other text
117+
def _create_fm_layers(self, drawing):
118+
"""Create FM-specific layers with specific colors"""
119+
fm_layers = {
120+
"FM-Frame": 3, # Green - frames, ticks, gridlines
121+
"FM-Graph": 4, # Cyan - data graphs/lines
122+
"FM-Location": 6, # Magenta - location name text
123+
"FM-Method": 5, # Blue- method icons and names
124+
"FM-Depth": 1, # Red- Y-axis values (depth/elevation)
125+
"FM-Value": 8, # Grey - X-axis values
126+
"FM-Text": 2, # Yellow - axis labels and other text
127127
}
128128

129-
for layer_name, color in ngi_layers.items():
129+
for layer_name, color in fm_layers.items():
130130
layer = drawing.layers.add(layer_name)
131131
layer.dxf.color = color
132132

@@ -137,7 +137,7 @@ def clear(self):
137137

138138
def _determine_element_layer(self):
139139
"""Determine which layer to use based on matplotlib element context"""
140-
if not self.use_ngi_layers:
140+
if not self.use_fm_layers:
141141
return "0"
142142

143143
if not self._groupd:
@@ -146,8 +146,6 @@ def _determine_element_layer(self):
146146
context_str = " ".join(self._groupd).lower()
147147
current_element = self._groupd[-1].lower()
148148

149-
print(f"DETERMINE LAYER: Element='{current_element}', Context='{context_str}'")
150-
151149
# Patches - defer to size analysis
152150
if current_element == "patch":
153151
return "PENDING" # Will be resolved in _draw_mpl_patch
@@ -156,19 +154,15 @@ def _determine_element_layer(self):
156154
elif current_element == "line2d":
157155
# Frame elements: ticks and axis lines
158156
if any(keyword in context_str for keyword in ["tick", "matplotlib.axis"]):
159-
print(f" -> FM-Frame (tick/axis line)")
160157
return "FM-Frame"
161158
# Data lines in axes context
162159
elif "axes" in context_str:
163-
print(f" -> FM-Graph (data line)")
164160
return "FM-Graph"
165161
else:
166-
print(f" -> FM-Graph (other line)")
167162
return "FM-Graph"
168163

169164
# Collections - these are often method symbols
170165
elif current_element == "collection":
171-
print(f" -> FM-Method (collection)")
172166
return "FM-Method"
173167

174168
# Text elements
@@ -177,10 +171,8 @@ def _determine_element_layer(self):
177171

178172
# Specific frame elements
179173
elif any(keyword in context_str for keyword in ["tick", "matplotlib.axis"]):
180-
print(f" -> FM-Frame (frame element)")
181174
return "FM-Frame"
182175

183-
print(f" -> 0 (default)")
184176
return "0"
185177

186178
def _analyze_patch_size(self, vertices):
@@ -199,90 +191,71 @@ def _analyze_patch_size(self, vertices):
199191
width = max_x - min_x
200192
height = max_y - min_y
201193

202-
print(f" -> Patch size: {width:.1f}x{height:.1f}")
203-
204194
# Avoid division by zero
205195
if height == 0 or width == 0:
206-
print(f" -> FM-Frame (zero dimension)")
207196
return "FM-Frame"
208197

209198
# Calculate aspect ratio
210199
aspect_ratio = max(width, height) / min(width, height)
211200

212-
print(f" -> Aspect ratio: {aspect_ratio:.2f}")
213-
214201
# Shape-based classification:
215202
# - Very thin/long elements (spines, gridlines) -> Frame
216203
# - Square-ish elements (method icons) -> Method
217204
# - Large backgrounds -> Frame
218205

219206
if aspect_ratio > 10: # Very long/thin = spines, gridlines, borders
220-
print(f" -> FM-Frame (thin line/border)")
221207
return "FM-Frame"
222208
elif (
223209
aspect_ratio < 3 and width < 100 and height < 100
224210
): # Roughly square and small = method icon
225-
print(f" -> FM-Method (square small patch - likely icon)")
226211
return "FM-Method"
227212
else: # Everything else = frame elements
228-
print(f" -> FM-Frame (frame element)")
229213
return "FM-Frame"
230214

231215
def open_group(self, s, gid=None):
232216
"""Open a grouping element with label *s*."""
233217
self._groupd.append(s)
234-
print(f"OPEN GROUP: {s}, Full context: {self._groupd}")
235218

236219
# Track axes changes with a unique counter
237220
if s == "axes":
238221
self._axes_counter += 1
239222
self._current_axes_id = self._axes_counter
240223
if self._current_axes_id not in self._axes_patch_count:
241224
self._axes_patch_count[self._current_axes_id] = 0
242-
print(f" -> New axes #{self._current_axes_id}")
243225

244226
# Check if we're entering a method context
245227
if s.lower() in ["offsetbox", "drawingarea"]:
246228
self._method_context = True
247-
print(f" -> METHOD CONTEXT ACTIVATED")
248229

249230
def close_group(self, s):
250231
"""Close a grouping element with label *s*."""
251-
print(f"CLOSE GROUP: {s}, Context before: {self._groupd}")
252232
if self._groupd and self._groupd[-1] == s:
253233
self._groupd.pop()
254234

255235
# Check if we're exiting a method context
256236
if s.lower() in ["offsetbox", "drawingarea"]: # Remove "anchored"
257237
self._method_context = False
258-
print(f" -> METHOD CONTEXT DEACTIVATED")
259238

260239
def _determine_text_layer(self, text_content, fontsize):
261240
"""Determine text layer based on matplotlib context and content"""
262-
if not self.use_ngi_layers:
241+
if not self.use_fm_layers:
263242
return "0"
264243

265244
context_str = " ".join(self._groupd).lower() if self._groupd else ""
266245

267-
print(f"DETERMINE TEXT LAYER: Text='{text_content}', Context='{context_str}'")
268-
269246
# Y-axis elements -> Depth
270247
if any(keyword in context_str for keyword in ["yaxis", "ytick"]):
271-
print(f" -> FM-Depth (y-axis)")
272248
return "FM-Depth"
273249

274250
# X-axis elements -> Value
275251
if any(keyword in context_str for keyword in ["xaxis", "xtick"]):
276-
print(f" -> FM-Value (x-axis)")
277252
return "FM-Value"
278253

279254
# Title elements and large text -> Location
280255
if "title" in context_str:
281256
if fontsize > 8:
282-
print(f" -> FM-Location (title)")
283257
return "FM-Location"
284258
else:
285-
print(f" -> FM-Method (title small)")
286259
return "FM-Method"
287260

288261
# Text in general axes context - check position and content
@@ -291,20 +264,16 @@ def _determine_text_layer(self, text_content, fontsize):
291264
# This is often location text even if it's just a number
292265
if len(self._groupd) == 3: # ['figure', 'axes', 'text']
293266
if fontsize > 8:
294-
print(f" -> FM-Location (axes title text)")
295267
return "FM-Location"
296268
else:
297-
print(f" -> FM-Method (axes title text small)")
298269
return "FM-Method"
299270

300271
# Legend elements -> Method
301272
if "legend" in context_str:
302-
print(f" -> FM-Method (legend)")
303273
return "FM-Method"
304274

305275
# Axis labels -> Text
306276
if any(keyword in context_str for keyword in ["xlabel", "ylabel"]):
307-
print(f" -> FM-Text (axis labels)")
308277
return "FM-Text"
309278

310279
# Content-based classification
@@ -316,38 +285,32 @@ def _determine_text_layer(self, text_content, fontsize):
316285
for keyword in ["boring", "bh-", "hole", "site", "location"]
317286
):
318287
if fontsize > 8:
319-
print(f" -> FM-Location (location pattern)")
320288
return "FM-Location"
321289
else:
322-
print(f" -> FM-Method (location pattern small)")
323290
return "FM-Method"
324291

325292
# Method text patterns
326293
if any(
327294
keyword in text_lower
328295
for keyword in ["cpt", "spt", "pmt", "dmt", "method", "test"]
329296
):
330-
print(f" -> FM-Method (method pattern)")
331297
return "FM-Method"
332298

333299
# Numeric patterns
334300
import re
335301

336302
if re.match(r"^\s*[-+]?\d*\.?\d+\s*$", text_content):
337303
if "y" in context_str or "ytick" in context_str:
338-
print(f" -> FM-Depth (numeric y)")
339304
return "FM-Depth"
340305
elif "x" in context_str or "xtick" in context_str:
341-
print(f" -> FM-Value (numeric x)")
342306
return "FM-Value"
343307

344-
print(f" -> FM-Text (default)")
345308
return "FM-Text"
346309

347310
def _get_polyline_attribs(self, gc):
348311
"""Get polyline attributes with correct layer and color"""
349312
attribs = {}
350-
if self.use_ngi_layers:
313+
if self.use_fm_layers:
351314
layer_name = self._determine_element_layer()
352315
attribs["layer"] = layer_name
353316
attribs["color"] = 256 # ByLayer color
@@ -447,11 +410,10 @@ def _draw_mpl_patch(self, gc, path, transform, rgbFace=None):
447410
if layer_name == "PENDING":
448411
# Use simple size-based analysis
449412
layer_name = self._analyze_patch_size(vertices)
450-
print(f" -> Final layer: {layer_name}")
451413

452414
# Set up DXF attributes
453415
dxfattribs = {}
454-
if self.use_ngi_layers:
416+
if self.use_fm_layers:
455417
dxfattribs["layer"] = layer_name
456418
dxfattribs["color"] = 256 # ByLayer color
457419
else:
@@ -517,7 +479,6 @@ def _draw_mpl_hatch(self, gc, path, transform, pline):
517479
)
518480
hpatht = hpath.transformed(_transform)
519481

520-
# print("\tHatch Path:", hpatht)
521482
# now place the hatch to cover the parent path
522483
for irow in range(-rows, rows + 1):
523484
for icol in range(-cols, cols + 1):
@@ -576,7 +537,6 @@ def draw_path_collection(
576537
offset_position,
577538
):
578539
"""Path collections might be method icons - force to method layer"""
579-
print(f"DRAW PATH COLLECTION: Context: {self._groupd}")
580540

581541
# Force path collections to method layer (these are often scatter plots/symbols)
582542
original_groupd = self._groupd.copy()
@@ -625,7 +585,7 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
625585
fontsize = self.points_to_pixels(prop.get_size_in_points()) / 2
626586

627587
dxfattribs = {}
628-
if self.use_ngi_layers:
588+
if self.use_fm_layers:
629589
layer_name = self._determine_text_layer(s, fontsize)
630590
dxfattribs["layer"] = layer_name
631591
dxfattribs["color"] = 256 # ByLayer color
@@ -759,14 +719,14 @@ class FigureCanvasDxf(FigureCanvasBase):
759719

760720
DXFVERSION = "AC1032"
761721

762-
def __init__(self, figure, use_ngi_layers=False):
722+
def __init__(self, figure, use_fm_layers=False):
763723
super().__init__(figure)
764-
self.use_ngi_layers = use_ngi_layers
724+
self.use_fm_layers = use_fm_layers
765725

766726
def get_dxf_renderer(self, cleared=False):
767727
"""Get a renderer to use."""
768728
l, b, w, h = self.figure.bbox.bounds
769-
key = w, h, self.figure.dpi, self.use_ngi_layers
729+
key = w, h, self.figure.dpi, self.use_fm_layers
770730
try:
771731
self._lastKey, self.dxf_renderer
772732
except AttributeError:
@@ -776,7 +736,7 @@ def get_dxf_renderer(self, cleared=False):
776736

777737
if need_new_renderer:
778738
self.dxf_renderer = RendererDxf(
779-
w, h, self.figure.dpi, self.DXFVERSION, self.use_ngi_layers
739+
w, h, self.figure.dpi, self.DXFVERSION, self.use_fm_layers
780740
)
781741
self._lastKey = key
782742
elif cleared:
@@ -806,11 +766,11 @@ def get_default_filetype(self):
806766
return "dxf"
807767

808768

809-
class FigureCanvasDxfNGI(FigureCanvasDxf):
810-
"""NGI-specific DXF canvas with predefined layers"""
769+
class FigureCanvasDxfFM(FigureCanvasDxf):
770+
"""FM-specific DXF canvas with predefined layers"""
811771

812772
def __init__(self, figure):
813-
super().__init__(figure, use_ngi_layers=True)
773+
super().__init__(figure, use_fm_layers=True)
814774

815775

816776
FigureManagerDXF = FigureManagerBase

0 commit comments

Comments
 (0)