Versions Compared

Key

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

How to work with build an ML Model.NET.

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


This Tutorial Teaches you to:

Edge AI with ML.NET (Tutorial) demonstrates using ML.NET 4.0 This tutorial demonstrates how to use machine learning for real-time anomaly detection on sensor data using FrameworX Script TasksClasses.

Prerequisites:

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

    Table of Contents
    maxLevel2
    minLevel2
    indent10px
    excludeSteps
    stylenone


    Step 1: Create

    Monitoring Tags
  • Navigate to Unified Namespace → Tags
  • 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

    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 Anomaly Detection

    Task

    Script Class

    Go
    1. Navigate to Scripts →

    Tasks
    1. Classes

  • Create task: AnomalyDetector
  • Set trigger: Period = 1000ms
  • 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
    1. Click the "Create a New Class" button

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

    3. 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
    1. .


    In this section...

    Page Tree
    root@parent