コード例 #1
0
ファイル: PersistenceApi.cs プロジェクト: ArtiDi/HTM.Net
            private FileInfo EnsurePathExists(SerialConfig config, String fileName)
            {
                FileInfo serializedFile = null;

                try
                {
                    //writeMonitor.lock () ;

                    String        path      = Environment.CurrentDirectory + "\\" + config.GetFileDir();
                    DirectoryInfo customDir = new DirectoryInfo(path);
                    // Make sure container directory exists
                    Directory.CreateDirectory(customDir.FullName);

                    // Check to make sure the fileName doesn't already include the full path.
                    serializedFile = new FileInfo(fileName.IndexOf(customDir.FullName) != -1 ?
                                                  fileName : customDir.FullName + "\\" + fileName);
                    if (!serializedFile.Exists)
                    {
                        using (serializedFile.Create())
                        {
                            // just create it.
                        }
                    }
                }
                catch (Exception io)
                {
                    throw;
                }
                finally
                {
                    //writeMonitor.unlock();
                }

                return(serializedFile);
            }
コード例 #2
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeParameters()
        {
            Parameters p = GetParameters();

            SerialConfig config = new SerialConfig("testSerializeParameters", SerialConfig.SERIAL_TEST_DIR);

            IPersistenceAPI api = Persistence.Get(config);

            // 1. serialize
            byte[] data = api.Write(p, "testSerializeParameters");

            // 2. deserialize
            Parameters serialized = api.Read <Parameters>(data);

            Assert.IsTrue(p.Keys().Count == serialized.Keys().Count);
            Assert.IsTrue(p.IsDeepEqual(serialized));
            foreach (Parameters.KEY k in p.Keys())
            {
                DeepCompare(serialized.GetParameterByKey(k), p.GetParameterByKey(k));
            }

            // 3. reify from file
            /////////////////////////////////////
            //  SHOW RETRIEVAL USING FILENAME  //
            /////////////////////////////////////
            Parameters fromFile = api.Read <Parameters>("testSerializeParameters");

            Assert.IsTrue(p.Keys().Count == fromFile.Keys().Count);
            Assert.IsTrue(p.IsDeepEqual(fromFile));
            foreach (Parameters.KEY k in p.Keys())
            {
                DeepCompare(fromFile.GetParameterByKey(k), p.GetParameterByKey(k));
            }
        }
コード例 #3
0
        public SerialConfig get()
        {
            SerialConfig    serial          = new SerialConfig();
            SystemConfigDAL systemConfigDAL = new SystemConfigDALImpl();
            SystemConfig    portName        = systemConfigDAL.get("Serial.portName");
            SystemConfig    baudRate        = systemConfigDAL.get("Serial.baudRate");
            SystemConfig    dataBits        = systemConfigDAL.get("Serial.dataBits");
            SystemConfig    parity          = systemConfigDAL.get("Serial.parity");
            SystemConfig    stopBits        = systemConfigDAL.get("Serial.stopBits");

            if (portName != null &&
                baudRate != null &&
                dataBits != null &&
                parity != null &&
                stopBits != null)
            {
                //使用数据库默认配置
                serial.PortName = portName.Value;
                serial.BaudRate = int.Parse(baudRate.Value);
                serial.DataBits = int.Parse(dataBits.Value);
                serial.Parity   = parity.Value;
                serial.StopBits = stopBits.Value;
            }
            else
            {
                //使用客户端默认配置
                serial.PortName = "COM1";
                serial.BaudRate = 115200;
                serial.DataBits = 8;
                serial.Parity   = "None";
                serial.StopBits = "1";
            }
            return(serial);
        }
コード例 #4
0
ファイル: PersistenceApi.cs プロジェクト: ArtiDi/HTM.Net
 public static IPersistenceAPI Get(SerialConfig config)
 {
     if (access == null)
     {
         access = new PersistenceAccess(config);
     }
     return(access);
 }
コード例 #5
0
    static SerialConfig GetConfig()
    {
        if (s_config == null)
        {
            s_config = new SerialConfig();
        }

        return(s_config);
    }
