public void OutputPipelineContinuity(
            [Values(1000, 5000, 10000, 15000, 20000)] double sampleRate,
            [Values(0.1, 0.5, 1, 5)] double blockDurationSeconds
            )
        {
            const double epochDuration = 2; //seconds
            var srate = new Measurement((decimal) sampleRate, "Hz");

            var daq = new TestDAQController();
            var outStream = new DAQOutputStream("OUT")
                                {
                                    SampleRate = srate,
                                    MeasurementConversionTarget = "V"
                                };
            var inStream = new DAQInputStream("IN")
                                {
                                    SampleRate = srate,
                                    MeasurementConversionTarget = "V"
                                };

            var controller = new Controller() { Clock = daq, DAQController = daq };

            var dev = new UnitConvertingExternalDevice("dev", "co", controller, new Measurement(0, "V"))
                          {
                              Clock = daq,
                              MeasurementConversionTarget = "V",
                              OutputSampleRate = srate,
                              InputSampleRate = srate
                          };
            dev.BindStream(outStream).BindStream(inStream);

            // Setup Epoch
            var e = new Epoch("OutputPipelineContinuity");

            var nSamples = (int)TimeSpan.FromSeconds(epochDuration).Samples(srate);
            IList<IMeasurement> stimData = (IList<IMeasurement>) Enumerable.Range(0, nSamples)
                                                       .Select(i => new Measurement((decimal) (8 * Math.Sin(((double)i) / (nSamples / 10.0))), "V") as IMeasurement)
                                                       .ToList();
            IOutputData stimOutputData = new OutputData(stimData, srate);

            var stim = new RenderedStimulus((string) "RenderedStimulus", (IDictionary<string, object>) new Dictionary<string, object>(),
                                            stimOutputData);
            e.Stimuli[dev] = stim;
            e.Responses[dev] = new Response();
            e.Backgrounds[dev] = new Background(new Measurement(0, "V"), srate);

            controller.EnqueueEpoch(e);

            var blockSpan = TimeSpan.FromSeconds(blockDurationSeconds);
            foreach (var stimBlock in stim.DataBlocks(blockSpan))
            {
                var cons = stimOutputData.SplitData(blockSpan);
                var expected = cons.Head.Data;
                stimOutputData = cons.Rest;

                Assert.That(stimBlock.Data, Is.EqualTo(expected));
            }
        }
        public void FiresStimulusOutputEvents()
        {
            var c = new TestDAQController();
            var srate = new Measurement(10, "Hz");
            var outStream = new DAQOutputStream("out")
                                {
                                    MeasurementConversionTarget = "V",
                                    SampleRate = srate
                                };
            var inStream = new DAQInputStream("in")
                               {
                                   MeasurementConversionTarget = "V",
                                   SampleRate = srate
                               };

            var outputData = new Dictionary<IDAQOutputStream, Queue<IOutputData>>();
            var dataQueue = new Queue<IOutputData>();
            var outputIOData = new OutputData(
                Enumerable.Range(0, 100).Select(i => new Measurement(i, "V")),
                new Measurement(10, "Hz")
                );

            dataQueue.Enqueue(outputIOData);

            outputData[outStream] = dataQueue;

            var dev = new TestDevice("test", outputData) { MeasurementConversionTarget = "V" };

            dev.BindStream(outStream);

            bool fired = false;
            c.StimulusOutput += (daq, args) =>
                                    {
                                        Assert.That(args.Stream == outStream);
                                        Assert.That(args.Data != null);
                                        Assert.That(args.Data.Configuration.Count() > 0);
                                        fired = true;

                                        ((IDAQController) daq).RequestStop();
                                    };

            c.AddStreamMapping(outStream, inStream);

            c.Start(false);

            while (c.IsRunning)
            {
                Thread.Sleep(1);
            }

            Assert.That(fired, Is.True);
        }
        public void ShouldSurfaceExceptionInPersistorTask()
        {
            var c = new Controller();
            bool evt = false;

            c.DAQController = new TestDAQController();
            c.Clock = c.DAQController as IClock;
            var persistor = new AggregateExceptionThrowingEpochPersistor();

            c.SavedEpoch += (co, args) =>
            {
                evt = true;
            };

            var dev = new UnitConvertingExternalDevice(UNUSED_DEVICE_NAME, UNUSED_DEVICE_MANUFACTURER, UNUSED_BACKGROUND)
            {
                Controller = c,
                MeasurementConversionTarget = "V"
            };

            var outStream = new DAQOutputStream("outStream") { MeasurementConversionTarget = "V" };

            var inStream = new DAQInputStream("inStream") { MeasurementConversionTarget = "V" };

            (c.DAQController as IMutableDAQController).AddStream(outStream);
            (c.DAQController as IMutableDAQController).AddStream(inStream);

            var srate = new Measurement(10, "Hz");
            outStream.SampleRate = srate;
            inStream.SampleRate = srate;

            dev.BindStream(outStream);
            dev.BindStream(inStream);

            var e = new Epoch(UNUSED_PROTOCOL);
            var samples = new List<IMeasurement> { new Measurement(1.0m, "V"), new Measurement(1.0m, "V"), new Measurement(1.0m, "V") };
            var data = new OutputData(samples,
                srate,
                true);

            e.Stimuli[dev] = new RenderedStimulus((string) "stimID",
                                                  (IDictionary<string, object>) new Dictionary<string, object>(),
                                                  (IOutputData) data);
            e.Responses[dev] = new Response();
            e.Background[dev] = new Epoch.EpochBackground(new Measurement(0, "V"), srate);

            ((TestDAQController)c.DAQController).AddStreamMapping(outStream, inStream);

            Assert.That(() => c.RunEpoch(e, persistor), Throws.TypeOf<SymphonyControllerException>());
        }
        public void ShouldPersistCompletedEpochs()
        {
            Converters.Register("V", "V",
                (IMeasurement m) => m);

            var c = new Controller();
            bool evt = false;

            c.DAQController = new TestDAQController();
            c.Clock = c.DAQController as IClock;
            var persistor = new FakeEpochPersistor();

            c.SavedEpoch += (co, args) =>
                                {
                                    evt = true;
                                };

            var srate = new Measurement(10, "Hz");

            var dev = new UnitConvertingExternalDevice(UNUSED_DEVICE_NAME, UNUSED_DEVICE_MANUFACTURER, c, UNUSED_BACKGROUND)
                          {
                              MeasurementConversionTarget = "V",
                              Clock = c.Clock,
                              OutputSampleRate = srate,
                              InputSampleRate = srate
                          };

            var outStream = new DAQOutputStream("outStream") { MeasurementConversionTarget = "V", Clock = c.Clock };

            var inStream = new DAQInputStream("inStream") { MeasurementConversionTarget = "V", Clock = c.Clock };

            (c.DAQController as IMutableDAQController).AddStream(outStream);
            (c.DAQController as IMutableDAQController).AddStream(inStream);

            outStream.SampleRate = srate;
            inStream.SampleRate = srate;

            dev.BindStream(outStream);
            dev.BindStream(inStream);

            var e = new Epoch(UNUSED_PROTOCOL);
            var samples = new List<IMeasurement> { new Measurement(1.0m, "V"), new Measurement(1.0m, "V"), new Measurement(1.0m, "V") };
            var data = new OutputData(samples,
                srate,
                true);

            e.Stimuli[dev] = new RenderedStimulus((string) "stimID",
                                                  (IDictionary<string, object>) new Dictionary<string, object>(),
                                                  (IOutputData) data);
            e.Responses[dev] = new Response();
            e.Backgrounds[dev] = new Background(new Measurement(0, "V"), srate);

            ((TestDAQController)c.DAQController).AddStreamMapping(outStream, inStream);

            c.RunEpoch(e, persistor);

            Assert.That(evt, Is.True.After(10*1000,100));
            Assert.That(persistor.PersistedEpochs, Has.Member(e));
        }
        public void PushesDataToEpoch()
        {
            const string UNUSED_NAME = "UNUSED";

            var c = new SingleEpochController();
            var dev = new UnitConvertingExternalDevice(UNUSED_NAME, UNUSED_DEVICE_MANUFACTURER, UNUSED_BACKGROUND);
            c.AddDevice(dev);

            var srate = new Measurement(100, "Hz");
            var samples = Enumerable.Range(0, 100).Select(i => new Measurement(1, "V")).ToList();

            var e = new Epoch("PushesDataToEpoch");
            e.Responses[dev] = new Response();

            e.Stimuli[dev] = new RenderedStimulus((string) "ID1", (IDictionary<string, object>) new Dictionary<string, object>(), (IOutputData) new OutputData(samples, srate, false));

            c.SetCurrentEpoch(e);

            var streamFake = new DAQInputStream("StreamFake");

            var data = new InputData(samples, srate, DateTimeOffset.Now)
                .DataWithStreamConfiguration(streamFake, new Dictionary<string, object>());

            c.PushInputData(dev, data);

            Assert.That(e.Responses[dev].Data, Is.EqualTo(data.Data));
            Assert.That(e.Responses[dev].InputTime, Is.EqualTo(data.InputTime));
            Assert.That(e.Responses[dev].DataConfigurationSpans.First().Nodes.First(),
                Is.EqualTo(data.NodeConfigurationWithName(streamFake.Name)));
        }
        public void ShouldNotPersistEpochGivenNullPersistor()
        {
            var c = new Controller();
            bool evt = false;

            c.DAQController = new TestDAQController();
            c.Clock = c.DAQController as IClock;

            c.DiscardedEpoch += (co, args) => Assert.Fail("Run failed");

            var dev = new UnitConvertingExternalDevice(UNUSED_DEVICE_NAME, UNUSED_DEVICE_MANUFACTURER, UNUSED_BACKGROUND)
            {
                Controller = c,
                MeasurementConversionTarget = "V"
            };

            var outStream = new DAQOutputStream("outStream") { MeasurementConversionTarget = "V" };

            var inStream = new DAQInputStream("inStream") { MeasurementConversionTarget = "V" };

            (c.DAQController as IMutableDAQController).AddStream(outStream);
            (c.DAQController as IMutableDAQController).AddStream(inStream);

            var srate = new Measurement(10, "Hz");
            outStream.SampleRate = srate;
            inStream.SampleRate = srate;

            dev.BindStream(outStream);
            dev.BindStream(inStream);

            var e = new Epoch(UNUSED_PROTOCOL);
            var samples = new List<IMeasurement> { new Measurement(1.0m, "V"), new Measurement(1.0m, "V"), new Measurement(1.0m, "V") };
            var data = new OutputData(samples,
                srate,
                true);

            e.Stimuli[dev] = new RenderedStimulus((string) "stimID",
                                                  (IDictionary<string, object>) new Dictionary<string, object>(),
                                                  (IOutputData) data);
            e.Responses[dev] = new Response();
            e.Background[dev] = new Epoch.EpochBackground(new Measurement(0, "V"), srate);

            ((TestDAQController)c.DAQController).AddStreamMapping(outStream, inStream);

            c.RunEpoch(e, null);

            Assert.Pass();
        }
        private void SetupInputPipeline(IDAQController c, out IOutputData expectedOutput, out DAQOutputStream outStream, out DAQInputStream inStream)
        {
            SetupOutputPipeline(c, out expectedOutput, out outStream);

            inStream = new DAQInputStream("IN");
            inStream.SampleRate = outStream.SampleRate;
            outStream.Device.BindStream(inStream);
            inStream.MeasurementConversionTarget = outStream.MeasurementConversionTarget;
        }
        public void CreatePipeline()
        {
            // Based on the "Minimal Rig.pdf" in the docs folder
            Converters.Clear();

            // We need an IClock
            IClock clock = new FakeClock();

            // We need a controller ...
            Controller con = new Controller();

            Converters.Register("units", "units",
                // just an identity conversion for now, to pass Validate()
                (IMeasurement m) => m);
            Converters.Register("V", "units",
                // just an identity conversion for now, to pass Validate()
               (IMeasurement m) => m);

            con.Clock = clock;

            // Three ExternalDevices
            CoalescingDevice amp = new CoalescingDevice("Amp", UNUSED_DEVICE_MANUFACTURER, con, UNUSED_BACKGROUND)
                                       {
                                           MeasurementConversionTarget = "units"
                                       };
            var LED = new UnitConvertingExternalDevice("LED", UNUSED_DEVICE_MANUFACTURER, UNUSED_BACKGROUND)
            {
                MeasurementConversionTarget = "units"
            };
            var temp = new UnitConvertingExternalDevice("Temp", UNUSED_DEVICE_MANUFACTURER, UNUSED_BACKGROUND)
            {
                MeasurementConversionTarget = "units"
            };
            amp.Clock = clock;
            LED.Clock = clock;
            temp.Clock = clock;
            con.AddDevice(LED).AddDevice(temp);
            // There should be no difference whether we use the
            // ExternalDevice constructor to wire up the Controller
            // to the ExternalDevice, or the explicit Add() call

            Assert.IsNotNull(amp.Controller);
            Assert.IsNotNull(LED.Controller);
            Assert.IsNotNull(temp.Controller);

            Assert.IsTrue(amp.Controller == con);
            Assert.IsTrue(LED.Controller == con);
            Assert.IsTrue(temp.Controller == con);

            // Five DAQStreams
            DAQInputStream in0 = new DAQInputStream("In-0"); in0.Clock = clock;
            DAQInputStream in1 = new DAQInputStream("In-1"); in1.Clock = clock;
            DAQInputStream in2 = new DAQInputStream("In-2"); in2.Clock = clock;
            DAQOutputStream out0 = new DAQOutputStream("Out-0"); out0.Clock = clock;
            DAQOutputStream out1 = new DAQOutputStream("Out-1"); out1.Clock = clock;
            in0.MeasurementConversionTarget = "units";
            in1.MeasurementConversionTarget = "units";
            in2.MeasurementConversionTarget = "units";
            out0.MeasurementConversionTarget = "units";
            out1.MeasurementConversionTarget = "units";

            //amp.Coalesce = CoalescingDevice.OneItemCoalesce;
            amp.Configuration["CoalesceProc"] = "Symphony.Core.CoalescingDevice.OneItemCoalesce";

            LED.BindStream(out0);
            amp.BindStream(out1).BindStream(in0).BindStream(in1);
            amp.Connect(in0, in1);
            temp.BindStream(in2);

            Assert.IsTrue(LED.Streams.Count == 1);
            Assert.IsTrue(amp.Streams.Count == 3);
            Assert.IsTrue(temp.Streams.Count == 1);

            Assert.IsTrue(in0.Devices.Contains(amp));
            Assert.IsTrue(in1.Devices.Contains(amp));
            Assert.IsTrue(in2.Devices.Contains(temp));
            Assert.IsTrue(out0.Device == LED);
            Assert.IsTrue(out1.Device == amp);

            // One DAQController
            IDAQController dc =
                new SimpleDAQController(new IDAQStream[] { in0, in1, in2, out0, out1 });

            con.DAQController = dc;

            // DAQController-to-streams
            Assert.IsTrue(dc.InputStreams.Contains(in0));
            Assert.IsTrue(dc.InputStreams.Contains(in1));
            Assert.IsTrue(dc.InputStreams.Contains(in2));
            Assert.IsTrue(dc.OutputStreams.Contains(out0));
            Assert.IsTrue(dc.OutputStreams.Contains(out0));

            // Validate and report the validation results
            Maybe<string> conVal = con.Validate();
            Assert.IsTrue(conVal, conVal.Item2);

            Assert.IsTrue(amp.Coalesce == CoalescingDevice.OneItemCoalesce);
        }
        private static Epoch CreateTestEpoch(out ExternalDeviceBase dev1, out ExternalDeviceBase dev2)
        {
            dev1 = new UnitConvertingExternalDevice("dev1", "man1", new Measurement(0, "V"));
            dev2 = new UnitConvertingExternalDevice("dev2", "man2", new Measurement(0, "V"));

            var stream1 = new DAQInputStream("Stream1");
            var stream2 = new DAQInputStream("Stream2");

            var stimParameters = new Dictionary<string, object>();
            stimParameters["param1"] = 1;
            stimParameters["param2"] = 2;

            var srate = new Measurement(1000, "Hz");

            List<Measurement> samples =
                Enumerable.Range(0, 10000).Select(i => new Measurement((decimal)Math.Sin((double)i / 100), "V")).ToList();
            var stimData = new OutputData(samples, srate, false);

            var stim1 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData);
            var stim2 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData)
                {
                    ShouldDataBePersisted = true
                };

            var protocolParameters = new Dictionary<string, object>
                {
                    {"one", 1},
                    {"two", "second"},
                    {"three", 5.55}
                };

            var epoch = new TestEpoch("protocol.banana", protocolParameters);
            epoch.Stimuli[dev1] = stim1;
            epoch.Stimuli[dev2] = stim2;

            DateTimeOffset start = DateTimeOffset.Now;
            epoch.SetStartTime(Maybe<DateTimeOffset>.Yes(start));

            epoch.Backgrounds[dev1] = new Background(new Measurement(0, "V"), new Measurement(1000, "Hz"));
            epoch.Backgrounds[dev2] = new Background(new Measurement(1, "V"), new Measurement(1000, "Hz"));

            epoch.Responses[dev1] = new Response();
            epoch.Responses[dev2] = new Response();

            var streamConfig = new Dictionary<string, object>();
            streamConfig["configParam1"] = 1;

            var devConfig = new Dictionary<string, object>();
            devConfig["configParam2"] = 2;

            IInputData responseData1 = new InputData(samples, srate, start)
                .DataWithStreamConfiguration(stream1, streamConfig)
                .DataWithExternalDeviceConfiguration(dev1, devConfig);
            IInputData responseData2 = new InputData(samples, srate, start + TimeSpanExtensions.FromSamples((uint) samples.Count, srate))
                .DataWithStreamConfiguration(stream1, streamConfig)
                .DataWithExternalDeviceConfiguration(dev1, devConfig);

            IInputData responseData3 = new InputData(samples, srate, start)
                .DataWithStreamConfiguration(stream2, streamConfig)
                .DataWithExternalDeviceConfiguration(dev2, devConfig);
            IInputData responseData4 = new InputData(samples, srate, start + TimeSpanExtensions.FromSamples((uint)samples.Count, srate))
                .DataWithStreamConfiguration(stream2, streamConfig)
                .DataWithExternalDeviceConfiguration(dev2, devConfig);

            epoch.Responses[dev1].AppendData(responseData1);
            epoch.Responses[dev1].AppendData(responseData2);

            epoch.Responses[dev2].AppendData(responseData3);
            epoch.Responses[dev2].AppendData(responseData4);

            epoch.Properties.Add("prop1", 5);
            epoch.Properties.Add("prop2", "banana");

            epoch.Keywords.Add("word1");
            epoch.Keywords.Add("word2");

            return epoch;
        }
        public void GetStreamReturnsStreamWithName()
        {
            var c = new SimpleDAQController();

            const string name = "stream-name";
            var outStream = new DAQOutputStream(name);
            (c as IMutableDAQController).AddStream(outStream);
            var inputStream = new DAQInputStream(name);
            (c as IMutableDAQController).AddStream(inputStream);

            Assert.That(c.GetStream<IDAQOutputStream>(name), Is.EqualTo(outStream));
            Assert.That(c.GetStream<IDAQInputStream>(name), Is.EqualTo(inputStream));
        }
        public void PushesDataToEpoch()
        {
            const string UNUSED_NAME = "UNUSED";

            var daq = new SimpleDAQController();
            var c = new NonValidatingController { DAQController = daq };
            var dev = new UnitConvertingExternalDevice(UNUSED_NAME, UNUSED_DEVICE_MANUFACTURER, c, UNUSED_BACKGROUND);
            var outStream = new DAQOutputStream("out");
            var inStream = new DAQInputStream("in");

            dev.BindStream(outStream).BindStream(inStream);

            var srate = new Measurement(100, "Hz");
            var samples = Enumerable.Range(0, 100).Select(i => new Measurement(1, "V")).ToList();

            var e = new Epoch("PushesDataToEpoch");
            e.Responses[dev] = new Response();

            e.Stimuli[dev] = new RenderedStimulus((string) "ID1", (IDictionary<string, object>) new Dictionary<string, object>(), (IOutputData) new OutputData(samples, srate, false));

            var data = new InputData(samples, srate, DateTimeOffset.Now).DataWithStreamConfiguration(inStream, new Dictionary<string, object>());
            bool pushed = false;

            daq.Started += (evt, args) =>
                {
                    c.PushInputData(dev, data);
                    pushed = true;

                    c.RequestStop();
                };

            c.EnqueueEpoch(e);
            c.StartAsync(null);

            while (!pushed)
            {
                Thread.Sleep(1);
            }

            Assert.That(e.Responses[dev].Data, Is.EqualTo(data.Data));
            Assert.That(e.Responses[dev].InputTime, Is.EqualTo(data.InputTime));
            Assert.That(e.Responses[dev].DataConfigurationSpans.First().Nodes.First(),
                Is.EqualTo(data.NodeConfigurationWithName(inStream.Name)));
        }
        public void ShouldAllowLongStringEpochParameters()
        {
            if (File.Exists("..\\..\\..\\ShouldAllowLongStringEpochParameters.h5"))
                File.Delete("..\\..\\..\\ShouldAllowLongStringEpochParameters.h5");

            var gID = new Guid("{2F2719F7-4A8C-4C22-9698-BE999DBC5385}");
            using (
                var exp = new EpochHDF5Persistor("..\\..\\..\\ShouldAllowLongStringEpochParameters.h5", null, () => gID)
                )
            {
                var time = new DateTimeOffset(1000, TimeSpan.Zero);
                var guid = new Guid("053C64D4-ED7A-4128-AA43-ED115716A97D");
                var props = new Dictionary<string, object>();
                props["key1"] =
                    "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
                    //100 elements
                props["key2"] = 2;

                const string protocolID = "Epoch.Fixture";
                Dictionary<string, object> parameters = props;

                dev1 = new UnitConvertingExternalDevice(dev1Name, "DEVICECO", new Measurement(0, "V"));
                dev2 = new UnitConvertingExternalDevice(dev2Name, "DEVICECO", new Measurement(0, "V"));

                var stream1 = new DAQInputStream("Stream1");
                var stream2 = new DAQInputStream("Stream2");

                var stimParameters = new Dictionary<string, object>();
                stimParameters[param1] = value1;
                stimParameters[param2] = value2;

                var srate = new Measurement(1000, "Hz");

                List<Measurement> samples =
                    Enumerable.Range(0, 10000).Select(i => new Measurement((decimal) Math.Sin((double) i/100), "mV")).
                        ToList();
                var stimData = new OutputData(samples, srate, false);

                var stim1 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData);
                    //.Data does not need to be persisted
                var stim2 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData);
                    //.Data does not need to be persisted

                var e = new Epoch(protocolID, parameters);
                e.Stimuli[dev1] = stim1;
                e.Stimuli[dev2] = stim2;

                DateTimeOffset start = DateTimeOffset.Parse("1/11/2011 6:03:29 PM -08:00");
                // Do this to match the XML stored in the EpochXML.txt resource
                e.StartTime = Maybe<DateTimeOffset>.Yes(start);

                e.Background[dev1] = new Epoch.EpochBackground(new Measurement(0, "V"), new Measurement(1000, "Hz"));
                e.Background[dev2] = new Epoch.EpochBackground(new Measurement(1, "V"), new Measurement(1000, "Hz"));

                e.Responses[dev1] = new Response();
                e.Responses[dev2] = new Response();

                var streamConfig = new Dictionary<string, object>();
                streamConfig[param1] = value1;

                var devConfig = new Dictionary<string, object>();
                devConfig[param2] = value2;

                IInputData responseData1 = new InputData(samples, srate, start)
                    .DataWithStreamConfiguration(stream1, streamConfig)
                    .DataWithExternalDeviceConfiguration(dev1, devConfig);
                IInputData responseData2 = new InputData(samples, srate, start)
                    .DataWithStreamConfiguration(stream2, streamConfig)
                    .DataWithExternalDeviceConfiguration(dev2, devConfig);

                e.Responses[dev1].AppendData(responseData1);
                e.Responses[dev2].AppendData(responseData2);

                e.Keywords.Add(kw1);
                e.Keywords.Add(kw2);

                exp.BeginEpochGroup("label", "source identifier", new[] {"keyword1", "keyword2"}, props, guid,
                                    time);

                exp.Serialize(e);

                exp.EndEpochGroup(time.AddMilliseconds(100));
                exp.Close();
            }

            H5.Close();

            var startInfo = new ProcessStartInfo(@"..\..\..\..\..\..\externals\HDF5\bin\h5dump",
                                                 @" --xml ..\..\..\ShouldAllowLongStringEpochParameters.h5");
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            Process proc = Process.Start(startInfo);

            Approvals.VerifyXml(proc.StandardOutput.ReadToEnd());
        }
        public void InputStreamSetSampleRateUnits()
        {
            DAQInputStream s = new DAQInputStream("");

            s.SampleRate = new Measurement(10, "A");
        }
        public void InputStreamSetSampleRateNegativeRate()
        {
            DAQInputStream s = new DAQInputStream("");

            s.SampleRate = new Measurement(-1, "Hz");
        }
        public void StreamSetSampleRate()
        {
            DAQInputStream s1 = new DAQInputStream("");
            Measurement expected = new Measurement(10, "Hz");

            s1.SampleRate = expected;
            Assert.AreEqual(expected, s1.SampleRate);

            DAQOutputStream s2 = new DAQOutputStream("");
            s2.SampleRate = expected;

            Assert.AreEqual(expected, s2.SampleRate);
        }
        public void PushesDataToDevices()
        {
            String units = "V";
            DAQInputStream s = new DAQInputStream("IN");
            s.MeasurementConversionTarget = units;

            TestDevice inDevice = new TestDevice("IN-DEVICE", null);
            inDevice.MeasurementConversionTarget = units;

            inDevice.BindStream(s);

            IList<IMeasurement> data = new List<IMeasurement>(2);
            data.Add(new Measurement(1, units));
            data.Add(new Measurement(2, units));

            IMeasurement sampleRate = new Measurement(1000, "Hz");
            DateTimeOffset time = DateTimeOffset.Now;
            IDictionary<string, object> config = null;

            IInputData inData = new InputData(data, sampleRate, time);
            s.PushInputData(inData);

            IInputData actual = inDevice.InputData[s].First();

            CollectionAssert.AreEqual(inData.Data, actual.Data);
            Assert.AreEqual(inData.InputTime, actual.InputTime);
        }
        public void InputStreamShouldReadValue()
        {
            var controller = Substitute.For<IDAQController>();
            var s = new DAQInputStream("test", controller)
                {
                    MeasurementConversionTarget = "V"
                };

            var expected = new InputData(Enumerable.Repeat(new Measurement(1, "V"), 1), null, DateTimeOffset.Now);

            controller.ReadStream(s).Returns(expected);

            var actual = s.Read();

            controller.Received().ReadStream(s);
        }
        public void ShouldAllowNumericEpochParameters()
        {
            if (File.Exists("..\\..\\..\\ShouldAllowNumericEpochParameters.h5"))
                File.Delete("..\\..\\..\\ShouldAllowNumericEpochParameters.h5");

            var gID = new Guid("{2F2719F7-4A8C-4C22-9698-BE999DBC5385}");
            using (var exp = new EpochHDF5Persistor("..\\..\\..\\ShouldAllowNumericEpochParameters.h5", null, () => gID)
                )
            {
                var time = new DateTimeOffset(1000, TimeSpan.Zero);
                var guid = new Guid("053C64D4-ED7A-4128-AA43-ED115716A97D");
                var props = new Dictionary<string, object>();
                props["int"] = 2;
                props["float"] = 2.0f;
                props["double"] = 2.0d;
                props["decimal"] = 2.0m;
                props["array"] = new[] {1.0, 2.0, 3.0};
                props["short"] = (short) 2;
                props["unit16"] = (UInt16) 1;
                props["uint32"] = (UInt32) 2;
                props["byte"] = (byte) 1;
                props["bool"] = true;

                const string protocolID = "Epoch.Fixture";
                Dictionary<string, object> parameters = props;

                dev1 = new UnitConvertingExternalDevice(dev1Name, "DEVICECO", new Measurement(0, "V"));
                dev2 = new UnitConvertingExternalDevice(dev2Name, "DEVICECO", new Measurement(0, "V"));

                var stream1 = new DAQInputStream("Stream1");
                var stream2 = new DAQInputStream("Stream2");

                var stimParameters = new Dictionary<string, object>();
                stimParameters[param1] = value1;
                stimParameters[param2] = value2;

                var srate = new Measurement(1000, "Hz");

                List<Measurement> samples =
                    Enumerable.Range(0, 10000).Select(i => new Measurement((decimal) Math.Sin((double) i/100), "V")).
                        ToList();
                var stimData = new OutputData(samples, srate, false);

                var stim1 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData);
                    //.Data does not need to be persisted
                var stim2 = new RenderedStimulus("RenderedStimulus", stimParameters, stimData);
                    //.Data does not need to be persisted

                var e = new Epoch(protocolID, parameters);
                e.Stimuli[dev1] = stim1;
                e.Stimuli[dev2] = stim2;

                DateTimeOffset start = DateTimeOffset.Parse("1/11/2011 6:03:29 PM -08:00");
                // Do this to match the XML stored in the EpochXML.txt resource
                e.StartTime = Maybe<DateTimeOffset>.Yes(start);

                e.Background[dev1] = new Epoch.EpochBackground(new Measurement(0, "V"), new Measurement(1000, "Hz"));
                e.Background[dev2] = new Epoch.EpochBackground(new Measurement(1, "V"), new Measurement(1000, "Hz"));

                e.Responses[dev1] = new Response();
                e.Responses[dev2] = new Response();

                var streamConfig = new Dictionary<string, object>();
                streamConfig[param1] = value1;

                var devConfig = new Dictionary<string, object>();
                devConfig[param2] = value2;

                IInputData responseData1 = new InputData(samples, srate, start)
                    .DataWithStreamConfiguration(stream1, streamConfig)
                    .DataWithExternalDeviceConfiguration(dev1, devConfig);
                IInputData responseData2 = new InputData(samples, srate, start)
                    .DataWithStreamConfiguration(stream2, streamConfig)
                    .DataWithExternalDeviceConfiguration(dev2, devConfig);

                e.Responses[dev1].AppendData(responseData1);
                e.Responses[dev2].AppendData(responseData2);

                e.Keywords.Add(kw1);
                e.Keywords.Add(kw2);

                exp.BeginEpochGroup("label", "source identifier", new[] {"keyword1", "keyword2"}, props, guid,
                                    time);
                exp.Serialize(e);
                exp.EndEpochGroup();
                exp.Close();
            }

            H5.Close();
            Approvals.VerifyFile("..\\..\\..\\ShouldAllowNumericEpochParameters.h5");
        }
        public void ShouldTruncateResponseAtEpochBoundary()
        {
            Converters.Register("V", "V",
                (IMeasurement m) => m);

            var daq = new SimpleDAQController();
            var c = new NonValidatingController { DAQController = daq };
            var dev = new UnitConvertingExternalDevice("dev", UNUSED_DEVICE_MANUFACTURER, c, UNUSED_BACKGROUND);
            var outStream = new DAQOutputStream("out");
            var inStream = new DAQInputStream("in");
            dev.BindStream(outStream).BindStream(inStream);

            var sampleRate = new Measurement(1, "Hz");

            var samples = new List<IMeasurement> { new Measurement(1, "V"), new Measurement(2, "V"), new Measurement(3, "V") };

            var data = new OutputData(samples,
                                      sampleRate, true);

            var e = new Epoch(UNUSED_PROTOCOL);

            e.Stimuli[dev] = new RenderedStimulus((string) "ID1",
                                                   (IDictionary<string, object>) new Dictionary<string, object>(),
                                                   (IOutputData) data);
            e.Responses[dev] = new Response();

            bool pushed = false;
            daq.Started += (evt, args) =>
            {
                c.PullOutputData(dev, data.Duration);
                c.PushInputData(dev, new InputData(samples.Concat(samples).ToList(),
                                                   sampleRate,
                                                   DateTimeOffset.Now)
                                         .DataWithStreamConfiguration(streamFake, new Dictionary<string, object>())
                                         .DataWithExternalDeviceConfiguration(devFake, new Dictionary<string, object>()));
                pushed = true;

                c.RequestStop();
            };

            c.EnqueueEpoch(e);
            c.StartAsync(null);

            while (!pushed)
            {
                Thread.Sleep(1);
            }

            Assert.That(((TimeSpan)e.Responses[dev].Duration), Is.EqualTo((TimeSpan)e.Duration));
        }
        public void Setup()
        {
            const string protocolID = "Epoch.Fixture";
            var parameters = new Dictionary<string, object>();
            parameters[param1] = value1;
            parameters[param2] = value2;

            dev1 = new UnitConvertingExternalDevice(dev1Name, "DEVICECO", new Measurement(0, "V"));
            dev2 = new UnitConvertingExternalDevice(dev2Name, "DEVICECO", new Measurement(0, "V"));

            var stream1 = new DAQInputStream("Stream1");
            var stream2 = new DAQInputStream("Stream2");

            var stimParameters = new Dictionary<string, object>();
            stimParameters[param1] = value1;
            stimParameters[param2] = value2;

            var srate = new Measurement(1000, "Hz");

            var samples = Enumerable.Range(0, 1000).Select(i => new Measurement((decimal)Math.Sin((double)i / 100), "V")).ToList();
            var stimData = new OutputData(samples, srate, false);

            RenderedStimulus stim1 = new RenderedStimulus((string) "RenderedStimulus", (IDictionary<string, object>) stimParameters, (IOutputData) stimData); //.Data does not need to be persisted
            RenderedStimulus stim2 = new RenderedStimulus((string) "RenderedStimulus", (IDictionary<string, object>) stimParameters, (IOutputData) stimData); //.Data does not need to be persisted

            Epoch e = new Epoch(protocolID, parameters);
            e.Stimuli[dev1] = stim1;
            e.Stimuli[dev2] = stim2;

            var start = DateTimeOffset.Parse("1/11/2011 6:03:29 PM -08:00");
            // Do this to match the XML stored in the EpochXML.txt resource
            e.StartTime = Maybe<DateTimeOffset>.Yes(start);

            e.Background[dev1] = new Epoch.EpochBackground(new Measurement(0, "V"), new Measurement(1000, "Hz"));
            e.Background[dev2] = new Epoch.EpochBackground(new Measurement(1, "V"), new Measurement(1000, "Hz"));

            e.Responses[dev1] = new Response();
            e.Responses[dev2] = new Response();

            var streamConfig = new Dictionary<string, object>();
            streamConfig[param1] = value1;

            var devConfig = new Dictionary<string, object>();
            devConfig[param2] = value2;

            var responseData1 = new InputData(samples, srate, start)
                .DataWithStreamConfiguration(stream1, streamConfig)
                .DataWithExternalDeviceConfiguration(dev1, devConfig);
            var responseData2 = new InputData(samples, srate, start)
                .DataWithStreamConfiguration(stream2, streamConfig)
                .DataWithExternalDeviceConfiguration(dev2, devConfig);

            e.Responses[dev1].AppendData(responseData1);
            e.Responses[dev2].AppendData(responseData2);

            e.Keywords.Add(kw1);
            e.Keywords.Add(kw2);

            testEpoch = e;
        }
        public void ExternalDeviceStreams()
        {
            var ed = new UnitConvertingExternalDevice("TestDevice", UNUSED_DEVICE_MANUFACTURER, UNUSED_BACKGROUND);

            DAQInputStream in0 = new DAQInputStream("In-0");
            DAQOutputStream out0 = new DAQOutputStream("Out-0");
            ed.BindStream(in0).BindStream(out0);

            Assert.IsTrue(ed.Streams.ContainsKey(in0.Name));
            Assert.IsTrue(in0.Devices.Contains(ed));
            Assert.IsTrue(ed.Streams.ContainsKey(out0.Name));
            Assert.IsTrue(out0.Device == ed);

            ed.UnbindStream("In-0");
            Assert.IsFalse(ed.Streams.ContainsKey(in0.Name));
            Assert.IsFalse(in0.Devices.Contains(ed));
            Assert.IsTrue(ed.Streams.ContainsKey(out0.Name));
            Assert.IsTrue(out0.Device == ed);

            ed.UnbindStream("Out-0");
            Assert.IsFalse(ed.Streams.ContainsKey(in0.Name));
            Assert.IsFalse(in0.Devices.Contains(ed));
            Assert.IsFalse(ed.Streams.ContainsKey(out0.Name));
            Assert.IsFalse(out0.Device == ed);
        }
        public void GetsStreamsByName()
        {
            string name1 = "IN1";
            string name2 = "IN2";
            string name3 = "OUT1";

            IDAQStream in1 = new DAQInputStream(name1);
            IDAQStream in2 = new DAQInputStream(name2);
            IDAQStream in3 = new DAQInputStream(name1);
            IDAQStream out1 = new DAQOutputStream(name3);
            var c = new SimpleDAQController();
            (c as IMutableDAQController).AddStream(in1);
            (c as IMutableDAQController).AddStream(in2);
            (c as IMutableDAQController).AddStream(in3);
            (c as IMutableDAQController).AddStream(out1);

            Assert.AreEqual(2, c.GetStreams(name1).Count());
            Assert.AreEqual(1, c.GetStreams(name2).Count());
            Assert.AreEqual(1, c.GetStreams(name3).Count());

            Assert.AreEqual(in2, c.GetStreams(name2).First());
            Assert.AreEqual(out1, c.GetStreams(name3).First());
        }
        private static Controller SetupController(double sampleRate, out Epoch e, out IExternalDevice dev0, out RenderedStimulus stim1, out IExternalDevice dev1, out RenderedStimulus stim2, out IList<IMeasurement> stimData, int nChannels)
        {
            Converters.Clear();
            Converters.Register("V", "V",
                // just an identity conversion for now, to pass Validate()
                                (IMeasurement m) => m);

            // use an incrementing clock so timestamps are predictable
            var incrementingClock = new IncrementingClock();

            var daq = new SimulationDAQController { Clock = incrementingClock };

            var out0 = new DAQOutputStream("Out0")
            {
                MeasurementConversionTarget = "V",
                Clock = daq.Clock,
                SampleRate = new Measurement((decimal)sampleRate, "Hz")
            };

            var out1 = new DAQOutputStream("Out1")
            {
                MeasurementConversionTarget = "V",
                Clock = daq.Clock,
                SampleRate = new Measurement((decimal)sampleRate, "Hz")
            };

            var in0 = new DAQInputStream("In0")
                {
                    MeasurementConversionTarget = "V",
                    Clock = daq.Clock,
                    SampleRate = new Measurement((decimal) sampleRate, "Hz")
                };

            var in1 = new DAQInputStream("In1")
            {
                MeasurementConversionTarget = "V",
                Clock = daq.Clock,
                SampleRate = new Measurement((decimal)sampleRate, "Hz")
            };

            daq.AddStream(out0);
            daq.AddStream(out1);
            daq.AddStream(in0);
            daq.AddStream(in1);

            var controller = new Controller(daq, daq.Clock);

            var streamNameMap = new Dictionary<string, string>();
            streamNameMap["Out0"] = "In0";
            if (nChannels > 1)
                streamNameMap["Out1"] = "In1";

            foreach (var stream in daq.Streams)
            {
                stream.SampleRate = new Measurement((decimal) sampleRate, "Hz");
            }

            daq.SimulationRunner += (output, timestep) =>
                                        {
                                            var input = new ConcurrentDictionary<IDAQInputStream, IInputData>();

                                            Parallel.ForEach(output, (kv) =>
                                                                         {
                                                                             var outData = kv.Value;
                                                                             var outStream = kv.Key;
                                                                             var inStream = daq.InputStreams.Where((s) =>
                                                                                                                   s.Name == streamNameMap[outStream.Name]).First();

                                                                             var data = outData.DataWithUnits("V").Data;
                                                                             var inData = new InputData(data,
                                                                                                        outData.SampleRate,
                                                                                                        incrementingClock.Now)
                                                                                                        .DataWithNodeConfiguration("SimulationController",daq.Configuration);

                                                                             input[inStream] = inData;
                                                                         }
                                                );

                                            return input;
                                        };

            var protocolParams = new Dictionary<string, object>(1);
            protocolParams["key1"] = "value1";

            e = new Epoch("LowGainSimulation", protocolParams);

            dev0 = new UnitConvertingExternalDevice("Device0", "Manufacturer", controller, new Measurement(0, "V"))
                {
                    MeasurementConversionTarget = "V",
                    Clock = daq.Clock,
                    InputSampleRate = new Measurement((decimal)sampleRate, "Hz"),
                    OutputSampleRate = new Measurement((decimal)sampleRate, "Hz")
                };
            dev0.BindStream(out0);
            dev0.BindStream(in0);

            dev1 = new UnitConvertingExternalDevice("Device1", "Manufacturer", controller, new Measurement(0, "V"))
                {
                    MeasurementConversionTarget = "V",
                    Clock = daq.Clock,
                    InputSampleRate = new Measurement((decimal)sampleRate, "Hz"),
                    OutputSampleRate = new Measurement((decimal)sampleRate, "Hz")
                };
            dev1.BindStream(out1);
            dev1.BindStream(in1);

            if (nChannels == 1)
            {
                dev1.UnbindStream(dev1.Streams.Values.First().Name);
            }

            stimData = Enumerable.Range(0, (int)(10 * sampleRate))
                                   .Select(i => new Measurement(i, -3, "V") as IMeasurement)
                                   .ToList();
            var srate = new Measurement((decimal) sampleRate, "Hz");

            stim1 = new RenderedStimulus((string) "RenderedStimulus",
                                         (IDictionary<string, object>) new Dictionary<string, object>(),
                                         (IOutputData) new OutputData(stimData, srate, false));
            stim2 = new RenderedStimulus((string) "RenderedStimulus",
                                         (IDictionary<string, object>) new Dictionary<string, object>(),
                                         (IOutputData) new OutputData(stimData, srate, false));

            e.Stimuli[dev0] = stim1;

            if (nChannels > 1)
                e.Stimuli[dev1] = stim2;

            e.Responses[dev0] = new Response();
            if (nChannels > 1)
                e.Responses[dev1] = new Response();

            e.Backgrounds[dev0] = new Background(new Measurement(0, "V"), srate);
            e.Backgrounds[dev1] = new Background(new Measurement(0, "V"), srate);

            return controller;
        }