コード例 #1
0
ファイル: DataStoreReader.cs プロジェクト: annelo-msft/psi
 /// <summary>
 /// Updates the cursor epsilon for a registered instant visualization object.
 /// </summary>
 /// <param name="registrationToken">The registration token that the target was given when it was initially registered.</param>
 /// <param name="epsilon">A relative time interval specifying the window around a message time that may be considered a match.</param>
 internal void UpdateInstantDataTargetEpsilon(Guid registrationToken, RelativeTimeInterval epsilon)
 {
     foreach (IStreamReader streamReader in this.streamReaders)
     {
         streamReader.UpdateInstantDataTargetEpsilon(registrationToken, epsilon);
     }
 }
コード例 #2
0
ファイル: RelativeTimeWindow.cs プロジェクト: yusharth/psi
 /// <summary>
 /// Initializes a new instance of the <see cref="RelativeTimeWindow{TInput, TOutput}"/> class.
 /// </summary>
 /// <param name="pipeline">Pipeline to which this component belongs.</param>
 /// <param name="relativeTimeInterval">The relative time interval over which to gather messages.</param>
 /// <param name="selector">Select output message from collected window of input messages.</param>
 public RelativeTimeWindow(Pipeline pipeline, RelativeTimeInterval relativeTimeInterval, Func <IEnumerable <Message <TInput> >, TOutput> selector)
     : base(pipeline)
 {
     this.relativeTimeInterval = relativeTimeInterval;
     this.selector             = selector;
     this.In.Unsubscribed     += _ => this.OnUnsubscribed();
 }
コード例 #3
0
        /// <summary>
        /// Crop a store, generating a new store.
        /// </summary>
        /// <param name="store">Store name.</param>
        /// <param name="path">Store path.</param>
        /// <param name="output">Output store name.</param>
        /// <param name="start">Start time relative to beginning.</param>
        /// <param name="length">Length relative to start.</param>
        /// <returns>Success flag.</returns>
        internal static int CropStore(string store, string path, string output, string start, string length)
        {
            Console.WriteLine($"Concatenating stores (stores={store}, path={path}, output={output}, start={start}, length={length})");

            var startTime = TimeSpan.Zero; // start at beginning if unspecified

            if (!string.IsNullOrWhiteSpace(start) && !TimeSpan.TryParse(start, CultureInfo.InvariantCulture, out startTime))
            {
                throw new Exception($"Could not parse start time '{start}' (see https://docs.microsoft.com/en-us/dotnet/api/system.timespan.parse for valid format).");
            }

            var lengthRelativeInterval = RelativeTimeInterval.LeftBounded(TimeSpan.Zero); // continue to end if unspecified

            if (!string.IsNullOrWhiteSpace(length))
            {
                if (TimeSpan.TryParse(length, CultureInfo.InvariantCulture, out var lengthTimeSpan))
                {
                    lengthRelativeInterval = RelativeTimeInterval.Future(lengthTimeSpan);
                }
                else
                {
                    throw new Exception($"Could not parse length '{length}' (see https://docs.microsoft.com/en-us/dotnet/api/system.timespan.parse for valid format).");
                }
            }

            Store.Crop((store, path), (output, path), startTime, lengthRelativeInterval, true, new Progress <double>(p => Console.WriteLine($"Progress: {p * 100.0:F2}%")), Console.WriteLine);
            return(0);
        }
