private void CreateView()
        {
            OxyColor color;
            if (!this.ParentViewModel.ColorMapping.TryGetValue(this.Data.ItemType, out color))
            {
                color = OxyColor.FromArgb(100, 0, 120, 0);
            }
            this.intervallBarItem = new IntervalBarItem(Axis.ToDouble(this.Data.StartPoint), Axis.ToDouble(this.Data.EndPoint?? this.Data.StartPoint)) { Color = color, CategoryIndex = this.Index };
            this.intervallBarSeries.Items.Add(this.intervallBarItem);

            dataViewModels.AddRange(DataItemViewModel.CreateIntervallItems(this.ParentViewModel, this.Data.Children, this.Index, this.intervallBarSeries));
        }
        private void CreateView()
        {
            OxyColor color;

            if (!this.ParentViewModel.ColorMapping.TryGetValue(this.Data.ItemType, out color))
            {
                color = OxyColor.FromArgb(100, 0, 120, 0);
            }
            this.intervallBarItem = new IntervalBarItem(Axis.ToDouble(this.Data.StartPoint), Axis.ToDouble(this.Data.EndPoint ?? this.Data.StartPoint))
            {
                Color = color, CategoryIndex = this.Index
            };
            this.intervallBarSeries.Items.Add(this.intervallBarItem);

            dataViewModels.AddRange(DataItemViewModel.CreateIntervallItems(this.ParentViewModel, this.Data.Children, this.Index, this.intervallBarSeries));
        }
 /// <summary>
 /// Inicializar dados escalonados.
 /// </summary>
 /// <param name="processes">Processes.</param>
 private void SetUtilizationData(List <PlotableProcess> processes)
 {
     for (int index = 0; index < processes.Count; index++)
     {
         PlotableProcess process = processes[index];
         IntervalBarItem item    = new IntervalBarItem
         {
             Start         = process.ExecTime - 0.5f,
             End           = process.ExecTime + 0.5f,
             CategoryIndex = YLabel.IndexOf(process.name),
             //Title = process.Name,
             Color = process.attColor,
         };
         intervalBarSeries.Items.Add(item);
     }
 }
 /// <summary>
 /// Inicializar dados ha escalonar.
 /// </summary>
 /// <param name="processes">Processes.</param>
 private void SetUtilizationData(List <Process> processes)
 {
     for (int index = 0; index < processes.Count; index++)
     {
         Process         process = processes[index];
         IntervalBarItem item    = new IntervalBarItem
         {
             Start         = process.arrivalTime,
             End           = process.arrivalTime + process.runtime,
             CategoryIndex = index,
             //Title = process.Name,
             Color = ((PlotableProcess)process).attColor,
         };
         intervalBarSeries.Items.Add(item);
     }
 }
