Exemplo n.º 1
0
        private void LoadSelectedForecasts()
        {
            try
            {
                var collection = WeatherDataSelecter.GetGroupedByParameterForecastPlots(new ForecastViewerRequest(
                                                                                            _settings.CurrentStation,
                                                                                            SelectedDate.AddHours(SelectedTime == allDayString ? 0 : int.Parse(SelectedTime)),
                                                                                            GivenTimeKind,
                                                                                            SelectedTime == allDayString ? RequestTimeDeterminateness.AllDay : RequestTimeDeterminateness.DateAndHour,
                                                                                            SourceParamPicker.CheckedSources,
                                                                                            SourceParamPicker.CheckedParameters.Select(p => p.ShortTypeName)));

                foreach (var plot in Plots)
                {
                    plot.Dispose();
                }
                Plots.Clear();
                foreach (var parameter in collection.Keys)
                {
                    var plot = new PlotViewModel(collection[parameter]);
                    Plots.Add(plot);
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
            }
        }
Exemplo n.º 2
0
        public ViewModel()
        {
            _plot = new Plots();

            Cosinus cosinus = new Cosinus();

            cosinus.PropertyChanged += (s, e) => { RaisePropertyChanged("Amplitude_Cos"); };
            MyFunction.Add(cosinus);

            Sinus sinus = new Sinus();

            sinus.PropertyChanged += (s, e) => { RaisePropertyChanged("Amplitude_Sin"); };
            MyFunction.Add(sinus);

            Tangens tangens = new Tangens();

            tangens.PropertyChanged += (s, e) => { RaisePropertyChanged("Amplitude_Tan"); };
            MyFunction.Add(tangens);

            Cotangens cotangens = new Cotangens();

            cotangens.PropertyChanged += (s, e) => { RaisePropertyChanged("Amplitude_Cot"); };
            MyFunction.Add(cotangens);

            plotModel = new PlotModel();
            plotModel = _plot._PlotModel;
        }
Exemplo n.º 3
0
        private void LoadSelected()
        {
            try
            {
                var plotDatas = WeatherDataSelecter.GetGroupedByParameterAccuracyPlots(new AccuracyRequest(
                                                                                           _settings.CurrentStation,
                                                                                           SelectedDate,
                                                                                           SelectedComparisonMode,
                                                                                           SourceParamPicker.CheckedSources,
                                                                                           SourceParamPicker.CheckedParameters.Select(p => p.ShortTypeName)));

                foreach (var plot in Plots)
                {
                    plot.Dispose();
                }
                Plots.Clear();

                AccuracyPlots.Clear();

                foreach (var parameter in plotDatas.Keys)
                {
                    var plot   = new PlotViewModel(plotDatas[parameter]);
                    var acPlot = new AccuracyPlotViewModel(AccuracyMeter.CalcAccuracy(plotDatas[parameter], StatisticMethods.All));
                    Plots.Add(plot);
                    AccuracyPlots.Add(acPlot);
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
            }
        }
Exemplo n.º 4
0
 public static void OnLoad()
 {
     foreach (RenderableBuilding b in Buildings.Values)
     {
         b.Dispose();
     }
     Buildings.Clear();
     foreach (RenderablePlot p in Plots.Values)
     {
         p.Dispose();
     }
     Plots.Clear();
     foreach (Plot p in Haswell.Controller.City.Grid)
     {
         if (p.Building != null)
         {
             if (p.Building is Road)
             {
                 Buildings[p.Building] = new RenderableRoad((Road)p.Building);
             }
             else
             {
                 Buildings[p.Building] = new RenderableBuilding(p.Building);
             }
         }
         Plots[p] = new RenderablePlot(p);
         Plots[p].Create(SceneMgr, cityNode);
     }
     GameConsole.ActiveInstance.WriteLine("Game Loaded.");
     GuiMgr.AddInfoPopup("Game Loaded.");
 }
        public string Plot(IPlotParameters plotParameters)
        {
            var parameters = (SpectralPlotParameters)plotParameters;
            var xyPoints   = new List <Point>();

            foreach (var wv in parameters.Wavelengths)
            {
                switch (parameters.SpectralPlotType)
                {
                case SpectralPlotType.Mua:
                    xyPoints.Add(new Point(wv, parameters.Tissue.GetMua(wv)));
                    break;

                case SpectralPlotType.Musp:
                    xyPoints.Add(new Point(wv, parameters.Tissue.GetMusp(wv)));
                    break;
                }
            }
            var plotData = new PlotData {
                Data = xyPoints, Label = parameters.TissueType
            };
            var plot = new Plots {
                Id       = "Spectral" + parameters.SpectralPlotType,
                PlotList = new List <PlotDataJson>()
            };

            plot.PlotList.Add(new PlotDataJson {
                Data = plotData.Data.Select(item => new List <double> {
                    item.X, item.Y
                }).ToList(),
                Label = parameters.TissueType + " " + parameters.PlotName
            });
            return(JsonConvert.SerializeObject(plot));
        }
Exemplo n.º 6
0
        public void Save(XmlTextWriter writer)
        {
            writer.WriteElementString("plots", Plots.ToString());
            writer.WriteElementString("travelTime", TravelTime.ToString());
            writer.WriteElementString("foodRate", FoodRate.ToString());
            writer.WriteElementString("gameSeconds", GameSeconds.ToString());

            if (PlotProbabilities.Count > 0)
            {
                writer.WriteStartElement("plot-probabilities");

                foreach (var probabilitySet in PlotProbabilities)
                {
                    writer.WriteElementString("probability-set", CLIObject.ToArrayString(probabilitySet));
                }

                // plot-probabilities
                writer.WriteEndElement();
            }

            if (ProbabilityShiftTimes.Count > 0)
            {
                writer.WriteElementString("probability-shift-times", CLIObject.ToArrayString(ProbabilityShiftTimes));
            }
        }
Exemplo n.º 7
0
        public void UpdateReportPlots()
        {
            double maxTime  = double.MinValue;
            double minTime  = double.MaxValue;
            double maxValue = double.MinValue;
            double minValue = double.MaxValue;

            var plotModel = new PlotModel();
            var plots     = Plots.Where(p => p.Selected);


            foreach (var _timePlot in plots)
            {
                var lineSeries = new LineSeries();
                var plotColor  = _timePlot.PointColor;
                lineSeries.Color           = OxyColor.FromArgb(plotColor.A, plotColor.R, plotColor.G, plotColor.B);
                lineSeries.MarkerFill      = OxyColor.FromArgb(plotColor.A, plotColor.R, plotColor.G, plotColor.B);
                lineSeries.MarkerType      = MarkerType.None;
                lineSeries.StrokeThickness = 1;
                lineSeries.DataFieldX      = "Time";
                lineSeries.DataFieldY      = "Value";

                var orderedPoints = _timePlot.PlotPoints
                                    .GroupBy(point => point.Time)
                                    .Select(group => group.First())
                                    .OrderBy(point => point.Time)
                                    .ToList();
                foreach (var _point in orderedPoints)
                {
                    var time  = _point.Time.TimeOfDay.TotalSeconds;
                    var value = Convert.ToDouble(_point.Value);
                    maxTime  = maxTime < time ? time : maxTime;
                    minTime  = time < minTime ? time : minTime;
                    maxValue = maxValue < value ? value : maxValue;
                    minValue = value < minValue ? value : minValue;

                    lineSeries.Points.Add(new DataPoint {
                        X = time, Y = value
                    });
                }
                plotModel.Series.Add(lineSeries);
            }

            var dateTimeAxis = new TimeSpanAxis(AxisPosition.Bottom, minTime, maxTime, "Time");

            dateTimeAxis.SetColors();
            dateTimeAxis.AbsoluteMaximum = maxTime;
            dateTimeAxis.AbsoluteMinimum = minTime;
            plotModel.Axes.Add(dateTimeAxis);

            var linearAxis = new LinearAxis(AxisPosition.Left, minValue, maxValue, "Value");

            linearAxis.SetColors();
            linearAxis.AbsoluteMaximum = maxValue;
            linearAxis.AbsoluteMinimum = minValue;
            plotModel.Axes.Add(linearAxis);

            plotModel.SetColors();
            ReportPlots = plotModel;
        }
Exemplo n.º 8
0
 public IEnumerable <PlotsFeatures.Properties> GetProperties()
 {
     using (Plots collections = Plots.GetPlots())
     {
         return(collections.Proprties);
     }
 }
Exemplo n.º 9
0
        internal bool Remove(GamePlot gamePlot)
        {
            var result = Plots.Remove(gamePlot);

            GamePlots = Plots.ToLookup(p => p.GameObject, p => p.Plot);

            return(result);
        }
Exemplo n.º 10
0
        internal int Remove(Plot plot)
        {
            var result = Plots.RemoveAll(p => p.Plot == plot);

            GamePlots = Plots.ToLookup(p => p.GameObject, p => p.Plot);

            return(result);
        }
Exemplo n.º 11
0
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description                  = @"Buy when Fast EMA > Med EMA > Slow EMA, sell when Price < Prev-ATR(10)";
                Name                         = "EMACrosswithSL";
                Calculate                    = Calculate.OnBarClose;
                EntriesPerDirection          = 1;
                EntryHandling                = EntryHandling.AllEntries;
                IsExitOnSessionCloseStrategy = true;
                ExitOnSessionCloseSeconds    = 30;
                IsFillLimitOnTouch           = false;
                MaximumBarsLookBack          = MaximumBarsLookBack.TwoHundredFiftySix;
                OrderFillResolution          = OrderFillResolution.Standard;
                Slippage                     = 0;
                StartBehavior                = StartBehavior.WaitUntilFlat;
                TimeInForce                  = TimeInForce.Gtc;
                TraceOrders                  = true;
                RealtimeErrorHandling        = RealtimeErrorHandling.StopCancelClose;
                StopTargetHandling           = StopTargetHandling.PerEntryExecution;
                BarsRequiredToTrade          = 20;
                // Disable this property for performance gains in Strategy Analyzer optimizations
                // See the Help Guide for additional information
                IsInstantiatedOnEachOptimizationIteration = true;
                FastEma          = 5;
                MedEma           = 20;
                SlowEma          = 50;
                ATRPeriod        = 10;
                ATRMultipleSL    = 2;
                ATRMultipleLimit = 0.5;
                InitialCapital   = 100000;
                AddLine(Brushes.Blue, 1, "ATR");
                AddPlot(Brushes.LimeGreen, "FastEmaLine");
                AddPlot(Brushes.Orange, "MedEmaLine");
                AddPlot(Brushes.Salmon, "SlowEmaLine");
                PrintTo = PrintTo.OutputTab2;

                Print("set default");
            }
            else if (State == State.Configure)
            {
                //AddDataSeries("ADANIPORTS", Data.BarsPeriodType.Day, 1, Data.MarketDataType.Last);
                _atr        = ATR(this.ATRPeriod);
                _atr.Lines  = Lines.Where(l => l.Name == "ATR").ToArray();
                _fast       = EMA(FastEma);
                _fast.Plots = Plots.Where(p => p.Name == "FastEmaLine").ToArray();
                _med        = EMA(MedEma);
                _med.Plots  = Plots.Where(p => p.Name == "MedEmaLine").ToArray();
                _slow       = EMA(SlowEma);
                _slow.Plots = Plots.Where(p => p.Name == "SlowEmaLine").ToArray();
                base.AddChartIndicator(_atr);
                base.AddChartIndicator(_fast);
                base.AddChartIndicator(_med);
                base.AddChartIndicator(_slow);
                Print("configured");
            }
        }
