private void btnAddFilter_Click(object sender, RoutedEventArgs e)
        {
            Filter filter = null;

            switch ((sender as FrameworkElement).Name)
            {
            case "btnAddLPF": filter = new LowPassFilter(Filter.DefaultN, (double)globalSampleRate / 4); break;

            case "btnAddHPF": filter = new HighPassFilter(Filter.DefaultN, (double)globalSampleRate / 4); break;

            case "btnAddBPF": filter = new BandPassFilter(Filter.DefaultN, (double)globalSampleRate / 8, (double)globalSampleRate * 3 / 8); break;

            case "btnAddBSF": filter = new BandStopFilter(Filter.DefaultN, (double)globalSampleRate / 8, (double)globalSampleRate * 3 / 8); break;

            case "btnAddMF": filter = new AverageFilter(Filter.DefaultN); break;

            case "btnAddZPass": filter = new ZFilterPass(ZFilterPass.DefaultR, (double)globalSampleRate / 4); break;

            case "btnAddZPass1": filter = new ZFilterPass1(ZFilterPass1.DefaultR, (double)globalSampleRate / 4); break;

            case "btnAddNotch": filter = new NotchFilter(NotchFilter.DefaultR1, NotchFilter.DefaultR2, (double)globalSampleRate / 4); break;

            default: return;
            }

            filter.PropertyChanged += new PropertyChangedEventHandler(Filter_PropertyChanged);

            filters.Add(filter);
            filtersList.SelectedIndex = filters.IndexOf(filter);

            updateResult();
        }
Exemplo n.º 2
0
/*void SocketSend(string sendStr)
 *  {
 *      //清空发送缓存
 *      sendData=new byte[1024];
 *      //数据类型转换
 *      sendData=Encoding.ASCII.GetBytes(sendStr);
 *      //发送给指定客户端
 *      socket.SendTo(sendData,sendData.Length,SocketFlags.None,clientEnd);
 *  }*/

    void SocketReceive()
    {
        //进入接收循环
        while (true)
        {
            var filter = new LowPassFilter(0.95f);
            //对data清零
            recvData = new byte[1024];
            //获取客户端,获取客户端数据,用引用给客户端赋值
            recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
            //print("message from: "+clientEnd.ToString()); //打印客户端信息
            //输出接收到的数据
            recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
            // print(recvStr);
            char[]   splitChar = { ' ', ',', ':', '\t', ';' };
            string[] dataRaw   = recvStr.Split(splitChar);
            RotateX = float.Parse(dataRaw[2]);
            RotateY = float.Parse(dataRaw[1]);
            RotateZ = float.Parse(dataRaw[0]);
            PoseX2  = float.Parse(dataRaw[3]);
            PoseY2  = float.Parse(dataRaw[4]);
            PoseZ2  = float.Parse(dataRaw[5]);
            // Use the `LowPassFilter` to smooth out values
            filter.Step(RotateX);
            filter.Step(RotateY);
            filter.Step(RotateZ);
            filter.Step(PoseX2);
            filter.Step(PoseY2);
            filter.Step(PoseZ2);
        }
    }
Exemplo n.º 3
0
    private void Start()
    {
        //jeden kanal
        wahwah                  = musicCube.GetComponent <WahWahFilter>();
        wahwah.QValue           = 1.5f;
        wahwah.CutOffFrequency  = 300.0f;
        wahwah.FrequencyRange   = 800.0f;
        lowpass                 = musicCube.GetComponent <LowPassFilter>();
        lowpass.CutOffFrequency = 400.0f;
        lowpass.QValue          = 0.5f;


        //drugi kanal
        envelope                 = musicCube.GetComponent <EnvelopGenerator>();
        envelope.AttackRate      = 0.15f * 44100.0f;
        envelope.DecayRate       = 0.15f * 44100.0f;
        envelope.SustainLevel    = 0.6f;
        envelope.ReleaseRate     = 0.1f * 44100.0f;
        highpass                 = musicCube.GetComponent <HighPassFilter>();
        highpass.QValue          = 0.5f;
        highpass.CutOffFrequency = 300.0f;
        bandpass                 = musicCube.GetComponent <BandPassFilter>();
        bandpass.centreFrequency = 350.0f;
        bandpass.q               = 0.4f;
        bandpass.BandPassFilterConstantPeakGain();
        vibrato           = musicCube.GetComponent <VibratoFilter>();
        vibrato.delay     = 0.2f;
        vibrato.depth     = 0.03f;
        vibrato.frequency = 0.8f;
    }
Exemplo n.º 4
0
/*void SocketSend(string sendStr)
 *  {
 *      //清空發送緩存
 *      sendData=new byte[1024];
 *      //數據類型轉換
 *      sendData=Encoding.ASCII.GetBytes(sendStr);
 *      //發送給指定客戶端
 *      socket.SendTo(sendData,sendData.Length,SocketFlags.None,clientEnd);
 *  }*/

    void SocketReceive()
    {
        //進入接收循環
        while (true)
        {
            var filter = new LowPassFilter(0.95f);
            //對data清零
            recvData = new byte[1024];
            //獲取客戶端,獲取客戶端數據,用引用給客戶端賦值
            recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
            //print("message from: "+clientEnd.ToString()); //列印客户端信息
            //輸出接收到的數據
            recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
            // print(recvStr);
            char[]   splitChar = { ' ', ',', ':', '\t', ';' };
            string[] dataRaw   = recvStr.Split(splitChar);
            RotateX  = float.Parse(dataRaw[0]);
            RotateY  = float.Parse(dataRaw[1]);
            RotateZ  = float.Parse(dataRaw[2]);
            RotateX2 = float.Parse(dataRaw[3]);
            RotateY2 = float.Parse(dataRaw[4]);
            RotateZ2 = float.Parse(dataRaw[5]);
            Flexval  = int.Parse(dataRaw[6]);
            // Use the `LowPassFilter` to smooth out values
            filter.Step(RotateX);
            filter.Step(RotateY);
            filter.Step(RotateZ);
            filter.Step(RotateX2);
            filter.Step(RotateY2);
            filter.Step(RotateZ2);
        }
    }
Exemplo n.º 5
0
        private OneEuroFilter()
        {
            _xfilt         = new LowPassFilter();
            _dxfilt        = new LowPassFilter();
            _isFirstUpdate = true;

            SetProperties(OneEuroFilterPropertyBlock.Default);
        }
