{"spec_id":"heatmap-rainflow","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\nheatmap-rainflow: Rainflow Counting Matrix for Fatigue Analysis\nLibrary: bokeh 3.9.0 | Python 3.13.13\nQuality: 91/100 | Updated: 2026-06-02\n\"\"\"\n\nimport os\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, LogColorMapper, LogTicker\nfrom bokeh.plotting import figure\nfrom PIL import Image as _PILImage\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\"\n\n# Imprint sequential colormap: brand green → blue (256 stops, single-polarity counts)\n_c0 = np.array([0x00, 0x9E, 0x73], dtype=float)  # #009E73\n_c1 = np.array([0x44, 0x67, 0xA3], dtype=float)  # #4467A3\nANYPLOT_SEQ256 = [\"#{:02X}{:02X}{:02X}\".format(*np.round(_c0 + (_c1 - _c0) * t / 255).astype(int)) for t in range(256)]\n\n# Data — Simulated rainflow counting matrix for a vehicle suspension component\nnp.random.seed(42)\n\nn_bins = 20\namplitude_edges = np.linspace(10, 210, n_bins + 1)\nmean_edges = np.linspace(-100, 300, n_bins + 1)\namplitude_centers = (amplitude_edges[:-1] + amplitude_edges[1:]) / 2\nmean_centers = (mean_edges[:-1] + mean_edges[1:]) / 2\n\namplitude_grid, mean_grid = np.meshgrid(amplitude_centers, mean_centers, indexing=\"ij\")\n\n# Most cycles are low-amplitude near the mean load\ncycle_density = np.exp(-0.5 * ((amplitude_grid - 40) / 30) ** 2 - 0.5 * ((mean_grid - 80) / 60) ** 2) * 5000\n# Secondary cluster at moderate amplitude\ncycle_density += np.exp(-0.5 * ((amplitude_grid - 90) / 25) ** 2 - 0.5 * ((mean_grid - 120) / 45) ** 2) * 800\n# Sparse high-amplitude cycles (rare severe events)\ncycle_density += np.exp(-0.5 * ((amplitude_grid - 150) / 20) ** 2 - 0.5 * ((mean_grid - 100) / 50) ** 2) * 50\n\ncycle_counts = np.round(cycle_density).astype(int)\ncycle_counts[cycle_counts < 3] = 0\n\n# Numpy boolean indexing for non-zero bins\namp_idx, mean_idx = np.where(cycle_counts > 0)\namp_flat = amplitude_centers[amp_idx]\nmean_flat = mean_centers[mean_idx]\ncount_flat = cycle_counts[amp_idx, mean_idx]\n\nsource = ColumnDataSource(\n    data={\n        \"amplitude\": amp_flat,\n        \"mean\": mean_flat,\n        \"count\": count_flat,\n        \"amp_label\": [f\"{v:.0f}\" for v in amp_flat],\n        \"mean_label\": [f\"{v:.0f}\" for v in mean_flat],\n    }\n)\n\namp_bin_width = float(amplitude_centers[1] - amplitude_centers[0])\nmean_bin_width = float(mean_centers[1] - mean_centers[0])\n\n# Log color mapper with Imprint sequential palette (wide count range needs log scale)\nmin_count = int(max(1, count_flat.min()))\nmax_count = int(count_flat.max())\ncolor_mapper = LogColorMapper(palette=ANYPLOT_SEQ256, low=min_count, high=max_count, nan_color=PAGE_BG)\n\ntitle = \"heatmap-rainflow · python · bokeh · anyplot.ai\"\n\n# Plot — square 2400×2400 for symmetric heatmap\np = figure(\n    width=2400,\n    height=2400,\n    title=title,\n    x_axis_label=\"Cycle Mean Stress (MPa)\",\n    y_axis_label=\"Cycle Amplitude (MPa)\",\n    toolbar_location=None,\n    tools=\"\",\n    x_range=(mean_edges[0] - mean_bin_width / 2, mean_edges[-1] + mean_bin_width / 2),\n    y_range=(amplitude_edges[0] - amp_bin_width / 2, amplitude_edges[-1] + amp_bin_width / 2),\n    min_border_bottom=160,\n    min_border_left=180,\n    min_border_top=110,\n    min_border_right=200,\n)\n\n# Heatmap rectangles — thin cell border aids visual hierarchy at transition zones\nr = p.rect(\n    x=\"mean\",\n    y=\"amplitude\",\n    width=mean_bin_width,\n    height=amp_bin_width,\n    source=source,\n    fill_color={\"field\": \"count\", \"transform\": color_mapper},\n    line_color=INK_SOFT,\n    line_alpha=0.2,\n)\n\n# Color bar — wider for 2400px canvas, theme-adaptive text\ncolor_bar = r.construct_color_bar(\n    width=120,\n    ticker=LogTicker(),\n    label_standoff=24,\n    major_label_text_font_size=\"34pt\",\n    major_label_text_color=INK_SOFT,\n    border_line_color=None,\n    background_fill_color=PAGE_BG,\n    padding=30,\n    title=\"Cycle Count\",\n    title_text_font_size=\"38pt\",\n    title_text_color=INK,\n    title_standoff=40,\n)\np.add_layout(color_bar, \"right\")\n\n# Hover tool for interactive HTML\nhover = HoverTool(\n    tooltips=[(\"Amplitude\", \"@amp_label MPa\"), (\"Mean\", \"@mean_label MPa\"), (\"Count\", \"@count\")], renderers=[r]\n)\np.add_tools(hover)\n\n# Theme-adaptive chrome\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = None\n\np.title.text_font_size = \"50pt\"\np.title.text_color = INK\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\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 = None\np.yaxis.axis_line_color = None\np.xaxis.major_tick_line_color = INK_SOFT\np.yaxis.major_tick_line_color = INK_SOFT\np.axis.minor_tick_line_color = None\n\n# No grid for clean heatmap aesthetic\np.xgrid.grid_line_color = None\np.ygrid.grid_line_color = None\n\n# Annotations — storytelling guides viewer to dominant cluster and rare events (theme-adaptive)\ndominant_label = Label(\n    x=100,\n    y=25,\n    text=\"↑ Dominant loading cluster (~5000 cycles)\",\n    text_font_size=\"34pt\",\n    text_color=INK,\n    text_font_style=\"bold\",\n    text_align=\"center\",\n    background_fill_color=ELEVATED_BG,\n    background_fill_alpha=0.9,\n)\np.add_layout(dominant_label)\n\n# Rare events cluster is centered at amplitude ~150 MPa; label placed above it pointing down\nrare_label = Label(\n    x=150,\n    y=193,\n    text=\"↓ Rare severe events\",\n    text_font_size=\"34pt\",\n    text_color=INK,\n    text_font_style=\"bold\",\n    text_align=\"center\",\n    background_fill_color=ELEVATED_BG,\n    background_fill_alpha=0.9,\n)\np.add_layout(rare_label)\n\n# Save interactive HTML (catalog artifact)\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with headless Chrome — use CDP setDeviceMetricsOverride so the\n# inner viewport is authoritative (--window-size alone is eaten by Chrome chrome\n# in headless mode and gives ~139px less height than requested).\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)\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n\n# Belt-and-braces: pin the saved PNG to exact dims so the post-render gate passes\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"}