Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

How to build an ML Model.

Tutorials → Tutorial | Concept | How-to Guide | Reference


This Tutorial Teaches you to:

This tutorial demonstrates how to use machine learning for real-time anomaly detection on sensor data using FrameworX Script Classes.

Prerequisites:

Edge AI  with ML.NET (Tutorial) teaches you to create an MCP (Model Context Protocol) Tool that exposes production KPIs and historical data to AI models, enabling intelligent analysis of your industrial processes.

Prerequisites:

  • Complete Scripts & Data Enrichment (Tutorial)
  • Basic understanding of Script Classes
  • Tags configured for production metrics
In this page:

Table of Contents
maxLevel2
minLevel2
indent10px
excludeSteps
stylenone

Scripts → Tutorial | Concept | How-to Guide | Reference


Step 1:

Configure Historian
  1. Navigate to Historian → Tables
  2. Create table: ProductionData
  3. Add tags:
    • Tag.ProductionRate
    • Tag.Efficiency
    • Tag.QualityScore
    • Tag.DowntimeMinutes
  4. Set scan rate: 60 seconds
  5. Enable storage

Step 2: Create KPI Calculator Class

  1. Go to Scripts → Classes
  2. Create class: KPICalculator
  3. Configure as standard Methods class

csharp

public double CalculateOEE(double availability, double performance, double quality)
{
    return availability * performance * quality * 100;
}

public double GetAverageProduction(DateTime startTime, DateTime endTime)
{
    // Calculate average production rate over period
    double totalProduction = @Tag.TotalUnits;
    double hours = (endTime - startTime).TotalHours;
    return hours > 0 ? totalProduction / hours : 0;
}

public string GetProductionStatus()
{
    if (@Tag.ProductionRate > 100)
        return "High Performance";
    else if (@Tag.ProductionRate > 80)
        return "Normal";
    else
        return "Below Target";
}

Step 3: Create MCP Tool Class

  1. Create new class: ProductionMCPTool
  2. Select MCP Tool type
  3. Add decorated methods:

csharp

[MCPMethod(Description = "Get current production KPIs")]
public object GetCurrentKPIs()
{
    return new {
        ProductionRate = @Tag.ProductionRate,
        Efficiency = @Tag.Efficiency,
        OEE = @Script.Class.KPICalculator.CalculateOEE(
            @Tag.Availability, @Tag.Performance, @Tag.Quality),
        Status = @Script.Class.KPICalculator.GetProductionStatus(),
        Timestamp = DateTime.Now
    };
}

[MCPMethod(Description = "Get production history for specified hours")]
public object GetProductionHistory(
    [MCPParameter(Description = "Hours to look back")] int hours)
{
    var endTime = DateTime.Now;
    var startTime = endTime.AddHours(-hours);
    
    // Query historian
    var data = @Historian.Table.ProductionData.GetData(startTime, endTime);
    
    return new {
        Period = $"Last {hours} hours",
        AverageRate = @Script.Class.KPICalculator.GetAverageProduction(startTime, endTime),
        TotalUnits = @Tag.TotalUnits,
        DataPoints = data.Rows.Count
    };
}

[MCPMethod(Description = "Analyze production trend")]
public string AnalyzeProductionTrend(
    [MCPParameter(Description = "Time period in hours")] int periodHours)
{
    var current = @Tag.ProductionRate;
    var average = @Script.Class.KPICalculator.GetAverageProduction(
        DateTime.Now.AddHours(-periodHours), DateTime.Now);
    
    if (current > average * 1.1)
        return "Trending Up - Production improving";
    else if (current < average * 0.9)
        return "Trending Down - Requires attention";
    else
        return "Stable - Within normal range";
}

Step 4: Test MCP Tool

  1. Start runtime
  2. Verify KPIs calculating
  3. Check historian data collection
  4. Test with AI assistant:
    • "What are the current production KPIs?"
    • "Show me production history for last 8 hours"
    • "Analyze the production trend"

Edge AI with ML.NET (Tutorial)

This tutorial demonstrates using ML.NET 4.0 for real-time anomaly detection on sensor data using Script Tasks.

Prerequisites:

  • Complete Scripts & Data Enrichment (Tutorial)
  • Tags for sensor monitoring
  • ML.NET 4.0 references (included in FrameworX 10.1)

Step 1: Create Monitoring Tags

  1. Navigate to Unified Namespace → Tags
  2. Create tags:
    • Tag.SensorValue (Double) - Current reading
    • Tag.AnomalyScore (Double) - Detection score
    • Tag.IsAnomaly (Boolean) - Alert flag
    • Tag.Threshold (Double) - Detection threshold (default: 0.3)

Step 2: Create ML Detection Task

  1. Go to Scripts → Tasks
  2. Create task: AnomalyDetector
  3. Set trigger: Period = 1000ms
  4. Add code:

