public IPhaseExtractor NewPhaseExtractor()
        {
            if (GeneralConfigurations.Get().ViewPhase)
            {
                return(new FourierOnlyPhaseExtractor());
            }
            var config    = CorrectorConfigurations.Get();
            var misConfig = MiscellaneousConfigurations.Get();

            switch (config.PhaseType)
            {
            case PhaseType.FullRange:
                return(new FourierOnlyPhaseExtractor());

            case PhaseType.CenterInterpolation:
                return(new CorrectCenterPhaseExtractor(NewApodizer(),
                                                       config.CenterSpanLength / 2));

            case PhaseType.SpecificRange:
                return(new SpecificRangePhaseExtractor((int)config.RangeStart, (int)config.RangeEnd,
                                                       misConfig.MinFlatPhasePtsNumCnt, misConfig.MaxPhaseStd));

            case PhaseType.OldCenterInterpolation:
                return(new ClassicWrongPhaseExtractor(NewApodizer(),
                                                      config.CenterSpanLength / 2));

            case PhaseType.SpecificFreqRange:
                return(new SpecificFreqRangePhaseExtractor(config.RangeStart, config.RangeEnd,
                                                           SamplingConfigurations.Get().SamplingRateInMHz, misConfig.MinFlatPhasePtsNumCnt,
                                                           misConfig.MaxPhaseStd));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public bool TryNewSampler(out Sampler newSampler)
        {
            var configs = SamplingConfigurations.Get();

            return(Sampler.TryCreateSampler(out newSampler, configs.DeviceName, configs.Channel.ToString(),
                                            configs.Range, configs.SamplingRate,
                                            configs.RecordLength));
        }
 public SpectrumDisplayAdapter NewSpectrumAdapter(CanvasView view, HorizontalAxisView horizontalAxisView,
                                                  VerticalAxisView verticalAxisView, TextBox tbX, TextBox tbDelta, double?dipLockFreq, double lockDipScanRadius)
 {
     return(new SpectrumDisplayAdapter(view, horizontalAxisView, verticalAxisView, tbX, tbDelta,
                                       GeneralConfigurations.Get().DispPoints,
                                       SamplingConfigurations.Get().SamplingRate, 0,
                                       (int)Math.Round(SamplingConfigurations.Get().SamplingRateInMHz / 2), dipLockFreq, lockDipScanRadius));
 }
 public PhaseDisplayAdapter NewPhaseAdapter(CanvasView view, HorizontalAxisView horizontalAxisView,
                                            VerticalAxisView verticalAxisView, TextBox tbX, TextBox tbDelta)
 {
     return(new PhaseDisplayAdapter(view, horizontalAxisView, verticalAxisView, tbX, tbDelta,
                                    GeneralConfigurations.Get().DispPoints,
                                    SamplingConfigurations.Get().SamplingRate, 0,
                                    (int)Math.Round(SamplingConfigurations.Get().SamplingRateInMHz / 2)));
 }
        public virtual ICrestFinder NewCrestFinder()
        {
            var          config      = GeneralConfigurations.Get();
            var          sliceConfig = SliceConfigurations.Get();
            ICrestFinder finder;

            if (sliceConfig.FindAbsoluteValue)
            {
                finder = new AbsoluteCrestFinder(
                    config.RepetitionRate, SamplingConfigurations.Get().SamplingRate,
                    sliceConfig.PeakMinLength / 2, sliceConfig.CrestAmplitudeThreshold);
            }
            else
            {
                finder = new SimpleCrestFinder(
                    config.RepetitionRate, SamplingConfigurations.Get().SamplingRate,
                    sliceConfig.PeakMinLength / 2, sliceConfig.CrestAmplitudeThreshold);
            }
            return(sliceConfig.AutoAdjust ? new AutoAdjustCrestFinder(finder) : finder);
        }
 private void BnViewTemporal_OnClick(object sender, RoutedEventArgs e)
 {
     if (IsProgramRunning())
     {
         return;
     }
     if (!CheckPythonAndWarn())
     {
         return;
     }
     Task.Run(() => {
         var factory = new ParallelInjector();
         Sampler sampler;
         if (factory.TryNewSampler(out sampler))
         {
             var data         = sampler.Retrieve(SamplingConfigurations.Get().Channel);
             var finder       = factory.NewCrestFinder();
             var crestIndices = finder.Find(data);
             var path         = AppDomain.CurrentDomain.BaseDirectory + @"temporal\";
             if (!Directory.Exists(path))
             {
                 try {
                     Directory.CreateDirectory(path);
                 } catch (Exception) {
                     MessageBox.Show(
                         "Unable to create directory! Try run this program with administrator permission");
                     return;
                 }
             }
             Toolbox.WriteData(path + "temporal.txt", data);
             Toolbox.WriteData(path + "crests.txt", crestIndices.ToArray());
             Process.Start(MiscellaneousConfigurations.Get().PythonPath,
                           Quote(AppDomain.CurrentDomain.BaseDirectory + @"Pythons\TemporalViewer.py") + " " + AppDomain.CurrentDomain.BaseDirectory);
         }
         else
         {
             MessageBox.Show("Sampler can't be initialized. Maybe another instance is running.");
         }
     });
 }
        public void Update(IResult result)
        {
            var sizeInM = (int)(SamplingConfigurations.Get().RecordLength / 1e6);

            TotalCnt        += 1;
            TotalDataAmount += sizeInM;
            Speed            = TotalDataAmount / Time;
            if (result.IsSuccessful)
            {
                SuccessCnt += 1;
            }
            else
            {
                FailuresCnt += 1;
            }
            PeriodCnt += result.ValidPeriodCnt;
            SucessRate = SuccessCnt / (double)TotalCnt;
            if (result.HasException)
            {
                switch (result.Exception)
                {
                case ProcessException.NoPeakFound:
                    NoPeaksFoundCnt++;
                    break;

                case ProcessException.NoSliceValid:
                    NoSliceValidCnt++;
                    break;

                case ProcessException.NoFlatPhaseIntervalFound:
                    NoFlatPhaseCnt++;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
        public IAccumulator NewPulseSequenceProcessor()
        {
            var config = CorrectorConfigurations.Get();

            if (config.LockDip)
            {
                return(new LockDipAccumulator(NewCrestFinder(), NewSlicer(), NewPulsePreprocessor(), NewCorrector(), config.LockDipFreqInMHz,
                                              MiscellaneousConfigurations.Get().LockDipScanRadiusInMhz, SamplingConfigurations.Get().SamplingRateInMHz));
            }
            return(new Accumulator(NewCrestFinder(), NewSlicer(), NewPulsePreprocessor(), NewCorrector()));
        }
        private void FlattenCurves_OnClick(object sender, RoutedEventArgs e)
        {
            if (!CheckPythonAndWarn())
            {
                return;
            }
            var file = SelectFile();

            if (file == null)
            {
                return;
            }
            var pythonPath = MiscellaneousConfigurations.Get().PythonPath;
            var cmd        = Quote(AppDomain.CurrentDomain.BaseDirectory + @"Pythons\Flatter.py") + " " + file;

            if (File.Exists(file.Replace(".txt", "[WavelengthAxis].txt")))
            {
                Process.Start(pythonPath, cmd);
            }
            else
            {
                var command = Quote(AppDomain.CurrentDomain.BaseDirectory + @"Pythons\Mapper.py") + " " + file + " " + SamplingConfigurations.Get().SamplingRate;
                Process.Start(pythonPath, command);
                MessageBox.Show("Generating wavelength axis, please click 'OK' AFTER completion.");
                Process.Start(pythonPath, cmd);
            }
        }
        private void GenerateWavelengthAxis_OnClick(object sender, RoutedEventArgs e)
        {
            if (!CheckPythonAndWarn())
            {
                return;
            }
            var file = SelectFile();

            if (file != null)
            {
                var command = Quote(AppDomain.CurrentDomain.BaseDirectory + @"Pythons\Mapper.py") + " " + file + " " + SamplingConfigurations.Get().SamplingRate;
                Process.Start(MiscellaneousConfigurations.Get().PythonPath, command);
            }
        }
        public MainWindow()
        {
            // init system components
            InitializeComponent();

            _possibleWrongLabels = new[] { LbPeakMinAmp, LbRangeStart, LbRangeEnd, LbRepRate };
            _originalThickness   = _possibleWrongLabels[0].BorderThickness;
            _originalBrush       = _possibleWrongLabels[0].BorderBrush;

            if (File.Exists(@"default.svcfg"))
            {
                ConfigsHolder.Load(@"default.svcfg");
            }
            else
            {
                // init configurations
                SamplingConfigurations.Initialize(
                    deviceName: "Dev3",
                    channel: 0,
                    samplingRateInMHz: 100,
                    recordLengthInM: 1,
                    range: 10);

                GeneralConfigurations.Initialize(
                    repetitionRate: 400,
                    threadNum: 4,
                    dispPoints: 1000,
                    directory: @"C:\buffer\captured\",
                    viewPhase: false,
                    saveType: SaveType.Magnitude,
                    queueSize: 48,
                    saveSample: false,
                    saveSpec: false,
                    saveAcc: false,
                    operationMode: OperationMode.Manual,
                    targetCnt: 100);

                SliceConfigurations.Initialize(
                    crestAmplitudeThreshold: 0.5,
                    peakMinLength: 2000,
                    crestAtCenter: true,
                    rulerType: RulerType.MinLength,
                    findAbs: true,
                    autoAdjust: true,
                    fixedLength: 232171,
                    reference: false
                    );

                CorrectorConfigurations.Initialize(
                    zeroFillFactor: 1,
                    centerSpanLength: 512,
                    correctorType: CorrectorType.Mertz,
                    apodizerType: ApodizerType.Hann,
                    phaseType: PhaseType.FullRange,
                    realPhase: false,
                    rangeStart: 3,
                    rangeEnd: 4,
                    lockDip: false,
                    lockDipFreqInMHz: 5
                    );

                MiscellaneousConfigurations.Initialize(
                    waitEmptyProducerMsTimeout: 5000,
                    minFlatPhasePtsNumCnt: 200,
                    maxPhaseStd: 0.34,
                    pythonPath: @"C:\Anaconda3\python.exe",
                    lockDipScanRadiusInMHz: 0.4,
                    autoFlip: false);
            }


            SliceConfigs     = SliceConfigurations.Get();
            CorrectorConfigs = CorrectorConfigurations.Get();
            SampleConfigs    = SamplingConfigurations.Get();
            GeneralConfigs   = GeneralConfigurations.Get();

            CbPhaseType.SelectionChanged += (sender, args) => {
                HideAllPhaseOptions();

                var selected = (PhaseType)args.AddedItems[0];
                HandleAdditionalPhaseOptions(selected);
            };

            CbSliceLength.SelectionChanged += (sender, args) => {
                var selected = (RulerType)args.AddedItems[0];
                TbFixedLength.Visibility = selected == RulerType.FixLength ? Visibility.Visible : Visibility.Hidden;
            };

            CbCorrector.SelectionChanged += (sender, args) => {
                var selected = (CorrectorType)args.AddedItems[0];
                switch (selected)
                {
                case CorrectorType.Fake:
                    Hide(CbPhaseType);
                    Hide(LbPhaseType);
                    HideAllPhaseOptions();
                    break;

                case CorrectorType.Mertz:
                    Show(CbPhaseType);
                    Show(LbPhaseType);
                    HandleAdditionalPhaseOptions((PhaseType?)CbPhaseType.SelectedItem ?? PhaseType.FullRange);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            };
            CbOperationMode.SelectionChanged += (sender, args) => {
                var selected = (OperationMode)args.AddedItems[0];
                switch (selected)
                {
                case OperationMode.Manual:
                    Hide(TbTargetCnt);
                    break;

                case OperationMode.Single:
                case OperationMode.Loop:
                    Show(TbTargetCnt);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            };
            RoutedEventHandler ckPhaseOnChecked = (sender, args) => {
                var correct = !CkPhase.IsChecked.GetValueOrDefault(false);
                if (correct)
                {
                    Show(LbCorrector);
                    Show(CbCorrector);
                    Show(CbApodizationType);
                    Show(LbApodize);
                    Show(CkLockDip);
                    Show(TbLockDip);
                    Show(LbLockDip);
                    Show(CkSpecReal);
                    if ((CorrectorType)CbCorrector.SelectedItem != CorrectorType.Fake)
                    {
                        Show(CbPhaseType);
                        Show(LbPhaseType);
                        HandleAdditionalPhaseOptions((PhaseType?)CbPhaseType.SelectedItem ?? PhaseType.FullRange);
                    }
                }
                else
                {
                    Hide(CbCorrector);
                    Hide(LbCorrector);
                    Hide(CbApodizationType);
                    Hide(LbApodize);
                    Hide(CkLockDip);
                    Hide(TbLockDip);
                    Hide(LbLockDip);
                    Hide(CkSpecReal);
                    Hide(CbPhaseType);
                    Hide(LbPhaseType);
                    HideAllPhaseOptions();
                }
            };

            CkPhase.Checked   += ckPhaseOnChecked;
            CkPhase.Unchecked += ckPhaseOnChecked;

            // bind configs to controls
            DataContext = this;

//            SamplingConfigurations.Get().Bind(TbDeviceName, TbChannel, TbSamplingRate, TbRecordLength, TbRange);
//            GeneralConfigurations.Get()
//                .Bind(TbRepRate, TbThreadNum, TbDispPoints, TbSavePath, CkPhase, CbSaveType, TbQueueSize,
//                    CkCaptureSample, CkCaptureSpec, CkCaptureAcc, CbOperationMode, TbTargetCnt);
//            SliceConfigurations.Get()
//                .Bind(TbPtsBeforeCrest, TbCrestMinAmp, CbSliceLength, CkAutoAdjust, CkFindAbs, TbFixedLength, CkRef);
//            CorrectorConfigurations.Get()
//                .Bind(TbZeroFillFactor, TbCenterSpanLength, CbCorrector, CbApodizationType, CbPhaseType, TbRangeStart,
//                    TbRangeEnd, CkAutoFlip, CkSpecReal);
            // init custom components

            SwitchButton          = new ToggleButtonV2(ToggleButton, false, "Stop", "Start");
            SwitchButton.TurnOn  += TurnOn;
            SwitchButton.TurnOff += ClearFromRunningState;
            SizeChanged          += (sender, args) => { Adapter?.OnWindowZoomed(); };
            // todo text disapeared

            CkCaptureSpec.Checked += (sender, args) => { CkCaptureAcc.IsChecked = true; };

            Closing += (sender, args) => { _statsWindow?.Close(); };

            LocationChanged += (sender, args) => {
                if (_statsWindow == null)
                {
                    return;
                }
                _statsWindow.Left = this.Left + this.Width - 15;
                _statsWindow.Top  = this.Top;
            };
        }