Ejemplo n.º 5
0
        private static void PitchAndLyric()
        {
            float[] samples;
            int     rate;

            using (var wavReader = new WaveFileReader(Path.Combine(CommonUtils.GetTrainingDataDirectory(), "校歌 2018-01-17 15-10-46.wav")))
            {
                var provider = wavReader.ToSampleProvider().ToMono();
                rate = provider.WaveFormat.SampleRate;

                samples = new float[wavReader.SampleCount];
                for (var readSamples = 0; readSamples < samples.Length;)
                {
                    var count = provider.Read(samples, readSamples, samples.Length - readSamples);
                    if (count == 0)
                    {
                        break;
                    }
                    readSamples += count;
                }
            }

            const int analysisUnit    = 4096; // 4096 サンプルを 1 まとまりとする
            const int vowelWindowSize = 2048;
            const int pitchWindowSize = 1024;

            var classifier          = PrepareVowelClassifier();
            var series              = new IntervalBarSeries();
            var secsPerAnalysisUnit = (double)analysisUnit / rate;
            var analysisUnitCount   = samples.Length / analysisUnit;

            for (var i = 0; i < analysisUnitCount; i++)
            {
                var startIndex = analysisUnit * i;
                var endIndex   = startIndex + analysisUnit;

                var maxPower = 0f;
                for (var j = startIndex + 1; j < endIndex - 1; j++)
                {
                    if (samples[j] > maxPower)
                    {
                        maxPower = samples[j];
                    }
                }

                // 音量小さすぎ
                if (maxPower < 0.15)
                {
                    continue;
                }

                // 512 ずつずらしながら母音認識
                var vowelCandidates = new int[(int)VowelType.Other + 1];
                for (var offset = startIndex; offset <= endIndex - vowelWindowSize; offset += 512)
                {
                    vowelCandidates[(int)classifier.Decide(new ReadOnlySpan <float>(samples, offset, vowelWindowSize), rate)]++;
                }

                var vowelCandidate = default(VowelType?);
                var maxNumOfVotes  = 0;
                for (var j = 0; j < vowelCandidates.Length; j++)
                {
                    if (vowelCandidates[j] > maxNumOfVotes)
                    {
                        maxNumOfVotes  = vowelCandidates[j];
                        vowelCandidate = (VowelType)j;
                    }
                    else if (vowelCandidates[j] == maxNumOfVotes)
                    {
                        vowelCandidate = null;
                    }
                }

                // 母音が定まらなかったので、終了
                if (!vowelCandidate.HasValue || vowelCandidate.Value == VowelType.Other)
                {
                    continue;
                }

                // 512 ずつずらしながらピッチ検出
                const int pitchOffsetDelta = 512;
                var       basicFreqs       = new List <double>(analysisUnit / pitchOffsetDelta);
                for (var offset = startIndex; offset <= endIndex - pitchWindowSize; offset += pitchOffsetDelta)
                {
                    var f = McLeodPitchMethod.EstimateFundamentalFrequency(
                        rate,
                        new ReadOnlySpan <float>(samples, offset, pitchWindowSize)
                        );

                    if (f.HasValue)
                    {
                        basicFreqs.Add(f.Value);
                    }
                }

                // ピッチ検出に失敗したので終了
                if (basicFreqs.Count == 0)
                {
                    continue;
                }

                basicFreqs.Sort();
                var basicFreq = basicFreqs[basicFreqs.Count / 2]; // 中央値
                var noteNum   = CommonUtils.HzToMidiNote(basicFreq);

                var plotItem = new IntervalBarItem()
                {
                    Start         = secsPerAnalysisUnit * i,
                    End           = secsPerAnalysisUnit * (i + 1),
                    Title         = vowelCandidate.ToString(),
                    CategoryIndex = noteNum
                };

                var items = series.Items;
                if (items.Count > 0)
                {
                    var lastItem = items[items.Count - 1];
                    if (lastItem.End == plotItem.Start &&
                        lastItem.CategoryIndex == plotItem.CategoryIndex &&
                        lastItem.Title == plotItem.Title)
                    {
                        // マージできる
                        lastItem.End = plotItem.End;
                        continue;
                    }
                }

                items.Add(plotItem);
            }

            var categoryAxis = new CategoryAxis()
            {
                Position = AxisPosition.Left
            };
            var noteNames = new[] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };

            for (var i = 0; i <= 127; i++)
            {
                categoryAxis.Labels.Add(noteNames[i % 12] + (i / 12).ToString(CultureInfo.InvariantCulture));
            }

            ShowPlot(new PlotModel()
            {
                Title  = "ピッチと母音",
                Axes   = { categoryAxis },
                Series = { series }
            });
        }