Exemplo n.º 12
0
        private async Task PlotViewModel_ClosedAsync(object sender, ViewModelClosedEventArgs e)
        {
            PlotViewModel pvm = e.ViewModel as PlotViewModel;

            if (pvm == null)
            {
                return;
            }
            Plots.Remove(pvm.PlotModel);
        }
Exemplo n.º 13
0
        internal void Add(Plot plot)
        {
            Plots.Add(new GamePlot
            {
                GameObject = plot.Target,
                Plot       = plot
            });

            GamePlots = Plots.ToLookup(p => p.GameObject, p => p.Plot);
        }
Exemplo n.º 14
0
 /// <summary>
 /// プロットを設定
 /// </summary>
 /// <param name="user"></param>
 /// <param name="plots"></param>
 public void SetPlot(UserOrNpcInfo user, List <int> plots)
 {
     if (Plots.Keys.Contains(user))
     {
         Plots[user] = plots;
     }
     else
     {
         Plots.Add(user, plots);
     }
 }
        public async Task AddPlotAndSetIdAsync()
        {
            var repository = GetRepository();
            var plots      = new Plots();
            await repository.AddAsync(plots);

            var newPlots = (await repository.ListAllAsync()).FirstOrDefault();

            Assert.Equal(plots, newPlots);
            Assert.NotEqual(Guid.Empty, newPlots.Id);
        }