Exemplo n.º 6
0
        public void Calibrate()
        {
            double[] envelopeAverage = null;

            // create the envelope for each signal
            for (int i = 0; i < m_rawSignals.Count; i++)
            {
                Signal signal = Signal.FromArray(m_rawSignals[i],
                                                 EchoTubeSensor.SampleRate, SampleFormat.Format32BitIeeeFloat);

                LowPassFilter lowPassFilter = new LowPassFilter(100.0, EchoTubeSensor.SampleRate)
                {
                    Alpha = 0.05f
                };
                Signal filteredSignal = lowPassFilter.Apply(signal);

                // this is the filtered signal (and a single baseline)
                float[] filteredRawSData = filteredSignal.ToFloat();
                float[] processedData    = new float[filteredRawSData.Length];

                // now, shift and rectify the raw data
                Parallel.For(0, processedData.Length, j =>
                {
                    // shift & rectify
                    processedData[j] = Math.Abs(m_rawSignals[i][j] - filteredRawSData[j]);
                });

                Signal processedSignal = Signal.FromArray(processedData,
                                                          EchoTubeSensor.SampleRate, SampleFormat.Format32BitIeeeFloat);

                // now, we can create the calibration envelope
                EnvelopeFilter filter          = new EnvelopeFilter(Sensor.EnvelopeAlpha);
                Signal         envelopedSignal = filter.Apply(processedSignal);

                float[] envelopedData = envelopedSignal.ToFloat();
                if (envelopeAverage == null)
                {
                    envelopeAverage = new double[envelopedData.Length];
                }

                Parallel.For(0, envelopedData.Length, j =>
                {
                    envelopeAverage[j] += envelopedData[j];
                });
            }

            // now, we need to average over the envelope
            if (m_rawSignals.Count > 0)
            {
                Parallel.For(0, envelopeAverage.Length, i =>
                {
                    envelopeAverage[i] /= m_rawSignals.Count;
                });

                m_envelopedAvg = envelopeAverage.Select(x => (float)x).ToArray();
                IsValid        = true;
            }
        }
