Пример #1
0
        /// <summary>
        /// Frequency filter.
        /// </summary>
        /// <param name="source">Input stream</param>
        /// <param name="period">Period of input stream</param>
        /// <param name="window">Window size</param>
        /// <param name="filter">Filter function to select in frequencies</param>
        /// <returns>Signal after frequency filter pass.</returns>
        public static IStreamable <Empty, Signal> BandPassFilter(
            this IStreamable <Empty, Signal> source,
            long period,
            long window,
            double low,
            double high
            )
        {
            var bp = OnlineFilter.CreateBandpass(ImpulseResponse.Finite, period, low, high);

            return(source
                   .Multicast(s => s
                              .ShiftEventLifetime(window)
                              .Join(s
                                    .TumblingWindowLifetime(window, window)
                                    .Aggregate(w => new BatchAggregate <Signal>())
                                    .Select(input => FreqFilter(input, bp))
                                    .SelectMany(e => e),
                                    l => l.ts, r => r.ts,
                                    (l, r) => r
                                    )
                              )
                   .ShiftEventLifetime(-window)
                   );
        }
Пример #2
0
        public double[] Filter(double[] inputArray, MathNet.Filtering.ImpulseResponse responseType, int samplingFreq, int frequencyLow, int frequencyHigh, int q)//ResponseType: IIR or FIR, samplingFreq: Sampling frequency in Hz, frequencyLow: Low cuttoff for filter.
        {
            OnlineFilter bandpassFast = OnlineFilter.CreateBandpass(ImpulseResponse.Infinite, samplingFreq, frequencyLow, frequencyHigh, q);

            bandpassFast.ProcessSamples(inputArray);
            return(inputArray);//Double check to see if we really need to return, if this is working on a referenced array, then the input array should already be altered, which would be this classes data frame.
        }
        public ClientAudioProvider()
        {
            _filters    = new OnlineFilter[2];
            _filters[0] =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.INPUT_SAMPLE_RATE, 560, 3900);
            _filters[1] =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.INPUT_SAMPLE_RATE, 100, 4500);

            JitterBufferProviderInterface =
                new JitterBufferProviderInterface(new WaveFormat(AudioManager.INPUT_SAMPLE_RATE, 2));

            SampleProvider = new Pcm16BitToSampleProvider(JitterBufferProviderInterface);

            _decoder = OpusDecoder.Create(AudioManager.INPUT_SAMPLE_RATE, 1);
            _decoder.ForwardErrorCorrection = false;

            _highPassFilter = BiQuadFilter.HighPassFilter(AudioManager.INPUT_SAMPLE_RATE, 520, 0.97f);
            _lowPassFilter  = BiQuadFilter.LowPassFilter(AudioManager.INPUT_SAMPLE_RATE, 4130, 2.0f);

            var effect = new CachedAudioEffect(CachedAudioEffect.AudioEffectTypes.NATO_TONE);

            if (effect.AudioEffectBytes.Length > 0)
            {
                natoTone = ConversionHelpers.ByteArrayToShortArray(effect.AudioEffectBytes);

                var vol = Settings.GlobalSettingsStore.Instance.GetClientSetting(GlobalSettingsKeys.NATOToneVolume)
                          .FloatValue;

                for (int i = 0; i < natoTone.Length; i++)
                {
                    natoTone[i] = (short)(natoTone[i] * vol);
                }
            }
        }
Пример #4
0
        private void DistanceFromTime(Stopwatch time, OnlineFilter filter, out double distance)
        {
            // Formula: uS / 58 == centimeters
            double microsecondsPerTick = (1000.0 * 1000.0) / (double)Stopwatch.Frequency;
            double deltaInMicroseconds = (double)time.ElapsedTicks * microsecondsPerTick;
            double measuredDistance    = deltaInMicroseconds / 58.0;

            distance = filter.ProcessSample(measuredDistance);
        }
Пример #5
0
        public void notch_interference(double low_value, double high_value)
        {
            OnlineFilter bandstop = OnlineFirFilter.CreateBandstop(ImpulseResponse.Finite, fs_hz, low_value, high_value);

            for (int column_id = first_eeg_channel; column_id <= last_eeg_channel; column_id++)
            {
                double[] filtered = bandstop.ProcessSamples(data.GetColumn(column_id));
                data = data.SetColumn(column_id, filtered);
            }
        }
Пример #6
0
        public void lowpass(double value)
        {
            OnlineFilter lowpass = OnlineFirFilter.CreateLowpass(ImpulseResponse.Finite, fs_hz, value);

            for (int column_id = first_eeg_channel; column_id <= last_eeg_channel; column_id++)
            {
                double[] filtered = lowpass.ProcessSamples(data.GetColumn(column_id));
                data = data.SetColumn(column_id, filtered);
            }
        }
Пример #7
0
        // median
        public void denoise(int order)
        {
            OnlineFilter denoise = OnlineFirFilter.CreateDenoise(order);

            for (int column_id = first_eeg_channel; column_id <= last_eeg_channel; column_id++)
            {
                double[] filtered = denoise.ProcessSamples(data.GetColumn(column_id));
                data = data.SetColumn(column_id, filtered);
            }
        }