コード例 #6
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeAnomalyLikelihoodForUpdates()
        {
            Parameters @params = Parameters.Empty();

            @params.SetParameterByKey(Parameters.KEY.ANOMALY_KEY_MODE, Anomaly.Mode.LIKELIHOOD);

            AnomalyLikelihood an = (AnomalyLikelihood)Anomaly.Create(@params);

            // Serialize the Anomaly Computer without errors
            SerialConfig    config = new SerialConfig("testSerializeAnomalyLikelihood", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(an);

            // Deserialize the Anomaly Computer and make sure its usable (same tests as AnomalyTest.java)
            AnomalyLikelihood serializedAn = api.Read <AnomalyLikelihood>(bytes);

            Assert.IsNotNull(serializedAn);

            //----------------------------------------
            // Step 1. Generate an initial estimate using fake distribution of anomaly scores.
            List <Sample>            data1    = AnomalyLikelihoodTest.GenerateSampleData(0.2, 0.2, 0.2, 0.2).Take(1000).ToList();
            AnomalyLikelihoodMetrics metrics1 = serializedAn.EstimateAnomalyLikelihoods(data1, 5, 0);

            //----------------------------------------
            // Step 2. Generate some new data with a higher average anomaly
            // score. Using the estimator from step 1, to compute likelihoods. Now we
            // should see a lot more anomalies.
            List <Sample>            data2    = AnomalyLikelihoodTest.GenerateSampleData(0.6, 0.2, 0.2, 0.2).Take(300).ToList();
            AnomalyLikelihoodMetrics metrics2 = serializedAn.UpdateAnomalyLikelihoods(data2, metrics1.GetParams());

            // Serialize the Metrics too just to be sure everything can be serialized
            SerialConfig metricsConfig = new SerialConfig("testSerializeMetrics", SerialConfig.SERIAL_TEST_DIR);

            api = Persistence.Get(metricsConfig);
            api.Write(metrics2);

            // Deserialize the Metrics
            AnomalyLikelihoodMetrics serializedMetrics = api.Read <AnomalyLikelihoodMetrics>();

            Assert.IsNotNull(serializedMetrics);

            Assert.AreEqual(serializedMetrics.GetLikelihoods().Length, data2.Count);
            Assert.AreEqual(serializedMetrics.GetAvgRecordList().Count, data2.Count);
            Assert.IsTrue(serializedAn.IsValidEstimatorParams(serializedMetrics.GetParams()));

            // The new running total should be different
            Assert.IsFalse(metrics1.GetAvgRecordList().Total == serializedMetrics.GetAvgRecordList().Total);

            // We should have many more samples where likelihood is < 0.01, but not all
            int conditionCount = ArrayUtils.Where(serializedMetrics.GetLikelihoods(), d => d < 0.1).Length;

            Assert.IsTrue(conditionCount >= 25);
            Assert.IsTrue(conditionCount <= 250);
        }
コード例 #7
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeCLAClassifier()
        {
            CLAClassifier        classifier     = new CLAClassifier(new int[] { 1 }, 0.1, 0.1, 0);
            int                  recordNum      = 0;
            Map <String, Object> classification = new Map <string, object>();

            classification.Add("bucketIdx", 4);
            classification.Add("actValue", 34.7);
            Classification <double> result = classifier.Compute <double>(recordNum, classification, new int[] { 1, 5, 9 }, true, true);

            recordNum += 1;

            classification.Add("bucketIdx", 5);
            classification.Add("actValue", 41.7);
            result     = classifier.Compute <double>(recordNum, classification, new int[] { 0, 6, 9, 11 }, true, true);
            recordNum += 1;

            classification.Add("bucketIdx", 5);
            classification.Add("actValue", 44.9);
            result     = classifier.Compute <double>(recordNum, classification, new int[] { 6, 9 }, true, true);
            recordNum += 1;

            classification.Add("bucketIdx", 4);
            classification.Add("actValue", 42.9);
            result     = classifier.Compute <double>(recordNum, classification, new int[] { 1, 5, 9 }, true, true);
            recordNum += 1;

            // Serialize the Metrics too just to be sure everything can be serialized
            SerialConfig    config = new SerialConfig("testSerializeCLAClassifier", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            api.Write(classifier);

            // Deserialize the Metrics
            CLAClassifier serializedClassifier = api.Read <CLAClassifier>();

            Assert.IsNotNull(serializedClassifier);

            //Using the deserialized classifier, continue test
            classification.Add("bucketIdx", 4);
            classification.Add("actValue", 34.7);
            result     = serializedClassifier.Compute <double>(recordNum, classification, new int[] { 1, 5, 9 }, true, true);
            recordNum += 1;

            Assert.IsTrue(Arrays.AreEqual(new int[] { 1 }, result.StepSet()));
            Assert.AreEqual(35.520000457763672, result.GetActualValue(4), 0.00001);
            Assert.AreEqual(42.020000457763672, result.GetActualValue(5), 0.00001);
            Assert.AreEqual(6, result.GetStatCount(1));
            Assert.AreEqual(0.0, result.GetStat(1, 0), 0.00001);
            Assert.AreEqual(0.0, result.GetStat(1, 1), 0.00001);
            Assert.AreEqual(0.0, result.GetStat(1, 2), 0.00001);
            Assert.AreEqual(0.0, result.GetStat(1, 3), 0.00001);
            Assert.AreEqual(0.12300123, result.GetStat(1, 4), 0.00001);
            Assert.AreEqual(0.87699877, result.GetStat(1, 5), 0.00001);
        }
コード例 #8
0
        static void Main(string[] args)
        {
            string baseAddress = "http://*:9000/";

            try
            {
                SerialConfig.Inizialize();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //var config = new HttpSelfHostConfiguration("http://*:9000");

            /* Inizializzazione serra e timer */
            try
            {
                ValuesController.GreenhouseInizialization(); // Greenhouse inizialization from ValuesController class
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            /* Set timer per acquisizione dati */
            Timer tmr = new Timer(); // timer per ricezione dati dai sensori

            tmr.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            tmr.Interval = 1800000; // set timer interval to 1800 seconds (30 minutes)
            //tmr.Interval = 10000; // set timer interval to 10 seconds
            tmr.Enabled = true;

            /* Set timer per invio comando per nutrienti alla pianta */
            Timer tmr2 = new Timer(); // timer per l'invio del comando di rifornimento nutrienti per pianta

            tmr2.Elapsed += new ElapsedEventHandler(OnTimedEvent2);
            tmr2.Interval = 2592000000; // set timer interval to 2592000 seconds (30 day)
            //tmr2.Enabled = true;

            /* Inizializzazione server */

            // Start OWIN host
            Startup tmp = new Startup();

            tmp.Start();
            //using (WebApp.Start<Startup>(url: baseAddress))
            {
                // Create HttpCient and make a request to api/values
                Console.WriteLine("Premi return per chiudere l'applicazione...");
                Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "-kiosk -fullscreen " + "localhost:9000");
                Console.ReadLine();
            }
        }
コード例 #9
0
        public void TestSerialization()
        {
            _classifier = new CLAClassifier(new[] { 1 }, 0.1, 0.1, 0);
            int recordNum = 0;
            Map <string, object> classification = new Map <string, object>();

            classification.Add("bucketIdx", 4);
            classification.Add("actValue", 34.7);
            Classification <double> result = _classifier.Compute <double>(recordNum, classification, new[] { 1, 5, 9 }, true, true);

            recordNum += 1;

            classification.Add("bucketIdx", 5);
            classification.Add("actValue", 41.7);
            result     = _classifier.Compute <double>(recordNum, classification, new[] { 0, 6, 9, 11 }, true, true);
            recordNum += 1;

            classification.Add("bucketIdx", 5);
            classification.Add("actValue", 44.9);
            result     = _classifier.Compute <double>(recordNum, classification, new[] { 6, 9 }, true, true);
            recordNum += 1;

            classification.Add("bucketIdx", 4);
            classification.Add("actValue", 42.9);
            result     = _classifier.Compute <double>(recordNum, classification, new[] { 1, 5, 9 }, true, true);
            recordNum += 1;

            // Configure serializer
            SerialConfig    config = new SerialConfig("testSerializerClassifier", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            // 1. Serialize
            byte[] data = api.Write(_classifier, "testSerializeClassifier");

            // 2. Deserialize
            CLAClassifier serialized = api.Read <CLAClassifier>(data);

            // Using the deserialized classifier, continue test
            classification.Add("bucketIdx", 4);
            classification.Add("actValue", 34.7);
            result     = serialized.Compute <double>(recordNum, classification, new[] { 1, 5, 9 }, true, true);
            recordNum += 1;

            Assert.IsTrue(Arrays.AreEqual(new[] { 1 }, result.StepSet()));
            Assert.AreEqual(35.520000457763672, result.GetActualValue(4), 0.00001);
            Assert.AreEqual(42.020000457763672, result.GetActualValue(5), 0.00001);
            Assert.AreEqual(6, result.GetStatCount(1));
            Assert.AreEqual(0.0, result.GetStat(1, 0), 0.00001);
            Assert.AreEqual(0.0, result.GetStat(1, 1), 0.00001);
            Assert.AreEqual(0.0, result.GetStat(1, 2), 0.00001);
            Assert.AreEqual(0.0, result.GetStat(1, 3), 0.00001);
            Assert.AreEqual(0.12300123, result.GetStat(1, 4), 0.00001);
            Assert.AreEqual(0.87699877, result.GetStat(1, 5), 0.00001);
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: LyxInChina/GitHelloWorld
        /// <summary>
        /// 串口测试
        /// </summary>
        static void NewTestSerial()
        {
            var serialc = new SerialConfig()
            {
                BaudRate = 9600,
                DataBits = 8,
                Parity   = System.IO.Ports.Parity.None,
                StopBits = System.IO.Ports.StopBits.One,
                PortName = "com3"
            };

            Func(serialc);
        }
コード例 #11
0
 /// <summary>
 /// 打开串口
 /// </summary>
 /// <returns></returns>
 public int open()
 {
     if (!serialUtil.IsOpen())
     {
         SerialConfig config = serialConfigDAL.get();
         return(serialUtil.open(config.PortName,
                                config.BaudRate,
                                config.DataBits,
                                config.Parity,
                                config.StopBits));
     }
     return(0);
 }
コード例 #12
0
 public ScanController(SerialConfig config, Logging logger)
 {
     _logger = logger;
     Config  = config;
     port    = new GodSerialPort(c =>
     {
         c.PortName = Config.PortName;
         c.BaudRate = Config.BuadRate;
         c.DataBits = Config.DataBits;
         c.StopBits = StopBits.One;
         c.Parity   = Parity.None;
     });
     port.OnData = OnDataRead;
 }
コード例 #13
0
        /// <summary>
        /// 加载串口设置
        /// </summary>
        /// <param name="config"></param>
        private static void LoadSerialConfig(SerialConfig config)
        {
            string tmp;

            config.PortName = ConfigurationManager.AppSettings["PortName"];
            tmp             = ConfigurationManager.AppSettings["PortParity"];
            switch (tmp)             //校验位
            {
            case "None":
                WeightConfig.PortParity = Parity.None;
                break;

            case "Odd":
                WeightConfig.PortParity = Parity.Odd;
                break;

            case "Even":
                WeightConfig.PortParity = Parity.Even;
                break;

            default:
                WeightConfig.PortParity = Parity.None;
                break;
            }
            tmp = ConfigurationManager.AppSettings["PortStopBits"];
            switch (tmp)            //停止位
            {
            case "1":
                config.PortStopBits = StopBits.One;
                break;

            case "1.5":
                config.PortStopBits = StopBits.OnePointFive;
                break;

            case "2":
                config.PortStopBits = StopBits.Two;
                break;

            default:
                config.PortStopBits = StopBits.One;
                break;
            }
            config.PortDataBits = int.Parse(ConfigurationManager.AppSettings["PortDataBits"]);
            config.PortBaudRate = int.Parse(ConfigurationManager.AppSettings["PortBaudRate"]);
            config.Ratio        = decimal.Parse(ConfigurationManager.AppSettings["Ratio"]);
            config.ReadCommand  = ConfigurationManager.AppSettings["ReadCommand"];
            config.DataFormat   = SerialDataFormatEnum.Ascii;
            config.DecimalNum   = int.Parse(ConfigurationManager.AppSettings["DecimalNum"]);
        }
コード例 #14
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
 public void TestHierarchicalNetwork()
 {
     Net.Network.Network network = GetLoadedHotGymHierarchy();
     try
     {
         SerialConfig    config = new SerialConfig("testSerializeHierarchy", SerialConfig.SERIAL_TEST_DIR);
         IPersistenceAPI api    = Persistence.Get(config);
         api.Store(network);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         Assert.Fail();
     }
 }
コード例 #15
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeConnections()
        {
            Parameters  p   = GetParameters();
            Connections con = new Connections();

            p.Apply(con);

            TemporalMemory.Init(con);

            SerialConfig    config = new SerialConfig("testSerializeConnections", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            // 1. serialize
            byte[] data = api.Write(con);

            // 2. deserialize
            Connections serialized = api.Read <Connections>(data);

            Assert.IsTrue(con.IsDeepEqual(serialized));

            serialized.PrintParameters();
            int cellCount = con.GetCellsPerColumn();

            for (int i = 0; i < con.GetNumColumns(); i++)
            {
                DeepCompare(con.GetColumn(i), serialized.GetColumn(i));
                for (int j = 0; j < cellCount; j++)
                {
                    Cell cell = serialized.GetCell(i * cellCount + j);
                    DeepCompare(con.GetCell(i * cellCount + j), cell);
                }
            }

            // 3. reify from file
            Connections fromFile = api.Read <Connections>(data);

            Assert.IsTrue(con.IsDeepEqual(fromFile));
            for (int i = 0; i < con.GetNumColumns(); i++)
            {
                DeepCompare(con.GetColumn(i), fromFile.GetColumn(i));
                for (int j = 0; j < cellCount; j++)
                {
                    Cell cell = fromFile.GetCell(i * cellCount + j);
                    DeepCompare(con.GetCell(i * cellCount + j), cell);
                }
            }
        }
コード例 #16
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestEnsurePathExists()
        {
            SerialConfig    config  = new SerialConfig("testEnsurePathExists", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI persist = Persistence.Get();

            persist.SetConfig(config);

            try
            {
                ((Persistence.PersistenceAccess)persist).EnsurePathExists(config);
            }
            catch (Exception e) { Assert.Fail(); }

            FileInfo f1 = new FileInfo(Environment.CurrentDirectory + "\\" + config.GetFileDir() + "\\" + "testEnsurePathExists");

            Assert.IsTrue(f1.Exists);
        }
コード例 #17
0
        public bool update(SerialConfig config)
        {
            SystemConfigDAL systemConfigDAL = new SystemConfigDALImpl();
            SystemConfig    portName        = new SystemConfig()
            {
                Key = "Serial.portName", Value = config.PortName
            };
            SystemConfig baudRate = new SystemConfig()
            {
                Key = "Serial.baudRate", Value = config.BaudRate.ToString()
            };
            SystemConfig dataBits = new SystemConfig()
            {
                Key = "Serial.dataBits", Value = config.DataBits.ToString()
            };
            SystemConfig parity = new SystemConfig()
            {
                Key = "Serial.parity", Value = config.Parity
            };
            SystemConfig stopBits = new SystemConfig()
            {
                Key = "Serial.stopBits", Value = config.StopBits
            };

            if (!systemConfigDAL.update(portName))
            {
                return(false);
            }
            if (!systemConfigDAL.update(baudRate))
            {
                return(false);
            }
            if (!systemConfigDAL.update(dataBits))
            {
                return(false);
            }
            if (!systemConfigDAL.update(parity))
            {
                return(false);
            }
            if (!systemConfigDAL.update(stopBits))
            {
                return(false);
            }
            return(true);
        }
コード例 #18
0
        public SerialCommunicator(SerialPort port = null)
        {
            _config = SerialConfig.Default;

            if (port == null)
            {
                InitSerialPort();
            }
            else
            {
                _port = port;
            }

            _port.DataReceived += PortDataReceived;
            _receiver           = new Receiver();
            _sender             = new Sender(_port);
        }
コード例 #19
0
    static SerialConfig GetConfig()
    {
        if (s_config == null)
        {
            s_config = GameObject.FindObjectOfType <SerialConfig> ();
            if (!s_config)
            {
                Debug.LogWarning("Serial configuration not found. Using default values. To configure the prefered port names and speed, add the SerialConfig component to an empty GameObject", s_config);

                // Provide a default config compatible with old version of UnitySerial
                GameObject goConfig = new GameObject("Serial configuration");
                s_config = goConfig.AddComponent <SerialConfig> ();
            }
            DontDestroyOnLoad(s_config.gameObject);
        }

        return(s_config);
    }
コード例 #20
0
        private static void OnTimedEvent2(object source, ElapsedEventArgs e)
        {
            string packet = "#I1;$";

            do
            {
                try
                {
                    SerialConfig.sendData(packet);
                }
                catch (Exception ex)
                {
                    throw new Exception("C'è stato un errore con l'acquisizione dei dati nella serra!");
                }

                packet = SerialConfig.ReceivedData;
            } while (packet != "#Z1;$");
        }
コード例 #21
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeAnomalyLikelihood()
        {
            Parameters @params = Parameters.Empty();

            @params.SetParameterByKey(Parameters.KEY.ANOMALY_KEY_MODE, Anomaly.Mode.LIKELIHOOD);

            AnomalyLikelihood an = (AnomalyLikelihood)Anomaly.Create(@params);

            // Serialize the Anomaly Computer without errors
            SerialConfig    config = new SerialConfig("testSerializeAnomalyLikelihood", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(an);

            // Deserialize the Anomaly Computer and make sure its usable (same tests as AnomalyTest.java)
            Anomaly serializedAn = api.Read <Anomaly>(bytes);

            Assert.IsNotNull(serializedAn);
        }
コード例 #22
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeAnomaly()
        {
            Parameters @params = Parameters.Empty();

            @params.SetParameterByKey(Parameters.KEY.ANOMALY_KEY_MODE, Anomaly.Mode.PURE);
            Anomaly anomalyComputer = Anomaly.Create(@params);

            // Serialize the Anomaly Computer without errors
            SerialConfig    config = new SerialConfig("testSerializeAnomaly1", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(anomalyComputer);

            double score = anomalyComputer.Compute(new int[0], new int[0], 0, 0);

            score = anomalyComputer.Compute(new int[0], new int[0], 0, 0);
            Assert.AreEqual(0.0, score, 0);

            score = anomalyComputer.Compute(new int[0], new int[] { 3, 5 }, 0, 0);
            Assert.AreEqual(0.0, score, 0);

            score = anomalyComputer.Compute(new int[] { 3, 5, 7 }, new int[] { 3, 5, 7 }, 0, 0);
            Assert.AreEqual(0.0, score, 0);

            score = anomalyComputer.Compute(new int[] { 2, 3, 6 }, new int[] { 3, 5, 7 }, 0, 0);
            Assert.AreEqual(2.0 / 3.0, score, 0);

            // Deserialize the Anomaly Computer and make sure its usable (same tests as AnomalyTest.java)
            Anomaly serializedAnomalyComputer = api.Read <Anomaly>(bytes);

            score = serializedAnomalyComputer.Compute(new int[0], new int[0], 0, 0);
            Assert.AreEqual(0.0, score, 0);

            score = serializedAnomalyComputer.Compute(new int[0], new int[] { 3, 5 }, 0, 0);
            Assert.AreEqual(0.0, score, 0);

            score = serializedAnomalyComputer.Compute(new int[] { 3, 5, 7 }, new int[] { 3, 5, 7 }, 0, 0);
            Assert.AreEqual(0.0, score, 0);

            score = serializedAnomalyComputer.Compute(new int[] { 2, 3, 6 }, new int[] { 3, 5, 7 }, 0, 0);
            Assert.AreEqual(2.0 / 3.0, score, 0);
        }
コード例 #23
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeCumulativeAnomaly()
        {
            Parameters @params = Parameters.Empty();

            @params.SetParameterByKey(Parameters.KEY.ANOMALY_KEY_MODE, Anomaly.Mode.PURE);
            @params.SetParameterByKey(Parameters.KEY.ANOMALY_KEY_WINDOW_SIZE, 3);
            @params.SetParameterByKey(Parameters.KEY.ANOMALY_KEY_USE_MOVING_AVG, true);

            Anomaly anomalyComputer = Anomaly.Create(@params);

            // Serialize the Anomaly Computer without errors
            SerialConfig    config = new SerialConfig("testSerializeCumulativeAnomaly", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(anomalyComputer);

            // Deserialize the Anomaly Computer and make sure its usable (same tests as AnomalyTest.java)
            Anomaly serializedAnomalyComputer = api.Read <Anomaly>(bytes);

            Assert.IsNotNull(serializedAnomalyComputer);

            Object[] predicted =
            {
                new int[] { 1, 2, 6 }, new int[] { 1, 2, 6 }, new int[] { 1, 2, 6 },
                new int[] { 1, 2, 6 }, new int[] { 1, 2, 6 }, new int[] { 1, 2, 6 },
                new int[] { 1, 2, 6 }, new int[] { 1, 2, 6 }, new int[] { 1, 2, 6 }
            };
            Object[] actual =
            {
                new int[] {  1,  2,  6 }, new int[] {  1,  2,  6 }, new int[] {  1,  4,  6 },
                new int[] { 10, 11,  6 }, new int[] { 10, 11, 12 }, new int[] { 10, 11, 12 },
                new int[] { 10, 11, 12 }, new int[] {  1,  2,  6 }, new int[] {  1,  2,  6 }
            };

            double[] anomalyExpected = { 0.0, 0.0, 1.0 / 9.0, 3.0 / 9.0, 2.0 / 3.0, 8.0 / 9.0, 1.0, 2.0 / 3.0, 1.0 / 3.0 };
            for (int i = 0; i < 9; i++)
            {
                double score = serializedAnomalyComputer.Compute((int[])actual[i], (int[])predicted[i], 0, 0);
                Assert.AreEqual(anomalyExpected[i], score, 0.01);
            }
        }
コード例 #24
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestHTMSensor_HotGym()
        {
            Object[]             n      = { "some name", ResourceLocator.Path("rec-center-hourly-small.csv") };
            HTMSensor <FileInfo> sensor = (HTMSensor <FileInfo>) Sensor <FileInfo> .Create(
                FileSensor.Create, SensorParams.Create(SensorParams.Keys.Path, n));

            sensor.InitEncoder(GetTestEncoderParams());

            SerialConfig    config = new SerialConfig("testHTMSensor_HotGym");
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(sensor);
            Assert.IsNotNull(bytes);
            Assert.IsTrue(bytes.Length > 0);
            HTMSensor <FileInfo> serializedSensor = api.Read <HTMSensor <FileInfo> >(bytes);

            bool b = serializedSensor.IsDeepEqual(sensor);

            DeepCompare(serializedSensor, sensor);
            Assert.IsTrue(b);
        }
コード例 #25
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestSerializeObservableSensor()
        {
            PublisherSupplier supplier = PublisherSupplier.GetBuilder()
                                         .AddHeader("dayOfWeek")
                                         .AddHeader("darr")
                                         .AddHeader("B").Build();

            ObservableSensor <string[]> oSensor = new ObservableSensor <string[]>(
                SensorParams.Create(SensorParams.Keys.Obs, new Object[] { "name", supplier }));

            SerialConfig    config = new SerialConfig("testSerializeObservableSensor", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(oSensor);
            ObservableSensor <string[]> serializedOSensor = api.Read <ObservableSensor <string[]> >(bytes);

            bool b = serializedOSensor.IsDeepEqual(oSensor);

            DeepCompare(serializedOSensor, oSensor);
            Assert.IsTrue(b);
        }
コード例 #26
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestHTMSensor_DaysOfWeek()
        {
            Object[]             n      = { "some name", ResourceLocator.Path("days-of-week.csv") };
            HTMSensor <FileInfo> sensor = (HTMSensor <FileInfo>) Sensor <FileInfo> .Create(
                FileSensor.Create, SensorParams.Create(SensorParams.Keys.Path, n));

            Parameters p = GetParameters();

            p = p.Union(NetworkTestHarness.GetDayDemoTestEncoderParams());
            sensor.InitEncoder(p);

            SerialConfig    config = new SerialConfig("testHTMSensor_DaysOfWeek", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(sensor);
            HTMSensor <FileInfo> serializedSensor = api.Read <HTMSensor <FileInfo> >(bytes);

            bool b = serializedSensor.IsDeepEqual(sensor);

            DeepCompare(serializedSensor, sensor);
            Assert.IsTrue(b);
        }
コード例 #27
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestThreadedPublisher_TemporalMemoryNetwork()
        {
            Net.Network.Network network = CreateAndRunTestTemporalMemoryNetwork();
            ILayer      l  = network.Lookup("r1").Lookup("1");
            Connections cn = l.GetConnections();

            SerialConfig    config = new SerialConfig("testThreadedPublisher_TemporalMemoryNetwork", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[]      bytes = api.Write(cn);
            Connections serializedConnections = api.Read <Connections>(bytes);

            Net.Network.Network network2 = CreateAndRunTestTemporalMemoryNetwork();
            ILayer      l2      = network2.Lookup("r1").Lookup("1");
            Connections newCons = l2.GetConnections();

            newCons.ShouldDeepEqual(serializedConnections);

            bool b = newCons.IsDeepEqual(serializedConnections);

            DeepCompare(newCons, serializedConnections);
            Assert.IsTrue(b);
        }
コード例 #28
0
ファイル: PersistanceAPITest.cs プロジェクト: ArtiDi/HTM.Net
        public void TestThreadedPublisher_SpatialPoolerNetwork()
        {
            Net.Network.Network network = CreateAndRunTestSpatialPoolerNetwork(0, 6);
            ILayer      l  = network.Lookup("r1").Lookup("1");
            Connections cn = l.GetConnections();

            SerialConfig    config = new SerialConfig("testThreadedPublisher_SpatialPoolerNetwork", SerialConfig.SERIAL_TEST_DIR);
            IPersistenceAPI api    = Persistence.Get(config);

            byte[] bytes = api.Write(cn);
            //Serialize above Connections for comparison with same run but unserialized below...
            Connections serializedConnections = api.Read <Connections>(bytes);

            Net.Network.Network network2 = CreateAndRunTestSpatialPoolerNetwork(0, 6);
            ILayer      l2      = network2.Lookup("r1").Lookup("1");
            Connections newCons = l2.GetConnections();

            //Compare the two Connections (both serialized and regular runs) - should be equal
            bool b = newCons.IsDeepEqual(serializedConnections);

            DeepCompare(newCons, serializedConnections);
            Assert.IsTrue(b);
        }
コード例 #29
0
ファイル: MockStream.cs プロジェクト: RaviRawatMSFT/Firmata
 public void begin(uint baud_, SerialConfig config_)
 {
     this.BaudRate = baud_;
 }
コード例 #30
0
 public Config(Uri serverUrl, SerialConfig serialConfig)
 {
     this.serverUrl    = serverUrl;
     this.serialConfig = serialConfig;
 }
コード例 #31
0
 public void begin(uint baud_, SerialConfig config_)
 {
     this.BaudRate = baud_;
 }
コード例 #32
0
        void IStream.begin(uint baud_, SerialConfig config_)
        {

            Task.Factory.StartNew(Connect);

        }