Exemplo n.º 7
0
        public void ApplyTest()
        {
            int n          = 16384;
            int sampleRate = 1000;

            double f1 = 22;
            double f2 = 300;

            Signal cosine = new CosineGenerator(f1, 1, sampleRate).Generate(n);
            Signal sine   = new SineGenerator(f2, 1, sampleRate).Generate(n);

            var merge = new AddFilter(cosine);

            merge.Normalize = true;
            Signal original = merge.Apply(sine);

            var of1 = FindFrequencyCount(sampleRate, original, f1);
            var of2 = FindFrequencyCount(sampleRate, original, f2);

            Assert.AreEqual(0.359128660199268, of1, 1e-8);
            Assert.AreEqual(0.47955332752802149, of2, 1e-8);

            Signal lowFiltered1 = new LowPassFilter(f1, sampleRate).Apply(original);
            Signal lowFiltered2 = new LowPassFilter(f2, sampleRate).Apply(original);

            Signal highFiltered1 = new HighPassFilter(f1, sampleRate).Apply(original);
            Signal highFiltered2 = new HighPassFilter(f2, sampleRate).Apply(original);

            var lf11 = FindFrequencyCount(sampleRate, lowFiltered1, f1);
            var lf12 = FindFrequencyCount(sampleRate, lowFiltered1, f2);

            Assert.AreEqual(0.24589601823749971, lf11, 1e-8); // should be higher
            Assert.AreEqual(0.038266797164259778, lf12, 1e-8);
            Assert.IsTrue(lf11 > lf12);

            var lf21 = FindFrequencyCount(sampleRate, lowFiltered2, f1);
            var lf22 = FindFrequencyCount(sampleRate, lowFiltered2, f2);

            Assert.AreEqual(0.35642263929018364, lf21, 1e-8); // should not have much difference
            Assert.AreEqual(0.271181864130875, lf22, 1e-8);

            var hf11 = FindFrequencyCount(sampleRate, highFiltered1, f1);
            var hf12 = FindFrequencyCount(sampleRate, highFiltered1, f2);

            Assert.AreEqual(0.24542517074628975, hf11, 1e-8);  // should not have much difference
            Assert.AreEqual(0.44797847700473359, hf12, 1e-8);

            var hf21 = FindFrequencyCount(sampleRate, highFiltered2, f1);
            var hf22 = FindFrequencyCount(sampleRate, highFiltered2, f2);

            Assert.AreEqual(0.026113299330488803, hf21, 1e-8);
            Assert.AreEqual(0.23279968506488344, hf22, 1e-8); // should be higher
            Assert.IsTrue(hf22 > hf21);

            Assert.AreEqual(16384, cosine.Duration.TotalMilliseconds);
            Assert.AreEqual(16384, sine.Duration.TotalMilliseconds);
            Assert.AreEqual(16384, original.Duration.TotalMilliseconds);
        }
        public void ApplyTest()
        {
            int n          = 16384;
            int sampleRate = 1000;

            double f1 = 22;
            double f2 = 300;

            Signal cosine = new CosineGenerator(f1, 1, sampleRate).Generate(n);
            Signal sine   = new SineGenerator(f2, 1, sampleRate).Generate(n);

            var merge = new AddFilter(cosine);

            merge.Normalize = true;
            Signal original = merge.Apply(sine);

            var of1 = FindFrequencyCount(sampleRate, original, f1);
            var of2 = FindFrequencyCount(sampleRate, original, f2);

            Assert.AreEqual(2.1919473889115457E-05, of1, 1e-8);
            Assert.AreEqual(2.9269612275882952E-05, of2, 1e-8);

            Signal lowFiltered1 = new LowPassFilter(f1, sampleRate).Apply(original);
            Signal lowFiltered2 = new LowPassFilter(f2, sampleRate).Apply(original);

            Signal highFiltered1 = new HighPassFilter(f1, sampleRate).Apply(original);
            Signal highFiltered2 = new HighPassFilter(f2, sampleRate).Apply(original);

            var lf11 = FindFrequencyCount(sampleRate, lowFiltered1, f1);
            var lf12 = FindFrequencyCount(sampleRate, lowFiltered1, f2);

            Assert.AreEqual(1.5008301894378632E-05, lf11, 1e-8); // should be higher
            Assert.AreEqual(2.33561994410787E-06, lf12, 1e-8);
            Assert.IsTrue(lf11 > lf12);

            var lf21 = FindFrequencyCount(sampleRate, lowFiltered2, f1);
            var lf22 = FindFrequencyCount(sampleRate, lowFiltered2, f2);

            Assert.AreEqual(2.1754311480113727E-05, lf21, 1e-8); // should not have much difference
            Assert.AreEqual(1.6551627449395776E-05, lf22, 1e-8);

            var hf11 = FindFrequencyCount(sampleRate, highFiltered1, f1);
            var hf12 = FindFrequencyCount(sampleRate, highFiltered1, f2);

            Assert.AreEqual(1.4979563644182712E-05, hf11, 1e-8);  // should not have much difference
            Assert.AreEqual(2.7342436340623498E-05, hf12, 1e-8);

            var hf21 = FindFrequencyCount(sampleRate, highFiltered2, f1);
            var hf22 = FindFrequencyCount(sampleRate, highFiltered2, f2);

            Assert.AreEqual(1.5938293048394034E-06, hf21, 1e-8);
            Assert.AreEqual(1.420896515288728E-05, hf22, 1e-8); // should be higher
            Assert.IsTrue(hf22 > hf21);

            Assert.AreEqual(16384, cosine.Duration.TotalMilliseconds);
            Assert.AreEqual(16384, sine.Duration.TotalMilliseconds);
            Assert.AreEqual(16384, original.Duration.TotalMilliseconds);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Method for detecting the envelope of a signal
        /// </summary>
        /// <param name="signal">Signal</param>
        /// <param name="lowpassCutoff">LP filter cutoff frequency</param>
        /// <returns></returns>
        public static DiscreteSignal Envelope(DiscreteSignal signal, float lowpassCutoff = 0.05f)
        {
            var envelope = FullRectify(signal);

            var lowpassFilter = new LowPassFilter(lowpassCutoff);
            var smoothed      = lowpassFilter.ApplyTo(envelope);

            return(smoothed);
        }
Exemplo n.º 10
0
 private void lowPassFilterButton_Click(object sender, EventArgs e)
 {
     if (otherFiltersInputImgBox.Image != null)
     {
         var inputBitmap             = new Bitmap(otherFiltersInputImgBox.Image);
         var LowPassFilterMaskClient = new LowPassFilter(inputBitmap,
                                                         Settings.Default.StoreAsColorWherePossible);
         otherFiltersOutputImgBox.Image = LowPassFilterMaskClient.Filter();
     }
 }
Exemplo n.º 11
0
 /*
  * If in auto-update, the function just looks for the wrapper of filter component and assigns it to a variable.
  * Otherwise it instantiates a low pass filter.
  */
 void Start()
 {
     if (shouldUseComponent)
     {
         accelerometerControl = GetComponent <AccelerometerControl>();
     }
     else
     {
         lowPassFilter = new LowPassFilter <Vector3>(a, Vector3.zero);
     }
 }
Exemplo n.º 12
0
 /// <summary>
 /// This is a speed adaptive low-pass filter for smooting sensor data.
 /// </summary>
 /// <param name="frequency">Sensor frequency value.</param>
 /// <param name="mincutoff">Mincutoff value.</param>
 /// <param name="beta">Beta value.</param>
 /// <param name="dcutoff">D cutoff value.</param>
 public SpeedAdaptiveFilter(
     float frequency, float mincutoff = 1, float beta = 0, float dcutoff = 1)
 {
     SetFrequency(frequency);
     SetMinimumCutoff(mincutoff);
     SetBeta(beta);
     SetDerivateCutoff(dcutoff);
     m_XFilter  = new LowPassFilter(GetWeight(mincutoff), 0);
     m_DXFilter = new LowPassFilter(GetWeight(dcutoff), 0);
     m_PrevTime = DateTime.MinValue;
 }
Exemplo n.º 13
0
    public void Begin(string ipAddress, int port)
    {
        // Give the network stuff its own special thread
        var thread = new Thread(() =>
        {
            // We'll use `LowPassFilter` to filter out some incorrect readings coming from the sensor
            var filter = new LowPassFilter(0.95f);

            // This class makes it super easy to do network stuff
            var client = new TcpClient();

            // Change this to your devices real address
            client.Connect(ipAddress, port);
            var stream = new StreamReader(client.GetStream());

            // We'll read values and buffer them up in here
            var buffer = new List <byte>();
            while (client.Connected)
            {
                // Read the next byte
                var read = stream.Read();

                // We split readings with a carriage return, so check for it
                if (read == 13)
                {
                    // Once we have a reading, convert our buffer to a string, since the values are coming as strings
                    var str = Encoding.ASCII.GetString(buffer.ToArray());

                    // We assume that they're floats
                    var dist = float.Parse(str);

                    // Ignore any value outside of our expected input range
                    dist = Mathf.Clamp(dist, _minInputY, _maxInputY);

                    // Use the `LowPassFilter` to smooth out values
                    filter.Step(dist);

                    // Remap the value from our input range to our planes movement range
                    CurrentValue = filter.SmoothedValue.Remap(_minInputY, _maxInputY, _minFinalY, _maxFinalY);

                    // Clear the buffer ready for another reading
                    buffer.Clear();
                }
                else
                {
                    // If this wasn't the end of a reading, then just add this new byte to our buffer
                    buffer.Add((byte)read);
                }
            }
        });

        thread.Start();
    }
Exemplo n.º 14
0
        public SoundTest()
        {
            const string soundFilePath = @"C:\docs\music\Daft Punk - Random Access Memories (2013) [320 Kbps]\CD\08 Get Lucky (Feat. Pharrell Williams).mp3";
            var sound = Add(new SoundFx(soundFilePath));
            sound.Play();
            _lowpass = new LowPassFilter();
            sound.Filters.Add(_lowpass);

            _lpInterp = new Interpolation(-500, 500, 10, 8000, Sine.EaseOut);
            _resInterp = new Interpolation(-1000, 1000, 0, .4f, Sine.EaseIn);

            Add(new MouseButtonBinding(MouseButton.Left, ApplyLowpass, StopLowpass));
        }
Exemplo n.º 15
0
    public OneEuroFilter(float _freq, float _mincutoff = 1.0f, float _beta = 0.0f, float _dcutoff = 1.0f)
    {
        setFrequency(_freq);
        setMinCutoff(_mincutoff);
        setBeta(_beta);
        setDerivateCutoff(_dcutoff);
        x        = new LowPassFilter(alpha(mincutoff));
        dx       = new LowPassFilter(alpha(dcutoff));
        lasttime = -1.0f;

        currValue = 0.0f;
        prevValue = currValue;
    }
Exemplo n.º 16
0
        public AnalogTransmitter(string TagID, double Timestep)//Different constructors depending on the use of simulator/real process and Fuji PID/Software PID
        {
            TAG      = TagID;
            OPC_PV   = new OPC(TagID + "_PV", true);
            Alarm    = new OPC[Alarms.Length];
            AlarmLim = new OPC[Alarms.Length];
            Filter   = new LowPassFilter(Timestep);

            for (int i = 0; i < Alarms.Length; i++)//Initializing Reading Limits and writing the alarms to the OPC server
            {
                Alarm[i]    = new OPC(TAG + "_" + Alarms[i], true);
                AlarmLim[i] = new OPC(TAG + "_" + Alarms[i] + "_Lim");
            }
        }
Exemplo n.º 17
0
        public void Load()
        {
            const string soundFilePath = @"C:\docs\music\21. Cloud Atlas (Finale).mp3";

            var sound = Add(new SoundFx(soundFilePath));
            sound.Play();

            var lowpass = new LowPassFilter();
            sound.Filters.Add(lowpass);

            var timer = Create<Timeline>();
            timer.Tween(v => lowpass.Frequency = v, 10, lowpass.Frequency, 10, Cubic.EaseIn);

            Add(new SoundStateRecorder(sound, "couldAtlasOST"));
        }
Exemplo n.º 18
0
        public void ApplyFilter()
        {
            switch (fPostAction)
            {
            case PostAction.paSpline:
            {
                SplineFilter splineFilter = new SplineFilter(fSplineCount);
                for (int i = 0; i < fData.Count; i++)
                {
                    TrendPoint trendPt = this[i];
                    trendPt.pFilteredValue = splineFilter.Run(trendPt.pValue);
                }
                //splineFilter.Dispose();
            }
            break;

            case PostAction.paFilter:
            {
                int count = fData.Count;
                if (count != 0)
                {
                    LowPassFilter lowPassFilter = new LowPassFilter(count);
                    try {
                        for (int i = 0; i < count; i++)
                        {
                            lowPassFilter.SetInputDataItem(i, this[i].pValue);
                        }

                        lowPassFilter.SetMode(fFilter.Mode);
                        lowPassFilter.SetBandWidth(fFilter.BandWidth);
                        lowPassFilter.SetOvershoot(fFilter.Overshoot);
                        lowPassFilter.SetFrequencyResolution(fFilter.FrequencyResolution);
                        lowPassFilter.SetSuppressionDegree(fFilter.SuppressionDegree);
                        lowPassFilter.SetSubstractionNoiseDegree(fFilter.SubstractionNoiseDegree);
                        lowPassFilter.Execute();

                        for (int i = 0; i < count; i++)
                        {
                            this[i].pFilteredValue = lowPassFilter.GetOutputDataItem(i);
                        }
                    } finally {
                        //lowPassFilter.Dispose();
                    }
                }
            }
            break;
            }
        }
Exemplo n.º 19
0
        public SoundEmitter2D(SoundFx sound, Body body, float far, float close = 1, float panFactor = .3f)
        {
            Close = close;
            _panFactor = panFactor;
            Far = far;

            _range = far - close;

            _body = body;
            _sound = sound;

            _lowpass = new LowPassFilter();
            _sound.Filters.Add(_lowpass);

            _interp = new Interpolation(0, 1, 0, 1, Quart.EaseIn);
        }
Exemplo n.º 20
0
    void Start()
    {
        osc = new Oscillator();
        env = new Envelope();
        lpf = new LowPassFilter(env);
        amp = new Amplifier(env);

        lpf.cutoff = 0.2f;
        lpf.envMod = 0.2f;

        seq = new Sequencer(bpm,
                            new int[]
        {
            30, 30, 42, 30,
            30, 29, 30, 29,
            30, 30, 42, 30,
            30, 42, 29, 30
        },
                            new bool[]
        {
            true, true, true, true,
            true, true, false, true,
            true, false, false, true,
            true, true, false, true
        }
                            );

        drums = new Sampler[drumClips.Length];
        for (var i = 0; i < drumClips.Length; i++)
        {
            drums[i] = new Sampler(drumClips[i]);
        }

        drumSeq = new MatrixSequencer(bpm, drumClips.Length, 16);
        drumSeq.SetTrack(0,
                         new bool[]
        {
            true, false, false, false,
            true, false, false, false,
            true, false, false, false,
            true, false, false, false
        }
                         );

        GetComponent <AudioSource>().clip = AudioClip.Create("(null)", 0xfffffff, 1, SynthConfig.kSampleRate, true, delegate(float[] data) {});
        GetComponent <AudioSource>().Play();
    }
Exemplo n.º 21
0
        public bool lowPassFilter(Behavior behavior)
        {
            _jetTestConnection = new TestJetbusConnection(behavior, ipaddress, "Administrator", "wtx", delegate { return(true); });

            _dseObj = new DSEJet(_jetTestConnection, 100, update);

            _dseObj.Connect(this.OnConnect, 100);

            LowPassFilter filter = _dseObj.LowPassFilterMode;

            switch (behavior)
            {
            case Behavior.lowPassFilterNoFilter:
                if (filter == LowPassFilter.No_Filter)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }

            case Behavior.lowPassFilterIIRFilter:
                if (filter == LowPassFilter.IIR_Filter)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }

            case Behavior.lowPassFilterFIRFilter:
                if (filter == LowPassFilter.FIR_Filter)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }

            default:
                return(false);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// パラメータを指定して新しい OverSampling クラスのインスタンスを初期化します。
        /// </summary>
        /// <param name="samplingRate">サンプリング周波数。これはオーバーサンプリング後の周波数となります。</param>
        /// <param name="magnification">サンプリング倍率。</param>
        /// <param name="stereo">ステレオである場合は true、モノラルである場合は false。</param>
        /// <param name="filterSize">フィルタサイズ。</param>
        public OverSampling(double samplingRate, int magnification, bool stereo, int filterSize)
        {
            if (samplingRate <= 0.0)
            {
                throw new ArgumentOutOfRangeException("samplingRate");
            }

            if (magnification <= 0)
            {
                throw new ArgumentOutOfRangeException("magnification");
            }

            if (filterSize <= 0)
            {
                throw new ArgumentOutOfRangeException("filterSize");
            }

            if (filterSize % 2 != 0)
            {
                throw new ArgumentException();
            }

            this.samplingRate  = samplingRate;
            this.magnification = magnification;
            this.stereo        = stereo;
            this.filterSize    = filterSize;

            this.filter = new SoundFilter(stereo, filterSize);

            var filterGenerator = new LowPassFilter()
            {
                SamplingRate    = samplingRate * magnification,
                CutoffFrequency = samplingRate / 2 -
                                  FiniteImpulseResponse.GetDelta(samplingRate * magnification, filterSize)
            };

            double[] impulse = filterGenerator.Generate(filterSize / 2);

            Window.Blackman(impulse);
            filter.SetFilter(impulse);
        }