Пример #8
0
        public async Task initialize()
        {
            var controller = await GpioController.GetDefaultAsync();

            if (controller == null)
            {
                // Rogin?
                return;
            }

            frontFilter = OnlineFilter.CreateDenoise();
            backFilter  = OnlineFilter.CreateDenoise();
            rightFilter = OnlineFilter.CreateDenoise();
            leftFilter  = OnlineFilter.CreateDenoise();


            triggerFrontPin = controller.OpenPin(kTriggerFront);
            triggerBackPin  = controller.OpenPin(kTriggerBack);
            triggerLeftPin  = controller.OpenPin(kTriggerLeft);
            triggerRightPin = controller.OpenPin(kTriggerRight);
            echoFrontPin    = controller.OpenPin(kEchoFront);
            echoBackPin     = controller.OpenPin(kEchoBack);
            echoLeftPin     = controller.OpenPin(kEchoLeft);
            echoRightPin    = controller.OpenPin(kEchoRight);

            triggerFrontPin.SetDriveMode(GpioPinDriveMode.Output);
            triggerBackPin.SetDriveMode(GpioPinDriveMode.Output);
            triggerLeftPin.SetDriveMode(GpioPinDriveMode.Output);
            triggerRightPin.SetDriveMode(GpioPinDriveMode.Output);
            echoFrontPin.SetDriveMode(GpioPinDriveMode.Input);
            echoBackPin.SetDriveMode(GpioPinDriveMode.Input);
            echoLeftPin.SetDriveMode(GpioPinDriveMode.Input);
            echoRightPin.SetDriveMode(GpioPinDriveMode.Input);

            long debounceTicks = Stopwatch.Frequency / (1000 * 1000 * 50);

            echoFrontPin.DebounceTimeout = TimeSpan.FromTicks(debounceTicks);
            echoBackPin.DebounceTimeout  = TimeSpan.FromTicks(debounceTicks);
            echoLeftPin.DebounceTimeout  = TimeSpan.FromTicks(debounceTicks);
            echoRightPin.DebounceTimeout = TimeSpan.FromTicks(debounceTicks);

            echoFrontPin.ValueChanged += EchoFrontPin_ValueChanged;
            echoBackPin.ValueChanged  += EchoBackPin_ValueChanged;
            echoLeftPin.ValueChanged  += EchoLeftPin_ValueChanged;
            echoRightPin.ValueChanged += EchoRightPin_ValueChanged;

            // Every greater than 60 ms per datasheet due to echo.
            // Round robin, so servicing each sonar every 120ms, but
            // allowing for echo by servicing opposite sides.
            timer.Interval = TimeSpan.FromMilliseconds(30);
            timer.Tick    += Timer_Tick;
            timer.Start();
        }
        public ClientPassThroughAudioProvider()
        {
            profileSettings = Settings.GlobalSettingsStore.Instance.ProfileSettingsStore;
            _filters        = new OnlineFilter[2];
            _filters[0]     =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.OUTPUT_SAMPLE_RATE, 560, 3900);
            _filters[1] =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.OUTPUT_SAMPLE_RATE, 100, 4500);

            _highPassFilter = BiQuadFilter.HighPassFilter(AudioManager.OUTPUT_SAMPLE_RATE, 520, 0.97f);
            _lowPassFilter  = BiQuadFilter.LowPassFilter(AudioManager.OUTPUT_SAMPLE_RATE, 4130, 2.0f);
        }
Пример #10
0
        /// <summary>
        /// Samples the input stream and applies a high-pass filter (using MathNet.Filtering) over the sampled input stream. Removes low frequencies.
        /// </summary>
        /// <param name="input">The input source of doubles.</param>
        /// <param name="sampleRate">The desired sample rate for the filter.</param>
        /// <param name="cutoffRate">The desired cutoff for the filter.</param>
        /// <param name="impulseResponse">Specifies how the filter will respond to an impulse input (Finite or Infinite). Default is Finite.</param>
        /// <param name="sampleInterpolator">Optional sampling interpolator over the input. Default is a reproducible linear interpolation.</param>
        /// <param name="alignmentDateTime">If non-null, this parameter specifies a time to align the sampled messages with, and the sampled messages
        /// will have originating times that align with (i.e., are an integral number of intervals away from) the specified alignment time.</param>
        /// <param name="deliveryPolicy">An optional delivery policy for the input stream.</param>
        /// <returns>A high-pass filtered version of the input.</returns>
        public static IProducer <double> HighpassFilter(
            this IProducer <double> input,
            double sampleRate,
            double cutoffRate,
            ImpulseResponse impulseResponse = ImpulseResponse.Finite,
            Interpolator <double, double> sampleInterpolator = null,
            DateTime?alignmentDateTime             = null,
            DeliveryPolicy <double> deliveryPolicy = null)
        {
            var filter = OnlineFilter.CreateHighpass(impulseResponse, sampleRate, cutoffRate);

            return(MathNetFilter(input, sampleRate, sampleInterpolator ?? Reproducible.Linear(), alignmentDateTime, filter, deliveryPolicy));
        }
