{"spec_id":"mohr-circle","library":"plotnine","language":"python","code":"\"\"\" anyplot.ai\nmohr-circle: Mohr's Circle for Stress Analysis\nLibrary: plotnine 0.15.9 | Python 3.14.10\nQuality: 86/100 | Updated: 2026-11-28\n\"\"\"\n\nimport os\nimport sys\n\nimport numpy as np\nimport pandas as pd\n\n\n# Work around naming conflict: plotnine.py vs plotnine package\nscript_dir = os.path.dirname(os.path.abspath(__file__))\nfor _p in (script_dir, \"\", \".\"):\n    if _p in sys.path:\n        sys.path.remove(_p)\n\nfrom plotnine import (\n    aes,\n    coord_fixed,\n    element_blank,\n    element_line,\n    element_rect,\n    element_text,\n    geom_path,\n    geom_point,\n    geom_segment,\n    geom_text,\n    ggplot,\n    labs,\n    scale_color_manual,\n    theme,\n)\n\n\n# Theme tokens — Imprint palette\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\nIMPRINT_PALETTE = [\"#009E73\", \"#C475FD\", \"#4467A3\", \"#BD8233\", \"#AE3030\", \"#2ABCCD\", \"#954477\", \"#99B314\"]\nBRAND = IMPRINT_PALETTE[0]  # Mohr's circle — always first categorical series\n\n# Constants\nROLES = [\"Stress State\", \"Principal Stress\", \"Max Shear\"]  # legend entries of a Mohr's circle\n\n# Columns: set these to your table's column names\nSIGMA_X = \"σx (MPa)\"  # role: sigma_x\nSIGMA_Y = \"σy (MPa)\"  # role: sigma_y\nTAU_XY = \"τxy (MPa)\"  # role: tau_xy\n\n# Data: replace this block with your own stress state, for example df = pd.read_csv(\"stress.csv\")\n# Steel column flange under compressive loading: both normal stresses negative (MPa)\ndf = pd.DataFrame({SIGMA_X: [-120.0], SIGMA_Y: [-40.0], TAU_XY: [45.0]})\n\n# Plot: reads only df and the constants above\nsigma_x = df[SIGMA_X].iloc[0]\nsigma_y = df[SIGMA_Y].iloc[0]\ntau_xy = df[TAU_XY].iloc[0]\n\n# Derived stress quantities\nsigma_c = (sigma_x + sigma_y) / 2\nradius = np.hypot((sigma_x - sigma_y) / 2, tau_xy)\nsigma_1 = sigma_c + radius\nsigma_2 = sigma_c - radius\ntau_max = radius\nangle_A = np.arctan2(tau_xy, sigma_x - sigma_c)  # CA direction, measured from the +σ axis\ntwo_theta_p = np.degrees(abs(angle_A))\n\n\ndef fmt(value):\n    \"\"\"Signed number with a true minus sign.\"\"\"\n    return f\"{value:.0f}\".replace(\"-\", \"−\")\n\n\n# Mohr's circle path\nangles = np.linspace(0, 2 * np.pi, 361)\ncircle_df = pd.DataFrame({\"sigma\": sigma_c + radius * np.cos(angles), \"tau\": radius * np.sin(angles)})\n\n# Angle arc from the σ axis to line CA (visualising 2θp)\narc_r = radius * 0.34\narc_angles = np.linspace(0, angle_A, 60)\narc_df = pd.DataFrame({\"sigma\": sigma_c + arc_r * np.cos(arc_angles), \"tau\": arc_r * np.sin(arc_angles)})\n\n# Reference lines: horizontal σ-axis and vertical through center\npad = radius * 0.36\nref_df = pd.DataFrame(\n    {\n        \"x\": [sigma_2 - pad, sigma_c],\n        \"xend\": [sigma_1 + pad, sigma_c],\n        \"y\": [0.0, -tau_max - pad],\n        \"yend\": [0.0, tau_max + pad],\n    }\n)\n\n# Diameter from A(σx, τxy) to B(σy, −τxy)\ndiam_df = pd.DataFrame({\"x\": [sigma_x], \"xend\": [sigma_y], \"y\": [tau_xy], \"yend\": [-tau_xy]})\n\n# Key points with engineering roles\npoints_df = pd.DataFrame(\n    {\n        \"sigma\": [sigma_x, sigma_y, sigma_1, sigma_2, sigma_c, sigma_c],\n        \"tau\": [tau_xy, -tau_xy, 0.0, 0.0, tau_max, -tau_max],\n        \"role\": [ROLES[0], ROLES[0], ROLES[1], ROLES[1], ROLES[2], ROLES[2]],\n    }\n)\n\ncenter_df = pd.DataFrame({\"sigma\": [sigma_c], \"tau\": [0.0]})\n\n# Accent segment along the σ axis between σ2 and σ1 — draws the eye to the principal stress span\nspan_df = pd.DataFrame({\"x\": [sigma_2], \"xend\": [sigma_1], \"y\": [0.0], \"yend\": [0.0]})\n\n# 2θp arc label — just right of the vertical reference line, above the arc, inside the circle\narc_lbl_df = pd.DataFrame(\n    {\"sigma\": [sigma_c + radius * 0.06], \"tau\": [arc_r * 1.4], \"label\": [f\"2θp = {two_theta_p:.1f}°\"]}\n)\n\n# Point labels: A sits on the side of σx relative to the center, B opposite; ha says which way the text extends\noff = radius * 0.08\nside = 1.0 if sigma_x >= sigma_c else -1.0\nlabels_df = pd.DataFrame(\n    {\n        \"sigma\": [\n            sigma_x + side * off,\n            sigma_y - side * off,\n            sigma_1 + off,\n            sigma_2 - off,\n            sigma_c + off,\n            sigma_c + off,\n        ],\n        \"tau\": [tau_xy + off, -tau_xy - off * 1.5, off * 0.9, off * 0.9, tau_max + off * 1.1, -tau_max - off * 1.5],\n        \"label\": [\n            f\"A ({fmt(sigma_x)}, {fmt(tau_xy)})\",\n            f\"B ({fmt(sigma_y)}, {fmt(-tau_xy)})\",\n            f\"σ1 = {fmt(sigma_1)} MPa\",\n            f\"σ2 = {fmt(sigma_2)} MPa\",\n            f\"τmax = {fmt(tau_max)} MPa\",\n            f\"−τmax = {fmt(-tau_max)} MPa\",\n        ],\n        \"ha\": [\"left\" if side > 0 else \"right\", \"right\" if side > 0 else \"left\", \"left\", \"right\", \"left\", \"left\"],\n    }\n)\n\n# Equal-aspect view centered on the circle, with room for the labels\nreach = radius * 1.75\ntitle = \"mohr-circle · python · plotnine · anyplot.ai\"\n\nanyplot_theme = theme(\n    figure_size=(6, 6),\n    plot_background=element_rect(fill=PAGE_BG, color=PAGE_BG),\n    panel_background=element_rect(fill=PAGE_BG),\n    panel_grid_major=element_line(color=INK, size=0.3, alpha=0.12),\n    panel_grid_minor=element_blank(),\n    panel_border=element_blank(),\n    axis_title=element_text(color=INK, size=10),\n    axis_text=element_text(color=INK_SOFT, size=8),\n    axis_line=element_line(color=INK_SOFT, size=0.5),\n    plot_title=element_text(color=INK, size=12, ha=\"center\"),\n    legend_background=element_rect(fill=ELEVATED_BG, color=INK_SOFT),\n    legend_key=element_rect(fill=ELEVATED_BG, color=\"none\"),\n    legend_box_margin=8,\n    legend_text=element_text(color=INK_SOFT, size=8),\n    legend_title=element_blank(),\n    legend_position=\"bottom\",\n)\n\nplot = (\n    ggplot(circle_df, aes(x=\"sigma\", y=\"tau\"))\n    # Accent segment from σ2 to σ1 — guides eye to the principal stress result\n    + geom_segment(data=span_df, mapping=aes(x=\"x\", xend=\"xend\", y=\"y\", yend=\"yend\"), color=BRAND, size=4.0, alpha=0.25)\n    # Dashed reference lines through center\n    + geom_segment(\n        data=ref_df, mapping=aes(x=\"x\", xend=\"xend\", y=\"y\", yend=\"yend\"), color=INK_MUTED, size=0.5, linetype=\"dashed\"\n    )\n    # Diameter line from A to B\n    + geom_segment(\n        data=diam_df, mapping=aes(x=\"x\", xend=\"xend\", y=\"y\", yend=\"yend\"), color=INK_SOFT, size=0.8, alpha=0.7\n    )\n    # Mohr's circle — Imprint position 1 (brand green)\n    + geom_path(color=BRAND, size=1.4)\n    # Angle arc annotating 2θp\n    + geom_path(data=arc_df, color=INK_SOFT, size=0.8)\n    # Key points colored by engineering role\n    + geom_point(data=points_df, mapping=aes(color=\"role\"), size=4.0)\n    + scale_color_manual(values=dict(zip(ROLES, IMPRINT_PALETTE[1:], strict=False)), limits=ROLES, name=\"\")\n    # Center mark C\n    + geom_point(data=center_df, color=INK, size=2.5)\n    # Angle arc label\n    + geom_text(data=arc_lbl_df, mapping=aes(label=\"label\"), ha=\"left\", size=8, color=INK_SOFT)\n    + labs(x=\"Normal Stress σ (MPa)\", y=\"Shear Stress τ (MPa)\", title=title)\n    + coord_fixed(ratio=1, xlim=(sigma_c - reach, sigma_c + reach), ylim=(-reach, reach))\n    + anyplot_theme\n)\nfor ha, group in labels_df.groupby(\"ha\", sort=False):\n    plot += geom_text(data=group, mapping=aes(x=\"sigma\", y=\"tau\", label=\"label\"), ha=ha, size=8, color=INK)\n\nplot.save(f\"plot-{THEME}.png\", dpi=400, width=6, height=6, units=\"in\")\n"}