Exemplo n.º 23
0
        public void Load()
        {
            #if ANDROID
            /*var dir = Directory.GetParent(Assembly.GetExecutingAssembly().Location);
            var folder = dir.Parent.Parent;
            Explore (folder);*/
            var soundFilePath = @"Content/01 - The Poet Acts.mp3";
            var stream = Game.Activity.Assets.Open(soundFilePath);
            var content = ReadToEnd (stream);
            var memStream = new MemoryStream (content);
            var sound = Add(new SoundFx(new Mp3FileReader(memStream)));
            sound.Play();

            var lowpass = new LowPassFilter();
            sound.Filters.Add(lowpass);

            var timer = Create<Timer_>();
            timer.Tween(v => lowpass.Frequency = v, 10, lowpass.Frequency, 10, Cubic.EaseIn);
            Add(new SoundStateRecorder(sound, "couldAtlasOST"));
            #endif
        }
Exemplo n.º 24
0
        public void sample_test()
        {
            string basePath = NUnit.Framework.TestContext.CurrentContext.TestDirectory;
            string pathWhereTheDatasetShouldBeStored = Path.Combine(basePath, "mfcc");

            #region doc_example1
            // Let's say we would like to analyse an audio sample. To give an example that
            // could be reproduced by anyone without having to give a specific sound file
            // that would need to have been downloaded by every user trying to run this example,
            // we will use obtain an example from the Free Spoken Digits Dataset instead:
            var fsdd = new FreeSpokenDigitsDataset(path: pathWhereTheDatasetShouldBeStored);

            // Let's obtain one of the audio signals:
            Signal a          = fsdd.GetSignal(0, "jackson", 10);
            int    sampleRate = a.SampleRate; // 8000

            // Note: if you would like to load a signal from the
            // disk, you could use the following method directly:
            // Signal a = Signal.FromFile(fileName);

            // Create a low-pass filter to keep only frequencies below 100 Hz
            var filter = new LowPassFilter(frequency: 100, sampleRate: sampleRate);

            // Apply the filter to the signal
            Signal result = filter.Apply(a);

            // Create a spectrogram for the original
            var sourceSpectrum = new Spectrogram(a);

            // Create a spectrogram for the filtered signal:
            var resultSpectrum = new Spectrogram(result);

            // Get the count for a high frequency before and after the low-pass filter:
            double before = sourceSpectrum.GetFrequencyCount(windowIndex: 0, frequency: 1000); // 0.00028203820434203334
            double after  = resultSpectrum.GetFrequencyCount(windowIndex: 0, frequency: 1000); // 2.9116651158267508E-05
            #endregion

            Assert.AreEqual(0.00028203820434203334, before, 1e-8);
            Assert.AreEqual(2.9116651158267508E-05, after, 1e-8);
        }