Пример #11
0
        public ClientAudioProvider()
        {
            _filters    = new OnlineFilter[2];
            _filters[0] =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.INPUT_SAMPLE_RATE, 560, 3900);
            _filters[1] =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.INPUT_SAMPLE_RATE, 100, 4500);

            JitterBufferProviderInterface =
                new JitterBufferProviderInterface(new WaveFormat(AudioManager.INPUT_SAMPLE_RATE, 2));

            SampleProvider = new Pcm16BitToSampleProvider(JitterBufferProviderInterface);
        }
Пример #12
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            LineItem       kurvaMagnitude = zedGraphControl1.GraphPane.CurveList[0] as LineItem;
            IPointListEdit listMagnitude  = kurvaMagnitude.Points as IPointListEdit;

            dataMagnitude = new double[1000];

            try
            {
                for (int i = 0; i < 1000; i++)
                {
                    dataMagnitude[i] = double.Parse(uno.ReadLine(), CultureInfo.InvariantCulture.NumberFormat);
                }
            }
            catch (Exception)
            {
                //uno.Close();
                return;
            }


            OnlineFilter bandpass = OnlineFilter.CreateBandpass(MathNet.Filtering.ImpulseResponse.Finite, 1000, 20, 500);
            OnlineFilter bandstop = OnlineFilter.CreateBandstop(MathNet.Filtering.ImpulseResponse.Finite, 1000, 48.5, 51.5);
            OnlineFilter denoise  = OnlineFilter.CreateDenoise();

            dataFilter = new double[1000];
            dataFilter = bandpass.ProcessSamples(dataMagnitude);
            dataFilter = bandstop.ProcessSamples(dataFilter);
            dataFilter = denoise.ProcessSamples(dataFilter);
            var N = Enumerable.Range(1, dataMagnitude.Length).ToArray();

            waktu = Array.ConvertAll <int, double>(N, Convert.ToDouble);



            // double waktu = (Environment.TickCount - waktustart) / 1000.0;
            listMagnitude.Clear();

            for (int i = 0; i < 1000; i++)
            {
                listMagnitude.Add(waktu[i], dataFilter[i]);
            }

            label1.Text = Convert.ToString(dataFilter[500]);
            //uno.Close();



            zedGraphControl1.AxisChange();
            zedGraphControl1.Refresh();
        }
Пример #13
0
        public ClientAudioProvider()
        {
            _filters    = new OnlineFilter[2];
            _filters[0] =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.INPUT_SAMPLE_RATE, 560, 3900);
            _filters[1] =
                OnlineFilter.CreateBandpass(ImpulseResponse.Finite, AudioManager.INPUT_SAMPLE_RATE, 100, 4500);

            JitterBufferProviderInterface =
                new JitterBufferProviderInterface(new WaveFormat(AudioManager.INPUT_SAMPLE_RATE, 2));

            SampleProvider = new Pcm16BitToSampleProvider(JitterBufferProviderInterface);

            _decoder = OpusDecoder.Create(AudioManager.INPUT_SAMPLE_RATE, 1);
            _decoder.ForwardErrorCorrection = false;

            _highPassFilter = BiQuadFilter.HighPassFilter(AudioManager.INPUT_SAMPLE_RATE, 520, 0.97f);
            _lowPassFilter  = BiQuadFilter.LowPassFilter(AudioManager.INPUT_SAMPLE_RATE, 4130, 2.0f);
        }