csharp

// Simple spike detection using ML.NET
using Microsoft.ML;
using Microsoft.ML.Data;

// Static ML context (initialized once)
if (@Tag.MLContext == null)
{
    @Tag.MLContext = new MLContext(seed: 0);
    @Tag.DetectionEngine = InitializeDetector();
}

// Data class for ML model
public class SensorData
{
    public float Value { get; set; }
}

public class AnomalyPrediction
{
    [VectorType(3)]
    public double[] Prediction { get; set; }
}

// Initialize detector (runs once)
private ITransformer InitializeDetector()
{
    var dataView = @Tag.MLContext.Data.LoadFromEnumerable(new List<SensorData>());
    
    var pipeline = @Tag.MLContext.Transforms
        .DetectSpikeBySsa(
            outputColumnName: "Prediction",
            inputColumnName: "Value",
            confidence: 95,
            pvalueHistoryLength: 30,
            trainingWindowSize: 90,
            seasonalityWindowSize: 30);
    
    return pipeline.Fit(dataView);
}

// Detection logic (runs every second)
var currentValue = (float)@Tag.SensorValue;

var data = new SensorData { Value = currentValue };
var prediction = @Tag.DetectionEngine.Transform(
    @Tag.MLContext.Data.LoadFromEnumerable(new[] { data }));

var result = @Tag.MLContext.Data
    .CreateEnumerable<AnomalyPrediction>(prediction, false)
    .First();

// Update tags with results
@Tag.AnomalyScore = result.Prediction[0];  // Spike score
@Tag.IsAnomaly = result.Prediction[0] > @Tag.Threshold;

// Log anomalies
if (@Tag.IsAnomaly)
{
    @Alarm.GlobalSettings.AuditTrail.AddCustomMessage(
        $"Anomaly detected: Sensor={currentValue:F2}, Score={result.Prediction[0]:F3}");
}

Step 3: Create Simple Simulator

  1. Create task: SensorSimulator
  2. Set trigger: Period = 500ms
  3. Add simulation code:

csharp

// Simulate normal sensor data with occasional spikes
Random rand = new Random();
double baseValue = 50.0;
double noise = rand.NextDouble() * 5 - 2.5;

// Inject anomaly occasionally (5% chance)
if (rand.NextDouble() < 0.05)
{
    @Tag.SensorValue = baseValue + (rand.NextDouble() * 30 + 20);  // Spike
}
else
{
    @Tag.SensorValue = baseValue + noise;  // Normal variation
}

Step 4: Create Monitoring Display

  1. Create display with:
    • Trend chart for SensorValue
    • Indicator for IsAnomaly
    • Text display for AnomalyScore
    • Threshold adjustment slider

Step 5: Test ML Detection

  1. Start runtime
  2. Observe sensor simulation
  3. Watch for anomaly detection
  4. Adjust threshold as needed
  5. Check audit trail for logged anomalies

Next Steps

  • Advanced MCP Tools → Complex multi-tool scenarios
  • ML.NET Models → Regression and classification
  • Edge Computing → Deploy to field devices

Create Value Simulator

  1. With these tags created: Pressure (Integer) and AnomalyBuffer (Text Array 9 position)

  2. In Devices → Protocols, select the Value Simulator and click the "New Channel..." button.

  3. In Devices → Points, create points to generate simulated data.

TagName

Node

Address

DataType

AccessType

Tag.Pressure

Node.ValueSimulator1Node1

INTEGER:0,100,1

Native

AccessType.Read

For more information about the Value Simulator, see: Value Simulator Connector

Step 2: Create ML Anomaly Detection Script Class

  1. Navigate to Scripts → Classes

  2. Click the "Create a New Class" button

  3. In "Import code from Library:", select AnomalyML

  4. Open the script and uncomment the line that returns the detection to the AnomalyBuffer tag in Check() method.

Step 3: Create an Expression

This expression will check for anomalies each time the tag value changes.

  1. Go to Scripts → Expressions

  2. Create the following expression:

ObjectName

Expression

Execution


Script.Class.AnomalyML.Check(<DesiredTag>)

OnChange

Where:

  • <DesiredTag> is the tag you want to monitor for anomalies

Example:

ObjectName

Expression

Execution


Script.Class.AnomalyML.Check(Tag.Pressure)

OnChange

Step 4: Test the System

  1. Go in Runtime → “Run Startup”

  2. Wait a couple minutes to have some data in the model.

  3. Open the PropertyWatch

  4. See the values in the AnomalyBuffer, to see the predictions.

These tutorials provide simple, practical starting points for both MCP Tools and ML.NET integration, focusing on real industrial scenarios while keeping complexity minimal for learning purposes.

In this section...

Page Tree
root@parentspaces93DRAF