Ejemplo n.º 6
0
        public async Task <(List <StatClass> List, PlotModel PlotModel)> Calc_timeline_day()
        {
            var list = new List <StatClass>();

            #region Настройка графики
            var plotModel1 = new PlotModel();
            plotModel1.Title           = "Загрузка за день";
            plotModel1.IsLegendVisible = false;

            var dateAxis1 = new DateTimeAxis();
            dateAxis1.Position      = AxisPosition.Bottom;
            dateAxis1.IsZoomEnabled = false;
            dateAxis1.IsPanEnabled  = false;
            plotModel1.Axes.Add(dateAxis1);

            var categoryAxis1 = new CategoryAxis();
            categoryAxis1.IsZoomEnabled  = false;
            categoryAxis1.IsPanEnabled   = false;
            categoryAxis1.GapWidth       = 0.2;
            categoryAxis1.TickStyle      = TickStyle.None;
            categoryAxis1.MinimumPadding = 0.1;
            categoryAxis1.MaximumPadding = 0.1;
            categoryAxis1.Position       = AxisPosition.Left;
            plotModel1.Axes.Add(categoryAxis1);
            #endregion

            return(await Task.Run(() =>
            {
                using (var db = DbService.GetDb())
                {
                    var orders = db.Orders
                                 .LoadWith(p => p.Car)
                                 .LoadWith(p => p.Car.CarModel)
                                 .Where(p => p.CloseTime != null)
                                 .OnlyActive()
                                 .Where(p => p.InTime >= TimelineDayDate && p.InTime <= TimelineDayDate.AddDays(1).AddSeconds(-1))
                                 .ToList()
                                 .OrderByDescending(p => p.InTime)
                                 .ToList();

                    IntervalBarSeries barSeries = new OxyPlot.Series.IntervalBarSeries();
                    barSeries.TrackerFormatString = "Автомобиль: {6}\n{4:HH:mm} - {5:HH:mm}";
                    //barSeries.TextColor = OxyColors.White;
                    barSeries.FillColor = OxyColor.Parse("#CCFF90");

                    var i = 0;
                    foreach (var order in orders)
                    {
                        categoryAxis1.Labels.Add(order.Car.FedCode);
                        IntervalBarItem item = new IntervalBarItem
                        {
                            Start = OxyPlot.Axes.DateTimeAxis.ToDouble(order.InTime),
                            End = OxyPlot.Axes.DateTimeAxis.ToDouble(order.OutTime),
                            CategoryIndex = i,
                            Title = $"{order.Car.FedCode}, {order.Car.CarModel.Caption}"
                                    //Color = FlatPalette[0]
                        };
                        barSeries.Items.Add(item);
                        i++;
                    }

                    plotModel1.Series.Add(barSeries);
                }


                return (list, plotModel1);
            }));
        }
        public void MakeIntervalBars([JetBrains.Annotations.NotNull] ResultFileEntry srcResultFileEntry, [JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] DirectoryInfo basisPath,
                                     [ItemNotNull][JetBrains.Annotations.NotNull] List <Tuple <string, double> > consumption,
                                     [JetBrains.Annotations.NotNull] ChartTaggingSet taggingSet,
                                     [JetBrains.Annotations.NotNull] string newFileNameSuffix,
                                     bool showTitle,
                                     [JetBrains.Annotations.NotNull] GenericChartBase gcb, CalcOption sourceOption)
        {
            var fontsize = 48;

            if (consumption.Count <= 20)
            {
                fontsize = 22;
            }
            if (consumption.Count > 20 && consumption.Count <= 30)
            {
                fontsize = 16;
            }
            if (consumption.Count > 30 && consumption.Count <= 40)
            {
                fontsize = 14;
            }
            if (consumption.Count > 40 && consumption.Count <= 50)
            {
                fontsize = 12;
            }
            if (consumption.Count > 50)
            {
                fontsize = 10;
            }
            if (!Config.MakePDFCharts)
            {
                fontsize = (int)(fontsize * 0.8);
            }
            var unit       = "min";
            var xaxislabel = "Time Consumption in Percent";

            if (srcResultFileEntry.LoadTypeInformation != null)
            {
                var lti = srcResultFileEntry.LoadTypeInformation;
                if (!lti.ShowInCharts)
                {
                    return;
                }
                unit       = lti.UnitOfSum;
                xaxislabel = lti.Name + " in Percent";
            }
            consumption.Sort((x, y) => y.Item2.CompareTo(x.Item2));
            OxyPalette p;

            if (consumption.Count > 1)
            {
                if (taggingSet.Categories.Count > 1)
                {
                    p = OxyPalettes.HueDistinct(taggingSet.Categories.Count);
                }
                else
                {
                    p = OxyPalettes.Hue64;
                }
            }
            else
            {
                p = OxyPalettes.Hue64;
            }
            var plotModel1 = new PlotModel
            {
                LegendBorderThickness = 0,
                LegendOrientation     = LegendOrientation.Vertical,
                LegendPlacement       = LegendPlacement.Inside,
                LegendPosition        = LegendPosition.TopLeft,
                PlotAreaBorderColor   = OxyColors.White,
                LegendFontSize        = fontsize,
                LegendSymbolMargin    = 25
            };

            if (showTitle)
            {
                plotModel1.Title = plotName;
            }
            if (Config.MakePDFCharts)
            {
                plotModel1.DefaultFontSize = fontsize;
            }
            var ca = new CategoryAxis
            {
                Position       = AxisPosition.Left,
                GapWidth       = 0,
                MaximumPadding = 0.03,
                MajorTickSize  = 0
            };

            plotModel1.Axes.Add(ca);
            var la = new LinearAxis
            {
                Minimum        = 0,
                MinimumPadding = 0,
                Title          = ChartLocalizer.Get().GetTranslation(xaxislabel),
                Position       = AxisPosition.Bottom,
                MinorTickSize  = 0
            };

            plotModel1.Axes.Add(la);
            var caSub = new CategoryAxis
            {
                StartPosition = 0.5,
                EndPosition   = 1,
                Position      = AxisPosition.Left,
                Key           = "Sub",
                GapWidth      = 0.3,
                MajorTickSize = 0,
                MinorTickSize = 0
            };

            plotModel1.Axes.Add(caSub);
            double runningSum   = 0;
            var    row          = 0;
            var    sum          = consumption.Select(x => x.Item2).Sum();
            var    allBarSeries = new Dictionary <string, IntervalBarSeries>();
            var    ba           = new BarSeries
            {
                YAxisKey          = "Sub",
                LabelFormatString = "{0:N1} %"
            };

            foreach (var s in taggingSet.Categories)
            {
                caSub.Labels.Add(ChartLocalizer.Get().GetTranslation(s));
                var ibs = new IntervalBarSeries();
                // ibs.Title =
                var coloridx = taggingSet.GetCategoryIndexOfCategory(s);
                ibs.FillColor       = p.Colors[coloridx];
                ibs.StrokeThickness = 0;
                ibs.FontSize        = fontsize;
                allBarSeries.Add(s, ibs);
                double categorysum = 0;
                foreach (var tuple in consumption)
                {
                    if (taggingSet.AffordanceToCategories[tuple.Item1] == s)
                    {
                        categorysum += tuple.Item2;
                    }
                }
                var percent = categorysum / sum * 100;
                var bai     = new BarItem(percent)
                {
                    Color = p.Colors[coloridx]
                };
                ba.Items.Add(bai);
            }
            plotModel1.Series.Add(ba);
            foreach (var tuple in consumption)
            {
                var percentage = tuple.Item2 / sum * 100;
                var name       = ChartLocalizer.Get().GetTranslation(tuple.Item1.Trim());
                if (name.Length > 100)
                {
                    name = name.Substring(0, 97) + "...";
                }
                var textAnnotation1 = new TextAnnotation
                {
                    StrokeThickness = 0,
                    FontSize        = fontsize,
                    Padding         = new OxyThickness(10, 0, 10, 0)
                };
                var txtValue = tuple.Item2.ToString("N1", CultureInfo.CurrentCulture);
                if (srcResultFileEntry.LoadTypeInformation == null)
                {
                    var ts = TimeSpan.FromMinutes(tuple.Item2);
                    txtValue = ts.ToString();
                }
                textAnnotation1.Text = " " + name + " (" + txtValue + " " + unit + ", " +
                                       (tuple.Item2 / sum * 100).ToString("N1", CultureInfo.CurrentCulture) + " %)   ";
                if (runningSum < 50)
                {
                    textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Left;
                    textAnnotation1.TextPosition            = new DataPoint(runningSum + percentage, row - 0.6);
                }
                else
                {
                    textAnnotation1.TextPosition            = new DataPoint(runningSum, row - 0.5);
                    textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Right;
                }
                plotModel1.Annotations.Add(textAnnotation1);
                var item     = new IntervalBarItem(runningSum, runningSum + percentage);
                var category = taggingSet.AffordanceToCategories[tuple.Item1];
                allBarSeries[category].Items.Add(item);
                foreach (var pair in allBarSeries)
                {
                    if (pair.Key != category)
                    {
                        pair.Value.Items.Add(new IntervalBarItem(0, 0));
                    }
                }
                ca.Labels.Add(string.Empty);
                runningSum += percentage;
                row++;
            }
            foreach (var pair in allBarSeries)
            {
                plotModel1.Series.Add(pair.Value);
            }
            gcb.Save(plotModel1, plotName, srcResultFileEntry.FullFileName + newFileNameSuffix, basisPath, sourceOption); // ".interval"
        }
        private void AddBars([JetBrains.Annotations.NotNull] CalculationProfiler.ProgramPart part, int row, double offset, int fontsize,
                             [JetBrains.Annotations.NotNull] Dictionary <int, IntervalBarSeries> itemsByLevel, [JetBrains.Annotations.NotNull] OxyPalette palette, [JetBrains.Annotations.NotNull] PlotModel pm)
        {
            var runningsum = offset;

            for (var i = 0; i < part.Children.Count; i++)
            {
                var programPart = part.Children[i];
                AddBars(programPart, row + 1, runningsum, fontsize, itemsByLevel, palette, pm);
                runningsum += programPart.Duration2;
            }

            //bar
            var item = new IntervalBarItem(offset, offset + part.Duration2)
            {
                Color = palette.Colors[_parts.IndexOf(part)]
            };

            if (!itemsByLevel.ContainsKey(1))
            {
                var series = new IntervalBarSeries
                {
                    FontSize = fontsize
                };
                itemsByLevel.Add(1, series);
            }
            var ibs = new IntervalBarSeries();

            for (var i = 0; i < row; i++)
            {
                ibs.Items.Add(new IntervalBarItem(0, 0, ""));
            }
            ibs.StrokeThickness = 0.1;
            ibs.Items.Add(item);
            pm.Series.Add(ibs);
            //  item.Title = name;

            //annotation
            if (string.IsNullOrWhiteSpace(part.Key))
            {
                throw new LPGException("Empty profiler key");
            }
            var name = part.Key;

            if (name.Length > 100)
            {
                name = name.Substring(0, 97) + "...";
            }
            var textAnnotation1 = new TextAnnotation
            {
                StrokeThickness = 0,
                FontSize        = 6,
                Padding         = new OxyThickness(10, 0, 10, 0)
            };
            var txtValue = name + " - " + part.Duration2.ToString("N1", CultureInfo.InvariantCulture) + "s";

            textAnnotation1.Text = txtValue;

            textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Left;
            textAnnotation1.TextPosition            = new DataPoint(offset, row + GetOffset(row));

            pm.Annotations.Add(textAnnotation1);
        }