We received several emails to ask how to initialize the initial state from an external source recently, this post introduces a good pattern to do it.

We can implement our own data loader to load data from external source, and use this loader to initialize the state. Note that since data loading method might involve native invocation, we’d better set our loader to native (more details can be found at http://msdn.microsoft.com/en-us/library/ee620483.aspx).

Here is an example:

Model.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Microsoft.Modeling;
using Microsoft.Xrt.Runtime;
using System.IO;

[assembly: NativeType(typeof(Sample.MyLoader))]
namespace Sample
{
    static class MyLoader
    {
        internal static Sequence<UserData> Load()
        {
            int i;
            UserData data;
            Sequence<UserData> dataSequence = new Sequence<UserData>();
            string[] contents = File.ReadAllLines("c:\\temp\\data.txt");
            for (i = 0; i < contents.Length; i=i+2)
            {
                data.Name = contents[i];
                data.Address = contents[i + 1];
                dataSequence = dataSequence.Add(data);
            }
            return dataSequence;
        }
    }

    public struct UserData
    {
        public string Name;
        public string Address;
    }

    static class ModelProgram
    {
        static Sequence<UserData> Data = MyLoader.Load();

        [Rule]
        static Sequence<UserData> ShowData()
        {
            return Data;
        }

        [Rule]
        static void Clear()
        {
            Data = new Sequence<UserData>();
        }
    }
}

Config.cord

using Sample;
using Microsoft.Modeling;

config Main
{
    action abstract static Sequence<UserData> Adapter.ShowData();
    action abstract static void Adapter.Clear();

    switch StepBound = 128;
    switch PathDepthBound = 128;
}

machine ModelProgram() : Main
{
    construct model program from Main
}

And the data under c:\temp

Lisa
#5, Danling Street
Bob
Queen Square

Then we explore the ModelProgram machine, and get the exploration graph like:

image

Of course the data source is not limited to text files, you can design your own loader to make your model more powerful.

Please feel free to share your thoughts or other good approaches to initialize initial state.