Пример #14
0
        public MainWindow()
        {
            try
            {
                InitializeComponent();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //Graphing Add In Code-Behind
            SoundData = new XyDataSeries <double, short>();
            SoundData.FifoCapacity = this.Capacity * 16000;

            //View Model Update
            Sthetho             = new StethoViewModel(Init, Stop, Clear, Retrieve);
            this.DataContext    = Sthetho;
            Sthetho.IsStreaming = false;
            Sthetho.FilterHeart = false;

            //Open File (Remove for serial Stream)
            reader = OpenFile(inputfile);

            //Audio Class
            StethoPlayer = new AudioPlayer(15200, 16, 1);

            //Open Serial Port
            SerialDataIn = new SerialCom(921600, "COM8");

            //Open File For Writing
            Sthetho.OutFileName = "StethoSound"; //Deprecated
            Sthetho.WriteToFile = true;

            VertAnnotate.CoordinateMode    = SciChart.Charting.Visuals.Annotations.AnnotationCoordinateMode.Absolute;
            VertAnnotate.Y1                = -32000;
            VertAnnotate.VerticalAlignment = VerticalAlignment.Top;
            Sthetho.AnnotationX            = 0;

            //Create filter objects
            BandPassfilter = OnlineFilter.CreateHighpass(ImpulseResponse.Finite, samplerate, fc1);
            //Denoiser = OnlineFilter.CreateDenoise(25);
        }
Пример #15
0
        private static List <Signal> FreqFilter(List <Signal> input, OnlineFilter bp)
        {
            var len    = input.Count;
            var ival   = new double[len];
            var output = new List <Signal>(len);

            for (int i = 0; i < len; i++)
            {
                ival[i] = input[i].val;
            }

            var new_val = bp.ProcessSamples(ival);

            for (int k = 0; k < new_val.Length; k++)
            {
                output.Add(new Signal(input[k].ts, (float)new_val[k]));
            }

            return(output);
        }
Пример #16
0
        private void button4_Click(object sender, EventArgs e)
        {
            openFileDialog1.Multiselect = true;
            openFileDialog1.Title       = "Open Files...";
            openFileDialog1.FileName    = "";

            openFileDialog1.Filter = "CSV (comma delimited)|*.csv|All Files|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                MessageBox.Show("Choice Cancelled");
            }
            else
            {
                folderBrowserDialog1.Description = "Choose Folder to Save...";
                if (folderBrowserDialog1.ShowDialog() == DialogResult.Cancel)
                {
                    MessageBox.Show("Choice Cancelled");
                }
                else
                {
                    var saveto = folderBrowserDialog1.SelectedPath;

                    for (int i = 0; i < openFileDialog1.FileNames.Length; i++)
                    {
                        data          = File.ReadAllLines(openFileDialog1.FileNames[i]);
                        dataMagnitude = data.Select(x => double.Parse(x)).ToArray();

                        dataFilter = new double[dataMagnitude.Length];
                        OnlineFilter bandstop = OnlineFilter.CreateBandstop(MathNet.Filtering.ImpulseResponse.Finite, 80, 48.5, 51.5);
                        // OnlineFilter denoise = OnlineFilter.CreateDenoise();
                        dataFilter = bandstop.ProcessSamples(dataMagnitude);
                        //dataFilter = denoise.ProcessSamples(dataFilter);

                        var path = Path.Combine(saveto, "Datafilter" + Convert.ToString(i) + ".csv");
                        File.WriteAllLines(path, Array.ConvertAll <double, string>(dataFilter, Convert.ToString), Encoding.Default);
                    }
                    MessageBox.Show("Done");
                }
            }
        }
        public RadioFilter(ISampleProvider sampleProvider)
        {
            _source  = sampleProvider;
            _filters = new OnlineFilter[2];

            /**
             * From Coug4r
             * Apart from adding noise i'm only doing 3 things in this order:
             *  - Custom clipping (which basicly creates the overmodulation effect)
             *  - Run the audio through bandpass filter 1
             *  - Run the audio through bandpass filter 2
             *
             *  These are the values i use for the bandpass filters:
             *  1 - low 560, high 3900
             *  2 - low 100, high 4500
             *
             */

            _filters[0] = OnlineFilter.CreateBandpass(ImpulseResponse.Finite, sampleProvider.WaveFormat.SampleRate, 560,
                                                      3900);
            _filters[1] = OnlineFilter.CreateBandpass(ImpulseResponse.Finite, sampleProvider.WaveFormat.SampleRate, 100,
                                                      4500);
        }
Пример #18
0
        private void button2_Click(object sender, EventArgs e)
        {
            dataFilter = new double[dataMagnitude.Length];
            OnlineFilter bandpass = OnlineFilter.CreateBandpass(ImpulseResponse.Finite, 1000, 20, 500);
            OnlineFilter bandstop = OnlineFilter.CreateBandstop(MathNet.Filtering.ImpulseResponse.Finite, 1000, 49, 51);
            OnlineFilter denoise  = OnlineFilter.CreateDenoise();

            dataFilter = bandpass.ProcessSamples(dataMagnitude);
            dataFilter = bandstop.ProcessSamples(dataFilter);
            dataFilter = denoise.ProcessSamples(dataFilter);

            LineItem       kurvaMagnitude = zedGraphControl1.GraphPane.CurveList[1] as LineItem;
            IPointListEdit listFilter     = kurvaMagnitude.Points as IPointListEdit;

            listFilter.Clear();
            for (int i = 1; i < dataFilter.Length; i++)
            {
                listFilter.Add(dataN[i], dataFilter[i]);
            }
            zedGraphControl1.AxisChange();
            zedGraphControl1.Invalidate();
            button2.Enabled = false;
            button3.Enabled = true;
        }