Exemplo n.º 25
0
/* void SocketSend(string sendStr)
 *  {
 *      //清空發送緩存
 *      sendData=new byte[1024];
 *      //數據類型轉換
 *      sendData=Encoding.ASCII.GetBytes(sendStr);
 *      //發送給指定客戶端
 *      clientSocket.Send(sendData,sendData.Length,SocketFlags.None);
 *  }*/

    //伺服器接收
    void SocketReceive()
    {
        //連接
        SocketConnet();
        //接收迴圈
        while (true)
        {
            sw.Start();
            for (int i = 0; i < 10; i++)
            {
                var filter = new LowPassFilter(0.95f);
                //清空數據
                recvData = new byte[1024];
                //獲取收到的數據長度
                recvLen = clientSocket.Receive(recvData);
                //如果收到的數據長度為0,則重新連線進入下一個循環
                if (recvLen == 0)
                {
                    SocketConnet();
                    continue;
                }
                //輸出接收到的數據
                recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
                print(recvStr);
                //分割字串
                char[]   splitChar = { ' ', ',', ':', '\t', ';' };
                string[] dataRaw   = recvStr.Split(splitChar);
                RotateX = int.Parse(dataRaw[0]);
                RotateY = int.Parse(dataRaw[1]);
                RotateZ = int.Parse(dataRaw[2]);
                filter.Step(RotateX);
                filter.Step(RotateY);
                filter.Step(RotateZ);
            }
            sw.Stop();//碼錶停止
            string result1 = sw.Elapsed.TotalMilliseconds.ToString();
            print(result1);
        }
    }
Exemplo n.º 26
0
 void SocketReceive()
 {
     //接收資料端
     while (true)
     {
         var filter = new LowPassFilter(0.95f);
         //清空資料緩存
         recvData = new byte[1024];
         //獲取客戶端送來的資料
         recvLen = socket.ReceiveFrom(recvData, ref clientEnd);
         //輸出接收到的資料
         recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
         // print(recvStr);
         //分割字串
         char[]   splitChar = { ' ', ',', ':', '\t', ';' };
         string[] dataRaw   = recvStr.Split(splitChar);
         RotateX  = int.Parse(dataRaw[0]);
         RotateY  = int.Parse(dataRaw[1]);
         RotateZ  = int.Parse(dataRaw[2]);
         RotateX2 = int.Parse(dataRaw[3]);
         RotateY2 = int.Parse(dataRaw[4]);
         RotateZ2 = int.Parse(dataRaw[5]);
         AccX     = int.Parse(dataRaw[6]);
         AccY     = int.Parse(dataRaw[7]);
         AccZ     = int.Parse(dataRaw[8]);
         AccX2    = int.Parse(dataRaw[9]);
         AccY2    = int.Parse(dataRaw[10]);
         AccZ2    = int.Parse(dataRaw[11]);
         // FlexValue = float.Parse(dataRaw[6]);
         // 使用低通濾波
         filter.Step(RotateX);
         filter.Step(RotateY);
         filter.Step(RotateZ);
         filter.Step(RotateX2);
         filter.Step(RotateY2);
         filter.Step(RotateZ2);
         //filter.Step(FlexValue);
     }
 }
Exemplo n.º 27
0
        private DiscreteSignal ProcessDistortion(DiscreteSignal signal, int gain, int distortion)
        {
            var input  = signal.Samples;
            var output = new float[input.Length];


            for (var i = 0; i < signal.Length; i++)
            {
                // Process gain
                output[i] = Gain(input[i], gain);

                // Process distortion
                output[i] = Dist(output[i], distortion);
            }

            // Process lowpass filter
            var            freq      = 10000.0 /* Hz */ / signal.SamplingRate;
            LowPassFilter  lpf       = new LowPassFilter(freq);
            DiscreteSignal processed = new DiscreteSignal(signal.SamplingRate, output);
            DiscreteSignal res       = lpf.ApplyTo(processed);

            return(res);
        }
Exemplo n.º 28
0
        private void SetFilter(IFilter filter)
        {
            switch (filter)
            {
            case KarokeFilter karokeFilter:
                Karoke = karokeFilter;
                break;

            case TimescaleFilter timescaleFilter:
                Timescale = timescaleFilter;
                break;

            case TremoloFilter tremoloFilter:
                Tremolo = tremoloFilter;
                break;

            case VibratoFilter vibratoFilter:
                Vibrato = vibratoFilter;
                break;

            case RotationFilter rotationFilter:
                Rotation = rotationFilter;
                break;

            case DistortionFilter distortionFilter:
                Distortion = distortionFilter;
                break;

            case ChannelMixFilter channelMixFilter:
                ChannelMix = channelMixFilter;
                break;

            case LowPassFilter lowPassFilter:
                LowPass = lowPassFilter;
                break;
            }
        }
Exemplo n.º 29
0
        private void HandleFilterTypeChange(FilterChange message)
        {
            bpFilter = message.BPFilter;
            hpFilter = message.HPFilter;
            lpFilter = message.LPFilter;
            switch (message.FilterType)
            {
            case FilterType.None:
                Become(ProcessNone);
                break;

            case FilterType.HighPass:
                Become(ProcessHighPass);
                break;

            case FilterType.LowPass:
                Become(ProcessLowPass);
                break;

            case FilterType.BandPass:
                Become(ProcessBandPass);
                break;
            }
        }
 /*
  * This is the Constructor for the inner class, it assigns the new input object to a variable and then instantiates the filter.
  * Parameters are:
  *      - input - the object providing input to the filter, needs to be instantiated previous to invoking this method
  *      - a - smoothing factor, the lower, the more inertia
  *      - initialValue - the initial value for the filter, it should be as close as possible to the expected average value of the filtered variable.
  */
 public LowPassFilterController(IFilterInput <T> input, float a, T initialValue)
 {
     lowPassFilterInput = input;
     lowPassFilter      = new LowPassFilter <T>(a, initialValue);
 }