コード例 #4
0
        /// <inheritdoc/>
        public Guid RegisterStreamValueSubscriber <TTarget>(
            IStreamAdapter streamAdapter,
            RelativeTimeInterval epsilonTimeInterval,
            Action <bool, TTarget, DateTime, DateTime> callback)
        {
            var publisher = default(StreamValuePublisher <TSource, TTarget>);

            lock (this.publishers)
            {
                // Check if we have a publisher for this epsilon interval
                if (!this.publishers.ContainsKey(epsilonTimeInterval))
                {
                    this.publishers.Add(epsilonTimeInterval, new List <IStreamValuePublisher <TSource> >());
                }

                // Get the list of publishers for the specified epsilon interval
                var epsilonTimeIntervalPublishers = this.publishers[epsilonTimeInterval];

                // Check if we already have a publisher that uses the specified stream adapter
                publisher = epsilonTimeIntervalPublishers.FirstOrDefault(p => p.StreamAdapter.Equals(streamAdapter)) as StreamValuePublisher <TSource, TTarget>;
                if (publisher == null)
                {
                    // If not found, create a new publisher
                    publisher = new StreamValuePublisher <TSource, TTarget>(streamAdapter);
                    epsilonTimeIntervalPublishers.Add(publisher);
                }
            }

            // Register the subscriber with this publisher
            return(publisher.RegisterSubscriber(callback));
        }
コード例 #5
0
ファイル: MainWindow.cs プロジェクト: danbohus/psi-samples
        private void MainWindow_Shown(object sender, EventArgs e)
        {
            // Create the \psi pipeline
            this.pipeline = Pipeline.Create();

            // Create the webcam component
            var webcam = new MediaCapture(this.pipeline, 640, 480, "/dev/video0", PixelFormatId.YUYV);

            // Create the audio capture component
            var audio = new AudioCapture(this.pipeline, new AudioCaptureConfiguration {
                DeviceName = "plughw:0,0", Format = WaveFormat.Create16kHz1Channel16BitPcm()
            });

            // Create an acoustic features extractor component and pipe the audio to it
            var acousticFeatures = new AcousticFeaturesExtractor(this.pipeline);

            audio.PipeTo(acousticFeatures);

            // Fuse the webcam images with the audio log energy level
            var webcamWithAudioEnergy = webcam.Join(acousticFeatures.LogEnergy, RelativeTimeInterval.Past());

            // Overlay the audio energy on the webcam image and display it in the window.
            // The "Do" operator is executed on each fused webcam and audio energy sample.
            webcamWithAudioEnergy.Do(
                frame =>
            {
                // Update the window with the latest frame
                this.DrawFrame(frame);
            },
                DeliveryPolicy.LatestMessage);

            // Start the pipeline running
            this.pipeline.RunAsync();
        }
コード例 #6
0
ファイル: InstantDataTarget.cs プロジェクト: xiangzhi/psi
 /// <summary>
 /// Initializes a new instance of the <see cref="InstantDataTarget"/> class.
 /// </summary>
 /// <param name="streamName">The name of the stream from which to receive updates when new data is available.</param>
 /// <param name="streamAdapter">The stream adapter to convert the raw stream data to the type required by the callback target.</param>
 /// <param name="cursorEpsilon">The cursor epsilon to use when searching for data.</param>
 /// <param name="callback">The method to call when new data is available.</param>
 public InstantDataTarget(string streamName, IStreamAdapter streamAdapter, RelativeTimeInterval cursorEpsilon, Action <object, IndexEntry> callback)
 {
     this.RegistrationToken = Guid.NewGuid();
     this.StreamName        = streamName;
     this.StreamAdapter     = streamAdapter;
     this.CursorEpsilon     = cursorEpsilon;
     this.Callback          = callback;
 }
コード例 #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LastReproducibleInterpolator{T}"/> class.
 /// </summary>
 /// <param name="relativeTimeInterval">The relative time interval within which to search for the first message.</param>
 /// <param name="orDefault">Indicates whether to output a default value when no result is found.</param>
 /// <param name="defaultValue">An optional default value to use.</param>
 public LastReproducibleInterpolator(RelativeTimeInterval relativeTimeInterval, bool orDefault, T defaultValue = default)
 {
     this.relativeTimeInterval = relativeTimeInterval;
     this.orDefault            = orDefault;
     this.defaultValue         = defaultValue;
     this.name =
         (this.orDefault ? $"{nameof(Reproducible)}.{nameof(Available.LastOrDefault)}" : $"{nameof(Reproducible)}.{nameof(Available.Last)}") +
         this.relativeTimeInterval.ToString();
 }