Пример #19
0
        public RealtimeEngine()
        {
            nsamples = new int[MainClass.devices.Length];

            bool usehpf = MainClass.win._handles.useHPF.Active;
            bool uselpf = MainClass.win._handles.useLPF.Active;


            double hpf = 0.016;

            try
            {
                hpf = Convert.ToDouble(MainClass.win._handles.editHPF.Text);
            }
            catch
            {
                usehpf = false;
            }
            double lpf = 0.5;

            try
            {
                lpf = Convert.ToDouble(MainClass.win._handles.editLPF.Text);
            }
            catch
            {
                uselpf = false;
            }

            fs = new double[MainClass.devices.Length];
            OnlineFIRFiltersHPF  = new OnlineFilter[MainClass.devices.Length][];
            OnlineFIRFiltersHPF2 = new OnlineFilter[MainClass.devices.Length][];
            OnlineFIRFiltersLPF  = new OnlineFilter[MainClass.devices.Length][];
            MocoKalman           = new DiscreteKalmanFilter[MainClass.devices.Length][];

            mBLLmappings = new MBLLmapping[MainClass.devices.Length];

            for (int i = 0; i < MainClass.devices.Length; i++)
            {
                int nSDpairs = MainClass.win.nirsdata[i].probe.numChannels / MainClass.win.nirsdata[i].probe.numWavelengths;

                mBLLmappings[i]                  = new MBLLmapping();
                mBLLmappings[i].distances        = new double[nSDpairs];
                mBLLmappings[i].hboIndex         = new int[nSDpairs][];
                mBLLmappings[i].measurementPairs = new int[nSDpairs][];

                mBLLmappings[i].ExtCoefHbO = new double[nSDpairs][];
                mBLLmappings[i].ExtCoefHbR = new double[nSDpairs][];

                int   cnt  = 0;
                int[] cnt2 = new int[nSDpairs];
                for (int ii = 0; ii < nSDpairs; ii++)
                {
                    cnt2[ii] = 0;
                    mBLLmappings[i].hboIndex[ii]         = new int[2];
                    mBLLmappings[i].measurementPairs[ii] = new int[MainClass.win.nirsdata[i].probe.numWavelengths];
                    mBLLmappings[i].ExtCoefHbO[ii]       = new double[MainClass.win.nirsdata[i].probe.numWavelengths];
                    mBLLmappings[i].ExtCoefHbR[ii]       = new double[MainClass.win.nirsdata[i].probe.numWavelengths];
                }

                nirs.Media media = new nirs.Media();
                for (int sI = 0; sI < MainClass.win.nirsdata[i].probe.numSrc; sI++)
                {
                    for (int dI = 0; dI < MainClass.win.nirsdata[i].probe.numDet; dI++)
                    {
                        bool found = false;;
                        for (int mI = 0; mI < MainClass.win.nirsdata[i].probe.numChannels; mI++)
                        {
                            if (MainClass.win.nirsdata[i].probe.ChannelMap[mI].sourceindex == sI &
                                MainClass.win.nirsdata[i].probe.ChannelMap[mI].detectorindex == dI)
                            {
                                mBLLmappings[i].measurementPairs[cnt][cnt2[cnt]] = mI + MainClass.win.nirsdata[i].probe.numChannels;
                                if (mBLLmappings[i].hboIndex[cnt][0] == 0)
                                {
                                    mBLLmappings[i].hboIndex[cnt][0] = mI + MainClass.win.nirsdata[i].probe.numChannels * 2;
                                    mBLLmappings[i].hboIndex[cnt][1] = mI + nSDpairs + MainClass.win.nirsdata[i].probe.numChannels * 2;
                                }

                                mBLLmappings[i].distances[cnt] = 0;
                                media.GetSpectrum(MainClass.win.nirsdata[i].probe.ChannelMap[mI].wavelength,
                                                  out mBLLmappings[i].ExtCoefHbO[cnt][cnt2[cnt]], out mBLLmappings[i].ExtCoefHbR[cnt][cnt2[cnt]]);

                                mBLLmappings[i].distances[cnt] = Math.Sqrt((MainClass.win.nirsdata[i].probe.SrcPos[sI, 0] -
                                                                            MainClass.win.nirsdata[i].probe.DetPos[dI, 0]) *
                                                                           (MainClass.win.nirsdata[i].probe.SrcPos[sI, 0] -
                                                                            MainClass.win.nirsdata[i].probe.DetPos[dI, 0]) +
                                                                           (MainClass.win.nirsdata[i].probe.SrcPos[sI, 1] -
                                                                            MainClass.win.nirsdata[i].probe.DetPos[dI, 1]) *
                                                                           (MainClass.win.nirsdata[i].probe.SrcPos[sI, 1] -
                                                                            MainClass.win.nirsdata[i].probe.DetPos[dI, 1]));
                                cnt2[cnt]++;
                                found = true;
                            }
                        }
                        if (found)
                        {
                            cnt++;
                        }
                    }
                }



                nsamples[i] = 0;
                NIRSDAQ.info info = MainClass.devices[i].GetInfo();
                fs[i] = info.sample_rate;
                OnlineFIRFiltersHPF[i]  = new OnlineFilter[MainClass.win.nirsdata[i].probe.numChannels];
                OnlineFIRFiltersLPF[i]  = new OnlineFilter[MainClass.win.nirsdata[i].probe.numChannels];
                OnlineFIRFiltersHPF2[i] = new OnlineFilter[MainClass.win.nirsdata[i].probe.numChannels];
                MocoKalman[i]           = new DiscreteKalmanFilter[MainClass.win.nirsdata[i].probe.numChannels];

                for (int j = 0; j < MainClass.win.nirsdata[i].probe.numChannels; j++)
                {
                    OnlineFIRFiltersLPF[i][j]  = OnlineFilter.CreateLowpass(ImpulseResponse.Finite, fs[i], lpf);
                    OnlineFIRFiltersHPF[i][j]  = OnlineFilter.CreateHighpass(ImpulseResponse.Finite, fs[i], hpf);
                    OnlineFIRFiltersHPF2[i][j] = OnlineFilter.CreateHighpass(ImpulseResponse.Finite, fs[i], 0.001);

                    OnlineFIRFiltersHPF[i][j].Reset();
                    OnlineFIRFiltersHPF2[i][j].Reset();
                    OnlineFIRFiltersLPF[i][j].Reset();

                    int order = 5;
                    var x0    = MathNet.Numerics.LinearAlgebra.Matrix <double> .Build.Dense(order + 1, 1, 0);

                    var P0 = MathNet.Numerics.LinearAlgebra.Matrix <double> .Build.DenseIdentity(order + 1);

                    MocoKalman[i][j] = new DiscreteKalmanFilter(x0, P0);
                }
            }
        }
 public FeatureFilterSelection(FeaturesSelc aFeaturesSelc, OnlineFilter aOnlineFilter)
 {
     feature  = aFeaturesSelc;
     bandpass = aOnlineFilter;
 }