Exemplo n.º 31
0
        private static void InsertCorrectedGps(DataTable gpsRawTable, InsertConfig.GpsCorrection correction)
        {
            DataTable correctedGpsTable = DataTableUtil.GetCorrectedGpsTable();

            #region インデックスが 0 の場合
            DataRow firstRow = correctedGpsTable.NewRow();
            CopyRawDataToCorrectedRow(firstRow, gpsRawTable.Rows[0]);
            firstRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0);
            firstRow.SetField(CorrectedGpsDao.ColumnSpeed, 0);
            firstRow.SetField(CorrectedGpsDao.ColumnHeading, 0);

            correctedGpsTable.Rows.Add(firstRow);
            #endregion

            for (int i = 1; i < gpsRawTable.Rows.Count - 1; i++)
            {
                DataRow row = correctedGpsTable.NewRow();

                CopyRawDataToCorrectedRow(row, gpsRawTable.Rows[i]);

                // 距離の算出
                row.SetField(CorrectedGpsDao.ColumnDistanceDifference, DistanceCalculator.CalcDistance(
                                 gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                 gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude),
                                 gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                 gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude)));

                // 速度の算出
                row.SetField(CorrectedGpsDao.ColumnSpeed, SpeedCalculator.CalcSpeed(
                                 gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                 gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude),
                                 gpsRawTable.Rows[i - 1].Field <DateTime>(AndroidGpsRawDao.ColumnJst),
                                 gpsRawTable.Rows[i + 1].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                 gpsRawTable.Rows[i + 1].Field <double>(AndroidGpsRawDao.ColumnLongitude),
                                 gpsRawTable.Rows[i + 1].Field <DateTime>(AndroidGpsRawDao.ColumnJst),
                                 gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                 gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude)));

                //速度が1km以上になったらHEADINGを更新する(停止時に1つ1つ計算するとHEADINDが暴れるため)
                if (row.Field <Single>(CorrectedGpsDao.ColumnSpeed) > 1.0)
                {
                    row.SetField(CorrectedGpsDao.ColumnHeading, HeadingCalculator.CalcHeading(
                                     gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                     gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude),
                                     gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                     gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude)));
                }
                else
                {
                    row.SetField(CorrectedGpsDao.ColumnHeading, correctedGpsTable.Rows[i - 1].Field <Single>(CorrectedGpsDao.ColumnHeading));
                }

                correctedGpsTable.Rows.Add(row);
            }

            #region インデックスが最後の場合
            DataRow lastRow = correctedGpsTable.NewRow();
            CopyRawDataToCorrectedRow(lastRow, gpsRawTable.Rows[gpsRawTable.Rows.Count - 1]);
            lastRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0);
            lastRow.SetField(CorrectedGpsDao.ColumnSpeed, 0);
            lastRow.SetField(CorrectedGpsDao.ColumnHeading, 0);

            correctedGpsTable.Rows.Add(lastRow);

            #endregion

            // ファイルごとの挿入なので主キー違反があっても挿入されないだけ
            if (correction == InsertConfig.GpsCorrection.SpeedLPFMapMatching)//速度にローパスフィルタを適用
            {
                DataTable correctedGpsSpeedLPFTable = LowPassFilter.speedLowPassFilter(correctedGpsTable, 0.05);
                CorrectedGpsSpeedLPF005MMDao.Insert(correctedGpsSpeedLPFTable);
            }
            else if (correction == InsertConfig.GpsCorrection.MapMatching)
            {
                CorrectedGPSMMDao.Insert(correctedGpsTable);
            }
            else
            {
                CorrectedGpsDao.Insert(correctedGpsTable);
            }
        }
Exemplo n.º 32
0
        private static async Task TestBrainDeviceManager()
        {
            var cfg       = ClientConfig.GetConfig();
            var lowFilter = new LowPassFilter()
            {
                LowPassRate = 10
            };
            var highFilter = new HighPassFilter()
            {
                HighPassRate = 10000
            };
            var bPassFilter = new BandPassFilter()
            {
                LowCutoffRate = 20, HighCutoffRate = 30
            };
            var bStopFilter = new BandStopFilter()
            {
                LowPassRate = 35, HighPassRate = 38
            };
            var mFilter = new MedianFilter()
            {
                HalfMedianWindowSize = 7
            };
            var bandFilter = new BandPassStopFilter
            {
                BandFilterList = new List <BandFilter> {
                    lowFilter, highFilter, bPassFilter, bStopFilter
                }
            };

            bandFilter.Disable = true;
            var allFilter = new FilterTypeList()
            {
                Filters = new List <FilterType> {
                    bandFilter, mFilter
                }
            };
            var filterParameters = new Dictionary <string, string>
            {
                { FilterTypeList.FIRhalfOrderOptionName, 10.ToString() }
            };

            cfg.FilterLst = allFilter;
            IOnlineFilter         filter     = null;
            WaveletReconstruction waveletRec = null;

            cfg.WaveletRecCfg = new WaveletReconstructionConfig
            {
                AvgLevel          = 8,
                ConvolutionMode   = ConvolutionModeEnum.Normal,
                ExtensionMode     = SignalExtension.ExtensionMode.SymmetricHalfPoint,
                Level             = 8,
                MotherWaveletName = "db5",
                WindowSize        = 15
            };
            cfg.WriteToFile(ClientConfig.DefaultConfigFileName);


            BrainDeviceManager.Init();
            var sender = await BrainDeviceManager.Connnect("127.0.0.1", 9211);

            BrainDevState currentState = default(BrainDevState);

            //保证设备参数正常才继续跑逻辑
            BrainDeviceManager.BrainDeviceState.Subscribe(ss =>
            {
                currentState = ss;
                filterParameters.Update(
                    FilterTypeList.SampleRateOptionName,
                    BrainDevState.SampleCountPer1Sec(ss.SampleRate).ToString()
                    );
                //AppLogger.Debug($"Brain Device State Changed Detected: {ss}");
            }, () =>
            {
                AppLogger.Debug("device stop detected");
            });
            int totalReceived    = 0;
            var medianFilter     = OnlineFirFilter.CreateDenoise(7);
            var fastMedianFilter = new OnlineFastMedianFilter(3);

            BrainDeviceManager.SampleDataStream.Subscribe(tuple =>
            {
                var(order, datas, arr) = tuple;
                //Console.Write($" {order} ");
                var passTimes = BrainDevState.PassTimeMs(currentState.SampleRate, totalReceived) / 1000;
                var intArr    = datas.CopyToArray();
                var val       = intArr[0];
                var voltage   = BitDataConverter.Calculatevoltage(val, 4.5f, currentState.Gain);
                totalReceived++;
                var m1 = medianFilter.ProcessSample(voltage);
                var m2 = fastMedianFilter.ProcessSample(voltage);
                AppLogger.Debug($"passTimes:{passTimes},val:{val},voltage:{voltage},median filter:{m1},fast:{m2},{m1==m2}");
                if (filter == null)
                {
                    filter     = allFilter.CreateFilter(filterParameters);
                    waveletRec = cfg.WaveletRecCfg.Create(
                        BrainDevState.SampleCountPer1Sec(currentState.SampleRate));
                    waveletRec.ReconstructionStream.Subscribe(reconstruct =>
                    {
                        var(vol, tim) = reconstruct;
                        AppLogger.Debug($"wavelet reconstruction:{vol} at {tim}");
                    });
                }
                waveletRec?.BufferData((voltage, passTimes));
                AppLogger.Debug($"filter processed:{filter.ProcessSample(voltage)}");
                //AppLogger.Debug($"order:{order}");
                //AppLogger.Debug($"converted values:{datas.Show()}");
                //AppLogger.Debug($"original datas:{arr.Show()}");
            }, () =>
            {
                AppLogger.Debug("device sampling stream closed detected");
            });

            var cmdResult = await sender.QueryParam();

            AppLogger.Debug("QueryParam result:" + cmdResult);
            if (cmdResult != CommandError.Success)
            {
                AppLogger.Error("Failed to QueryParam, stop");
                BrainDeviceManager.DisConnect();
                return;
            }


            cmdResult = await sender.SetFilter(true);

            AppLogger.Debug("SetFilter result:" + cmdResult);

            cmdResult = await sender.SetTrap(TrapSettingEnum.Trap_50);

            AppLogger.Debug("SetTrap result:" + cmdResult);

            cmdResult = await sender.SetSampleRate(SampleRateEnum.SPS_2k);

            AppLogger.Debug("SetSampleRate result:" + cmdResult);

            cmdResult = await sender.QueryParam();

            AppLogger.Debug("QueryParam result:" + cmdResult);

            cmdResult = await sender.QueryFaultState();

            AppLogger.Debug("QueryFaultState result:" + cmdResult);

            cmdResult = await sender.TestSingleImpedance(1);

            AppLogger.Debug("TestSingleImpedance result:" + cmdResult);

            cmdResult = await sender.TestMultiImpedance(30);

            AppLogger.Debug("TestMultiImpedance result:" + cmdResult);

            Console.ReadLine();
            var fs = new FileResource(currentState, 19801983, 1, BrainDeviceManager.BufMgr);

            fs.StartRecord(BrainDeviceManager.SampleDataStream);
            cmdResult = await sender.Start();

            if (cmdResult != CommandError.Success)
            {
                AppLogger.Error("Failed to start sampler");
            }
            else
            {
                AppLogger.Debug($"start receive sample data");
                await Task.Delay(1000 *10);

                AppLogger.Debug($"stoping");
                await sender.Stop();

                AppLogger.Debug($"stop receive sample data");
                await Task.Delay(1000);
            }

            BrainDeviceManager.DisConnect();
            fs.Dispose();

            var readf = new FileSampleData(fs.ResourceId, BrainDeviceManager.BufMgr);

            Console.WriteLine($"expecte to read {totalReceived} blocks");
            Console.WriteLine($"start reading saved sampling data");
            int readCount = 0;

            readf.DataStream.Subscribe(tuple =>
            {
                var(order, datas, arr) = tuple;
                Console.Write($" {order} ");
                readCount++;
                //AppLogger.Debug($"order:{order}");
                //AppLogger.Debug($"converted values:{datas.Show()}");
                //AppLogger.Debug($"original datas:{arr.Show()}");
            }, () =>
            {
                AppLogger.Debug($"read sampling data file end,count :{readCount},expected count:{totalReceived}");
            });
            readf.Start();
            await Task.Delay(1000 *10);

            Console.Write($"wait complete");
        }