Exemplo n.º 16
0
        public async Task <IActionResult> Create([FromBody] Plots plots)
        {
            if (plots == null)
            {
                return(BadRequest());
            }

            await _plotsRepository.AddAsync(plots);

            return(CreatedAtRoute("GetPlot", new { id = plots.Id }, plots));
        }
        public void AddPlotAndSetId()
        {
            var repository = GetRepository();
            var plots      = new Plots();

            repository.Add(plots);

            var newPlots = repository.ListAll().FirstOrDefault();

            Assert.Equal(plots, newPlots);
            Assert.NotEqual(Guid.Empty, newPlots.Id);
        }
Exemplo n.º 18
0
        public void SinchroRun()
        {
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss tt"));

            using (Plots collections = Plots.GetPlots())
            {
                var props = collections.Proprties;
                var end   = table.Lenght;
                var it    = 1;
                Console.Write("Чтение данных:     [");
                while (it < end)
                {
                    mapInfo.Do(@"Fetch Rec " + it + @" From " + table.Name);
                    var doc          = mapInfo.Eval(table.Name + @".VRI_DOC");
                    var cadNum       = mapInfo.Eval(table.Name + @".CAD_NUM");
                    var areaAsString = mapInfo.Eval(@"Int( Area( " + table.Name + @".Obj, ""sq m"") )");
                    var area         = Convert.ToInt32(areaAsString);
                    var lo           = mapInfo.Eval(table.Name + @".lo_lvl");
                    var lo_lvl       = (lo == "true") ? true : false;
                    var mid          = mapInfo.Eval(table.Name + @".mid_lvl");
                    var mid_lvl      = (mid == "true") ? true : false;
                    var hi           = mapInfo.Eval(table.Name + @".hi_lvl");
                    var hi_lvl       = (hi == "true") ? true : false;
                    var klass        = mapInfo.Eval(table.Name + @".VRI_KLASSI");

                    if (doc.Length == 254)
                    {
                        doc = props.FirstOrDefault(p => p.CadNum.Equals(cadNum)).VriDoc;
                    }
                    var inputData = new InputData(klass, area, "", lo_lvl, mid_lvl, hi_lvl, doc);
                    var factory   = new Factory(inputData);
                    factory.Execute();


                    var rowid = it.ToString();

                    mapInfo.Do(@"Update " + table.Name + @" Set VRI_List = """ + factory.outputData.VRI_List + @""" Where RowID = " + rowid);
                    mapInfo.Do(@"Update " + table.Name + @" Set VRI_Sorted = """ + factory.outputData.VRI_List + @""" Where RowID = " + rowid);
                    mapInfo.Do(@"Update " + table.Name + @" Set Matches = """ + factory.outputData.Matches + @""" Where RowID = " + rowid);
                    mapInfo.Do(@"Update " + table.Name + @" Set fs_tip = """ + factory.outputData.Type.ToString() + @""" Where RowID = " + rowid);
                    mapInfo.Do(@"Update " + table.Name + @" Set fs_vid = """ + factory.outputData.Kind.ToString() + @""" Where RowID = " + rowid);

                    it++;
                    if (it % (table.Lenght / 20) == 0)
                    {
                        Console.Write(".");
                    }
                }
            }
            Console.WriteLine("]    OK");
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss tt"));
        }
Exemplo n.º 19
0
        private void DrawEntryAndExit(Point canvasPoint, int slotNumber)
        {
            if (!(0 <= canvasPoint.Y && canvasPoint.Y <= AvailableHeight))
            {
                return;
            }

            var barsPlot = Plots.FirstOrDefault(p => p.Type == PlotType.Candlestick);

            if (barsPlot == null)
            {
                return;
            }

            var pb = PlotBoundaries[barsPlot];

            var i = SlotOffset + slotNumber - pb.Left;

            if (i < 0)
            {
                return;
            }
            var bar   = ((DataSeries <Bar>)barsPlot.DataSeries)[i];
            var trade = Trades.FirstOrDefault(t => t.EntryTime.Date == bar.Timestamp);

            if (trade == null)
            {
                return;
            }

            //var p1 = PointToCanvas(0, trade.Entry, ViewRegion);
            //var xBase = slotNumber * ParentChart.SlotPxWidth;
            var p1    = PointToCanvas(slotNumber, trade.Entry, ViewRegion);
            var xBase = p1.X - ParentChart.SlotPxWidth / 2;

            var entryColor = trade.PositionDirection == PositionDirection.Long ? CandleGreen : CandleRed;

            EntryArrow = AddPolygon(Brushes.Black, 1, entryColor,
                                    new Point(xBase, p1.Y),
                                    new Point(xBase - 8, p1.Y - 8),
                                    new Point(xBase - 8, p1.Y + 8));

            var p2 = PointToCanvas(0, trade.Exit, ViewRegion);

            xBase += ParentChart.SlotPxWidth;
            var exitColor = trade.PositionDirection == PositionDirection.Short ? CandleGreen : CandleRed;

            ExitArrow = AddPolygon(Brushes.Black, 1, exitColor,
                                   new Point(xBase, p2.Y),
                                   new Point(xBase + 8, p2.Y - 8),
                                   new Point(xBase + 8, p2.Y + 8));
        }
Exemplo n.º 20
0
        public IDictionary <string, string> GetArguments()
        {
            var arguments = new Dictionary <string, string>();

            arguments["plots"]                   = Plots.ToString();
            arguments["travel-time"]             = TravelTime.ToString();
            arguments["food-rate"]               = FoodRate.ToString();
            arguments["game-duration"]           = GameSeconds.ToString();
            arguments["plot-probabilities"]      = CLIObject.ToMultiArrayString(PlotProbabilities.Cast <IEnumerable <int> >());
            arguments["probability-shift-times"] = CLIObject.ToArrayString(ProbabilityShiftTimes);

            return(arguments);
        }
        public async Task DeletePlotsAfterAddingItAsyc()
        {
            var repository  = GetRepository();
            var initialName = Guid.NewGuid().ToString();
            var plots       = new Plots()
            {
                Name = initialName
            };
            await repository.AddAsync(plots);

            await repository.DeleteAsync(plots);

            Assert.DoesNotContain(await repository.ListAllAsync(), i => i.Name == initialName);
        }
        public void DeletePlotsAfterAddingIt()
        {
            var repository  = GetRepository();
            var initialName = Guid.NewGuid().ToString();
            var plots       = new Plots()
            {
                Name = initialName
            };

            repository.Add(plots);

            repository.Delete(plots);

            Assert.DoesNotContain(repository.ListAll(), i => i.Name == initialName);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="connectionString"></param>
        public ApplicationDbContext(string connectionString)
            : base(connectionString)
        {
            Plots        = GetCollection <Plot>("Plots");
            Metadata     = GetCollection <Metadata>("Metadata");
            Translations = GetCollection <Translation>("Translations");

            Plots.EnsureIndex(o => o.num);
            Plots.EnsureIndex(o => o.provider);

            Metadata.EnsureIndex(o => o.num);
            Metadata.EnsureIndex(o => o.provider);
            Metadata.EnsureIndex(o => o.url);

            Translations.EnsureIndex(o => o.hash);
            Translations.EnsureIndex(o => o.lang);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Method to invoke when the NewPlotCommand command is executed.
 /// </summary>
 private async Task OnNewPlotCommandExecuteAsync()
 {
     try
     {
         var plotmodel = new Models.PlotModel();
         Plots.Add(plotmodel);
         var viewModel = new PlotViewModel(plotmodel);
         viewModel.ClosedAsync += PlotViewModel_ClosedAsync;
         ServiceLocator.Default.ResolveType <IUIVisualizerService>().Show(viewModel);
     }
     catch (Exception ex)
     {
         string errmsg = string.Format("Error creating new plot: {0}", ex.Message);
         LogTo.Error(errmsg);
         await Shared.Utility.ShowErrorMsgAsync(this, errmsg);
     }
 }
Exemplo n.º 25
0
        // Runs the population code for the mod,
        // registering all objects and populating
        // them
        internal static void PopulateMod()
        {
            // Register extra modules for registration
            foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (ass.GetName().Name.StartsWith("VikDisk."))
                {
                    RegistryUtils.extraModules.Add(ass);
                }
            }


            // Registers the all game content
            Others.RegisterAll();
            Identifiables.RegisterAll();
            SpawnResources.RegisterAll();
            Gadgets.RegisterAll();
            Upgrades.RegisterAll();
            UIs.RegisterAll();
            Plots.RegisterAll();

            //GordoRegistry.Setup();

            // Adds new commands to the game
            Console.RegisterCommand(new DumperCommand());
            Console.RegisterCommand(new UnlockAllCommand());
            Console.RegisterCommand(new TPCommand());
            Console.RegisterCommand(new DebugModeCommand());

            if (TESTING)
            {
                Console.RegisterCommand(new TestModeCommand());
            }

            // Registers the remaining callback
            CallbackHandler.LateSetup();

            // Runs fixing methods
            GameFixer.FixAtGameLoad();

            // Run Injectors
            foreach (Injector inject in injectors)
            {
                inject.PopulateMod();
            }
        }
        public async Task UpdatePlotsAfterAddingItAsync()
        {
            var repository       = GetRepository();
            var initialName      = Guid.NewGuid().ToString();
            var initialOwnerName = Guid.NewGuid().ToString();
            var plots            = new Plots()
            {
                Name      = initialName,
                OwnerName = initialOwnerName
            };

            await repository.AddAsync(plots);

            // detach the plots so we get a different instace
            _dbContext.Entry(plots).State = EntityState.Detached;

            var newPlots = (await repository.ListAllAsync()).FirstOrDefault();

            Assert.NotSame(plots, newPlots);

            // We can use AutoFixure to generate random string
            // need to check and implement if relevant
            var newName      = Guid.NewGuid().ToString();
            var newOwnerName = Guid.NewGuid().ToString();

            newPlots.Name      = newName;
            newPlots.OwnerName = newOwnerName;

            await repository.UpdateAsync(newPlots);


            // Detach the newPlots so we get a different instace
            _dbContext.Entry(newPlots).State = EntityState.Detached;

            var updatedPlots = (await repository.ListAllAsync()).FirstOrDefault();

            Assert.NotSame(newPlots, updatedPlots);
            Assert.NotEqual(newPlots.Name, updatedPlots.Name);
            Assert.NotEqual(newPlots.OwnerName, updatedPlots.OwnerName);
        }
Exemplo n.º 27
0
        public async Task <IActionResult> Update(Guid id, [FromBody] Plots plots)
        {
            if (plots == null || plots.Id != id)
            {
                return(BadRequest());
            }

            var efPlots = await _plotsRepository.GetByIdAsync(id);

            if (efPlots == null)
            {
                return(NotFound());
            }

            efPlots.Name             = plots.Name;
            efPlots.OwnerName        = plots.OwnerName;
            efPlots.OwnerPhoneNumber = plots.OwnerPhoneNumber;

            await _plotsRepository.UpdateAsync(efPlots);

            return(new NoContentResult());
        }
        public void GetItemUsingId()
        {
            var repository  = GetRepository();
            var initialName = Guid.NewGuid().ToString();
            var plots       = new Plots()
            {
                Name = initialName
            };

            repository.Add(plots);
            var initialId = plots.Id;

            Assert.NotEqual(Guid.Empty, initialId);

            // detach
            _dbContext.Entry(plots).State = EntityState.Detached;

            var newPlot = repository.GetById(initialId);

            Assert.NotNull(newPlot);
            Assert.NotSame(plots, newPlot);
            Assert.Equal(initialName, newPlot.Name);
        }
Exemplo n.º 29
0
        public void Redraw()
        {
            double minVal = double.PositiveInfinity;
            double maxVal = double.NegativeInfinity;

            bool anythingVisible = false;

            foreach (var p in Plots)
            {
                var pb = PlotBoundaries[p];
                pb.ClipLeft  = Math.Max(SlotOffset, pb.Left);
                pb.ClipRight = Math.Min(SlotOffset + SlotsInView - 1, pb.Right);
                var ds = p.DataSeries.Elements.ToArray();
                for (int i = pb.ClipLeft; i <= pb.ClipRight; i++)
                {
                    var el = ds[i - pb.Left];
                    if (!double.IsNaN(el.Min))
                    {
                        minVal = Math.Min(minVal, el.Min);
                    }
                    if (!double.IsNaN(el.Max))
                    {
                        maxVal = Math.Max(maxVal, el.Max);
                    }
                    if (!double.IsNaN(el.Min) || !double.IsNaN(el.Max))
                    {
                        anythingVisible = true;
                    }
                }
            }

            if (!anythingVisible)
            {
                minVal = maxVal = 0;
            }

            GraphCanvas.Children.Clear();

            ViewRegion = new Rect(-0.5, minVal, (double)SlotsInView, maxVal - minVal);

            if (anythingVisible)
            {
                var axisInfo = CalcAxisInfo(minVal, maxVal);

                AddGridLines(axisInfo);

                foreach (var p in Plots)
                {
                    var pb = PlotBoundaries[p];

                    if (p.Type == PlotType.ValueLine)
                    {
                        var path = new Path();
                        path.Stroke          = p.Color;
                        path.StrokeThickness = Math.Max(1, p.LineThickness);
                        SetLineStyle(path, p.LineStyle);

                        var geom = new StreamGeometry();
                        using (var ctx = geom.Open())
                        {
                            var es = ((DataSeries <Value>)p.DataSeries).ToArray();
                            for (int i = pb.ClipLeft; i < pb.ClipRight; i++)
                            {
                                int k = i - pb.Left;
                                if (i == pb.ClipLeft)
                                {
                                    ctx.BeginFigure(PointToCanvas(i - SlotOffset, es[k], ViewRegion), false, false);
                                }
                                else
                                {
                                    ctx.LineTo(PointToCanvas(i + 1 - SlotOffset, es[k + 1], ViewRegion), true, true);
                                }
                            }
                        }

                        geom.Freeze();
                        path.Data = geom;
                        GraphCanvas.Children.Add(path);
                    }
                    else if (p.Type == PlotType.Bar || p.Type == PlotType.Dash || p.Type == PlotType.Dot || p.Type == PlotType.Circle)
                    {
                        var vs = ((DataSeries <Value>)p.DataSeries).ToArray();
                        for (int i = pb.ClipLeft; i <= pb.ClipRight; i++)
                        {
                            int k = i - pb.Left;

                            var val = vs[k].Val;
                            if (double.IsNaN(val))
                            {
                                continue;
                            }

                            var p1 = PointToCanvas(i - SlotOffset, val, ViewRegion);
                            if (p.Type == PlotType.Bar)
                            {
                                var p2 = PointToCanvas(i - SlotOffset, Math.Max(minVal, Math.Min(maxVal, 0)), ViewRegion);
                                AddRectangle(
                                    p2.X - Math.Floor((ParentChart.SlotPxWidth - 3) / 2),
                                    p2.Y,
                                    p1.X + Math.Floor((ParentChart.SlotPxWidth - 3) / 2),
                                    p1.Y,
                                    p.Color);
                            }
                            else if (p.Type == PlotType.Dash)
                            {
                                AddRectangle(
                                    p1.X - Math.Floor((ParentChart.SlotPxWidth - 3) / 2),
                                    p1.Y,
                                    p1.X + Math.Floor((ParentChart.SlotPxWidth - 3) / 2),
                                    p1.Y + 1,
                                    p.Color);
                            }
                            else if (p.Type == PlotType.Dot || p.Type == PlotType.Circle)
                            {
                                AddCircle(p1.X, p1.Y, Math.Min(5, (ParentChart.SlotPxWidth - 3) / 2), p.Color,
                                          p.Type == PlotType.Circle ? Brushes.Transparent : null);
                            }
                        }
                    }
                    else if (p.Type == PlotType.Candlestick)
                    {
                        var bars = ((DataSeries <Bar>)p.DataSeries).ToArray();
                        for (int i = pb.ClipLeft; i <= pb.ClipRight; i++)
                        {
                            int   k   = i - pb.Left;
                            var   bar = bars[k];
                            Brush brush;
                            if (p.CandleColors == CandleColors.WhiteBlack)
                            {
                                brush = Brushes.Black;
                            }
                            else
                            {
                                brush = bar.Close < bar.Open ? CandleRed : CandleGreen;
                            }
                            AddLine(i - SlotOffset, bar.High, i - SlotOffset, bar.Low, brush, LineStyle.Solid, 1, ViewRegion);
                            var p1 = PointToCanvas(i - SlotOffset, bar.Open, ViewRegion);
                            var p2 = PointToCanvas(i - SlotOffset, bar.Close, ViewRegion);
                            AddRectangle(
                                p1.X - Math.Floor((ParentChart.SlotPxWidth - 3) / 2),
                                p1.Y,
                                p2.X + Math.Floor((ParentChart.SlotPxWidth - 3) / 2),
                                p2.Y,
                                brush, (p.CandleColors == CandleColors.WhiteBlack && bar.IsGreen) ? Brushes.White : null);
                        }
                    }
                }

                AddVerticalAxis(axisInfo);
            }

            // time axis
            if (DrawTimeAxis)
            {
                AddTimeAxis();
            }

            double yOffset = 0;

            if (!string.IsNullOrEmpty(Title))
            {
                AddText(Title, 2, 0, "bold");
                yOffset += 16;
            }
            foreach (var p in Plots.Where(x => x.Type != PlotType.Candlestick && !string.IsNullOrEmpty(x.Title)))
            {
                AddText(p.Title, 16, yOffset, "normal", Brushes.Black, Brushes.GhostWhite);
                double thickness = p.Type == PlotType.ValueLine ? 2 : 6;
                AddLine(2, yOffset + 9, 14, yOffset + 9, p.Color, LineStyle.Solid, thickness);
                yOffset += 16;
            }
        }
        public string Plot(IPlotParameters plotParameters)
        {
            var msg               = "";
            var parameters        = (SolutionDomainPlotParameters)plotParameters;
            var fs                = parameters.ForwardSolverType;
            var op                = parameters.OpticalProperties;
            var xAxis             = parameters.XAxis;
            var noise             = parameters.NoiseValue;
            var independentAxis   = parameters.IndependentAxes.Label;
            var independentValue  = parameters.IndependentAxes.Value;
            var independentValues = xAxis.AsEnumerable().ToArray();

            try
            {
                IEnumerable <double>  doubleResults;
                IEnumerable <Complex> complexResults;
                double[]            xs;
                IEnumerable <Point> xyPoints, xyPointsReal, xyPointsImaginary;
                PlotData            plotData, plotDataReal, plotDataImaginary;
                Plots plot;
                switch (parameters.SolutionDomain)
                {
                case SolutionDomainType.ROfRho:
                    doubleResults = ROfRho(fs, op, xAxis, noise);
                    xs            = independentValues;
                    xyPoints      = xs.Zip(doubleResults, (x, y) => new Point(x, y));
                    plotData      = new PlotData {
                        Data = xyPoints, Label = "ROfRho"
                    };
                    plot = new Plots
                    {
                        Id       = "ROfRho", Detector = "R(ρ)", Legend = "R(ρ)", XAxis = "ρ", YAxis = "Reflectance",
                        PlotList = new List <PlotDataJson>()
                    };
                    plot.PlotList.Add(new PlotDataJson
                    {
                        Data = plotData.Data.Select(item => new List <double> {
                            item.X, item.Y
                        }).ToList(),
                        Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp
                    });
                    msg = JsonConvert.SerializeObject(plot);
                    break;

                case SolutionDomainType.ROfRhoAndTime:
                    if (independentAxis == "t")
                    {
                        var time = independentValue;
                        doubleResults = ROfRhoAndTime(fs, op, xAxis, time, noise);
                        xs            = independentValues;
                        xyPoints      = xs.Zip(doubleResults, (x, y) => new Point(x, y));
                        plotData      = new PlotData {
                            Data = xyPoints, Label = "ROfRhoAndTime"
                        };
                        plot = new Plots
                        {
                            Id    = "ROfRhoAndTimeFixedTime", Detector = "R(ρ,time)", Legend = "R(ρ,time)",
                            XAxis = "ρ", YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotData.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " t=" + time
                        });
                        msg = JsonConvert.SerializeObject(plot);
                    }
                    else
                    {
                        var rho = independentValue;
                        doubleResults = ROfRhoAndTime(fs, op, rho, xAxis, noise);
                        xs            = independentValues.ToArray(); // the Skip(1) is giving inverse problems
                        xyPoints      = xs.Zip(doubleResults, (x, y) => new Point(x, y));
                        plotData      = new PlotData {
                            Data = xyPoints, Label = "ROfRhoAndTime"
                        };
                        plot = new Plots
                        {
                            Id    = "ROfRhoAndTimeFixedRho", Detector = "R(ρ,time)", Legend = "R(ρ,time)",
                            XAxis = "Time", YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotData.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ρ=" + rho
                        });
                        msg = JsonConvert.SerializeObject(plot);
                    }
                    break;

                case SolutionDomainType.ROfRhoAndFt:
                    if (independentAxis == "ft")
                    {
                        var rho = xAxis;
                        var ft  = independentValue;
                        complexResults    = ROfRhoAndFt(fs, op, rho, ft, noise).ToArray();
                        xs                = independentValues;
                        xyPointsReal      = xs.Zip(complexResults, (x, y) => new Point(x, y.Real));
                        xyPointsImaginary = xs.Zip(complexResults, (x, y) => new Point(x, y.Imaginary));
                        plotDataReal      = new PlotData {
                            Data = xyPointsReal, Label = "ROfRhoAndFt"
                        };
                        plotDataImaginary = new PlotData {
                            Data = xyPointsImaginary, Label = "ROfRhoAndFt"
                        };
                        plot = new Plots
                        {
                            Id    = "ROfRhoAndFtFixedFt", Detector = "R(ρ,ft)", Legend = "R(ρ,ft)", XAxis = "ρ",
                            YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotDataReal.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ft=" + ft + "(real)"
                        });
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotDataImaginary.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ft=" + ft + "(imag)"
                        });
                        msg = JsonConvert.SerializeObject(plot);
                    }
                    else
                    {
                        var rho = independentValue;
                        complexResults    = ROfRhoAndFt(fs, op, rho, xAxis, noise).ToArray();
                        xs                = independentValues;
                        xyPointsReal      = xs.Zip(complexResults, (x, y) => new Point(x, y.Real));
                        xyPointsImaginary = xs.Zip(complexResults, (x, y) => new Point(x, y.Imaginary));
                        var realPlot = new PlotData {
                            Data = xyPointsReal, Label = "ROfRhoAndFt"
                        };
                        var imagPlot = new PlotData {
                            Data = xyPointsImaginary, Label = "ROfRhoAndFt"
                        };
                        var rhoPlot = new Plots
                        {
                            Id    = "ROfRhoAndFtFixedRho", Detector = "R(ρ,ft)", Legend = "R(ρ,ft)", XAxis = "ft",
                            YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        rhoPlot.PlotList.Add(new PlotDataJson
                        {
                            Data = realPlot.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ρ=" + rho + "(real)"
                        });
                        rhoPlot.PlotList.Add(new PlotDataJson
                        {
                            Data = imagPlot.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ρ=" + rho + "(imag)"
                        });
                        msg = JsonConvert.SerializeObject(rhoPlot);
                    }
                    break;

                case SolutionDomainType.ROfFx:
                    doubleResults = ROfFx(fs, op, xAxis, noise);
                    xs            = independentValues;
                    xyPoints      = xs.Zip(doubleResults, (x, y) => new Point(x, y));
                    plotData      = new PlotData {
                        Data = xyPoints, Label = "ROfFx"
                    };
                    plot = new Plots
                    {
                        Id       = "ROfFx", Detector = "R(fx)", Legend = "R(fx)", XAxis = "fx", YAxis = "Reflectance",
                        PlotList = new List <PlotDataJson>()
                    };
                    plot.PlotList.Add(new PlotDataJson
                    {
                        Data = plotData.Data.Select(item => new List <double> {
                            item.X, item.Y
                        }).ToList(),
                        Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp
                    });
                    msg = JsonConvert.SerializeObject(plot);
                    break;

                case SolutionDomainType.ROfFxAndTime:
                    if (independentAxis == "t")
                    {
                        var time = independentValue;
                        doubleResults = ROfFxAndTime(fs, op, xAxis, time, noise);
                        xs            = independentValues;
                        xyPoints      = xs.Zip(doubleResults, (x, y) => new Point(x, y));
                        plotData      = new PlotData {
                            Data = xyPoints, Label = "ROfFxAndTime"
                        };
                        plot = new Plots
                        {
                            Id    = "ROfFxAndTimeFixedTime", Detector = "R(fx,time)", Legend = "R(fx,time)",
                            XAxis = "fx", YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotData.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " t=" + time
                        });
                        msg = JsonConvert.SerializeObject(plot);
                    }
                    else
                    {
                        var fx = independentValue;
                        doubleResults = ROfFxAndTime(fs, op, fx, xAxis, noise);
                        xs            = independentValues;
                        xyPoints      = xs.Zip(doubleResults, (x, y) => new Point(x, y));
                        plotData      = new PlotData {
                            Data = xyPoints, Label = "ROfFxAndTime"
                        };
                        plot = new Plots
                        {
                            Id    = "ROfFxAndTimeFixedFx", Detector = "R(fx,time)", Legend = "R(fx,time)",
                            XAxis = "Time", YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotData.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ρ=" + fx
                        });
                        msg = JsonConvert.SerializeObject(plot);
                    }
                    break;

                case SolutionDomainType.ROfFxAndFt:
                    if (independentAxis == "ft")
                    {
                        var ft = independentValue;
                        complexResults    = ROfFxAndFt(fs, op, xAxis, ft, noise).ToArray();
                        xs                = independentValues;
                        xyPointsReal      = xs.Zip(complexResults, (x, y) => new Point(x, y.Real));
                        xyPointsImaginary = xs.Zip(complexResults, (x, y) => new Point(x, y.Imaginary));
                        plotDataReal      = new PlotData {
                            Data = xyPointsReal, Label = "ROfFxAndFt"
                        };
                        plotDataImaginary = new PlotData {
                            Data = xyPointsImaginary, Label = "ROfFxAndFt"
                        };
                        plot = new Plots
                        {
                            Id    = "ROfFxAndFtFixedFt", Detector = "R(fx,ft)", Legend = "R(fx,ft)", XAxis = "fx",
                            YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotDataReal.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ft=" + ft + "(real)"
                        });
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotDataImaginary.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " ft=" + ft + "(imag)"
                        });
                        msg = JsonConvert.SerializeObject(plot);
                    }
                    else
                    {
                        var fx = independentValue;
                        complexResults    = ROfFxAndFt(fs, op, fx, xAxis, noise).ToArray();
                        xs                = independentValues;
                        xyPointsReal      = xs.Zip(complexResults, (x, y) => new Point(x, y.Real));
                        xyPointsImaginary = xs.Zip(complexResults, (x, y) => new Point(x, y.Imaginary));
                        plotDataReal      = new PlotData {
                            Data = xyPointsReal, Label = "ROfFxAndFt"
                        };
                        plotDataImaginary = new PlotData {
                            Data = xyPointsImaginary, Label = "ROfFxAndFt"
                        };
                        plot = new Plots
                        {
                            Id    = "ROfFxAndFtFixedFx", Detector = "R(fx,ft)", Legend = "R(fx,ft)", XAxis = "ft",
                            YAxis = "Reflectance", PlotList = new List <PlotDataJson>()
                        };
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotDataReal.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " fx=" + fx + "(real)"
                        });
                        plot.PlotList.Add(new PlotDataJson
                        {
                            Data = plotDataImaginary.Data.Select(item => new List <double> {
                                item.X, item.Y
                            }).ToList(),
                            Label = fs + " μa=" + op.Mua + " μs'=" + op.Musp + " fx=" + fx + "(imag)"
                        });
                        msg = JsonConvert.SerializeObject(plot);
                    }
                    break;
                }
                return(msg);
            }
            catch (Exception e)
            {
                _logger.LogError("An error occurred: {Message}", e.Message);
                throw;
            }
        }