コード例 #8
0
        private bool initialBuffer; // constructing first initial buffer

        /// <summary>
        /// Initializes a new instance of the <see cref="RelativeTimeWindow{TInput, TOutput}"/> class.
        /// </summary>
        /// <param name="pipeline">Pipeline to which this component belongs.</param>
        /// <param name="relativeTimeInterval">The relative time interval over which to gather messages.</param>
        /// <param name="selector">Select output message from collected window of input messages.</param>
        /// <param name="waitForCompleteWindow">Whether to wait for seeing a complete window before computing the selector function and posting the first time. True by default.</param>
        public RelativeTimeWindow(Pipeline pipeline, RelativeTimeInterval relativeTimeInterval, Func <IEnumerable <Message <TInput> >, TOutput> selector, bool waitForCompleteWindow = true)
            : base(pipeline)
        {
            this.relativeTimeInterval = relativeTimeInterval;
            this.selector             = selector;
            this.In.Unsubscribed     += _ => this.OnUnsubscribed();

            // If false, processing should begin immediately without waiting for full window length.
            this.initialBuffer = waitForCompleteWindow;
        }
コード例 #9
0
        public void ImplicitCastsToInterpolator()
        {
            var tolerance = TimeSpan.FromSeconds(1);
            var window    = new RelativeTimeInterval(-tolerance, tolerance);

            // note: takes Match.Interpolator, but passing TimeSpan/RelativeTimeInterval below
            Func <Match.Interpolator <int>, Match.Interpolator <int> > testFn = id => id;

            this.AssertInterpolatorProperties <int>(testFn(tolerance /* TimeSpan, converted to Match.Best<int>() */), -tolerance, tolerance, true, false);
            this.AssertInterpolatorProperties <int>(testFn(new RelativeTimeInterval(-tolerance, tolerance) /* RelativeTimeInterval, converted to Match.Best<int>() */), -tolerance, tolerance, true, false);
        }
コード例 #10
0
ファイル: IntervalTests.cs プロジェクト: yusharth/psi
        public void RelativeTimeIntervalCoverage()
        {
            var a = new RelativeTimeInterval(TimeSpan.FromSeconds(7), TimeSpan.FromSeconds(42));
            var b = new RelativeTimeInterval(TimeSpan.FromSeconds(40), TimeSpan.FromSeconds(50));
            var c = new RelativeTimeInterval(TimeSpan.FromSeconds(200), TimeSpan.FromSeconds(100)); // negative
            var e = RelativeTimeInterval.Empty;

            var empty  = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { });
            var single = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { a });
            var ab     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { a, b });
            var ba     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { b, a });
            var ac     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { a, c });
            var ca     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { c, a });
            var ae     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { a, e });
            var ea     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { e, a });
            var bc     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { b, c });
            var cb     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { c, b });
            var be     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { b, e });
            var eb     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { e, b });
            var ce     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { c, e });
            var ec     = RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { e, c });

            Assert.IsTrue(c.IsNegative);
            Assert.AreEqual(TimeSpan.Zero, empty.Right);
            Assert.AreEqual(TimeSpan.Zero, empty.Left);
            Assert.AreEqual(a.Left, single.Left);
            Assert.AreEqual(a.Right, single.Right);
            Assert.AreEqual(ab.Left, a.Left);
            Assert.AreEqual(ab.Right, b.Right);
            Assert.AreEqual(ba.Left, a.Left);
            Assert.AreEqual(ba.Right, b.Right);
            Assert.AreEqual(ac.Left, a.Left);
            Assert.AreEqual(ac.Right, c.Left); // c is negative
            Assert.AreEqual(ae.Left, a.Left);
            Assert.AreEqual(ae.Right, a.Right);
            Assert.AreEqual(ea.Left, a.Left);
            Assert.AreEqual(ea.Right, a.Right);
            Assert.AreEqual(ca.Left, a.Left);
            Assert.AreEqual(ca.Right, c.Left); // c is negative
            Assert.AreEqual(bc.Left, b.Left);
            Assert.AreEqual(bc.Right, c.Left); // c is negative
            Assert.AreEqual(cb.Left, b.Left);
            Assert.AreEqual(cb.Right, c.Left); // c is negative
            Assert.AreEqual(be.Left, b.Left);
            Assert.AreEqual(be.Right, b.Right);
            Assert.AreEqual(eb.Left, b.Left);
            Assert.AreEqual(eb.Right, b.Right);
            Assert.AreEqual(ce.Left, c.Right);                                                      // c is negative
            Assert.AreEqual(ec.Right, c.Left);                                                      // c is negative
            Assert.IsTrue(RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { }).IsEmpty);   // empty sequence -> empty interval
            Assert.IsTrue(RelativeTimeInterval.Coverage(new RelativeTimeInterval[] { e }).IsEmpty); // sequence of only empty intervals -> empty interval
        }