Exemplo n.º 33
0
        private void ProviderDataReceived(object sender, ushort[] data)
        {
            // check the device state
            if (DeviceState == DeviceState.Startup)
            {
                if (m_detectorType == Detector.Old)
                {
                    if (m_calibrationSamples == null)
                    {
                        m_calibrationSamples = new double[data.Length];
                    }

                    Parallel.For(0, data.Length, i =>
                    {
                        m_calibrationSamples[i] += data[i];
                    });
                    m_calibrationCounter++;

                    if (m_calibrationCounter == NumberOfCalibrationSamples)
                    {
                        Parallel.For(0, data.Length, i =>
                        {
                            m_calibrationSamples[i] /= m_calibrationCounter;
                        });

                        DeviceState = DeviceState.Running;
                    }
                }
                else
                {
                    if (!m_calibration.IsValid)
                    {
                        m_calibration.AddSample(data);
                        m_calibrationCounter++;

                        if (m_calibrationCounter == NumberOfCalibrationSamples)
                        {
                            // now, we can calibrate
                            m_calibration.Calibrate();

                            if (m_calibration.IsValid)
                            {
                                DeviceState = DeviceState.Running;
                            }
                            else
                            {
                                m_calibration.Reset();
                            }
                        }
                    }
                }
            }
            else if (DeviceState == DeviceState.Running)
            {
                // preprocess the signal (get baseline and shift)
                float[]  rawData        = data.Select(value => (float)value).ToArray();
                ushort[] calibratedData = new ushort[rawData.Length];

                if (m_detectorType == Detector.Old)
                {
                    // calibrate
                    Parallel.For(0, rawData.Length, i =>
                    {
                        calibratedData[i] = (ushort)Math.Abs(rawData[i] - m_calibrationSamples[i]);
                    });
                }
                else if (m_detectorType == Detector.New)
                {
                    Signal        rawSignal     = Signal.FromArray(rawData, SampleRate, SampleFormat.Format32BitIeeeFloat);
                    LowPassFilter lowPassFilter = new LowPassFilter(100.0, SampleRate)
                    {
                        Alpha = 0.05f
                    };
                    rawSignal = lowPassFilter.Apply(rawSignal);

                    float[] baseline = rawSignal.ToFloat();
                    Parallel.For(0, rawData.Length, i =>
                    {
                        rawData[i] = Math.Abs(rawData[i] - baseline[i]);
                    });
                }
                else if (m_detectorType == Detector.Advanced)
                {
                }

                // good, raw data is shifted now
                SensorDataEventArgs eventArgs = null;
                if (m_detectorType == Detector.Old)
                {
                    eventArgs = m_signalProcessor.ProcessData(calibratedData, true);
                }
                else
                {
                    eventArgs = m_signalProcessor.ProcessData(m_calibration, rawData, true);
                }

                // notify the receviers about the raw data
                DataReceived?.Invoke(this, eventArgs);

                // now, do touch processing
                ProcessTouches(eventArgs);
            }
        }