Пример #21
0
        private void InitPlots(CallModel callModel)
        {
            BatCall call = callModel.Call;

            PlotModel  pmPower       = new PlotModel();
            LineSeries pwrLineSeries = new LineSeries();

            pwrLineSeries.LineJoin = LineJoin.Round;
            pmPower.Series.Add(pwrLineSeries);
            pmPower.Axes.Add(new LinearAxis {
                Maximum = 260, Minimum = 0, Position = AxisPosition.Left, Title = "Intensität"
            });
            pmPower.Axes.Add(new LinearAxis {
                Position = AxisPosition.Bottom, Title = "Dauer [ms]"
            });

            if (call.PowerData != null)
            {
                pwrLineSeries.Points.AddRange(call.PowerData.Select((b, i) => new DataPoint(i * 0.251, b)));
            }

            //if (call.OriginalCalls.Count > 1)
            //{
            //    int leftSum = call.OriginalCalls[0].PowerData.Length;
            //    for (int i = 0; i < call.OriginalCalls.Count-1; i++)
            //    {
            //        int width = (int)Math.Round((call.OriginalCalls[i + 1].StartTimeMs - call.OriginalCalls[i].EndTimeMs) / 0.251);
            //        double left = leftSum* 0.251;
            //        double right = left + (width* 0.251);
            //        RectangleAnnotation annotation = new RectangleAnnotation { Fill = OxyColors.LightGray, Layer = AnnotationLayer.BelowAxes, MinimumX = left, MaximumX = right, MinimumY = 0, MaximumY = 260 };
            //        //LineAnnotation lineAnnotation = new LineAnnotation { Color = OxyColors.Red, StrokeThickness = 2, LineStyle = LineStyle.Dash, Type = LineAnnotationType.Vertical, X = linePos };
            //        pmPower.Annotations.Add(annotation);
            //        leftSum = leftSum + width + call.OriginalCalls[i].PowerData.Length;
            //    }
            //}


            OnlineFilter filter = OnlineFilter.CreateBandstop(ImpulseResponse.Infinite, 20, 20, 150);

            LineSeries pwrLineSeriesAvg = new LineSeries();

            pwrLineSeriesAvg.LineJoin = LineJoin.Round;
            pwrLineSeriesAvg.Color    = OxyColors.Blue;
            pmPower.Series.Add(pwrLineSeriesAvg);

            //double[] input = call.PowerData.Select(d => (double)d).ToArray();
            //double[] data = filter.ProcessSamples(input);
            //pwrLineSeriesAvg.Points.AddRange(data.Select((d, i) => new DataPoint(i * 0.251, d)));

            int[] window  = new int[] { 2, 4, 8, 4, 2 };
            int   divisor = window.Sum();

            byte[] input = call.PowerData;
            for (int i = 0; i < input.Length; i++)
            {
                double sum = 0;
                for (int j = 0; j < 5; j++)
                {
                    int    x = i + (j - 2);
                    double q;
                    if (x < 0)
                    {
                        q = input[0];
                    }
                    else if (x >= input.Length)
                    {
                        q = input[input.Length - 1];
                    }
                    else
                    {
                        q = input[x];
                    }
                    sum += q * window[j];
                }
                pwrLineSeriesAvg.Points.Add(new DataPoint(i * 0.251, sum / divisor));
            }


            LineSeries pwrLineSeriesAvg2 = new LineSeries();

            pwrLineSeriesAvg2.LineJoin = LineJoin.Round;
            pwrLineSeriesAvg2.Color    = OxyColors.Crimson;
            pmPower.Series.Add(pwrLineSeriesAvg2);

            int avgCount = 7;

            int[] ringBuffer  = Enumerable.Repeat(-1, avgCount).ToArray();
            int   bufferIndex = 0;

            for (int i = 0; i < call.PowerData.Length; i++)
            {
                ringBuffer[bufferIndex++] = call.PowerData[i];
                if (bufferIndex >= ringBuffer.Length)
                {
                    bufferIndex = 0;
                }

                if (i > 4)
                {
                    int    c    = 0;
                    double mAvg = 0;
                    for (int j = 0; j < ringBuffer.Length; j++)
                    {
                        if (ringBuffer[j] >= 0)
                        {
                            c++;
                            mAvg += ringBuffer[j];
                        }
                    }
                    pwrLineSeriesAvg2.Points.Add(new DataPoint((i - 4) * 0.251, mAvg / c));
                }
            }


            LineAnnotation lineAnnotation = new LineAnnotation {
                Color = OxyColors.Red, StrokeThickness = 2, LineStyle = LineStyle.Dash, Type = LineAnnotationType.Horizontal, Y = call.AveragePower
            };

            pmPower.Annotations.Add(lineAnnotation);

            Power = pmPower.AddStyles();


            PlotModel    pmFreq     = new PlotModel();
            ColumnSeries freqSeries = new ColumnSeries();

            pmFreq.Series.Add(freqSeries);
            CategoryAxis item = new CategoryAxis();

            item.Position               = AxisPosition.Bottom;
            item.Title                  = "Frequenz [kHz]";
            item.GapWidth               = 0.1;
            item.IsTickCentered         = true;
            item.LabelFormatter         = i => LogAnalyzer.GetFrequencyFromFftBin((int)i).ToString(CultureInfo.CurrentCulture);
            item.MajorGridlineThickness = 0;
            pmFreq.Axes.Add(item);

            if (call.FftData != null)
            {
                freqSeries.Items.AddRange(call.FftData.Select((f, i) =>
                {
                    ColumnItem columnItem = new ColumnItem(f, i);
                    columnItem.Color      = i == call.MaxFrequencyBin ? OxyColors.Red : OxyColors.Green;
                    return(columnItem);
                }));
            }
            Frequency = pmFreq.AddStyles();
        }
        public void StorePeakAcceleration(DataItemVehicle itemVehicle, DataItemRun itemRun)
        {
            if (samples.Count == 0)
            {
                Debug.LogToFileMethod("peak-a: no samlpes");
                return;
            }

            if (isPeakAStored == true)
            {
                // refuse to process peakA again
                Debug.LogToFileEventText("peak-a: already found");
                return;
            }

            double peakA     = 0;
            double speed     = 0;
            double magnitude = 0;
            int    count     = samples.Count;

            // user calibrated profile before run -> get accelerometer offsets
            // to eleminate earth gravitation and slope of the device in the car mount
            double offsetX = itemVehicle.AxisOffsetX;
            double offsetY = itemVehicle.AxisOffsetY;
            double offsetZ = itemVehicle.AxisOffsetZ;

            // from collection to array with offset compensation ("normalize" to axis origin)
            ToArray(offsetX, offsetY, offsetZ);

            // apply low pass filter to each "normalized" axis
            OnlineFilter filter = OnlineFilter.CreateLowpass(ImpulseResponse.Finite,
                                                             FILTER_SAMPLE_RATE,
                                                             FILTER_CUT_OFF_RATE,
                                                             FILTER_ORDER);

            double[] filteredX = filter.ProcessSamples(samplesX);
            filter.Reset();

            double[] filteredY = filter.ProcessSamples(samplesY);
            filter.Reset();

            double[] filteredZ = filter.ProcessSamples(samplesZ);
            filter.Reset();

            // search max value of magnitude of all filtered axes
            for (int i = 0; i < count; i++)
            {
                // magnitude of all components
                magnitude = Math.Sqrt(filteredX[i] * filteredX[i] +
                                      filteredY[i] * filteredY[i] +
                                      filteredZ[i] * filteredZ[i]);

                // store if new max
                if (magnitude > peakA)
                {
                    peakA = magnitude;
                    speed = samplesS[i];
                }
            }

            // store to given run
            itemRun.PeakAcceleration = (float)peakA;

            Debug.LogToFileEventText("found peak-a [m/s^2]: " + peakA.ToString("0.00") +
                                     " at speed [m/s]: " + speed.ToString("0.00"));

            if ((count >= SIZE_MAX) && (peakA > 0))
            {
                isPeakAStored = true;
            }
        }
