<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ali Baghi Zadeh on Medium]]></title>
        <description><![CDATA[Stories by Ali Baghi Zadeh on Medium]]></description>
        <link>https://medium.com/@alibaghizade?source=rss-8e86e08deb77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P3habaoBmoI7cJB5LfYaUQ.jpeg</url>
            <title>Stories by Ali Baghi Zadeh on Medium</title>
            <link>https://medium.com/@alibaghizade?source=rss-8e86e08deb77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:45:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alibaghizade/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[When More Data Wasn’t the Answer: A Simulation Study of Magnetic Pipeline Inspection]]></title>
            <link>https://medium.com/@alibaghizade/when-more-data-wasnt-the-answer-a-simulation-study-of-magnetic-pipeline-inspection-46287632c970?source=rss-8e86e08deb77------2</link>
            <guid isPermaLink="false">https://medium.com/p/46287632c970</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[simulation-hypothesis]]></category>
            <category><![CDATA[physical-data-model]]></category>
            <category><![CDATA[magnetic-inspection]]></category>
            <dc:creator><![CDATA[Ali Baghi Zadeh]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 15:00:18 GMT</pubDate>
            <atom:updated>2026-09-24T15:00:18.201Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Building an end-to-end ML pipeline to learn what magnetic inspection signals can — and cannot — tell us.</em></p><p>This project is a simulation study. I didn’t collect field data, use an inspection tool, or try to build one. Because real magnetic inspection data isn’t available to the public, I built a physics-inspired generator to create a controlled environment for data analysis. This gave me known defects, known interference, repeated surveys, and results that I could easily check against the ground truth.</p><p>The final pipeline turns simulated walk-over surveys into a prioritized list of locations to inspect. My main goal is to show the parts of data work that are easy to overlook: data contracts, validation, spatial registration, leakage-aware evaluation, uncertainty, and deciding when a model has not earned a positive conclusion.</p><p><strong>1- The question isn’t “where is the strongest signal?”</strong></p><p>Magnetic inspection is difficult because the signal of interest is tiny relative to the ambient field and to other magnetic sources. In the simulation, the ambient field is about 48,800 nT, while defect-scale residuals can be around 25 nT. Welds and external metallic interference can be much stronger than the defect signal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43ZxCPSQE16awIpG7bfRXg.png" /><figcaption><strong>Figure 1 — Why a strong magnetic signal is not automatically a defect.</strong> The simulated raw total-field signal is dominated by the ambient field and sharp weld responses. Background removal exposes both simulated defects and external interference; the zoomed view shows why local shape and context matter more than peak amplitude alone.</figcaption></figure><p>The generator simulates a buried pipeline with different types of defects, welds, outside interference, shifting background fields, sensor noise, uneven walking speeds, varying heights, and lost GPS signals. It outputs data from a simulated three-sensor setup. Each sensor reports total field magnitude, not directional field components. While the sensors are set up along a virtual rod in the code, no real hardware was built.</p><p>Using total-field measurements creates a specific challenge: a reading only shows how a local disturbance aligns with the main background field. Because of this, certain defect angles look much weaker than they actually are. This is a limitation of how this simulation is set up, not a claim about real-world tools.</p><p>The core data science problem is simple: an external piece of metal can look just as strong and unusual as a real defect. Signal amplitude alone cannot separate them. Peak shape, local context, repeat-survey behavior, and carefully defined labels may help — but only if the measurement contains enough information to distinguish the classes.</p><p><strong>2- One pipeline, from raw survey to ranked indications</strong></p><p>The final project uses one coherent workflow:</p><ol><li><strong><em>Create fake survey data</em>:</strong> Generate synthetic surveys with known physical sources and clear ground truth.</li><li><strong><em>Import the raw files</em>:</strong> Track each raw survey using file hashing, so the original data stays untouched and easy to trace.</li><li><strong><em>Run quick health checks</em>:</strong> Automatically catch and isolate bad data instead of crashing the whole pipeline.</li><li><strong><em>Fix position along the pipe</em>:</strong> Figure out the exact distance along the pipeline by combining GPS, tracking movement from your last known spot, and matching known weld patterns</li><li><strong><em>Clean the signals &amp; group leads</em>:</strong> Filter out background noise, build features comparing sensor readings, and group strong signals into candidate defect spots.</li><li><strong><em>Test model performance</em>:</strong> Train and test detection, severity, classification, and defect-growth models using grouped splits that prevent data leakage.</li><li><strong><em>Rank top leads &amp; set quality gates</em>:</strong> Rank candidate spots based on a fixed follow-up budget and stop models from moving to production if they fail strict statistical checks.</li></ol><p>The three simulated heads (the three magnetic sensors) support two derived quantities. A first difference helps suppress background common to nearby heads. A second difference can suppress a linear background gradient. These are analysis features — not evidence for a new sensing design.</p><p><strong>3- Start by making the data trustworthy</strong></p><p>The <em>most useful engineering lesson</em> was that model training is downstream of data discipline. Each survey is checked at load time for schema and unit violations, implausible ranges, repeated values consistent with a stuck sensor, GPS jumps, and abnormal noise. Hard failures are quarantined with a report while other surveys continue. Raw data is content-hashed: re-ingesting identical bytes is a no-op, while different bytes under an existing identity are rejected. That protects reproducibility and makes a training result traceable to its inputs.</p><p><strong><em>I also tested background removal against a trap I built into my own code.</em></strong></p><p>A simple, synthetic background drift can easily make a matching filter look much better than it actually is. To avoid fooling myself with an overly convenient data generator, I swapped in real data from a geomagnetic observatory for the background noise.</p><p>My two-step noise removal method still worked well with this more unpredictable, real-world data — though it’s still worth remembering this is not a field test on a real pipeline.</p><p><strong>4- Testing had to use truly independent data</strong></p><p>A single survey has thousands of data points, but points close to each other look almost identical. Repeat surveys also scan the exact same defects multiple times. If you treat every data point or repeat run as a brand-new sample, your test results will look unnaturally confident.</p><p>To avoid this, the pipeline splits data by physical location and groups repeated scans together during testing. It also uses a realistic budget for follow-up inspections — a model only gets credit for defects that actually fit inside that budget. For comparison, I set up a simple, rule-based baseline. A smarter machine learning model has to prove it is undeniably better than this simple rule, not just get lucky on a single run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgJCAAjlubbos-JPOU0mJw.png" /><figcaption><strong>Figure 2 — The detector did not earn promotion. </strong>At the fixed follow-up budget, IsolationForest and the robust threshold baseline both achieve 0.106 recall. The estimated recall gap is 0.000, with a 95% confidence interval of −0.050 to +0.061, well short of the +0.150 lower-bound requirement for promotion.</figcaption></figure><p>This strict setup made one disappointing result very clear: the fancier model didn’t win. On this dataset, both the IsolationForest model and the simple baseline (global mean baseline — MAD) found the exact same percentage of defects (10.6%) within the inspection budget. The performance gap between them was zero. Because the model couldn’t prove it was better, the system blocked it from moving forward.</p><p>That red flag isn’t a bug in the code. It just means the software is doing its job: keeping models out of production until they actually earn their spot with solid proof.</p><p><strong>5- What the tests actually showed</strong></p><p>I stripped down the pipeline step by step to see how much each feature actually helped. Comparing the first two sensor heads gave a small but real improvement in finding defects. Adding more steps such as a second sensor comparison, height correction, or weld-pattern matching did not reliably improve detection, even when those changes affected the estimated locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K2t5GVfXplhF3u_fIFmvQ.png" /><figcaption><strong>Figure 3 — Software changes helped only a little</strong>; <strong>richer measurements helped more</strong>. The chart compares defect recall at the same follow-up budget. On the existing three-head scalar setup, calculating the first difference between heads produced a small but reliable improvement of +0.056 [0.014, 0.111]. The later processing steps did not produce reliable gains. The final bar is a simulated three-axis measurement — not another software feature — and reaches 0.611 recall, showing the potential value of measuring field direction rather than only total-field magnitude.</figcaption></figure><p>This is a useful result, not a failure to hide. It shows that mathematical processing cannot create information the sensors never captured. If a defect and an external metal object look too similar in the measurements, more complicated features cannot reliably tell them apart.</p><p>The classification test made that limitation clearer. The model had to distinguish actual defects from external magnetic objects. Under the final scalar, walked-survey simulation, only about one in three cases labelled as interference was actually interference. That is far too uncertain for real-world use. I kept this difficult test because an honest low score is more useful than a flattering score from an easier simulation.</p><p>I also tested whether the model could estimate severity, the synthetic strength assigned to each simulated defect. This value controls the size of the defect’s simulated magnetic signature and grows between repeat surveys. It is useful for testing prediction and uncertainty methods, but it is not a calculation of steel stress or a validated %SMYS measurement.</p><p>The severity estimates were not reliable enough. The model’s uncertainty ranges were designed to contain the true synthetic value 90% of the time, but they did so only 61.8% of the time. Simply predicting the average value did slightly better, at 66.7%. In other words, the model was not yet giving trustworthy severity estimates.</p><p>Growth prediction appeared to work because the simulated defects were programmed to grow by a regular 15% rule. That confirms the pipeline can reproduce a rule built into the simulator; it does not show that the model can forecast how real defects will grow.</p><p><strong>6- A clean test environment proved what went wrong</strong></p><p>The most useful experiment wasn’t trying another algorithm — it was testing a “what if” scenario. I generated a clean simulated test spool: known defects, no external interference, no welds, and accurate chainage. On that clean corpus, the same detector beat its baseline by +0.199 recall, with a 95% interval of +0.139 to +0.255, and localization improved from about 812 cm to 75 cm.</p><p>That does not mean you should train models on clean data to solve real-world problems. When I took the model trained on clean data and tested it on the messy, realistic dataset, its performance dropped sharply because it couldn’t handle interference it had never seen before. Clean data is great for diagnosing <em>why</em> a model fails, but it can’t replace realistic data for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAKViBMjl5YmbPlt30ABNw.png" /><figcaption><strong>Table 1 — The clean-room counterfactual diagnoses the failure.</strong> Removing interference, welds, and chainage error changes the detector from a field-control recall gap of −0.019 [−0.051, +0.019] and 812 cm localisation error to a clean-room gap of +0.199 [+0.139, +0.255] and 75 cm localisation error. This is a diagnostic counterfactual, not evidence of deployment performance.</figcaption></figure><p>The takeaway is more specific than just “the model failed.” In this simulation, getting more data isn’t the fix. The real issue is that real-world noise and interference hide the exact signals the model needs to tell a defect from harmless metal. More representative labels and better measurement assumptions may be worth studying, but the current evidence does not justify claiming that the detection model works.</p><p><strong><em>What I learned</em></strong></p><p>The project taught me that the model is only one component of an analysis pipeline. The durable parts are the contracts that prevent silent data changes, the validation that isolates bad surveys, grouped evaluation that prevents leakage, uncertainty intervals that show when a comparison is unresolved, and promotion gates that are allowed to say no.</p><p>The final result is intentionally grounded: a reliable simulation pipeline designed to show how magnetic inspection models <em>should</em> be tested. It doesn’t claim to solve real-world inspections or diagnose actual pipelines. Its biggest success is showing clear failures, explaining <em>why</em> they happened, and keeping attractive numbers from turning into false promises.</p><p><em>All data, labels, models, and metrics in this project are synthetic. They are intended for methodology and software demonstration only.</em></p><p>GitHub Repo: <a href="https://github.com/AliBaghizadeh/lsm-integrity.git">https://github.com/AliBaghizadeh/lsm-integrity.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46287632c970" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What It Took to Build a Trustworthy Onboarding Agent]]></title>
            <link>https://medium.com/@alibaghizade/what-it-took-to-build-a-trustworthy-onboarding-agent-9a2e3e61dcee?source=rss-8e86e08deb77------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a2e3e61dcee</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[evaluation]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <dc:creator><![CDATA[Ali Baghi Zadeh]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 17:40:26 GMT</pubDate>
            <atom:updated>2026-09-01T10:28:23.304Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Three iterations taught me that a useful onboarding agent needs less unchecked autonomy — and stronger evidence controls.</em></p><p>An onboarding assistant sounds simple on paper: connect a chatbot to company documents and let new employees ask questions.</p><p>In practice, standard RAG falls short. Internal information is often outdated, duplicated, contradictory, incomplete, or access-controlled. A system that provides a fluent answer without knowing whether the underlying evidence supports it isn’t trustworthy — it’s just persuasive.</p><p>The question that reshaped my project was: <strong>what should the system do when it does not know?</strong></p><p>I built the same onboarding-agent idea three times. The outcome was not a more autonomous system. It was a more disciplined one.</p><p><strong>1- Start with clear response modes</strong></p><p>Before tweaking prompts or switching models, I defined a strict answer contract. Every response had to map to one of four specific modes: answer, clarify, unavailable, or decline.</p><p>Those distinctions are critical:</p><ul><li><strong>unavailable:</strong> A question is clear, but unsupported by the approved knowledge base.</li><li><strong>clarify:</strong> A question is too vague or missing key context to answer safely.</li><li><strong>decline:</strong> A question requests information outside the system&#39;s evidence or permission boundaries.</li></ul><p>Treating all three as a generic refusal might simplify system design, but it makes the product far less useful. New employees need to know whether they should rephrase their question, ask a colleague, or stop looking for restricted information altogether.</p><p>I also built an evaluation dataset early on. It covered standard queries, typos, ambiguous requests, conflicting dates, exact quantities, unsupported claims, and prompt-injection attempts. I measured retrieval quality, citation accuracy, response mode selection, abstention rate, and answer completeness separately. A strong final answer can easily hide weak retrieval, while a model that refuses everything might appear safe while being entirely useless.</p><p><strong>1.1 Project A: a simple RAG baseline</strong></p><p>The first version was a fixed RAG pipeline (Figure 1):</p><pre>question -&gt; retrieval -&gt; grounded draft -&gt; evidence check -&gt; cited answer</pre><p>Each retrieved chunk retained a stable source identifier, and images were transcribed during ingestion so visual content remained searchable. The system was intentionally simple: the verification step could not route the workflow back for a follow-up search.</p><p>That simplicity made failures straightforward to diagnose. The baseline quickly revealed classic RAG vulnerabilities: semantic search could miss exact technical terms, models could misapply related numerical data, temporal answers often omitted critical context, and ambiguous questions frequently yielded confident yet unsupported answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URKeyffaRJVQ_chWl4RDFw.png" /><figcaption>Figure 1. Project A: A fixed, one-pass RAG baseline with dense retrieval, optional figure QA, and single-pass verification.</figcaption></figure><p>The lesson was clear: build a complete, measurable baseline before adding agent loops. Otherwise, extra complexity only makes failures harder to understand.</p><p><strong>1.2 Project B: better retrieval and bounded recovery</strong></p><p>The second version combined dense vector retrieval with BM25 keyword search, then fused and reranked the results (Figure 2). This significantly improved coverage for repository names, abbreviations, version strings, and misspellings — the exact kinds of terminology common in internal documentation.</p><p>It also introduced a limited recovery loop. After drafting an answer, an evidence verifier could request a narrower follow-up search if the initial evidence proved insufficient. The loop was strictly capped: it stopped after a small number of retries, once enough evidence was found, or when no new information appeared.</p><p>This represented a useful, healthy form of autonomy: the system could recover from a weak initial search without spiraling into open-ended, unpredictable behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uBGW5IAHypcd2sqicspDA.png" /><figcaption>Figure 2. Project B: Hybrid retrieval, an intent gate, and a bounded evidence-driven re-search loop.</figcaption></figure><p>However, Project B exposed two critical limits:</p><ul><li><strong>Retrieval ≠ Relevance:</strong> Better retrieval can actually make a system less safe if it pulls up plausible documents that don’t actually answer the exact question. Finding a related figure is not the same as finding evidence for the exact quantity requested.</li><li><strong>Brittle Intent Gating:</strong> A keyword-based intent gate proved too rigid. It reliably recognized expected phrasing while completely missing equivalent questions framed in different words.</li></ul><p><strong>1.3 Project C: explicit controls for repeated failures</strong></p><p>The third version kept the overall workflow but replaced weak components with targeted controls (Figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K45PsEh8wRNhVvjIOAKpDQ.png" /><figcaption>Figure 3. Project C: A bounded onboarding-agent workflow with conservative routing, deterministic tools, evidence-based refinement, and operational<br> controls.</figcaption></figure><p>A lightweight classifier replaced the keyword-based rules for routing answer, clarify, and decline requests. It only stopped a request early when operating at high confidence; uncertain cases proceeded directly to retrieval. I deliberately omitted unavailable from the initial classifier because availability is an evidence-based decision—the system must search before it can verify that an answer is truly missing.</p><p>Exact quantities followed a much stricter path: retrieval identified the documented formula alongside its source, deterministic code performed the calculation, and the model simply explained the output. This stopped the LLM from treating nearby numerical data as factual proof.</p><p>Time-based comparisons were given a clear output contract: whenever a query compares different years or software versions, the response must preserve both data points and explicitly distinguish the historical context from the current state. This is better than hard-coding a sentence for one test case; it creates a general rule that can apply to new questions.</p><p>Finally, the service became observable. Each request carried citations, retrieved sources, tool traces, timing information, and audit records. Without that information, an incorrect answer is just an anecdote. With it, the failure can be traced to retrieval, evidence selection, calculation, generation, or another specific component.</p><p><strong>2. What model testing taught me</strong></p><p>I compared hosted and local models while keeping retrieval, prompts, tools, and evaluation constant. No model was universally best (Figure 4). Some produced more reliable structured output; some were better options for private deployment after calibration; others handled response modes well but struggled with citation selectivity or figure evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YR7hv_0MgxZrHe0g2rlAQg.png" /><figcaption>Figure 4. These are development-split results from an LLM-based judge, not a general model ranking; retrieval, prompts, tools, and evaluation conditions were held constant. The Gemini model is gemini-3.1-flash-lite, via Google AI Studio’s OpenAI-compatible endpoint. The context window for both open models has changed to 8 K.</figcaption></figure><p>The important conclusion was that model choice is part of the architecture, not a substitute for it. A stronger model does not remove the need for provenance, permission checks, calculation safeguards, bounded retries, and held-out evaluation. Figure 5 compares some metrics on the same test for all 3 models. All three models were run through the same workflow on the 30-question development split. Held-out sets were reserved for later transfer testing; GPT-OSS was screened only on the 30-question development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZtCBMgtRyCL8lVSq0ZC5A.png" /><figcaption>Figure 5. Development-split model comparison. Under the same RAG workflow, Gemini achieved the highest answer-correctness score, while GPT-OSS had the weakest citation selection. GPT-OSS was not evaluated on sealed splits.</figcaption></figure><p><strong><em>Note:</em></strong><em> Semantic answer correctness was evaluated using </em><em>gemini-3.1-flash-lite. On 16 balanced, human-labeled calibration controls, the judge model achieved perfect agreement with human annotations (Cohen’s kappa = 1.00). While this validates alignment on a small control set, it does not guarantee universal judge accuracy—and since Gemini was also evaluated as a candidate model, self-family bias remains a potential factor.</em></p><p><strong>3. A practical architecture for a smaller company</strong></p><p>For a company with fewer than 1,000 employees, I would start with one service and one bounded workflow:</p><pre>user<br>  -&gt; authentication and permission filter<br>  -&gt; conservative intent gate<br>  -&gt; hybrid retrieval over permitted sources<br>  -&gt; optional deterministic or multimodal tool<br>  -&gt; grounded draft with citations<br>  -&gt; evidence check and limited retry<br>  -&gt; deterministic response checks<br>  -&gt; answer, provenance, and audit trace</pre><p>Access control must happen before retrieval. The system should never retrieve a restricted document and rely on the prompt not to disclose it.</p><p>At this scale, a modest index and plain Python orchestration are often enough. Managed vector databases, graph frameworks, long-term memory, and multiple agents should be added only when the product has a measured need for them.</p><p><strong>The central lesson</strong></p><p>The hardest discipline is resisting the temptation to optimize away honest failures. A metric may expose an incomplete answer even when it sounds convincing. A held-out test set stops being held out once it influences a design change. Lower scores can sometimes reflect a more honest system.</p><p>Trustworthy agents come from clear responsibility boundaries: retrieval finds evidence; code handles hard constraints and arithmetic; the model interprets and explains; verification judges sufficiency; and the service enforces identity, permissions, and traceability.</p><p>&gt; <strong>Agentic design is not about maximizing model autonomy. It is about deciding where autonomy helps the system recover, then surrounding it with evidence, limits, and measurement.</strong></p><p>References:</p><p>I found these books interesting, though I just read the relevant chapters for this project.</p><p>1- Grootendorst, M., &amp; Alammar, J. (2026). <em>An Illustrated Guide to AI Agents: Building Autonomous Systems with LLMs, Tools, and Memory</em>. O’Reilly Media. <a href="https://learning.oreilly.com/library/view/an-illustrated-guide/9798341662681/">https://learning.oreilly.com/library/view/an-illustrated-guide/9798341662681/</a></p><p>2- Lanham, M. (2026). <em>AI agents in action</em> (2nd ed.). Manning Publications. <a href="https://learning.oreilly.com/library/view/ai-agents-in/9781633434530/">https://learning.oreilly.com/library/view/ai-agents-in/9781633434530/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a2e3e61dcee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Forecasting App That Knows When Not to Forecast]]></title>
            <link>https://medium.com/@alibaghizade/building-a-forecasting-app-that-knows-when-not-to-forecast-abebc08d9b86?source=rss-8e86e08deb77------2</link>
            <guid isPermaLink="false">https://medium.com/p/abebc08d9b86</guid>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[in-situ-gas-analyzer]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Ali Baghi Zadeh]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 08:49:22 GMT</pubDate>
            <atom:updated>2026-06-12T10:16:09.263Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A practical look at R&amp;D time series, seasonality, Gaussian peak fitting, model contracts, and human-reviewed inference</strong></p><p>Most forecasting demos begin with a clean dataset and end with a prediction chart. Real R&amp;D, metrology, instrument, and process data rarely follow that script. Measurements can be incomplete, experiments can run for different lengths of time subject to external factors like temperature, pressure, different gases, etc., then periodic behavior can appear and disappear, and a model can receive data that looks valid while being far outside what it learned.</p><p>I built <strong>**Forecast Platform**</strong> to explore the engineering around the forecast, not only the forecast itself. The application connects data review, chronological preprocessing, exploratory signal analysis, all main steps which usually are undermined in high-tech R&amp;D, and then it brings data into model training, inference governance, and result comparison in one interactive workflow. The inspiration for this work began with experimental reaction time-series data from mass spectrometry data with applications in XPS and in-situ electron microscopy [1]; the same design can apply to laboratory measurements, metrology instruments, industrial processes, environmental sensors, and equipment monitoring.</p><p>The central question is not only “What will happen next?” It is also “Should this model be trusted on this data?”</p><p><strong>From raw observations to a reviewed forecast</strong></p><p>The app follows a guided workflow rather than sending uploaded data directly into a model (Image 1). It silently undergoes full ETL and EDA processes common to time series forecasting [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3vU2ieFVLJkajrWlPhnAw.png" /><figcaption>Image 1: Forecast Platform workflow overview. It connects domain review, forecasting, and inference.</figcaption></figure><p>The main stages are:</p><ul><li>Review the uploaded data and its schema.</li><li>Split observations chronologically to reduce leakage risk.</li><li>Inspect patterns, periodicity, and selected intervals.</li><li>Train and compare XGBoost and LSTM models.</li><li>Bind trained models to their preprocessing and feature contracts.</li><li>Review new observations before inference.</li><li>Produce separate forecasts for every approved model.</li></ul><p>The Streamlit interface acts as the reviewer journey. It places evidence before decisions and makes blocking conditions visible. A FastAPI endpoint demonstrates how the same validated batch-inference workflow can be called by another service. This separation matters. A convenient interface should not silently weaken the rules used by the underlying forecasting pipeline.</p><p><strong>Seasonality is not always a fixed calendar</strong></p><p>In business forecasting, seasonality often means a repeated daily, weekly, or annual pattern. Scientific and industrial process signals can be more complicated. A cycle may emerge only during one operating regime. Its period may change as temperature, pressure, or other process conditions change. Multiple periodic components may also overlap. The platform therefore examines periodicity at several levels (Image 2):</p><ul><li>A <strong>**global periodogram**</strong> identifies strong candidate periods across a signal.</li><li>A <strong>**rolling spectrogram**</strong> shows how spectral power changes over time.</li><li>Window-level peak extraction identifies the strongest local periods.</li><li><strong>**Fourier components**</strong> reconstruct and quantify selected repeating patterns.</li></ul><p>The global view answers, “Which cycles are important overall during the whole experiment?” The rolling view asks, “Are those cycles stable, or do they appear only during certain parts of the experiment?”. It answers this question directly: “What external parameters are driving those cycles at a certain time and external parameter(s)?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzfGAvGyh8CycbmbH-NlaA.png" /><figcaption>Image 2. The App identifies periodic regions and suggests them, whereas the user is allowed to accept, remove, add more, or expand/reduce the current interval. It is also important to choose the train/validation split wisely. The app tries to avoid the split in the middle of the identified intervals.</figcaption></figure><p>The App detects periods for the user. The app does not automatically treat every detected period as a valid interval. It analyzes the training and validation datasets separately and uses rolling periodograms to identify<br> candidate repeating timescales within different parts of each signal. It then examines the original time-domain signal for prominent peaks that repeat at approximately those timescales.</p><p>A candidate interval must contain at least four cycles with reasonably consistent spacing between peaks. Candidates with unstable periods, unusually large gaps, or insufficiently prominent peaks are rejected. The app then fits Fourier components to each remaining candidate and checks whether the fitted repeating pattern sufficiently represents the observed signal. When multiple candidates overlap, it retains the strongest non-overlapping intervals based on cycle count, Fourier agreement, and period stability.</p><p>These automatically detected intervals are only proposed starting points (Image 2). The reviewer can inspect the signal, Fourier fit, periodogram, folded seasonal profile, autocorrelation, and optional Gaussian peak fitting. The reviewer can also resize an interval, add a missed interval manually, and accept or reject each proposed interval. Only explicitly accepted intervals are used during model training.</p><p><strong>Why add Gaussian peak fitting?</strong></p><p>Periodicity tells us that a pattern repeats. It does not necessarily explain the shape inside each cycle. For a selected periodic interval, one cycle may contain a single broad peak. Another may contain two overlapping peaks produced by different mechanisms or process phases. Looking only at the maximum value can miss that structure. This also depends on the underlying physical or chemical mechanisms of the phenomena under investigation during the experiment. Only a domain expert can properly interpret the meaning of the peaks.</p><p>The application includes optional Gaussian peak fitting for this selected-region analysis. The app only helps the expert to identify such features and propose properties like frequencies. Each cycle is compared using:</p><ul><li>A linear baseline plus one Gaussian peak.</li><li>A linear baseline plus two Gaussian peaks.</li></ul><p>The preferred model is selected only when the two-peak fit improves the Bayesian Information Criterion, or BIC, by a configured margin. This discourages adding a second peak simply because a more complex curve can fit noise more closely.</p><p>When two peaks are supported, the analysis records quantities such as (Image 3):</p><ul><li>The lag between peaks;</li><li>Each peak’s amplitude and width;</li><li>The area under each Gaussian component;</li><li>The ratio between the second and first peak areas, and</li><li>The fraction of cycles that support a two-peak interpretation.</li></ul><p>Gaussian peak area is calculated from the amplitude and width. Depending on the domain, it can provide a useful selected-region proxy for the contribution represented by a peak. It still requires calibration, a defensible baseline, and a reasonable peak-shape assumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfO4CoS2M7DiZMKkjjNXpQ.png" /><figcaption>Image 3. a. The interval region detected by the App shows poor Gaussian peak fitting because of the additional overlapped peak. Image 3. b shows the two Gaussian peak fittings that cover all cycles. In most cases, using the proposed fitting by App will result in proper training and inference results in similar cycles.</figcaption></figure><p>This feature is deliberately optional. Running Gaussian decomposition across every signal and every candidate interval would create a large amount of analysis without guaranteeing a useful interpretation. The app uses it only after a reviewer selects a scientifically relevant region.</p><p><strong>Two models, two kinds of evidence</strong></p><p>Forecast Platform compares XGBoost and LSTM models without collapsing their results into one anonymous ensemble output. XGBoost works with a tabular feature representation containing information such as lags, rolling statistics, expanding history, Fourier position, and interval context. The LSTM uses ordered input sequences and can learn temporal relationships from recent history [3].</p><p>The app keeps its parameters, metrics, predictions, and plots separate [Image 4]. This is important because two models can produce similar aggregate errors while failing in different regimes. A reviewer should be able to ask:</p><ul><li>Which model performs better during periodic intervals?</li><li>Does one model respond more reliably when experimental conditions change?</li><li>Is the improvement consistent, or driven by a small part of the timeline?</li><li>Does the model still receive the inputs it was trained to use?</li></ul><p>The goal is not to declare one algorithm universally better. It is to make their behavior inspectable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eU9Ssyakx7e_u645KjFxNA.png" /><figcaption>Image 4. a) The observed versus predicted plots for XGBoost forecasting with learning rate = 0.05<br> (Parameter that controls how much each new tree changes the model), maximum depth = 8<br>(Parameter that controls tree complexity) and num_boost_round = 200 (Parameter that controls the number of sequential trees created during training). Image 4. b) The observed versus predicted plots for LSTM forecasting with sequence length = 103 (Parameter that controls the number of previous observations provided to predict the next value), hidden size = 32 (Parameter that controls the number of internal LSTM features used to represent temporal patterns), and number of layers= 2 (Parameter that controls the depth of the stacked LSTM). The default number of epochs is 6.</figcaption></figure><p><strong>A model contract prevents the wrong forecast from looking valid</strong></p><p>A trained model file is not enough to reproduce or safely use a forecast. The platform publishes a model contract that binds the checkpoint to its target, forecast horizon, expected feature columns, approved preprocessing evidence, and artifact hashes.</p><p>Before inference, the app verifies that the selected model still matches that contract. This helps detect stale checkpoints, modified artifacts, wrong targets, and incompatible feature sets (Image 5). This is a software control, but it protects domain interpretation. A prediction from the wrong model can still look plausible on a chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbMrNGxcn4RqZSn_QpVpIQ.png" /><figcaption>Image 5. The selected signal by the app from the trained dataset and the inference dataset (new data), which shows the shape change (5.a) and distribution change (5.b). This is the responsibility of the user to analyze the shift or drift in new data, and the app only flags the changes in features and datasets. Even though the app allows for proceeding with inference, the results might not be correct when there is a significant amount of change in the trained data and inference data.</figcaption></figure><p><strong>Drift should start a review, not end the conversation</strong></p><p>New experiments are expected to be different. Their duration, time origin, external parameters like temperature, process context, or signal ranges may change (Image 5). If every difference is treated as a failure, the forecasting system becomes unusable. If every difference is ignored, the model can be trusted far beyond its evidence. The inference workflow separates three situations:</p><p>1. <strong>**Expected novelty**</strong> remains visible but does not automatically block inference.</p><p>2. <strong>**Model-support shift or reduced completeness**</strong> requires an identified reviewer, justification, and explicit approval.</p><p>3. <strong>**Integrity, leakage, missing input, or invalid-contract failures**</strong> block inference.</p><p>I believe that the power of forecasting in experimental time series data is not just to build a model that can predict new data. Rather, it lies in the fact that if the model trained on previous experiments can successfully predict the new experimental data, it might imply that both experiments are quite similar in terms of underlying physics or chemistry. This fact emphasizes the importance of domain knowledge in scientific and technological forecasting using machine learning techniques.</p><p>Derived features are grouped by their physical source signal during support review. This prevents one changed measurement from casting many independent drift votes through its lag, rolling, and statistical derivatives. When inference is approved, every valid selected model runs and produces its own output. When inference is blocked, the app explains the cause, impact, and recovery action rather than presenting only a disabled button or traceback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyrWUajUi20TboHUCTzGiw.png" /><figcaption>Image 6. The result of the inference for each model trained on the training dataset (Image 2) using the same intervals shown in Image 2. Image 6. a) shows the inference performance using the XGBoost model with the default parameters of the app (Image 4. a). Image 6. b) shows the performance of the LSTM forecasting on new data using the same data as in Image 2 with the default parameters of the app for the LSTM model (Image 4. b).</figcaption></figure><p><strong>A local AI assistant summarizes evidence, not decisions</strong></p><p>An optional final workflow section includes a local Ollama assistant for R&amp;D and metrology reviewers. It receives a bounded structured summary of preprocessing, review status, existing metrics, interval reports, periodicity evidence, Gaussian-fit evidence, model results, and the latest inference governance state.</p><p>The assistant returns a concise briefing with key findings, model comparison, limitations, and recommended review actions. Its output is schema-validated and cached using a fingerprint of the supplied evidence and local model.</p><p>The boundary is important: the assistant cannot create forecasts, approve a model, change governance decisions, or read arbitrary files. It explains deterministic evidence and shows the reviewer exactly what evidence it received. Running the assistant through a local model also provides a practical option when instrument or process results should not be sent to an external service. The choice of the local model depends on the GPU VRAM of the system. I do not believe that one needs very complex model ( like 30B or more parameters) to pull out the information and creates a report.</p><p><strong>What this project taught me</strong></p><p>Building the forecasting models was only one part of the work. The more difficult and more transferable engineering questions were:</p><ul><li>How do we use the best practice ETL and EDA in time series data processing/cleaning?</li><li>How do we make chronological leakage controls visible?</li><li>How do we preserve domain review without making the workflow unusable?</li><li>How do we distinguish expected novelty from unsupported model inputs?</li><li>How do we prove that a checkpoint belongs to the preprocessing and features used at inference?</li><li>How do we expose multiple models without hiding meaningful disagreement?</li></ul><p>The resulting application is a production-oriented portfolio demonstrator, not a fully hardened production deployment. Real deployment would still require durable orchestration, immutable model promotion and rollback, stronger identity and access controls, calibrated alerting thresholds, and operational monitoring.</p><p>That limitation is intentional. The project focuses on making the complete measurement-to-forecast workflow understandable and reviewable before adding infrastructure that would hide it.</p><p>GitHub link to the repo of this story:</p><p><a href="https://github.com/AliBaghizadeh/in-situ-forecasting-platform.git">https://github.com/AliBaghizadeh/in-situ-forecasting-platform.git</a></p><h4><strong>References</strong></h4><p>[1] Claudiu Colbea et al, Correlated Operando Electron Microscopy and Photoemission Spectroscopy in Partial Oxidation of Ethylene over Nickel, ACS Catal. 2024, 14, 23, 17850–17861. (DOI: <a href="https://doi.org/10.1021/acscatal.4c04437)">https://doi.org/10.1021/acscatal.4c04437)</a></p><p>[2] Changquan Huang, Alla Petukhina, Applied Time Series Analysis and Forecasting with Python, Springer Cham, 2023. (DOI: <a href="https://doi.org/10.1007/978-3-031-13584-2)">https://doi.org/10.1007/978-3-031-13584-2)</a></p><p>[3] Ralf C. Staudemeyer, Eric Rothstein Morris, Understanding LSTM — a tutorial into Long Short-Term Memory Recurrent Neural Networks, 2019. (DOI: <a href="https://doi.org/10.48550/arXiv.1909.09586)">https://doi.org/10.48550/arXiv.1909.09586)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abebc08d9b86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From DFT to MLIP: A Lightweight Materials Modelling Pipeline for Semiconductor Metrology]]></title>
            <link>https://medium.com/@alibaghizade/from-dft-to-mlip-a-lightweight-materials-modelling-pipeline-for-semiconductor-metrology-a6a6958674a3?source=rss-8e86e08deb77------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a6958674a3</guid>
            <category><![CDATA[computation]]></category>
            <category><![CDATA[machine-learninig]]></category>
            <category><![CDATA[dft]]></category>
            <category><![CDATA[semiconductors]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Ali Baghi Zadeh]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 21:26:02 GMT</pubDate>
            <atom:updated>2026-03-05T21:26:02.175Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From DFT to MLIP: A Lightweight Materials Modelling Pipeline for Semiconductor Metrology</strong></p><p><strong>Why Modelling Matters in Semiconductor Metrology</strong></p><p>Modern semiconductor devices are engineered at the scale of atoms. As device dimensions shrink and new materials enter fabrication lines, understanding how atomic structures influence measurable signals becomes increasingly important.</p><p>Metrology tools — such as electron microscopy, X-ray techniques, and optical inspection — can capture extremely detailed information about materials. However, interpreting those signals is not always straightforward. Experimental observations alone often cannot reveal the underlying defect mechanisms responsible for device performance issues.</p><p>Materials modelling helps bridge this gap. By simulating how atoms arrange themselves and how defects form, modelling provides a reference framework for interpreting measurements [1].</p><p>For semiconductor materials such as <strong>gallium nitride (GaN)</strong>, modelling can help answer practical questions [2]:</p><ul><li>How do atomic defects affect properties?</li><li>What structures remain stable under realistic conditions?</li><li>What types of defects or interface quality might exist in the material?</li></ul><p>Traditionally, answering these questions requires <strong>density functional theory (DFT)</strong> — a quantum mechanical method widely used to compute energies and forces in materials. While DFT is extremely powerful, it is also computationally expensive, particularly when studying large structures or complex defects.</p><p>This is where machine learning is beginning to play an important role.</p><p><strong>The Challenge: Accuracy vs. Scale</strong></p><p>DFT calculations can describe materials with high fidelity, but they scale poorly with system size. A simulation containing a few dozen atoms may be manageable, but realistic semiconductor defects, interfaces, and extended structures can easily require hundreds or thousands of atoms.</p><p>This creates a familiar trade-off:</p><ul><li><strong>DFT:</strong> accurate but computationally expensive</li><li><strong>Large-scale simulations:</strong> necessary for realistic defects but difficult using quantum methods alone</li></ul><p>Machine-learned interatomic potentials (MLIPs) aim to bridge this gap [3]. Instead of solving the full quantum problem every time, an ML model learns the relationship between atomic configurations and the energies and forces produced by DFT [4]. Once trained, the model can evaluate new atomic structures orders of magnitude faster than DFT.</p><p>In practice, this leads to a hybrid workflow where:</p><ul><li><strong>DFT provides accurate reference data</strong></li><li><strong>Machine learning enables simulations at much larger scales</strong>.</li></ul><p><strong>A Minimal Pipeline: From DFT to MLIP</strong></p><p>To demonstrate this idea, I built a lightweight modelling pipeline using <strong>wurtzite gallium nitride (GaN)</strong> as a case study. GaN is widely used in power electronics, RF devices, and optoelectronics, making it a relevant material for semiconductor applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vo4b4uEWv8Rko1JOFmgP3g.png" /><figcaption>Figure 1: The schematic of the pipeline indicating the workflow of ingesting cif file, DFT calculation, MLIP training, and further validation/checks. The emergence of agents enables one to accelerate materials exploration with agentic information extraction and to summarize results with respect to literature or previous experiments.</figcaption></figure><p>The pipeline intentionally focuses on a simple but complete workflow:</p><pre>Structure generation → DFT labeling → dataset extraction → MLIP training → large-scale relaxation → validation</pre><p>Even though the demonstration dataset is small, the workflow can be easily extended to the larger industrial modelling pipelines.</p><p><strong>Essential Commands That Drive the Workflow</strong></p><p>Below are a few representative commands that illustrate how the pipeline works in practice. These commands highlight the key parameters typically tuned during modeling workflows.</p><p><strong>DFT Labeling</strong></p><p>The first step generates reference energies and forces using DFT.</p><pre>MLIP_GPAW_GPU_ECUT=350 python dft/scripts/tier_b_calculations.py - gpu - calc-type single_point - structure-ids GaN_bulk_sc_2x2x2 - max-structures 1 - maxiter 25 - conv-energy 1e-3 - conv-density 1e-2 - conv-eigenstates 1e-4 - mag-config no</pre><p>Important parameters include:</p><ul><li><strong>plane-wave cutoff energy</strong></li><li><strong>SCF convergence thresholds</strong></li><li><strong>maximum iteration count</strong></li></ul><p>These parameters control the stability and accuracy of the DFT calculation.</p><p><strong>Dataset Extraction</strong></p><p>Once DFT calculations finish, the results are collected and converted into a training dataset.</p><pre>python dft/scripts/extract_dft_data.py - max-atoms 30</pre><p>This step gathers completed calculations and writes them into training formats such as <strong>extxyz</strong>, which store atomic structures together with energies and forces.</p><p><strong>Training the ML Potential</strong></p><p>Next, a machine-learned interatomic potential is trained using the <strong>MACE framework</strong>. MACE is a modern neural network architecture designed specifically for atomistic simulations. Instead of treating atoms independently, it models how atoms interact with their neighbors by passing information through a graph representing the atomic structure. Each atom receives messages from nearby atoms, allowing the model to learn how local environments determine forces and energies.</p><pre>python mlip/scripts/train_mlip.py - max-epochs 80 - patience 10 - eval-interval 20 - energy-weight 10.0 - forces-weight 10.0</pre><p>The model learns how atomic structures map to forces and energies. Once trained, the ML potential can evaluate new configurations far faster than DFT.</p><p><strong>Validation Gates</strong></p><p>Before applying the model to larger systems, quick validation checks are performed.</p><p>Energy comparison example:</p><pre>python analysis/scripts/energy_gate.py - model path/to/model.model - dft-json dft/results/tier_b_results.json - device cuda - threshold 0.01 - case GaN_bulk_sc_4x4x4_relaxed:dft/structures/GaN_bulk_sc_4x4x4_relaxed.cif</pre><p>These simple “validation gates” ensure that the ML model remains reasonably consistent with the original DFT reference data.</p><p><strong>Scaling Simulations to Larger Structures</strong></p><p>With the trained ML potential, simulations can be applied to <strong>larger GaN supercells</strong> — containing hundreds of atoms rather than a few dozen.</p><p>The MLIP can relax these structures and estimate their energies and forces quickly. This allows exploration of defect configurations and structural variations that would otherwise be expensive to compute using DFT alone.</p><p>To maintain physical reliability, selected configurations are occasionally re-evaluated with DFT as spot checks.</p><p><strong>Connecting Structure to Metrology</strong></p><p>The ultimate goal of modeling in semiconductor workflows is not simply to compute energies — it is to connect <strong>atomic structure to measurable signals</strong>.</p><p>In this project, relaxed GaN structures can be used to generate synthetic atomic resolution electron microscopy images using simulation tools such as <strong>abTEM [5]</strong>, which can produce STEM-like images directly from atomic models. One can also calculate optical properties for the large supercells imposed on defects and stress/strain. The atomic structure can be validated by atomic resolution microscopy images.</p><p>By combining:</p><ul><li>atomistic modeling</li><li>machine-learned potentials</li><li>simulated observables</li></ul><p>We can begin to build a bridge between <strong>structure prediction and measurement interpretation</strong>.</p><p><strong>Why This Matters</strong></p><p>Although this demonstration pipeline is intentionally lightweight, it illustrates several ideas that are becoming increasingly important in semiconductor research:</p><p><strong>Hybrid modelling workflows</strong><br> Combining physics-based simulations with machine learning enables scaling beyond traditional computational limits.</p><p><strong>Data-driven materials modelling</strong><br> Even relatively small datasets can seed machine-learned models that expand exploration of atomic configurations.</p><p><strong>Integration with experimental observables</strong><br> Simulated structures can help interpret signals from microscopy and metrology tools.</p><p><strong>Reproducible computational pipelines</strong><br> Packaging modelling workflows into structured pipelines makes them easier to reproduce and extend.</p><p><strong>Looking Ahead</strong></p><p>Machine learning will not replace physics-based modelling, but it is rapidly becoming an important complementary tool. In semiconductor materials research, ML-assisted simulations may help accelerate tasks such as:</p><ul><li>defect exploration</li><li>interface modelling</li><li>interpretation of microscopy data</li><li>screening of new material structures</li></ul><p>As semiconductor devices continue to scale and material complexity increases, <strong>integrating modeling with metrology may become essential to future engineering workflows</strong>.</p><p><em>This project demonstrates a minimal, reproducible example of such a workflow: using DFT data to train a machine-learned potential and exploring larger GaN structures while maintaining a connection to experimental observables. The scripts of the project can be found on GitHub:</em></p><p><a href="https://github.com/AliBaghizadeh/A-Machine-Learning-Pipeline-for-Semiconductor-Materials-Modeling-GaN-Case-Study-.git">https://github.com/AliBaghizadeh/A-Machine-Learning-Pipeline-for-Semiconductor-Materials-Modeling-GaN-Case-Study-.git</a></p><h4>References:</h4><p>[1] Even, J., Pedesseau, L., Tea, E., Almosni, S., Rolland, A., Robert, C., Jancu, J. M., Cornet, C., Katan, C., Guillemoles, J. F., &amp; Durand, O. (2013). Density Functional Theory Simulations of Semiconductors for Photovoltaic Applications: Hybrid Organic-Inorganic Perovskites and III/V Heterostructures. <em>International Journal of Photoenergy</em>, <em>2014</em>(1), 649408. <a href="https://doi.org/10.1155/2014/649408">https://doi.org/10.1155/2014/649408</a></p><p>[2]Huaping Lei, Jun Chen, Pierre Ruterana; Comparative studies of interatomic potentials for modeling point defects in wurtzite GaN. <em>AIP Advances</em> 1 January 2023; 13 (1): 015015. <a href="https://doi.org/10.1063/5.0127110">https://doi.org/10.1063/5.0127110</a></p><p>[3] Ryan Jacobs, Dane Morgan, Siamak Attarian, Jun Meng, Chen Shen, Zhenghao Wu, Clare Yijia Xie, Julia H. Yang, Nongnuch Artrith, Ben Blaiszik, Gerbrand Ceder, Kamal Choudhary, Gabor Csanyi, Ekin Dogus Cubuk, Bowen Deng, Ralf Drautz, Xiang Fu, Jonathan Godwin, Vasant Honavar, Olexandr Isayev, Anders Johansson, Boris Kozinsky, Stefano Martiniani, Shyue Ping Ong, Igor Poltavsky, KJ Schmidt, So Takamoto, Aidan P. Thompson, Julia Westermayr, Brandon M. Wood,<br>A practical guide to machine learning interatomic potentials — Status and future, Current Opinion in Solid State and Materials Science, Volume 35,<br>2025, 101214, ISSN 1359–0286. <a href="https://doi.org/10.1016/j.cossms.2025.101214">https://doi.org/10.1016/j.cossms.2025.101214</a>.</p><p>[4] Vincent G. Fletcher, Albert P. Bartok, Livia B. Partay, Autonomous thermodynamically informed database generation for machine-learned interatomic potentials and application to magnesium. <br><a href="https://doi.org/10.48550/arXiv.2508.08864">https://doi.org/10.48550/arXiv.2503.09814</a></p><p>[5] Jacob Madsen and Toma Susi. The abTEM code: transmission electron microscopy from first principles. <em>Open Research Europe</em> 1:24, 2021. doi:<a href="https://doi.org/10.12688/openreseurope.13015.1">10.12688/openreseurope.13015.1</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a6958674a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From 30 Minutes to 15 Seconds: Automating SEM Microstructure Segmentation with MatSAM +…]]></title>
            <link>https://medium.com/@alibaghizade/from-30-minutes-to-15-seconds-automating-sem-microstructure-segmentation-with-matsam-9839c02b6df1?source=rss-8e86e08deb77------2</link>
            <guid isPermaLink="false">https://medium.com/p/9839c02b6df1</guid>
            <category><![CDATA[sem]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[material-analysis]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[Ali Baghi Zadeh]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 09:24:49 GMT</pubDate>
            <atom:updated>2026-02-06T09:26:36.742Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From 30 Minutes to 15 Seconds: Automating SEM Microstructure Segmentation with MatSAM + Lightweight Fine-Tuning</strong></h3><p>A materials engineer sits in front of an SEM (secondary electron microscopy) micrograph: click, drag, trace — repeat. After ~30 minutes, one 1024×1024 tile is annotated. With 500 images, that becomes ~250 hours of manual work.</p><p>Traditional computer vision methods promise automation but struggle on real SEM data: variable contrast, complex morphologies, beam artifacts, detectors, and noise. A threshold that works perfectly for one imaging condition might fail on the next.</p><p>This is the problem I set out to solve. Not just to automate segmentation, but to create a production pipeline that handles batch processing, enables fine-tuning on custom datasets, and autonomously recovers from failures.</p><p><strong>Part 1: Building on MatSAM — A Materials-Specialized Foundation</strong></p><p>In April 2023, Meta AI Research released the Segment Anything Model (SAM) [1] — a vision transformer trained on a massive corpus of natural images. While SAM excels at segmenting everyday objects (dogs, cars, furniture), it struggles with the specialized domain of materials microscopy. SEM images are grayscale, texture-dominated, and lack the discrete object boundaries SAM was trained to recognize. To bridge this gap, researchers developed MatSAM [2] — a training-free adaptation of SAM specifically designed for materials microstructure extraction. MatSAM introduces structure-aware prompt generation to guide SAM’s mask decoder toward material-specific features like grain boundaries and secondary phases.</p><p><strong>Current Pipeline: Image Processing + Optional Fine-Tuning</strong></p><p>MatSAM is a strong baseline, but two things break it in practice:</p><ol><li>Image variability: contrast/noise/artifacts change with detector, materials, and beam — one fixed preprocessing recipe won’t fit all.</li><li>Silent failures: the model can miss faint boundaries/phases without obvious warnings, especially on new materials or imaging regimes.</li></ol><p>We can address both challenges:</p><ul><li>Diagnostics + auto-rescue: score image quality and segmentation sanity checks, try controlled brightness/contrast variants to recover weak signals.</li><li>Optional fine-tuning: if the baseline is still insufficient, fine-tune only the mask decoder while keeping the encoder frozen.</li></ul><p>This approach has two advantages:</p><ol><li>Minimal Training Burden: Optional fine-tuning is only needed for specific datasets where the baseline fails. Fine-tuning ~4M-parameter decoder takes hours, not days, because the encoder stays frozen.</li><li>Data Efficiency: ~1,500 annotated images suffice, vs. millions needed for training from scratch. Annotation started from the original MatSAM weights, while the user can try different image contrasts to improve model performance.</li></ol><p><strong>Part 2: Implementation Guide</strong></p><p>The pipeline is organized into steps. You can skip any step that isn’t needed for your dataset.</p><p><strong>Info-bar removal</strong>: remove scale bars/overlays that can distract the model during segmentation. (preprocessing/remove_info_bar.py)</p><p><strong><em>Tiling/padding: </em></strong>MatSAM expects proper input size. I tile large images and pad partial tiles to 1024×1024. In the script, e.g. 921×1024 pixels, gets padded to 1024×1024 pixels.</p><pre>preprocessing/tile_images.py --input_dir --output_dir --tile_height 921 --tile_width 1024 --overlap 0.2<br># 0.2 is 20% overlap to prevent grain boundary truncation at tile edges</pre><p><strong><em>Inference:</em></strong> Run inference using either the original MatSAM weights or your own checkpoint. (preprocessing/auto_label.py)</p><p>Now compare the mask to the SEM tile. If MatSAM misses faint boundaries or phases, try image enhancement before fine-tuning — it’s cheaper and often enough. Enhancement boosts weak features, but it can also suppress others, so define the segmentation target first (grains vs. boundaries vs. secondary phases). For that reason, I keep separate workflows per objective.</p><p><strong><em>Image Enhancement:</em></strong> Run a small grid search (CLAHE + Frangi + bilateral smoothing [3]) using the gridsearch_single_image.py script on a few representative tiles to find settings that improve the feature of interest (multi-CPU supported). Grid search parameters are:</p><pre>    --scales 0.2 \                # Frangi filter scale (detects boundary thickness)<br>    --dog_sigma_small 1.0 \       # DoG small sigma (fine edge detection)<br>    --dog_sigma_large 10.0 \      # DoG large sigma (coarse edge detection)<br>    --dirt_thresholds 0.1 0.5 \   # Dirt removal sensitivity (higher = more aggressive)<br>    --clips 4.0 10.0 \            # CLAHE contrast enhancement (higher = more contrast)<br>    --blends 0.3 0.9 1.2 \        # Mix ratio: 0.0=full enhancement, 1.0=original,&gt;1.0=over-enhanced<br>    --output_dir &quot;output folder&quot;  # Where to save results</pre><p>Next, I re-run masking on the processed images using apply_rescue.py and save overlays for fast visual QC (recommended GPU for this stage).</p><p>Now we apply the result of the grid search on all images to create a final image dataset. The masking will be applied to the same images, and eventually, there will be a pair of (image, mask) for each image.</p><pre>apply_enhancement.py --input_dir &quot;data/tiles&quot; --output_dir &quot;data/images&quot; --scales 0.2 --dog_sigma_small 1.0 --dog_sigma_large 10.0 --dirt_threshold 0.5 --clip 10.0 --blend 0.9<br>python apply_rescue.py --all --input_dir &quot;data/images&quot; --output_dir &quot;data/masks&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHS9v0J9f_U6TCdnPt3osg.png" /><figcaption><strong><em>Figure 1.</em></strong><em> Same SEM tile with two blend ratios: B=0.9 (more weight on the original image) vs B=1.2 (over-enhanced). Small intensity changes can shift MatSAM’s masks (red arrows). Here, B indicates a blend ratio, the mix of the Raw image with the Enhanced (Frangi/CLAHE) image.</em></figcaption></figure><p><strong><em>Evaluation:</em></strong> You can evaluate the results of the grain analysis using analyze_grains.py script. It also helps to inspect <strong>summary statistics</strong> (CSV) to catch failures that look “okay” visually. You can evaluate the pipeline at three milestones:</p><pre># Output statistics are (a csv file):<br>grain_count: Number of grains detected<br>mean_area_um2: Average grain size (μm²)<br>median_area_um2: Median grain size (μm²)<br>std_area_um2: Size variation<br>mean_diameter_um: Average equivalent diameter (μm)<br>mean_aspect_ratio: Grain elongation (1.0 = circular)<br>mean_circularity: Grain roundness (1.0 = perfect circle)<br>total_boundary_length_um: Total boundary length (μm)<br>boundary_density_um_per_um2: Boundary length per area<br>coverage_fraction: % of image covered by grains<br>mean_nearest_neighbor_um: Average spacing between grains (μm)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCyfLhPRl4jSgOns_Vj-4Q.png" /><figcaption><em>Image 2: A total of 8,497 grains were analysed across 200 tiles. Mean Diameter is 74.3 μm. The size distribution (Plot a) shows a primary peak around 90 μm, as well as a significant population of fine grains (~20 μm), suggesting a bimodal distribution. The area histogram (Plot b) confirms a high frequency of smaller grains by area. Grain Morphology shows an aspect ratio of 2.09 in ©. This is a key finding — most grains are more than twice as long as they are wide. This suggests a strong directional texture. Circularity ~0.45 indicates irregular boundaries; together with aspect ratio, it points to non-equiaxed grains.</em></figcaption></figure><p><strong>Optional Fine-Tuning:</strong> Up to this point, masks are generated using either the original MatSAM weights or a previous checkpoint. For best results, add a small set of manually verified ground-truth masks (or masks from another trusted tool) and fine-tune the decoder. This is a trade-off between annotation time and computation; for very faint features, some manual labelling is usually unavoidable. Fine-tuning takes hours, depending on the GPU and dataset size.</p><pre>finetuning/train_sam.py --train_data &quot;data/images&quot; --mask_data &quot;data/masks&quot; --# Parameters explained:<br>--epochs: Number of training epochs (50 is a good start)<br>--batch_size: Images per batch (4 for RTX 5080, reduce to 2 if OOM)<br>--lr: Learning rate (1e-4 is default, safe for fine-tuning)<br>--output_dir: Where to save checkpoints and training logs<br>--val_split: Fraction of data for validation (0.2 = 20%)<br>--checkpoint: Base MatSAM weights to start from<br>--model_type: Model architecture (vit_l, vit_b, or vit_h</pre><p><strong>Part 3: Validation and Reproducibility</strong></p><p>For quality analysis, I recommend labelling some of the tiles manually as the ground truth. The rule of thumb is to have a mix of different images with different microstructure or contrast/brightness in your dataset. The evaluate_metrics.py script provides 5 standard computer vision metrics [4].</p><p><strong>1. IoU (Intersection over Union) — <em>The “Standard”:</em></strong> The overlapping area between your AI mask generated by MatSAM and the human mask as ground truth, divided by the total area covered by both. This is the most honest metric. A score of &gt; 0.85 shows an excellent match and &lt; 0.60 indicates a poor match.</p><p><strong>2. Dice Coefficient (F1-Score) — <em>The “Similarity” Score: </em></strong>Very similar to IoU, but it gives more weight to the overlap and how well the model captures the “mass” of the grains. It is usually slightly higher than IoU, and it is sensitive to the size of the objects.</p><p><strong>3. Precision — <em>The “Honesty” Score: </em></strong>Of all the pixels the AI labelled as “Grain”, how many actually <em>are</em> grains in the human version? High precision means the AI is not creating fake grains (low “false positives”). If precision is low, your AI is probably “bleeding” over the grain boundaries into the background.</p><p><strong>4. Recall — <em>The “Completeness” Score: </em></strong>Of all the actual grain pixels in the human mask, how many did the AI successfully find? High recall means the AI is not missing grains. If recall is low, your AI is probably being too conservative and leaving a lot of “empty space” or thick black lines where grains should be.</p><p><strong>5. Hausdorff Distance — <em>The “Boundary Quality” Score: </em></strong>Measures the maximum distance between the <em>edges</em> of the AI mask and the human mask. It looks at the shape accuracy of the boundaries and is measured in pixels. In this case, lower is better. A high Hausdorff distance means that even if the grain size is correct, the <em>boundary</em> is very wobbly or far away from where the real boundary is.</p><p>In summary, the pipeline is handy when one deals with large sets of SEM images, and it is recommended to fine-tune MatSAM on processed images when you need to work on the same materials and similar microstructures. The weights will be on your hand and can be used for similar SEM images.</p><p><strong>Acknowledgments.</strong> I thank <em>Dr. Claudiu Colbea</em> for sharing the SEM dataset (≈2,000–3,000 images) used in this work and for helpful discussions on in-situ SEM imaging conditions. The underlying experimental context is described in [5].</p><p><strong>Code &amp; Resources</strong></p><p><a href="https://github.com/AliBaghizadeh/sem-image--agent-segmentation">GitHub - AliBaghizadeh/sem-image--agent-segmentation: Automatic segmentation of scanning electron micrsocopy images of materials using agentic AI</a></p><p><strong>References</strong></p><p>[1] Kirillov, A., Mintun, E., Ravi, N., Mao, H., Rolland, C., Gustafson, L., Xiao, T., Whitehead, S., Berg, A. C., Lo, W.-Y., Dollár, P., &amp; Girshick, R. (2023). <em>Segment Anything.</em> arXiv:2304.02643.<br> [2] <em>C. Li, X. Han, C. Yao, and X. Ban, “MatSAM: Efficient Extraction of Microstructures of Materials via Visual Large Model,” arXiv preprint arXiv:2401.05638, 2024.</em><br> [3] Baghi Zadeh, A. (Dec 11, 2025). <em>Multi-scale pre-processing for SEM micrographs of line-like features</em>. Medium.</p><p><a href="https://medium.com/@alibaghizade/multi-scale-pre-processing-for-sem-micrographs-of-line-like-features-88303fb25631">Multi-scale Pre-processing for SEM Micrographs of Line-like Features</a></p><p>[4] Müller, D., Soto-Rey, I. &amp; Kramer, F. Towards a guideline for evaluation metrics in medical image segmentation. <em>BMC Res Notes</em> <strong>15</strong>, 210 (2022).</p><p>[5] Correlated Operando Electron Microscopy and Photoemission Spectroscopy in Partial Oxidation of Ethylene over Nickel, Claudiu Colbea, Milivoj Plodinec, Man Guo, Luca Artiglia, Jeroen Anton van Bokhoven, and Marc Willinger, ACS Catalysis 2024 14 (23), 17850–17861.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9839c02b6df1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-scale Pre-processing for SEM Micrographs of Line-like Features]]></title>
            <link>https://medium.com/@alibaghizade/multi-scale-pre-processing-for-sem-micrographs-of-line-like-features-88303fb25631?source=rss-8e86e08deb77------2</link>
            <guid isPermaLink="false">https://medium.com/p/88303fb25631</guid>
            <category><![CDATA[image-preprocessing]]></category>
            <category><![CDATA[feature-enhancement]]></category>
            <category><![CDATA[sem-imaging]]></category>
            <category><![CDATA[image-feature-extraction]]></category>
            <dc:creator><![CDATA[Ali Baghi Zadeh]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 13:19:54 GMT</pubDate>
            <atom:updated>2025-12-11T13:19:54.760Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<p><strong><em>Finding </em></strong>important line-like features in Scanning Electron Microscopy (SEM) images is hard because they are often faint, rare, and easily overshadowed by grain boundaries and surface artefacts. In many cases, grains are dominant in the image, and therefore the density of grain boundaries is much higher than line-like features, and surface artefacts (dirt, spots) introduce segmentation errors. To address the issue of distinguishing features like ferroelastic and similar line-like features from grain boundaries, I present a modular pre-processing pipeline combining (1) advanced line detection filters (Hessian-based filtering), (2) automated surface cleaning, and (3) specialized contrast and smoothing techniques (Contrast-Limited Adaptive Histogram Equalization, CLAHE, and bilateral filtering). The cleaned images can then be used as high-quality inputs for subsequent automated segmentation tools (like AI/Machine Learning models), significantly improving their ability to map material features.</p><h4>Introduction: The Invisible Challenge</h4><p>In materials science and correlating microstructure with physical and chemical properties of the materials, quantifying internal features such as domain walls is crucial. However, SEM micrographs often exhibit highly varying grain geometries, non-uniform contrast, and other features, like line-like features, which are faint in contrast and/or low in density compared to grain boundaries. Conventional segmentation methods often struggle with such heterogeneity and low-contrast features. To overcome these issues, a targeted pre-processing workflow is required to <em>boost line visibility</em> and <em>suppress artefacts</em> before segmentation.</p><p>A foundational method for enhancing elongated, line-like structures is a multiscale ‘vesselness’ filter, which looks at how brightness bends around each pixel to decide whether it belongs to a thin line or to a flat background [1]. Intuitively, the filter examines the local shape of the image and asks: Does this patch look more like part of a narrow tube or like a uniform region? This technique was originally developed for precise visualization and quantification of human vasculature in medical images such as Magnetic Resonance Angiography (MRA) and Computed Tomography Angiography (CTA) [1]. For readers with a math background, this is implemented by analysing the Hessian matrix at multiple scales and combining its eigenvalues into a response that is high for line-like structures and low for blobs or flat regions.</p><p>Meanwhile, techniques like CLAHE and bilateral filtering have been shown to improve feature visibility in low-contrast microscopy images [2, 3]. The pipeline is designed to serve as a high-quality input layer for subsequent machine learning models by addressing the limitations of relying on pixel intensity alone.</p><h4>Methods: Pre-processing Pipeline</h4><p>We use a three-stage pre-processing pipeline, implemented in the project’s <a href="https://github.com/AliBaghizadeh/SEM-contrast-enhancement">sem_line_enhancer</a> package, to prepare SEM micrographs for downstream segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hhFN2CYRL6UqPo-a3zUvA.png" /><figcaption>Image 1.a. A raw SEM micrograph showing line-like features with varying contrast around grain boundaries and bright surface artifacts, which complicates automated segmentation. 1.b. Another raw SEM micrograph of grain boundaries without line-like features.</figcaption></figure><h4>Stage 1: Targeted Feature Enhancement</h4><p>In the first stage, a multi-scale filter enhances faint, elongated lines. This method works by analyzing the image’s underlying shape — essentially detecting the unique ‘geometric fingerprint’ of tubular structures like ferroelastic lines. The filter is successful because it determines the principal directions of local curvature, allowing it to specifically find line-like structures and suppress isotropic regions. The filter analyzes the image across several different sizes or thicknesses (multi-scale, σ) to ensure lines of all widths are detected reliably [1].</p><p>In practice, the “lines” preset in our package uses scales σ ∈ {0.5, 1.0, 2.0} (in pixels) and a blending factor α = 0.25, which empirically provides strong line enhancement without amplifying noise. To come to this conclusion, a grid search was used on a wide range of values, and the top-performing parameters based on the std and mean of the contrast of the image after applying the set of parameters were chosen. In most cases, visual inspection follows the same trend as the calculated values.</p><pre># Multi-scale Hessian line enhancement (Frangi-style)<br>from sem_line_enhancer.enhancers import enhance_lines_frangi<br><br># Example parameters used for the &quot;lines&quot; preset<br>scales = (0.5, 1.0, 2.0)   # multi-scale probing in pixels<br>alpha  = 0.25              # blending factor between input and enhancement<br><br>enhanced_img = enhance_lines_frangi(<br>    normalized_input,<br>    scales=scales,<br>    alpha=alpha,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*OO1rzT1xQTZKrH4wcZPxww.png" /><figcaption>Image 2: Line Enhancement Effect. Comparison demonstrating how the Frangi filter enhances the internal ferroelastic lines of the raw image (a) to (d), making them distinct from the surrounding grain texture. a) raw image, b) base image, c) fused image, and d) lines.</figcaption></figure><h4><strong>Stage 2 — Cleaning the surface</strong></h4><p>The second stage suppresses surface contamination such as dust, small pits, and charging artefacts. In the preprocessed images, dirt and small artefacts usually appear as small, bright, roughly circular spots with noticeable local brightness variation compared to their surroundings (e.g., below 40 pixels and local standard deviation above roughly 10–15 gray levels). Bright “dirt” blobs are then removed by thresholding the Frangi output, labeling connected components, and inpainting qualifying spots using classical image inpainting schemes (fast marching and Navier–Stokes–based methods as implemented in OpenCV)</p><pre># Dirt blob detection and inpainting<br>from sem_line_enhancer.enhancers import safe_dirt_filter<br><br># Example parameters (from grid search &quot;M20&quot;, &quot;dirtT0.12&quot;)<br>threshold = 0.12   # normalized local std-dev threshold for detection<br>max_size  = 20     # maximum object radius/size in pixels<br><br>cleaned_img = safe_dirt_filter(<br>    enhanced_img,<br>    threshold=threshold,<br>    max_size=max_size,<br>)</pre><h4><strong>Stage 3 — Normalizing and sharpening</strong></h4><p>The final stage normalizes contrast and smooths non-essential texture. We begin with CLAHE. CLAHE improves contrast by dividing the image into small tiles and computing a custom contrast curve for each tile instead of treating the whole image at once. It computes specialized contrast transformation functions for distinct regions of the image, which results in enhanced local edge definitions. The ‘Contrast-Limited’ feature prevents the filter from over-amplifying noise in dark or featureless areas by limiting the amount of contrast increase applied locally. This ensures a sharp contrast without introducing unwanted artifacts.</p><p>In our work, CLAHE is applied with a clip limit between 15 and 25 and a small tile grid (e.g., 4×4 tiles) to boost local contrast without saturating bright regions. This is followed by a bilateral filter with a spatial scale d ≈ 4 pixels and intensity/space parameters around 30, which denoises within grains but keeps grain boundaries and ferroelastic lines sharp.</p><pre># Dirt blob detection and inpainting<br>from sem_line_enhancer.enhancers import safe_dirt_filter<br><br># Example parameters (from grid search &quot;M20&quot;, &quot;dirtT0.12&quot;)<br>threshold = 0.12   # normalized local std-dev threshold for detection<br>max_size  = 20     # maximum object radius/size in pixels<br><br>cleaned_img = safe_dirt_filter(<br>    enhanced_img,<br>    threshold=threshold,<br>    max_size=max_size,<br>)</pre><h4>Stage 4 — Parameter Grid Search and Tuning</h4><p>This section explains how the parameter values were chosen; it is mainly intended for readers who want to reproduce or modify the code and can be safely skipped on a first read. For each candidate parameter set, we look at simple image statistics such as minimum, maximum, mean, and standard deviation to find settings that increase contrast without making the image too bright or too dark overall (Image 3). Configurations with high standard deviation (strong local contrast) but a balanced mean intensity (avoiding saturation or overall darkening) are preferred. This procedure yields two practical presets, stored in sem_line_enhancer/presets.py:</p><ol><li>“lines” preset — optimized for ferroelastic or needle-like features, using relatively strong Frangi filtering (e.g., multi-scale σ ∈ {0.5, 1.0, 2.0} ) combined with more aggressive dirt removal to reveal faint internal lines.​</li><li>“boundaries” preset — tuned for grain-only micrographs, applying lighter Frangi weighting (or none) and placing more emphasis on CLAHE-based contrast normalization to cleanly highlight grain boundaries without over-enhancing line-like artefacts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxLYgNMOC4KRZ8fr0QY7gg.png" /><figcaption>Image 3: A diagnostic panel from the parameter grid search showing the Raw image, the Preprocessed image output by a specific parameter set (Frangi scales (0.5, 1.0, 2.0), CLAHE clip=25, tile=4), the resulting Histogram (indicating high, balanced contrast), and the successful Edges Overlay.</figcaption></figure><h4>Stage 5 — Difference-of-Gaussians</h4><p>In addition to the Frangi enhancement, the “lines” preset optionally adds a Difference-of-Gaussians (DoG) filter channel. The DoG filter adds an extra boost for features whose size falls between two blur scales (Gaussians with different standard deviations σ_small and σ_large), which makes it easier to highlight lines that are neither extremely thin nor very wide [4]. For our SEM data, we use σ_small = 1.0 and σ_large = 4.0 (in pixels) and weight this response by W_DoG = 1.0 before blending it with the Frangi vesselness and other channels. These DoG parameters are currently fixed (not included in the grid search), but they can be exposed to the grid search framework if needed.</p><p>In the implementation, these settings are defined in the “lines” preset and passed through the command-line interface in cli.py; runs that use — preset lines (or any preset with “use_dog”: true) will call enhance_lines_modular in sem_line_enhancer/enhancers.py with “use_dog”: true, “dog_sigma_small”: 1.0, “dog_sigma_large”: 4.0, and “w_dog”: 1.0, so the DoG channel is always included in the final line-map generation for that preset.</p><p><strong><em>In conclusion,</em></strong> our preprocessing approach addresses two major pitfalls in materials analysis: (i) faint internal lines below typical contrast thresholds and (ii) heterogeneity in grain scale across magnification. By transferring vessel-enhancement ideas from biomedical imaging to SEM micrographs, it is possible to improve line visibility. The combined use of CLAHE and the bilateral filter, carefully tuned for material micrographs, ensures enhanced contrast without grain boundary blowout. The segmentation pipeline benefits strongly from this preprocessing, significantly improving the base input quality for the downstream machine learning workflow.</p><p><strong><em>Please also check:</em></strong></p><p><em>The GitHub repo:</em></p><p><a href="https://github.com/AliBaghizadeh/SEM-contrast-enhancement">https://github.com/AliBaghizadeh/SEM-contrast-enhancement</a></p><p><em>The simple app to try out your own SEM image:</em></p><p><a href="https://huggingface.co/spaces/alibaghizade/SEM-contrast-enhancement">https://huggingface.co/spaces/alibaghizade/SEM-contrast-enhancement</a></p><p><strong>References:</strong></p><p><a href="https://link.springer.com/chapter/10.1007/BFb0056195">[1] Frangi, A.F., Niessen, W.J., Vincken, K.L., Viergever, M.A. (1998). Multiscale vessel enhancement filtering. In: Wells, W.M., Colchester, A., Delp, S. (eds) Medical Image Computing and Computer-Assisted Intervention — MICCAI’98. MICCAI 1998. Lecture Notes in Computer Science, vol 1496. Springer, Berlin, Heidelberg.</a></p><p><a href="https://www.sciencedirect.com/science/article/abs/pii/S0208521617300220">[2] Justin Joseph, J. Sivaraman, R. Periyasamy, V.R. Simi, An objective method to identify optimum clip-limit and histogram specification of contrast limited adaptive histogram equalization for MR images, Biocybernetics and Biomedical Engineering, Volume 37, Issue 3, 2017, Pages 489–497</a>.</p><p><a href="https://ieeexplore.ieee.org/document/6968381">[3] G. Yadav, S. Maheshwari and A. Agarwal, “Contrast-limited adaptive histogram equalization-based enhancement for real time video system,” <em>2014 International Conference on Advances in Computing, Communications and Informatics (ICACCI)</em>, Delhi, India, 2014, pp. 2392–2397.</a></p><p><a href="https://link.springer.com/article/10.1023/B:VISI.0000029664.99615.94">[4]. Lowe, D.G. Distinctive Image Features from Scale-Invariant Keypoints. International Journal of Computer Vision 60, 91–110 (2004).</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88303fb25631" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>