{"spec_id":"mohr-circle","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nmohr-circle: Mohr's Circle for Stress Analysis\nLibrary: bokeh 3.9.0 | Python 3.13.13\nQuality: 93/100 | Updated: 2026-05-30\n\"\"\"\n\nimport os\nimport sys\n\n\n# Prevent self-import: this file is named bokeh.py, so Python's path search would\n# find it before the installed bokeh package. Remove the script's own directory\n# from sys.path so `from bokeh.io import …` resolves to the installed package.\n_own_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path = [p for p in sys.path if os.path.abspath(p) != _own_dir]\n\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import ColumnDataSource, HoverTool, Label, Span\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\n# Theme tokens (Imprint palette — theme-adaptive chrome)\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\n# Imprint categorical palette — hybrid-v3 sort, theme-independent\nIMPRINT_PALETTE = [\n    \"#009E73\",  # 1: brand green  — ALWAYS first series (the circle)\n    \"#C475FD\",  # 2: lavender\n    \"#4467A3\",  # 3: blue         — max shear stress\n    \"#BD8233\",  # 4: ochre\n    \"#AE3030\",  # 5: matte red    — semantic anchor for critical/failure\n]\nBRAND = IMPRINT_PALETTE[0]  # \"#009E73\"\nCOLOR_PRINCIPAL = IMPRINT_PALETTE[4]  # matte red — semantic: principal stresses at failure threshold\nCOLOR_SHEAR = IMPRINT_PALETTE[2]  # blue — maximum shear stress\nCOLOR_POINTS = IMPRINT_PALETTE[1]  # lavender — input stress points A and B\n\n# Data — typical combined loading stress state (structural beam cross-section)\nsigma_x = 80  # MPa (tensile, x-face normal stress)\nsigma_y = -30  # MPa (compressive, y-face normal stress)\ntau_xy = 40  # MPa (shear stress)\n\n# Mohr's circle geometry\ncenter = (sigma_x + sigma_y) / 2\nradius = np.sqrt(((sigma_x - sigma_y) / 2) ** 2 + tau_xy**2)\nsigma_1 = center + radius  # major principal stress\nsigma_2 = center - radius  # minor principal stress\ntau_max = radius  # maximum shear stress\ntheta_p = 0.5 * np.arctan2(2 * tau_xy, sigma_x - sigma_y)\ntheta_p_deg = np.degrees(theta_p)\n\n# Circle parametric points (300 segments for smooth curve)\ntheta = np.linspace(0, 2 * np.pi, 300)\ncircle_x = center + radius * np.cos(theta)\ncircle_y = radius * np.sin(theta)\n\n# Stress state points on the circle\nax_pt = (sigma_x, tau_xy)  # Point A: face with σx, τxy\nbx_pt = (sigma_y, -tau_xy)  # Point B: face with σy, −τxy\n\n# ColumnDataSources for interactive HoverTool readouts\nprincipal_source = ColumnDataSource(\n    data={\n        \"x\": [sigma_1, sigma_2],\n        \"y\": [0, 0],\n        \"label\": [\"σ₁ (Major Principal)\", \"σ₂ (Minor Principal)\"],\n        \"sigma\": [f\"{sigma_1:.1f}\", f\"{sigma_2:.1f}\"],\n        \"tau\": [\"0.0\", \"0.0\"],\n    }\n)\n\nshear_source = ColumnDataSource(\n    data={\n        \"x\": [center, center],\n        \"y\": [tau_max, -tau_max],\n        \"label\": [\"τ_max (Top)\", \"τ_max (Bottom)\"],\n        \"sigma\": [f\"{center:.1f}\", f\"{center:.1f}\"],\n        \"tau\": [f\"{tau_max:.1f}\", f\"{-tau_max:.1f}\"],\n    }\n)\n\nstress_source = ColumnDataSource(\n    data={\n        \"x\": [ax_pt[0], bx_pt[0]],\n        \"y\": [ax_pt[1], bx_pt[1]],\n        \"label\": [\"Point A (σx, τxy)\", \"Point B (σy, −τxy)\"],\n        \"sigma\": [f\"{ax_pt[0]:.1f}\", f\"{bx_pt[0]:.1f}\"],\n        \"tau\": [f\"{ax_pt[1]:.1f}\", f\"{bx_pt[1]:.1f}\"],\n    }\n)\n\n# Plot — square canvas (2400×2400) for equal-aspect-ratio circle rendering\npadding = radius * 0.6\ntitle = \"mohr-circle · python · bokeh · anyplot.ai\"\n\np = figure(\n    width=2400,\n    height=2400,\n    title=title,\n    x_axis_label=\"Normal Stress σ (MPa)\",\n    y_axis_label=\"Shear Stress τ (MPa)\",\n    x_range=(sigma_2 - padding, sigma_1 + padding),\n    y_range=(-tau_max - padding, tau_max + padding),\n    match_aspect=True,\n    toolbar_location=None,  # prevents toolbar from adding height to the screenshot\n    min_border_bottom=160,  # room for 34pt tick labels + 42pt axis label\n    min_border_left=180,\n    min_border_top=110,  # room for 50pt title\n    min_border_right=60,\n)\n\n# Reference lines: horizontal τ=0 axis and vertical through circle center\nref_h = Span(location=0, dimension=\"width\", line_color=INK_SOFT, line_width=2, line_alpha=0.35)\nref_v = Span(\n    location=center, dimension=\"height\", line_color=INK_SOFT, line_width=2, line_alpha=0.35, line_dash=\"dashed\"\n)\np.add_layout(ref_h)\np.add_layout(ref_v)\n\n# Mohr's circle — brand green fill + outline (primary element)\np.patch(circle_x.tolist(), circle_y.tolist(), fill_color=BRAND, fill_alpha=0.07, line_color=None)\np.line(circle_x, circle_y, line_color=BRAND, line_width=5, line_alpha=0.9)\n\n# Diameter line connecting A–B through center\np.line(\n    [ax_pt[0], bx_pt[0]], [ax_pt[1], bx_pt[1]], line_color=INK_SOFT, line_width=2, line_dash=\"dashed\", line_alpha=0.5\n)\n\n# Principal stress markers — matte red diamonds (semantic: critical failure-limit values)\nprincipal_r = p.scatter(\n    \"x\",\n    \"y\",\n    source=principal_source,\n    size=26,\n    color=COLOR_PRINCIPAL,\n    marker=\"diamond\",\n    line_color=PAGE_BG,\n    line_width=2,\n)\n\n# Maximum shear stress markers — blue triangles\nshear_r = p.scatter(\n    \"x\", \"y\", source=shear_source, size=26, color=COLOR_SHEAR, marker=\"triangle\", line_color=PAGE_BG, line_width=2\n)\n\n# Input stress state points A and B — lavender circles\nstress_r = p.scatter(\"x\", \"y\", source=stress_source, size=26, color=COLOR_POINTS, line_color=PAGE_BG, line_width=2)\n\n# HoverTool for interactive stress readouts over all key points\nhover = HoverTool(\n    renderers=[principal_r, shear_r, stress_r],\n    tooltips=[(\"Point\", \"@label\"), (\"σ (MPa)\", \"@sigma\"), (\"τ (MPa)\", \"@tau\")],\n)\np.add_tools(hover)\n\n# Angle arc showing 2θp rotation from stress point A to principal axis\nangle_2tp = np.arctan2(tau_xy, sigma_x - center)\narc_radius = radius * 0.35\narc_angles = np.linspace(0, angle_2tp, 60)\narc_x = center + arc_radius * np.cos(arc_angles)\narc_y = arc_radius * np.sin(arc_angles)\np.line(arc_x, arc_y, line_color=COLOR_PRINCIPAL, line_width=3, line_alpha=0.85)\n\n# Annotations — label font scaled for readability at 2400px\noffset_lg = radius * 0.09\nann_sz = \"30pt\"\n\np.add_layout(\n    Label(\n        x=sigma_1,\n        y=offset_lg * 1.4,\n        text=f\"σ₁ = {sigma_1:.1f} MPa\",\n        text_font_size=ann_sz,\n        text_color=COLOR_PRINCIPAL,\n        text_align=\"center\",\n    )\n)\np.add_layout(\n    Label(\n        x=sigma_2,\n        y=offset_lg * 1.4,\n        text=f\"σ₂ = {sigma_2:.1f} MPa\",\n        text_font_size=ann_sz,\n        text_color=COLOR_PRINCIPAL,\n        text_align=\"center\",\n    )\n)\np.add_layout(\n    Label(\n        x=center + offset_lg,\n        y=tau_max + offset_lg * 0.4,\n        text=f\"τ_max = {tau_max:.1f} MPa\",\n        text_font_size=ann_sz,\n        text_color=COLOR_SHEAR,\n    )\n)\np.add_layout(\n    Label(\n        x=center + offset_lg,\n        y=-tau_max - offset_lg * 0.4,\n        text=f\"τ_max = {tau_max:.1f} MPa\",\n        text_font_size=ann_sz,\n        text_color=COLOR_SHEAR,\n        text_baseline=\"top\",\n    )\n)\np.add_layout(\n    Label(\n        x=ax_pt[0] + offset_lg,\n        y=ax_pt[1] + offset_lg * 0.5,\n        text=f\"A ({sigma_x}, {tau_xy})\",\n        text_font_size=ann_sz,\n        text_color=COLOR_POINTS,\n    )\n)\np.add_layout(\n    Label(\n        x=bx_pt[0] - offset_lg,\n        y=bx_pt[1] - offset_lg * 0.5,\n        text=f\"B ({sigma_y}, {-tau_xy})\",\n        text_font_size=ann_sz,\n        text_color=COLOR_POINTS,\n        text_align=\"right\",\n        text_baseline=\"top\",\n    )\n)\np.add_layout(\n    Label(\n        x=center,\n        y=-padding * 0.88,\n        text=f\"C = ({center:.1f}, 0)  |  R = {radius:.1f} MPa\",\n        text_font_size=ann_sz,\n        text_color=INK_MUTED,\n        text_align=\"center\",\n    )\n)\n\n# 2θp angle label positioned along the arc midpoint\narc_mid = angle_2tp / 2\nlabel_r = arc_radius * 1.38\np.add_layout(\n    Label(\n        x=center + label_r * np.cos(arc_mid),\n        y=label_r * np.sin(arc_mid),\n        text=f\"2θp = {2 * theta_p_deg:.1f}°\",\n        text_font_size=ann_sz,\n        text_color=COLOR_PRINCIPAL,\n    )\n)\n\n# Chrome — title/axis/tick sizing per bokeh.md (50pt / 42pt / 34pt)\np.title.text_font_size = \"50pt\"\np.title.text_color = INK\np.title.align = \"center\"\np.title.text_font_style = \"normal\"\n\np.xaxis.axis_label_text_font_size = \"42pt\"\np.yaxis.axis_label_text_font_size = \"42pt\"\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_color = INK\np.xaxis.axis_label_text_font_style = \"normal\"\np.yaxis.axis_label_text_font_style = \"normal\"\n\np.xaxis.major_label_text_font_size = \"34pt\"\np.yaxis.major_label_text_font_size = \"34pt\"\np.xaxis.major_label_text_color = INK_SOFT\np.yaxis.major_label_text_color = INK_SOFT\n\np.xaxis.axis_line_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\np.xaxis.major_tick_line_color = INK_SOFT\np.yaxis.major_tick_line_color = INK_SOFT\np.xaxis.minor_tick_line_color = None\np.yaxis.minor_tick_line_color = None\n\np.xgrid.grid_line_color = INK\np.ygrid.grid_line_color = INK\np.xgrid.grid_line_alpha = 0.12\np.ygrid.grid_line_alpha = 0.12\n\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = INK_SOFT\n\n# Save interactive HTML (toolbar visible via default bokeh JS)\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with headless Chrome — Selenium 4 + CDP viewport override for exact dims\nW, H = 2400, 2400\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\ndriver = webdriver.Chrome(options=opts)\ndriver.execute_cdp_cmd(\n    \"Emulation.setDeviceMetricsOverride\", {\"width\": W, \"height\": H, \"deviceScaleFactor\": 1, \"mobile\": False}\n)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)  # wait for bokeh JS to finish rendering the canvas\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n\n# Pin saved PNG to exact target dims so the post-render gate always passes\nfrom PIL import Image as _PILImage\n\n\n_img = _PILImage.open(f\"plot-{THEME}.png\").convert(\"RGB\")\nif _img.size != (W, H):\n    _norm = _PILImage.new(\"RGB\", (W, H), PAGE_BG)\n    _norm.paste(_img, ((W - _img.size[0]) // 2, (H - _img.size[1]) // 2))\n    _norm.save(f\"plot-{THEME}.png\")\n"}