Пример #23
0
        /// <summary>
        /// Applies a de-noising filter (using MathNet.Filtering) over the input stream. Implemented as an unweighted median filter.
        /// </summary>
        /// <param name="input">The input source of doubles.</param>
        /// <param name="order">Window Size, should be odd. A larger number results in a smoother response but also in a longer delay.</param>
        /// <param name="deliveryPolicy">An optional delivery policy for the input stream.</param>
        /// <returns>A high-pass filtered version of the input.</returns>
        public static IProducer <double> DenoiseFilter(this IProducer <double> input, int order, DeliveryPolicy <double> deliveryPolicy = null)
        {
            var filter = OnlineFilter.CreateDenoise(order);

            return(input.Select(s => filter.ProcessSample(s), deliveryPolicy));
        }
Пример #24
0
    protected void ChangeBPF(object sender, EventArgs e)
    {
        double[] fs = new double[MainClass.devices.Length];
        for (int i = 0; i < MainClass.devices.Length; i++)
        {
            NIRSDAQ.info info = MainClass.devices[i].GetInfo();
            fs[i] = info.sample_rate;
        }

        double hpf = 0.016;
        double lpf = 0.5;

        try
        {
            lpf = Convert.ToDouble(MainClass.win._handles.editLPF.Text);
            if (lpf > fs[0] / 2)
            {
                lpf = fs[0] * 5 / 11;
                MainClass.win._handles.editLPF.Text = string.Format("{0}", lpf);
            }
        }
        catch
        {
            MainClass.win._handles.editLPF.Text = string.Format("{0}", 0.5);
            lpf = 0.5;
        }

        try
        {
            hpf = Convert.ToDouble(MainClass.win._handles.editHPF.Text);
            if (hpf < 0)
            {
                hpf = 0;
                MainClass.win._handles.editHPF.Text = string.Format("{0}", 0);
            }
            if (hpf > lpf)
            {
                hpf = lpf / 2;
                MainClass.win._handles.editHPF.Text = string.Format("{0}", hpf);
            }
        }
        catch
        {
            MainClass.win._handles.editHPF.Text = string.Format("{0}", 0.016);
            hpf = 0.016;
        }



        if (maindisplaythread.IsAlive)
        {
            for (int i = 0; i < MainClass.devices.Length; i++)
            {
                for (int j = 0; j < MainClass.win.nirsdata[i].probe.numChannels; j++)
                {
                    realtimeEngine.OnlineFIRFiltersLPF[i][j] = OnlineFilter.CreateLowpass(ImpulseResponse.Finite, fs[i], lpf);
                    realtimeEngine.OnlineFIRFiltersHPF[i][j] = OnlineFilter.CreateHighpass(ImpulseResponse.Finite, fs[i], hpf);
                }
            }
        }
    }
        static void Main(string[] args)
        {
            try
            {
                //Load data
                data_label_train = loadTrainingData("train.csv");
                data_label_test  = loadTestData("test_data.csv", "result.csv");

                //Normalize train data
                foreach (Data reading in data_label_train)
                {
                    reading.Normalize();
                }

                //Scaling test data and Normalize it
                Random rnd = new System.Random();
                foreach (LabeledData reading in data_label_test)
                {
                    double a = rnd.NextDouble() + 1.0;
                    double b = rnd.NextDouble();
                    reading.Scaling(a, b);
                    reading.Normalize();
                }

                double fs = 8000.0;
                //Create bandpass filters
                OnlineFilter bandpass0 = OnlineFilter.CreateLowpass(ImpulseResponse.Finite, fs, 200.0);
                OnlineFilter bandpass1 = OnlineFilter.CreateBandpass(ImpulseResponse.Finite, fs, 200.0, 2000.0);
                OnlineFilter bandpass2 = OnlineFilter.CreateBandpass(ImpulseResponse.Finite, fs, 2000.0, 3000.0);
                OnlineFilter bandpass3 = OnlineFilter.CreateBandpass(ImpulseResponse.Finite, fs, 3000.0, 3400.0);
                OnlineFilter bandpass4 = OnlineFilter.CreateHighpass(ImpulseResponse.Finite, fs, 3400.0);

                //Pre process: extract features from raw data
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.crestFactor, bandpass0));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.skew, bandpass0));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.kuri, bandpass0));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.std, bandpass0));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.var, bandpass0));

                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.crestFactor, bandpass1));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.skew, bandpass1));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.kuri, bandpass1));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.std, bandpass1));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.var, bandpass1));

                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.crestFactor, bandpass2));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.skew, bandpass2));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.kuri, bandpass2));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.std, bandpass2));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.var, bandpass2));

                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.crestFactor, bandpass3));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.skew, bandpass3));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.kuri, bandpass3));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.std, bandpass3));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.var, bandpass3));

                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.crestFactor, bandpass4));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.skew, bandpass4));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.kuri, bandpass4));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.std, bandpass4));
                selectedFeat.Add(new FeatureFilterSelection(FeaturesSelc.var, bandpass4));

                // learn the model
                var learner = new ClassificationRandomForestLearner(trees: 50);
                var model   = learner.Learn(FeatureExtract(data_label_train, selectedFeat), data_label_train.Select(x => x.label).ToArray());

                // Test: use the model for predicting new observations
                List <double> p = new List <double>();
                foreach (LabeledData reading in data_label_test)
                {
                    var prediction = model.Predict(reading.FeatureExtract(selectedFeat));
                    p.Add(prediction);
                }

                double accuracy = 0.0;
                for (int i = 0; i < data_label_test.Count; i++)
                {
                    if (data_label_test[i].label == p[i])
                    {
                        accuracy += 1.0 / data_label_test.Count * 100;
                    }
                    Console.WriteLine("Prediction result: {0} Ideal result: {1}", p[i], data_label_test[i].label);
                }

                Console.WriteLine("Accuracy {0}", accuracy.ToString());

                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadKey();
        }