コード例 #11
0
        public void SparseSample()
        {
            List <int> results = new List <int>();

            using (var p = Pipeline.Create())
            {
                Generators.Sequence(p, 0, i => i + 1, 10, TimeSpan.FromTicks(100))
                .Sample(TimeSpan.FromTicks(300), Match.Best <int>(RelativeTimeInterval.RightBounded(TimeSpan.Zero)))
                .Do(results.Add);

                p.Run();
            }

            CollectionAssert.AreEqual(new int[] { 0, 3, 6, 9 }, results);
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FirstReproducibleInterpolator{T}"/> class.
        /// </summary>
        /// <param name="relativeTimeInterval">The relative time interval within which to search for the first message.</param>
        /// <param name="orDefault">Indicates whether to output a default value when no result is found.</param>
        /// <param name="defaultValue">An optional default value to use.</param>
        public FirstReproducibleInterpolator(RelativeTimeInterval relativeTimeInterval, bool orDefault, T defaultValue = default)
        {
            if (!relativeTimeInterval.LeftEndpoint.Bounded)
            {
                throw new NotSupportedException($"{nameof(FirstReproducibleInterpolator<T>)} does not support relative time intervals that are " +
                                                $"left-unbounded. The use of this interpolator in a fusion operation like Fuse or Join could lead to an incremental, " +
                                                $"continuous accumulation of messages on the secondary stream queue held by the fusion component. If you wish to interpolate " +
                                                $"by selecting the very first message in the secondary stream, please instead apply the First() operator on the " +
                                                $"secondary (with an unlimited delivery policy), and use the {nameof(NearestReproducibleInterpolator<T>)}, as this " +
                                                $"will accomplish the same result.");
            }

            this.relativeTimeInterval = relativeTimeInterval;
            this.orDefault            = orDefault;
            this.defaultValue         = defaultValue;
        }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NearestReproducibleInterpolator{T}"/> class.
        /// </summary>
        /// <param name="relativeTimeInterval">The relative time interval within which to search for the first message.</param>
        /// <param name="orDefault">Indicates whether to output a default value when no result is found.</param>
        /// <param name="defaultValue">An optional default value to use.</param>
        public NearestReproducibleInterpolator(RelativeTimeInterval relativeTimeInterval, bool orDefault, T defaultValue = default)
        {
            this.relativeTimeInterval = relativeTimeInterval;
            this.orDefault            = orDefault;
            this.defaultValue         = defaultValue;

            if (this.relativeTimeInterval == RelativeTimeInterval.Zero)
            {
                this.name = this.orDefault ? $"{nameof(Reproducible)}.{nameof(Reproducible.ExactOrDefault)}" : $"{nameof(Reproducible)}.{nameof(Reproducible.Exact)}";
            }
            else
            {
                this.name =
                    (this.orDefault ? $"{nameof(Reproducible)}.{nameof(Reproducible.NearestOrDefault)}" : $"{nameof(Reproducible)}.{nameof(Reproducible.Nearest)}") +
                    this.relativeTimeInterval.ToString();
            }
        }
コード例 #14
0
ファイル: SampleTests.cs プロジェクト: yusharth/psi
        public void SparseSample()
        {
            List <int> results = new List <int>();

            using (var p = Pipeline.Create())
            {
                var source   = Generators.Sequence(p, 0, i => i + 1, 10, TimeSpan.FromTicks(50));
                var filtered = source.Where(i => i % 3 == 0);
                source
                .Sample(filtered, RelativeTimeInterval.Past())
                .Do(results.Add);

                p.Run();
            }

            CollectionAssert.AreEqual(new int[] { 0, 3, 6, 9 }, results);
        }
コード例 #15
0
ファイル: StreamReader{T}.cs プロジェクト: xiangzhi/psi
        /// <inheritdoc />
        public void UpdateInstantDataTargetEpsilon(Guid registrationToken, RelativeTimeInterval epsilon)
        {
            // Unregister and retrieve the old instant data target
            InstantDataTarget target = this.InternalUnregisterInstantDataTarget(registrationToken);

            if (target != null)
            {
                // Update the Ccursor epsilon
                target.CursorEpsilon = epsilon;

                // Create the internal register method
                MethodInfo method        = this.GetType().GetMethod(nameof(this.InternalRegisterInstantDataTarget), BindingFlags.NonPublic | BindingFlags.Instance);
                MethodInfo genericMethod = method.MakeGenericMethod(target.StreamAdapter.DestinationType);

                // Re-register the instant data target
                genericMethod.Invoke(this, new object[] { target });
            }
        }
コード例 #16
0
ファイル: IntervalTests.cs プロジェクト: yusharth/psi
        public void RightBoundedTimeSpanInterval()
        {
            var end      = TimeSpan.FromMinutes(10);
            var interval = RelativeTimeInterval.RightBounded(end);

            Assert.IsFalse(interval.LeftEndpoint.Bounded);
            Assert.IsFalse(interval.LeftEndpoint.Inclusive);
            Assert.AreEqual(TimeSpan.MinValue, interval.Left);
            Assert.IsTrue(interval.RightEndpoint.Bounded);
            Assert.IsTrue(interval.RightEndpoint.Inclusive);
            Assert.AreEqual(end, interval.Right);
            Assert.AreEqual(TimeSpan.MaxValue, interval.Span);
            Assert.IsFalse(interval.IsClosed);
            Assert.IsFalse(interval.IsDegenerate);
            Assert.IsFalse(interval.IsFinite);
            Assert.IsTrue(interval.IsHalfBounded);
            Assert.IsFalse(interval.IsOpen);
        }
コード例 #17
0
ファイル: IntervalTests.cs プロジェクト: yusharth/psi
        public void BoundedTimeSpanInterval()
        {
            var start    = TimeSpan.FromMinutes(-5);
            var end      = TimeSpan.FromMinutes(10);
            var interval = new RelativeTimeInterval(start, true, end, false);

            Assert.IsTrue(interval.LeftEndpoint.Bounded);
            Assert.IsTrue(interval.LeftEndpoint.Inclusive);
            Assert.AreEqual(start, interval.Left);
            Assert.IsTrue(interval.RightEndpoint.Bounded);
            Assert.IsFalse(interval.RightEndpoint.Inclusive);
            Assert.AreEqual(end, interval.Right);
            Assert.AreEqual(end.Subtract(start), interval.Span);
            Assert.IsFalse(interval.IsClosed);
            Assert.IsFalse(interval.IsDegenerate);
            Assert.IsTrue(interval.IsFinite);
            Assert.IsFalse(interval.IsHalfBounded);
            Assert.IsFalse(interval.IsOpen);
        }
コード例 #18
0
        public void InterpolatorKinds()
        {
            var tolerance = TimeSpan.FromSeconds(1);
            var window    = new RelativeTimeInterval(-tolerance, tolerance);

            this.AssertInterpolatorProperties <int>(Match.Any <int>(), TimeSpan.MinValue, TimeSpan.MaxValue, false, false);
            this.AssertInterpolatorProperties <int>(Match.Any <int>(tolerance), -tolerance, tolerance, false, false);
            this.AssertInterpolatorProperties <int>(Match.Any <int>(window), -tolerance, tolerance, false, false);
            this.AssertInterpolatorProperties <int>(Match.AnyOrDefault <int>(), TimeSpan.MinValue, TimeSpan.MaxValue, false, true);
            this.AssertInterpolatorProperties <int>(Match.AnyOrDefault <int>(tolerance), -tolerance, tolerance, false, true);
            this.AssertInterpolatorProperties <int>(Match.AnyOrDefault <int>(window), -tolerance, tolerance, false, true);
            this.AssertInterpolatorProperties <int>(Match.Best <int>(), TimeSpan.MinValue, TimeSpan.MaxValue, true, false);
            this.AssertInterpolatorProperties <int>(Match.Best <int>(tolerance), -tolerance, tolerance, true, false);
            this.AssertInterpolatorProperties <int>(Match.Best <int>(window), -tolerance, tolerance, true, false);
            this.AssertInterpolatorProperties <int>(Match.BestOrDefault <int>(), TimeSpan.MinValue, TimeSpan.MaxValue, true, true);
            this.AssertInterpolatorProperties <int>(Match.BestOrDefault <int>(tolerance), -tolerance, tolerance, true, true);
            this.AssertInterpolatorProperties <int>(Match.BestOrDefault <int>(window), -tolerance, tolerance, true, true);
            this.AssertInterpolatorProperties <int>(Match.Exact <int>(), TimeSpan.Zero, TimeSpan.Zero, true, false);
            this.AssertInterpolatorProperties <int>(Match.ExactOrDefault <int>(), TimeSpan.Zero, TimeSpan.Zero, true, true);
        }
コード例 #19
0
ファイル: IntervalTests.cs プロジェクト: yusharth/psi
        public void TimeIntervalFromDateTimeAndLeftBoundedTimeSpanInterval()
        {
            var start                       = TimeSpan.FromMinutes(-5);
            var timeSpanInterval            = RelativeTimeInterval.LeftBounded(start);
            var leftBoundedTimeSpanInterval = RelativeTimeInterval.LeftBounded(start);
            var origin                      = DateTime.Now;
            var timeInterval                = new TimeInterval(origin, timeSpanInterval);

            Assert.IsTrue(timeInterval.LeftEndpoint.Bounded);
            Assert.IsTrue(timeInterval.LeftEndpoint.Inclusive);
            Assert.AreEqual(origin + start, timeInterval.Left);
            Assert.IsFalse(timeInterval.RightEndpoint.Bounded);
            Assert.IsFalse(timeInterval.RightEndpoint.Inclusive);
            Assert.AreEqual(DateTime.MaxValue, timeInterval.Right);
            Assert.AreEqual(TimeSpan.MaxValue, timeInterval.Span);
            Assert.IsFalse(timeInterval.IsClosed);
            Assert.IsFalse(timeInterval.IsDegenerate);
            Assert.IsFalse(timeInterval.IsFinite);
            Assert.IsTrue(timeInterval.IsHalfBounded);
            Assert.IsFalse(timeInterval.IsOpen);
        }
コード例 #20
0
ファイル: IntervalTests.cs プロジェクト: yusharth/psi
        public void TimeIntervalFromDateTimeAndTimeSpanIntervalUsingOperator()
        {
            var start            = TimeSpan.FromMinutes(-5);
            var end              = TimeSpan.FromMinutes(10);
            var timeSpanInterval = new RelativeTimeInterval(start, end);
            var origin           = DateTime.Now;
            var timeInterval     = origin + timeSpanInterval;

            Assert.IsTrue(timeInterval.LeftEndpoint.Bounded);
            Assert.IsTrue(timeInterval.LeftEndpoint.Inclusive);
            Assert.AreEqual(origin + start, timeInterval.Left);
            Assert.IsTrue(timeInterval.RightEndpoint.Bounded);
            Assert.IsTrue(timeInterval.RightEndpoint.Inclusive);
            Assert.AreEqual(origin + end, timeInterval.Right);
            Assert.AreEqual(TimeSpan.FromMinutes(15), timeInterval.Span);
            Assert.IsTrue(timeInterval.IsClosed);
            Assert.IsFalse(timeInterval.IsDegenerate);
            Assert.IsTrue(timeInterval.IsFinite);
            Assert.IsFalse(timeInterval.IsHalfBounded);
            Assert.IsFalse(timeInterval.IsOpen);
        }
コード例 #21
0
ファイル: APITester.cs プロジェクト: vdedyukhin/psi
        public void JoinRepeatPipeline()
        {
            using (var p = Pipeline.Create("JoinRepeatPipeline"))
            {
                // create a generator that will produce a finite sequence
                var generator = Generators.Sequence(p, 1, x => x + 1, count: 100);

                var some = generator.Where(x => x % 10 == 0);

                var join = Operators.Join(
                    generator.Out,
                    some.Out,
                    Match.Any <int>(RelativeTimeInterval.RightBounded(TimeSpan.Zero)),
                    (all, _) => all);

                // var output = join.Do(x => Console.WriteLine(x));
                var check = join.Do((d, e) => Assert.AreEqual(d, e.SequenceId + 9));

                // start and run the pipeline
                p.Run();
            }
        }
コード例 #22
0
ファイル: StreamReader{T}.cs プロジェクト: xiangzhi/psi
        private EpsilonInstantStreamReader <T> GetInstantStreamReader(RelativeTimeInterval cursorEpsilon, bool createIfNecessary)
        {
            // Check if we have a registration for this instant stream reader
            lock (this.instantStreamReaders)
            {
                EpsilonInstantStreamReader <T> instantStreamReader = this.instantStreamReaders.FirstOrDefault(isr => isr.CursorEpsilon.Equals(cursorEpsilon));
                if (instantStreamReader == default)
                {
                    if (createIfNecessary)
                    {
                        // Create the instant stream reader
                        instantStreamReader = new EpsilonInstantStreamReader <T>(cursorEpsilon);
                        this.instantStreamReaders.Add(instantStreamReader);
                    }
                    else
                    {
                        throw new ArgumentException("The instant stream reader is not registered.");
                    }
                }

                return(instantStreamReader);
            }
        }
コード例 #23
0
ファイル: Window.cs プロジェクト: areilly711/psi
 /// <summary>
 /// Initializes a new instance of the <see cref="Window{T}"/> class.
 /// </summary>
 /// <param name="pipeline">Pipeline to which this component belongs.</param>
 /// <param name="relativeTimeInterval">The relative time interval over which to gather messages.</param>
 /// <param name="maxSize">Maximum buffer size.</param>
 public Window(Pipeline pipeline, RelativeTimeInterval relativeTimeInterval, int maxSize = int.MaxValue)
     : base(pipeline, maxSize)
 {
     this.relativeTimeInterval = relativeTimeInterval;
     this.InitializeLambdas(this.BufferRemoveCondition, this.BufferProcessor);
 }
コード例 #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NearestAvailableInterpolator{T}"/> class.
 /// </summary>
 /// <param name="relativeTimeInterval">The relative time interval within which to search for the first message.</param>
 /// <param name="orDefault">Indicates whether to output a default value when no result is found.</param>
 /// <param name="defaultValue">An optional default value to use.</param>
 public NearestAvailableInterpolator(RelativeTimeInterval relativeTimeInterval, bool orDefault, T defaultValue = default)
 {
     this.relativeTimeInterval = relativeTimeInterval;
     this.orDefault            = orDefault;
     this.defaultValue         = defaultValue;
 }
コード例 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EpsilonInstantStreamReader{T}"/> class.
 /// </summary>
 /// <param name="cursorEpsilon">The cursor epsilon to use when searching for messages around a cursor time.</param>
 public EpsilonInstantStreamReader(RelativeTimeInterval cursorEpsilon)
 {
     this.CursorEpsilon = cursorEpsilon;
     this.dataProviders = new List <IAdaptingInstantDataProvider <T> >();
 }
コード例 #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LastReproducibleInterpolator{T}"/> class.
 /// </summary>
 /// <param name="relativeTimeInterval">The relative time interval within which to search for the first message.</param>
 /// <param name="orDefault">Indicates whether to output a default value when no result is found.</param>
 /// <param name="defaultValue">An optional default value to use.</param>
 public LastReproducibleInterpolator(RelativeTimeInterval relativeTimeInterval, bool orDefault, T defaultValue = default)
 {
     this.relativeTimeInterval = relativeTimeInterval;
     this.orDefault            = orDefault;
     this.defaultValue         = defaultValue;
 }
コード例 #27
0
        public DeepSpeechRecognizer(Pipeline pipeline) : base(pipeline, nameof(DeepSpeechRecognizer))
        {
            // Create connector
            this.audioIn = this.CreateInputConnectorFrom <AudioBuffer>(pipeline, nameof(this.AudioIn));

            // Define the outputs
            var textOut = this.CreateOutputConnectorTo <String>(pipeline, nameof(this.TextOut));

            this.TextOut = textOut.Out;

            // sub-recognizer
            var recognizer = new DeepSpeechSubRecognizer(this);

            // voice activity detector
            var voiceDet = new SystemVoiceActivityDetector(this);

            this.audioIn.Out.PipeTo(voiceDet);
            //this.audioIn.Do(x =>
            //{
            //    Console.Write('.');
            //});
            var voiceAudio = this.audioIn.Out.Join(voiceDet.Out, Reproducible.Nearest <bool>(RelativeTimeInterval.Future()));

            voiceAudio.PipeTo(recognizer.In);

            recognizer.PipeTo(textOut);
        }
コード例 #28
0
        /// <summary>
        /// Gets the index id corresponding to a specified time for
        /// a collection of indices that are ordered by time.
        /// </summary>
        /// <param name="currentTime">The time to find the index for.</param>
        /// <param name="count">The number of items in the index collection.</param>
        /// <param name="timeAtIndex">A function that returns the time for a given index id.</param>
        /// <param name="cursorEpsilon">The cursor epsilon to use to determine if an index is close enough to the specified time to be counted as a match.</param>
        /// <returns>The index id closest to the specified time, using the specified interpolation style.</returns>
        public static int GetIndexForTime(DateTime currentTime, int count, Func <int, DateTime> timeAtIndex, RelativeTimeInterval cursorEpsilon)
        {
            // Perform a binary search
            SearchResult result = SearchIndex(currentTime, count, timeAtIndex);

            if (result.ExactMatchFound)
            {
                return(result.ExactIndex);
            }

            TimeInterval interval = currentTime + cursorEpsilon;

            // If there's only one entry in the index, return it if it's within the epsilon
            if (count == 1)
            {
                return(interval.PointIsWithin(timeAtIndex(0)) ? 0 : -1);
            }

            // Check if the high index is closer to the current time
            if ((timeAtIndex(result.HighIndex) - currentTime) < (currentTime - timeAtIndex(result.LowIndex)))
            {
                if (interval.PointIsWithin(timeAtIndex(result.HighIndex)))
                {
                    return(result.HighIndex);
                }
                else if (interval.PointIsWithin(timeAtIndex(result.LowIndex)))
                {
                    return(result.LowIndex);
                }
                else
                {
                    return(-1);
                }
            }

            // Check if the low index is closer to the current time
            else
            {
                if (interval.PointIsWithin(timeAtIndex(result.LowIndex)))
                {
                    return(result.LowIndex);
                }
                else if (interval.PointIsWithin(timeAtIndex(result.HighIndex)))
                {
                    return(result.HighIndex);
                }
                else
                {
                    return(-1);
                }
            }
        }