Exemplo n.º 34
0
        public static void InsertCorrectedGps(InsertDatum datum, InsertConfig.GpsCorrection correction)
        {
            var tripsTable = TripsDao.Get(datum);

            foreach (DataRow tripsRow in tripsTable.Rows)
            {
                DataTable gpsRawTable =
                    AndroidGpsRawDao.Get(tripsRow.Field <DateTime>(TripsDao.ColumnStartTime),
                                         tripsRow.Field <DateTime>(TripsDao.ColumnEndTime), datum);
                if (gpsRawTable.Rows.Count == 0)
                {
                    return;
                }
                DataTable correctedGpsTable = DataTableUtil.GetCorrectedGpsTable();

                #region インデックスが 0 の場合
                DataRow firstRow = correctedGpsTable.NewRow();
                CopyRawDataToCorrectedRow(firstRow, gpsRawTable.Rows[0]);
                firstRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0);
                //firstRow.SetField(CorrectedGpsDao.ColumnSpeed, 0);
                firstRow.SetField(CorrectedGpsDao.ColumnHeading, 0);
                var meshAndAltitude = AltitudeCalculator.GetInstance().CalcAltitude(
                    gpsRawTable.Rows[0].Field <double>(CorrectedGpsDao.ColumnLatitude),
                    gpsRawTable.Rows[0].Field <double>(CorrectedGpsDao.ColumnLongitude));

                firstRow.SetField(CorrectedGpsDao.ColumnTerrainAltitude, meshAndAltitude.Item2);



                var linkAndTheta = LinkMatcher.GetInstance().MatchLink(
                    firstRow.Field <double>(CorrectedGpsDao.ColumnLatitude),
                    firstRow.Field <double>(CorrectedGpsDao.ColumnLongitude),
                    0f, tripsRow.Field <string>(TripsDao.ColumnTripDirection), datum);

                firstRow.SetField(CorrectedGpsDao.ColumnLinkId, linkAndTheta.Item1);
                firstRow.SetField(CorrectedGpsDao.ColumnRoadTheta, linkAndTheta.Item2);

                correctedGpsTable.Rows.Add(firstRow);
                #endregion

                for (int i = 1; i < gpsRawTable.Rows.Count - 1; i++)
                {
                    DataRow row = correctedGpsTable.NewRow();

                    CopyRawDataToCorrectedRow(row, gpsRawTable.Rows[i]);

                    // 距離の算出
                    row.SetField(CorrectedGpsDao.ColumnDistanceDifference, DistanceCalculator.CalcDistance(
                                     gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                     gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude),
                                     gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                     gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude)));

                    meshAndAltitude = AltitudeCalculator.GetInstance().CalcAltitude(
                        gpsRawTable.Rows[i].Field <double>(CorrectedGpsDao.ColumnLatitude),
                        gpsRawTable.Rows[i].Field <double>(CorrectedGpsDao.ColumnLongitude));

                    row.SetField(CorrectedGpsDao.ColumnTerrainAltitude, meshAndAltitude.Item2);



                    // 速度の算出
                    //row.SetField(CorrectedGpsDao.ColumnSpeed, SpeedCalculator.CalcSpeed(
                    //    gpsRawTable.Rows[i - 1].Field<double>(AndroidGpsRawDao.ColumnLatitude),
                    //    gpsRawTable.Rows[i - 1].Field<double>(AndroidGpsRawDao.ColumnLongitude),
                    //    gpsRawTable.Rows[i - 1].Field<DateTime>(AndroidGpsRawDao.ColumnJst),
                    //    gpsRawTable.Rows[i + 1].Field<double>(AndroidGpsRawDao.ColumnLatitude),
                    //    gpsRawTable.Rows[i + 1].Field<double>(AndroidGpsRawDao.ColumnLongitude),
                    //    gpsRawTable.Rows[i + 1].Field<DateTime>(AndroidGpsRawDao.ColumnJst),
                    //    gpsRawTable.Rows[i].Field<double>(AndroidGpsRawDao.ColumnLatitude),
                    //    gpsRawTable.Rows[i].Field<double>(AndroidGpsRawDao.ColumnLongitude)));

                    //速度が1km以上になったらHEADINGを更新する(停止時に1つ1つ計算するとHEADINDが暴れるため)
                    if (row.Field <Single?>(CorrectedGpsDao.ColumnSpeed) > 1.0)
                    {
                        row.SetField(CorrectedGpsDao.ColumnHeading, HeadingCalculator.CalcHeading(
                                         gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                         gpsRawTable.Rows[i - 1].Field <double>(AndroidGpsRawDao.ColumnLongitude),
                                         gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLatitude),
                                         gpsRawTable.Rows[i].Field <double>(AndroidGpsRawDao.ColumnLongitude)));
                    }
                    else
                    {
                        row.SetField(CorrectedGpsDao.ColumnHeading, correctedGpsTable.Rows[i - 1].Field <double>(CorrectedGpsDao.ColumnHeading));
                    }

                    linkAndTheta = LinkMatcher.GetInstance().MatchLink(
                        row.Field <double>(CorrectedGpsDao.ColumnLatitude),
                        row.Field <double>(CorrectedGpsDao.ColumnLongitude),
                        Convert.ToSingle(row.Field <double>(CorrectedGpsDao.ColumnHeading))
                        , tripsRow.Field <string>(TripsDao.ColumnTripDirection), datum
                        );

                    row.SetField(CorrectedGpsDao.ColumnLinkId, linkAndTheta.Item1);
                    row.SetField(CorrectedGpsDao.ColumnRoadTheta, linkAndTheta.Item2);
                    correctedGpsTable.Rows.Add(row);
                }

                #region インデックスが最後の場合
                DataRow lastRow = correctedGpsTable.NewRow();
                CopyRawDataToCorrectedRow(lastRow, gpsRawTable.Rows[gpsRawTable.Rows.Count - 1]);
                lastRow.SetField(CorrectedGpsDao.ColumnDistanceDifference, 0);
                lastRow.SetField(CorrectedGpsDao.ColumnSpeed, 0);
                lastRow.SetField(CorrectedGpsDao.ColumnHeading, 0);

                meshAndAltitude = AltitudeCalculator.GetInstance().CalcAltitude(
                    gpsRawTable.Rows[gpsRawTable.Rows.Count - 1].Field <double>(CorrectedGpsDao.ColumnLatitude),
                    gpsRawTable.Rows[gpsRawTable.Rows.Count - 1].Field <double>(CorrectedGpsDao.ColumnLongitude));

                lastRow.SetField(CorrectedGpsDao.ColumnTerrainAltitude, meshAndAltitude.Item2);



                linkAndTheta = LinkMatcher.GetInstance().MatchLink(
                    firstRow.Field <double>(CorrectedGpsDao.ColumnLatitude),
                    firstRow.Field <double>(CorrectedGpsDao.ColumnLongitude),
                    0f, tripsRow.Field <string>(TripsDao.ColumnTripDirection), datum);

                lastRow.SetField(CorrectedGpsDao.ColumnLinkId, linkAndTheta.Item1);
                lastRow.SetField(CorrectedGpsDao.ColumnRoadTheta, linkAndTheta.Item2);

                correctedGpsTable.Rows.Add(lastRow);

                #endregion

                // ファイルごとの挿入なので主キー違反があっても挿入されないだけ
                if (correction == InsertConfig.GpsCorrection.SpeedLPFMapMatching)//速度にローパスフィルタを適用
                {
                    DataTable correctedGpsSpeedLPFTable = LowPassFilter.speedLowPassFilter(correctedGpsTable, 0.05);
                    CorrectedGpsSpeedLPF005MMDao.Insert(correctedGpsSpeedLPFTable);
                }
                else if (correction == InsertConfig.GpsCorrection.MapMatching)
                {
                    CorrectedGPSMMDao.Insert(correctedGpsTable);
                }
                else
                {
                    CorrectedGpsDao.Insert(correctedGpsTable);
                }
            }
        }