private Summary GetSummary(DateTime fromDate, DateTime toDate)
        {
            Summary s = new Summary();

            s.From = fromDate;
            s.To = toDate;

            s.Invoices = (from i in db.Invoices
                            where i.TimeStamp >= fromDate && i.TimeStamp <= toDate
                            select i).ToList();

            s.Purchases = (from p in db.Purchases
                             where p.TimeStamp >= fromDate && p.TimeStamp <= toDate
                             select p).ToList();


            s.NetExpense = s.Purchases.Sum(i => i.SubTotal);
            s.NetIncome = s.Invoices.Sum(i => i.NetTotal);

            s.VATReceived = s.Invoices.Sum(i => i.VATAmount);

            s.AmountPaid = s.Invoices.Where(i => i.Paid).Sum(i => i.TotalToPay);

            s.VATBalance = s.Invoices.Sum(i => i.VATAmount) - s.Purchases.Sum(p => p.VATAmount);

            return s;
        }
        private Summary GetSummary(DateTime fromDate, DateTime toDate)
        {
            Summary s = new Summary();

            s.From = fromDate;
            s.To = toDate;

            s.Invoices = (from i in db.Invoices.Include("InvoiceDetails")
                            where i.TimeStamp >= fromDate && i.TimeStamp <= toDate
                            select i).ToList().Where(i=>!i.IsProposal).ToList();

            s.Purchases = (from p in db.Purchases
                             where p.TimeStamp >= fromDate && p.TimeStamp <= toDate
                             select p).ToList();


            s.NetExpense = s.Purchases.Sum(i => i.SubTotal);
            s.GrossExpense = s.Purchases.Sum(i => i.TotalWithVAT);
            
            s.NetIncome = s.Invoices.Sum(i => i.NetTotal);
            s.GrossIncome = s.Invoices.Sum(i=>i.TotalWithVAT);

            s.VATReceived = s.Invoices.Sum(i => i.VATAmount);
            s.VATPaid = s.Purchases.Sum(i => i.VAT);
            s.VATBalance = s.Invoices.Sum(i => i.VATAmount) - s.Purchases.Sum(p => p.VATAmount);

            s.AmountPaid = s.Invoices.Where(i => i.Paid).Sum(i => i.TotalToPay);

            s.AdvancePaymentTaxPaid = s.Invoices.Sum(i => i.AdvancePaymentTaxAmount);
            return s;
        }
Exemple #3
0
        public static SummaryModel MapSummaryModelFrom(Summary summary)
        {
            Mapper.CreateMap<Summary, SummaryModel>()
                .ForMember(hosp => hosp.Hospital, source => source.Ignore())
                .ForMember(ad => ad.ReasonsOfAdmission, source => source.Ignore())
                .ForMember(al => al.Allergies, so => so.Ignore())
                .ForMember(di => di.Diagnostics, so => so.Ignore())
                .ForMember(proc => proc.Procedures, so => so.Ignore())
                .ForMember(hemo => hemo.Hemotransfusions, so => so.Ignore())
                .ForMember(ex => ex.Exams, so => so.Ignore())
                .ForMember(me => me.Medications, so => so.Ignore())
                 .ForMember(pres => pres.PrescriptionsForService, so => so.Ignore())
                .ForMember(hd => hd.DischargeData, so => so.Ignore())
                .ForMember(p => p.Patient, so => so.Ignore())
                .ForMember(ac => ac.Actions, souce => souce.Ignore())
                .ForMember(vi => vi.Views, source => source.Ignore())
                .ForMember(tr => tr.Treatment, source => source.Ignore());

            var summaryModel = Mapper.Map<Summary, SummaryModel>(summary);

            foreach (var professionalRegistration in ProfessionalRegistrationMapper.MapProfessionalRegistrationsModelFrom(summary.Account.ProfessionalRegistrations))
            {
                summaryModel.Account.ProfessionalRegistration.Add(professionalRegistration);
            }

            var views = new List<HistoryRecord>();
            var actions = new List<HistoryRecord>();

            foreach (var historyRecord in summary.History)
            {
                if (historyRecord.Action.Id == 4)
                {
                    views.Add(historyRecord);
                }
                else
                {
                    actions.Add(historyRecord);
                }
            }

            summaryModel.DischargeData = DischargeDataMapper.MapHighDataModelFrom(summary);
            summaryModel.ReasonsOfAdmission = ReasonsOfAdmissionMapper.MapReasonsOfAdmissionModelFrom(summary.ReasonOfAdmission);
            summaryModel.Allergies = AllergyMapper.MapAllergyModelsFrom(summary.Allergies);
            summaryModel.Diagnostics = DiagnosticMapper.MapDiagnosticsModelsFrom(summary.Diagnostics);
            summaryModel.Procedures = ProcedureMapper.MapProceduresModelsFrom(summary.Procedures);
            summaryModel.Medications = MedicationMapper.MapMedicationModelsFrom(summary.Medications);
            summaryModel.PrescriptionsForService = PrescriptionsForServiceMapper.MapDefModelsFrom(summary.PrescriptionsForService);
            summaryModel.Hemotransfusions = HemotransfusionMapper.MapHemotransfusionModelsFrom(summary.Hemotransfusions);
            summaryModel.Exams = ExamMapper.MapExamModelsFrom(summary.Exams);
            summaryModel.Patient = PatientMapper.MapPatientModelFrom(summary.Patient);
            summaryModel.Hospital = HospitalMapper.MapHospitalModelFrom(summary.Hospital);
            summaryModel.Actions = HistoryRecordMapper.MapHistoryRecordModelsFrom(actions.OrderByDescending(hr => hr.Date).Take(10));
            summaryModel.Views = HistoryRecordMapper.MapHistoryRecordModelsFrom(
                views.OrderByDescending(hr => hr.Date).GroupBy(x => x.Account.Id).Select(x => x.FirstOrDefault()).Take(10).ToList());
            if (summary.Treatment != null)
                summaryModel.Treatment = TreatmentMapper.MapTreatmentModelFrom(summary.Treatment);

            return summaryModel;
        }
Exemple #4
0
        public void create_procedure_witch_sucess()
        {
            var summary = new Summary();

            summary.CreateProcedure(1, 5, 2012, new TUSS { Id = 1 });

            Assert.IsTrue(summary.Procedures.Count > 0);
        }
Exemple #5
0
        public void remove_procedure_witch_sucess()
        {
            var summary = new Summary();

            summary.Procedures.Add(new Procedure { Id = 1 });
            summary.RemoveProcedure(1);

            Assert.IsTrue(summary.Procedures.Count == 0);
        }
		public override async Task JoinRoomGenAsync(String url) {
			try {
				this.joinedRoomSummary = Mapper.Map<Summary>(await this.client.GetSummaryAsync(url));
				await this.client.JoinRoomAsync(url);
			} catch (FormatException ex) {
				throw new CommentException(ex.Message, ex);
			} catch (CavetubeException ex) {
				throw new CommentException(ex.Message, ex);
			}
		}
        public void CreateReport(Summary summary, DirectoryInfo outputDirectory)
        {
            var outputFile = Path.Combine(outputDirectory.FullName, "CsvReport.csv");
            var errorTypes = new Dictionary<string, string>
            {
                {"paymenterror", "PaymentError"},
                {"StaleElementReferenceException", "Stale element" }
            };

            var rows = new List<List<string>>();
            using (var csvReportFile = File.CreateText(outputFile))
            {
                rows.Add(new List<string>
                {
                    "TestReport",
                    "TestFixture",
                    "Test",
                    "Result",
                    "Stream",
                    "IsNewBusiness",
                    "Error",
                    "ErrorType"
                });

                foreach (var report in summary.Reports)
                {
                    foreach (var testSuite in report.TestSuiteList)
                    {
                        foreach (var test in testSuite.TestList)
                        {
                            var errorType = "Unknown error";
                            if (test.StatusMessage != null && errorTypes.Any(e => test.StatusMessage.Contains(e.Key)))
                            {
                                errorType = errorTypes.First(e => test.StatusMessage.Contains(e.Key)).Value;
                            }
                            rows.Add(new List<string>
                            {
                                report.FileName,
                                testSuite.Name,
                                test.Name,
                                test.Status.ToString(),
                                testSuite.Name.Substring(0, testSuite.Name.IndexOf(".")),
                                testSuite.Name.Contains("NewBusiness").ToString(),
                                test.StatusMessage?.Replace("\n", " "),
                                errorType
                            });
                        }
                    }
                }
                foreach (var row in rows)
                {
                    csvReportFile.WriteLine(string.Join("\t", row));
                }
            }
        }
        /// <summary>
        /// Returns a discretized value given the source vector.
        /// </summary>
        /// <param name="row">Row vector to discretize.</param>
        /// <param name="summary">Summary.</param>
        /// <returns>Double.</returns>
        public override double Discretize(Vector row, Summary summary)
        {
            string s = "0";

            for (int c = 0; c < row.Length; c++)
            {
                s += this.Ranges[c].IndexOf(f => f.Test(row[c])) + 1;
            }

            return double.Parse(s);
        }
        /// <summary>
        ///   Visits the <c>summary</c> documentation element.
        /// </summary>
        /// 
        public override void VisitSummary(Summary summary)
        {
            builder.Clear();
            insideTextBlock = false;

            builder.AppendLine("<StackPanel>");
            base.VisitSummary(summary);
            builder.AppendLine("</StackPanel>");

            current.Summary = builder.ToString();
        }
 public MovementSummaryViewModel(Summary data)
 {
     NotificationId = data.Id;
     IntendedShipments = data.IntendedShipments;
     UsedShipments = data.UsedShipments;
     QuantityReceivedTotal = data.QuantityReceivedTotal.ToString("G29") + " " + EnumHelper.GetDisplayName(data.DisplayUnit);
     QuantityRemainingTotal = data.QuantityRemainingTotal.ToString("G29") + " " + EnumHelper.GetDisplayName(data.DisplayUnit);
     TableData = new List<MovementsSummaryTableViewModel>();
     NotificationStatus = data.NotificationStatus;
     NotificationType = data.NotificationType;
 }
Exemple #11
0
 public void Init()
 {
     CharaIndex = 0;
     MyChara = Player.MyCharas[CharaIndex];
     MyGameobject = gameObject;
     Go_Summary = transform.FindChild("Summary").gameObject;
     MySummary = Go_Summary.GetComponent<Summary>();
     MySummary.Init();
     Go_Detail = transform.FindChild("Detail").gameObject;
     UpdateInfo();
     MyGameobject.SetActive(false);
 }
Exemple #12
0
        /// <summary>
        /// Initializes the discretizer.
        /// </summary>
        /// <param name="rows">Matrix.</param>
        /// <param name="summary">Summary.</param>
        public override void Initialize(Matrix rows, Summary summary)
        {
            base.Initialize(rows, summary);

            this.Ranges = new Range[rows.Cols][];

            for (int idx = 0; idx < rows.Cols; idx++)
            {
                if (States[idx] >= 2.0)
                    this.Ranges[idx] = rows[idx, VectorType.Col].Segment((int) States[idx]);
                else
                    this.Ranges[idx] = new Range[] { new Range(summary.Minimum[idx], summary.Maximum[idx]) };
            }
        }
 public SummaryWindowViewModel(UIClient db, EmployeeDescription employee)
 {
     _db = db;
     _summary = new Summary();
     _summary.Date = DateTime.Today.AddDays(-DateTime.Today.Day);
     NotifyPropertyChanged("SummaryDate");
     _employee = employee;
     _summary.EmployeeDescription = employee;
     _workRecords = db.GetRecordsOfEmployee(employee);
     _selectedWorkRecords = new List<WorkRecord>();
     SummaryDate = DateTime.Now;
     var lastSum = db.GetLastSummaries(employee, 1);
     if (lastSum != null)
         _lastSummaryDate = lastSum.Last().Date;
 }
Exemple #14
0
        public void CreateReport(string reportingEngineName, IEnumerable<FileInfo> inputFiles, DirectoryInfo outputDirectory)
        {
            if (!outputDirectory.Exists)
                Directory.CreateDirectory(outputDirectory.FullName);

            var summary = new Summary();

            foreach (var filePath in inputFiles)
            {
                var testFileParser = GetTestFileParser(filePath.FullName);
                if (testFileParser == null)
                    continue;

                var report = testFileParser.Parse(filePath.FullName);
                summary.AddReport(report);
            }

            var reportingEngine = GetReportingEngine(reportingEngineName);
            reportingEngine.CreateReport(summary, outputDirectory);
        }
        public void CreateReport(Summary summary, DirectoryInfo outputDirectory)
        {
            var engineNamespace = GetType().Namespace;
            var templatesNamespace = engineNamespace + ".Templates";
            var templateService = new RazorTemplateService(templatesNamespace, outputDirectory.FullName);
            if (summary.Reports.Count > 1)
            {
                summary.InsertIndexSideNavLink();
                templateService.Save(summary);
            }

            var artifactsManager = new ArtifactsManager(outputDirectory);
            foreach (var report in summary.Reports)
            {
                report.SideNavLinks = summary.SideNavLinks;
                artifactsManager.CopyReportedArtifacts(report);
                if(report.XmlFileContents != null)
                    artifactsManager.SaveOriginalXmlContents(report);
                templateService.Save(report);
            }
            var assetsNamespace = engineNamespace + ".Assets";
            AssetsCopier.CopyTo(assetsNamespace, outputDirectory);
        }
Exemple #16
0
        public static DischargeDataModel MapHighDataModelFrom(Summary summary)
        {
            var dischargeData = summary.HighData;

            Mapper.CreateMap<DischargeData, DischargeDataModel>().ForMember(ec => ec.ComplementaryExams, source => source.Ignore())
                .ForMember(mr => mr.MedicalReviews, source => source.Ignore()).ForMember(cd => cd.ConditionAtDischarge, source => source.Ignore());

            var dischargeDataModel = Mapper.Map<DischargeData, DischargeDataModel>(dischargeData);

            dischargeDataModel.ConditionAtDischarge = dischargeData.ConditionAtDischarge == null ? short.MinValue : dischargeData.ConditionAtDischarge.Id;
            dischargeDataModel.DestinationOfThePatientAtDischarge = (short)dischargeData.DestinationAtDischarge;
            dischargeDataModel.MultidisciplinaryTeamsMet = (short)dischargeData.MultidisciplinaryTeamsMet;

            dischargeDataModel.PrescribedHighYear = summary.Date.Value.Year == null ? 0 : summary.Date.Value.Year;
            dischargeDataModel.PrescribedHighMonth = summary.Date.Value.Month == null ? 0 : summary.Date.Value.Month;
            dischargeDataModel.PrescribedHighDay = summary.Date.Value.Day == null ? 0 : summary.Date.Value.Day;

            dischargeDataModel.PrescribedHighHour = summary.Date.Value.Hour == null ? 0 : summary.Date.Value.Hour;
            dischargeDataModel.PrescribedHighMinute = summary.Date.Value.Minute == null ? 0 : summary.Date.Value.Minute;

            dischargeDataModel.DeliveredDateYear = dischargeData.Date == null ? 0 : dischargeData.Date.Value.Year;
            dischargeDataModel.DeliveredDateMonth = dischargeData.Date == null ? 0 : dischargeData.Date.Value.Month;
            dischargeDataModel.DeliveredDateDay = dischargeData.Date == null ? 0 : dischargeData.Date.Value.Day;

            foreach (var medicalReview in dischargeData.MedicalReviews)
            {
                dischargeDataModel.MedicalReviews.Add(MedicalReviewMapper.MapmedicalReviewModelFrom(medicalReview));
            }

            foreach (var complementaryExam in dischargeData.ComplementaryExams)
            {
                dischargeDataModel.ComplementaryExams.Add(ComplementaryExamMapper.MapComplementaryExamModelFrom(complementaryExam));
            }

            return dischargeDataModel;
        }
Exemple #17
0
        public IEnumerable<ResponseTimeDistribution> GetReponseTimeDistribution(Summary summary = null)
        {
            TimeSpan fastest;
            TimeSpan slowest;

            if (summary != null)
            {
                fastest = summary.FastestTime;
                slowest = summary.SlowestTime;
            }
            else
            {
                fastest = wrex.Results.Min(x => x.TimeTaken);
                slowest = wrex.Results.Max(x => x.TimeTaken);
            }

            const int NoOfDivisions = 10;

            var variance = (slowest.Ticks - fastest.Ticks) / (float)NoOfDivisions;

            var millisCeiling = new TimeSpan[NoOfDivisions + 1];

            for (int i = 0; i < NoOfDivisions; i++)
            {
                millisCeiling[i] = TimeSpan.FromTicks((long)(fastest.Ticks + (variance * i)));
            }

            millisCeiling[NoOfDivisions] = slowest;

            var distribution =
                wrex.Results.GroupBy(x => millisCeiling.FirstOrDefault(y => y >= x.TimeTaken))
                    .Select(x => new ResponseTimeDistribution { TimeSpan = x.Key, ResponseCount = x.Count() })
                    .OrderBy(x => x.TimeSpan);

            return distribution;
        }
Exemple #18
0
 public string GetValue(Summary summary, Benchmark benchmark)
 => Results.TryGetValue(benchmark, out var stats) && stats.Counters.ContainsKey(HardwareCounter.BranchMispredictions) && stats.Counters.ContainsKey(HardwareCounter.BranchInstructions)
         ? (stats.Counters[HardwareCounter.BranchMispredictions].Count / (double)stats.Counters[HardwareCounter.BranchInstructions].Count).ToString("P2")
         : "-";
Exemple #19
0
 public async Task UpdateSummaryAsync(Summary summary)
 {
     await _summaryRepository.UpdateAsync(summary);
 }
 /// <summary>
 /// Sets the Summary property.
 /// </summary>
 /// <param name="summary">Summary property.</param>
 /// <returns>this instance.</returns>
 public GetLowestPricedOffersForASINResult WithSummary(Summary summary)
 {
     this._summary = summary;
     return this;
 }
        /// <summary>
        /// Persists the object.
        /// </summary>
        public virtual void Persist(Summary persistObject, SqlTransaction sqlTrans)
        {
            // create local variable array for the sql parameters
            SqlParameterHash sqlparams = null;
            // Create a local variable for the connection
            SqlConnection cnn = null;

            // Use the parameter overload or create a new instance
            if (sqlTrans == null)
                cnn = new SqlConnection(Summary.GetConnectionString());

            try
            {
                // discover the parameters
                if (persistObject.Persisted)
                    sqlparams =  SqlHelperParameterCache.GetSpParameterSet(Summary.GetConnectionString(), "gsp_UpdateSummary");
                else
                    sqlparams =  SqlHelperParameterCache.GetSpParameterSet(Summary.GetConnectionString(), "gsp_CreateSummary");

                // Store the parameter for the BorrowerId attribute.
                if (!persistObject.BorrowerIdIsNull)
                    sqlparams["@borrowerId"].Value = persistObject.BorrowerId;
                // Store the parameter for the Amount attribute.
                if (!persistObject.AmountIsNull)
                    sqlparams["@amount"].Value = persistObject.Amount;
                // Store the parameter for the AmountType attribute.
                if (!persistObject.AmountTypeIsNull)
                    sqlparams["@amountType"].Value = persistObject.AmountType;
                // Store the parameter for the Id attribute.
                sqlparams["@id"].Value = persistObject.Id;
                if (!persistObject.Persisted)
                {
                    // store the create only (historical fixed) values
                }
                else
                {
                    // store the update only (historical changeable) values
                }

                if (sqlTrans == null)
                {
                    // Process using the isolated connection
                    using (cnn)
                    {
                        // open the connection
                        cnn.Open();

                        if (!persistObject.Persisted)
                        {
                            SqlHelper.ExecuteNonQuery(cnn, CommandType.StoredProcedure, "gsp_CreateSummary", sqlparams);
                        }
                        else
                        {
                            SqlHelper.ExecuteNonQuery(cnn, CommandType.StoredProcedure, "gsp_UpdateSummary", sqlparams);
                        }

                        // close the connection after usage
                        cnn.Close();
                    }

                    // nullify the connection var
                    cnn = null;
                }
                else
                {
                    // Process using the shared transaction
                    if (!persistObject.Persisted)
                    {
                        SqlHelper.ExecuteNonQuery(sqlTrans, CommandType.StoredProcedure, "gsp_CreateSummary", sqlparams);
                    }
                    else
                    {
                        SqlHelper.ExecuteNonQuery(sqlTrans, CommandType.StoredProcedure, "gsp_UpdateSummary", sqlparams);
                    }
                }
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }
        }
Exemple #22
0
        public override void ExportToLog(Summary summary, ILogger logger)
        {
            // We construct HostEnvironmentInfo manually, so that we can have the HardwareTimerKind enum as text, rather than an integer
            // SimpleJson serializer doesn't seem to have an enum String/Value option (to-be-fair, it is meant to be "Simple")
            var environmentInfo = new
            {
                HostEnvironmentInfo.BenchmarkDotNetCaption,
                summary.HostEnvironmentInfo.BenchmarkDotNetVersion,
                OsVersion     = summary.HostEnvironmentInfo.OsVersion.Value,
                ProcessorName = ProcessorBrandStringHelper.Prettify(summary.HostEnvironmentInfo.CpuInfo.Value),
                summary.HostEnvironmentInfo.CpuInfo.Value?.PhysicalProcessorCount,
                summary.HostEnvironmentInfo.CpuInfo.Value?.PhysicalCoreCount,
                summary.HostEnvironmentInfo.CpuInfo.Value?.LogicalCoreCount,
                summary.HostEnvironmentInfo.RuntimeVersion,
                summary.HostEnvironmentInfo.Architecture,
                summary.HostEnvironmentInfo.HasAttachedDebugger,
                summary.HostEnvironmentInfo.HasRyuJit,
                summary.HostEnvironmentInfo.Configuration,
                summary.HostEnvironmentInfo.JitModules,
                DotNetCliVersion = summary.HostEnvironmentInfo.DotNetSdkVersion.Value,
                summary.HostEnvironmentInfo.ChronometerFrequency,
                HardwareTimerKind = summary.HostEnvironmentInfo.HardwareTimerKind.ToString()
            };

            // If we just ask SimpleJson to serialise the entire "summary" object it throws several errors.
            // So we are more specific in what we serialise (plus some fields/properties aren't relevant)

            var benchmarks = summary.Reports.Select(report =>
            {
                var data = new Dictionary <string, object>
                {
                    // We don't need Benchmark.ShortInfo, that info is available via Benchmark.Parameters below
                    { "DisplayInfo", report.BenchmarkCase.DisplayInfo },
                    { "Namespace", report.BenchmarkCase.Descriptor.Type.Namespace },
                    { "Type", FullNameProvider.GetTypeName(report.BenchmarkCase.Descriptor.Type) },
                    { "Method", report.BenchmarkCase.Descriptor.WorkloadMethod.Name },
                    { "MethodTitle", report.BenchmarkCase.Descriptor.WorkloadMethodDisplayInfo },
                    { "Parameters", report.BenchmarkCase.Parameters.PrintInfo },
                    { "FullName", FullNameProvider.GetBenchmarkName(report.BenchmarkCase) }, // do NOT remove this property, it is used for xunit-performance migration
                    // { "Properties", r.Benchmark.Job.ToSet().ToDictionary(p => p.Name, p => p.Value) }, // TODO
                    { "Statistics", report.ResultStatistics }
                };

                // We show MemoryDiagnoser's results only if it is being used
                if (summary.Config.HasMemoryDiagnoser())
                {
                    data.Add("Memory", report.GcStats);
                }

                if (ExcludeMeasurements == false)
                {
                    // We construct Measurements manually, so that we can have the IterationMode enum as text, rather than an integer
                    data.Add("Measurements",
                             report.AllMeasurements.Select(m => new
                    {
                        IterationMode  = m.IterationMode.ToString(),
                        IterationStage = m.IterationStage.ToString(),
                        m.LaunchIndex,
                        m.IterationIndex,
                        m.Operations,
                        m.Nanoseconds
                    }));

                    if (report.Metrics.Any())
                    {
                        data.Add("Metrics", report.Metrics.Values);
                    }
                }

                return(data);
            });

            JsonSerializer.CurrentJsonSerializerStrategy.Indent = IndentJson;
            logger.WriteLine(JsonSerializer.SerializeObject(new Dictionary <string, object>
            {
                { "Title", summary.Title },
                { "HostEnvironmentInfo", environmentInfo },
                { "Benchmarks", benchmarks }
            }));
        }
Exemple #23
0
 public string GetValue(Summary summary, Benchmark benchmark) =>
 Format(summary[benchmark].ResultStatistics, summary.TimeUnit);
Exemple #24
0
        public static Summary[] Run(BenchmarkRunInfo[] benchmarkRunInfos, IConfig commonSettingsConfig, bool summaryPerType)
        {
            var resolver           = DefaultResolver;
            var artifactsToCleanup = new List <string>();
            var title = GetTitle(benchmarkRunInfos);

            var rootArtifactsFolderPath = (commonSettingsConfig?.ArtifactsPath ?? DefaultConfig.Instance.ArtifactsPath).CreateIfNotExists();

            using (var logStreamWriter = Portability.StreamWriter.FromPath(Path.Combine(rootArtifactsFolderPath, title + ".log")))
            {
                var logger = new CompositeLogger(commonSettingsConfig.GetCompositeLogger(), new StreamLogger(logStreamWriter));

                var supportedBenchmarks = GetSupportedBenchmarks(benchmarkRunInfos, logger, resolver);

                var validationErrors = Validate(supportedBenchmarks, logger);
                if (validationErrors.Any(validationError => validationError.IsCritical))
                {
                    return new [] { Summary.CreateFailed(
                                        supportedBenchmarks.SelectMany(b => b.BenchmarksCases).ToArray(),
                                        title, HostEnvironmentInfo.GetCurrent(), commonSettingsConfig, GetResultsFolderPath(rootArtifactsFolderPath), validationErrors) }
                }
                ;

                var buildPartitions = BenchmarkPartitioner.CreateForBuild(supportedBenchmarks, resolver);

                logger.WriteLineHeader("// ***** BenchmarkRunner: Start   *****");
                var globalChronometer = Chronometer.Start();

                var buildResults = BuildInParallel(logger, rootArtifactsFolderPath, buildPartitions, ref globalChronometer);

                try
                {
                    var results = new List <Summary>();

                    var benchmarkToBuildResult = buildResults
                                                 .SelectMany(buildResult => buildResult.Key.Benchmarks.Select(buildInfo => (buildInfo.BenchmarkCase, buildInfo.Id, buildResult.Value)))
                                                 .ToDictionary(info => info.BenchmarkCase, info => (info.Id, info.Value));

                    foreach (var benchmarkRunInfo in supportedBenchmarks) // we run them in the old order now using the new build artifacts
                    {
                        var runChronometer = Chronometer.Start();

                        var summary = Run(benchmarkRunInfo, benchmarkToBuildResult, resolver, logger, artifactsToCleanup, rootArtifactsFolderPath, ref runChronometer);

                        if (summaryPerType)
                        {
                            PrintSummary(logger, benchmarkRunInfo.Config, summary);
                        }

                        LogTotalTime(logger, runChronometer.GetElapsed().GetTimeSpan(), summary.GetNumberOfExecutedBenchmarks(), message: "Run time");
                        logger.WriteLine();

                        results.Add(summary);
                    }

                    if (!summaryPerType)
                    {
                        var joinedSummary = Summary.Join(results, commonSettingsConfig, globalChronometer.GetElapsed());

                        PrintSummary(logger, commonSettingsConfig, joinedSummary);

                        results.Clear();
                        results.Add(joinedSummary);
                    }

                    return(results.ToArray());
                }
                finally
                {
                    logger.WriteLineHeader("// * Artifacts cleanup *");
                    Cleanup(new HashSet <string>(artifactsToCleanup.Distinct()));
                }
            }
        }
Exemple #25
0
 /// <summary>
 /// Discretizes a Vector into a single real value.
 /// </summary>
 /// <param name="row">Vector to process.</param>
 /// <param name="summary">Feature properties from the original set.</param>
 /// <returns>Double.</returns>
 public abstract double Discretize(Vector row, Summary summary);
Exemple #26
0
 /// <summary>
 /// Performs any preconditioning steps prior to discretizing values.
 /// </summary>
 /// <param name="rows">Matrix.</param>
 /// <param name="summary">Feature properties from the original set.</param>
 public virtual void Initialize(Matrix rows, Summary summary)
 {
 }
Exemple #27
0
 public string GetValue(Summary summary, Benchmark benchmark, ISummaryStyle style) => GetValue(summary, benchmark);
Exemple #28
0
 public bool IsAvailable(Summary summary)
 => summary.Benchmarks.Any(
     benchmark =>
     !benchmark.Job.Diagnoser.HardwareCounters.IsNullOrEmpty() &&
     benchmark.Job.Diagnoser.HardwareCounters.Contains(HardwareCounter.BranchInstructions) &&
     benchmark.Job.Diagnoser.HardwareCounters.Contains(HardwareCounter.BranchMispredictions));
        /// <summary>
        /// Fills a single instance with data based on its primary key values.
        /// </summary>
        public virtual void Fill(Summary summary, System.Int64 id)
        {
            // create the connection to use
            SqlConnection cnn = new SqlConnection(Summary.GetConnectionString());
            try
            {
                // discover the sql parameters
                SqlParameterHash sqlparams = SqlHelperParameterCache.GetSpParameterSet(Summary.GetConnectionString(), "gsp_SelectSummary");

                using (cnn)
                {
                    // open the connection
                    cnn.Open();

                    // set the parameters
                    sqlparams["@id"].Value = id;

                    // create an instance of the reader to fill.
                    SqlDataReader datareader = SqlHelper.ExecuteReader(cnn, "gsp_SelectSummary", sqlparams);

                    if (datareader.Read())
                        summary.SetMembers(ref datareader);

                    cnn.Close(); // close the connection
                }

                // nullify the connection var
                cnn = null;
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }
        }
Exemple #30
0
        private async void GetTahunBulan()
        {
            summary = new Summary(string.Empty);
            Task <List <Summary> > getDetail = new Task <List <Summary> >(() => summary.GetTahunBulanMax());

            getDetail.Start();

            int    total   = 0;
            string tanggal = "";

            double oldKenaikan = 0;
            double kenaikan    = 0;

            int oldpem = 0;
            int newpem = 0;

            double kenaikantertinggi = 0;
            string tanggalkenaikan   = "";

            string statusKenaikan = "";

            foreach (Summary sum in await getDetail)
            {
                oldpem = newpem;
                newpem = sum.tahunbulan_total;

                oldKenaikan = kenaikan;
                kenaikan    = ((double)newpem / (double)oldpem) * 100 / 100;
                if (kenaikan.ToString() == "∞")
                {
                    kenaikan = 0;
                }

                if (oldpem > newpem)
                {
                    //Kenaikan turun
                    statusKenaikan            = "⏬ " + String.Format("{0:0.0}", kenaikan) + "%";
                    lblPersenUntung.ForeColor = Color.Red;
                }
                else if (oldpem < newpem)
                {
                    //Kenaikan naik
                    statusKenaikan            = "⏫ " + String.Format("{0:0.0}", kenaikan) + "%";
                    lblPersenUntung.ForeColor = Color.SeaGreen;
                }
                else
                {
                    lblPersenUntung.ForeColor = Color.Black;
                }

                if (total < sum.tahunbulan_total)
                {
                    total   = sum.tahunbulan_total;
                    tanggal = sum.tahunbulan;

                    kenaikantertinggi = kenaikan;
                    tanggalkenaikan   = sum.tahunbulan;
                }
            }
            try
            {
                lblTanggalPemasukan.Text  = ConvertToDates(tanggal);
                lblPemasukan.Text         = "Rp" + total.ToString("N0");
                lblPersenUntung.Text      = statusKenaikan + " Kenaikan";
                lblKenaikanTertinggi.Text = "Tertinggi pada bulan " + ConvertToMonth(tanggalkenaikan) + ": " + String.Format("{0:0.0}", kenaikantertinggi) + "%";
            }
            catch (Exception ex)
            {
            }
        }
 protected SummarySkippedEntity()
 {
     Summary = new Summary();
 }
Exemple #32
0
        private async void btnApply_Click(object sender, EventArgs e)
        {
            string selected = treePembukuan.SelectedNode.Name;

            GridPembukuan.Rows.Clear();
            int oldpem = 0;
            int newpem = 0;

            int oldpeng = 0;
            int newpeng = 0;

            double oldKenaikanPem = 0;
            double kenaikanPem    = 0;

            double oldKenaikanPeng = 0;
            double kenaikanPeng    = 0;

            string statusKenaikanPem  = "";
            string statusKenaikanPeng = "";

            if (selected == "Harian")
            {
                summary = new Summary(string.Empty);
                Task <List <Summary> > getDetail = new Task <List <Summary> >(()
                                                                              => summary.GetPembukuanHarian());
                getDetail.Start();

                int rows = 0;
                foreach (Summary sum in await getDetail)
                {
                    /* Menghitung Persen Kenaikan
                     * */
                    bool isUpPem  = false;
                    bool isUpPeng = false;

                    oldpem = newpem;
                    newpem = sum.pemasukan;

                    oldKenaikanPem = kenaikanPem;
                    kenaikanPem    = ((double)newpem / (double)oldpem) * 100 / 100;
                    if (kenaikanPem.ToString() == "∞" || kenaikanPem.ToString() == "NaN")
                    {
                        kenaikanPem = 0;
                    }

                    if (oldpem > newpem)
                    {
                        //Kenaikan turun
                        statusKenaikanPem = "⏬ " + String.Format("{0:0.0}", kenaikanPem) + "%";
                        isUpPem           = false;
                    }
                    else
                    {
                        //Kenaikan naik
                        statusKenaikanPem = "⏫ " + String.Format("{0:0.0}", kenaikanPem) + "%";
                        isUpPem           = true;
                    }


                    /* Menghitung Persen Kenaikan Pengeluaran
                     * */
                    oldpeng = newpeng;
                    newpeng = sum.pengeluaran;

                    oldKenaikanPeng = kenaikanPeng;
                    kenaikanPeng    = ((double)newpeng / (double)oldpeng) * 100 / 100;
                    if (kenaikanPeng.ToString() == "∞" || kenaikanPeng.ToString() == "NaN")
                    {
                        kenaikanPeng = 0;
                    }

                    if (oldpeng > newpeng)
                    {
                        //Kenaikan turun
                        statusKenaikanPeng = "⏬ " + String.Format("{0:0.0}", kenaikanPeng) + "%";
                        isUpPeng           = false;
                    }
                    else
                    {
                        //Kenaikan naik
                        statusKenaikanPeng = "⏫ " + String.Format("{0:0.0}", kenaikanPeng) + "%";
                        isUpPeng           = true;
                    }

                    string dates = ConvertToDay(sum.tahunbulan);
                    GridPembukuan.Rows.Add(new object[]
                    {
                        dates,
                        sum.pemasukan.ToString("N0"),
                        statusKenaikanPem,
                        sum.pengeluaran.ToString("N0"),
                        statusKenaikanPeng
                    });

                    //Change kenaikan perubahan color
                    if (isUpPem)
                    {
                        GridPembukuan.Rows[rows].Cells[2].Style.ForeColor = Color.SeaGreen;
                    }
                    else
                    {
                        GridPembukuan.Rows[rows].Cells[2].Style.ForeColor = Color.Red;
                    }

                    //Change kenaikan perubahan color
                    if (isUpPeng)
                    {
                        GridPembukuan.Rows[rows].Cells[4].Style.ForeColor = Color.Red;
                    }
                    else
                    {
                        GridPembukuan.Rows[rows].Cells[4].Style.ForeColor = Color.SeaGreen;
                    }

                    rows++;
                    //GridPembukuan.Sort(GridPembukuan.Columns[0], ListSortDirection.Ascending);
                }
            }
            else if (selected == "Bulanan")
            {
                summary = new Summary(string.Empty);
                Task <List <Summary> > getDetail = new Task <List <Summary> >(()
                                                                              => summary.GetPembukuanBulanan());
                getDetail.Start();

                int rows = 0;
                foreach (Summary sum in await getDetail)
                {
                    bool isUpPem  = false;
                    bool isUpPeng = false;

                    oldpem = newpem;
                    newpem = sum.pemasukan;

                    oldKenaikanPem = kenaikanPem;
                    kenaikanPem    = ((double)newpem / (double)oldpem) * 100 / 100;
                    if (kenaikanPem.ToString() == "∞" || kenaikanPem.ToString() == "NaN")
                    {
                        kenaikanPem = 0;
                    }

                    if (oldpem > newpem)
                    {
                        //Kenaikan turun
                        statusKenaikanPem = "⏬ " + String.Format("{0:0.0}", kenaikanPem) + "%";
                        isUpPem           = false;
                    }
                    else
                    {
                        //Kenaikan naik
                        statusKenaikanPem = "⏫ " + String.Format("{0:0.0}", kenaikanPem) + "%";
                        isUpPem           = true;
                    }

                    /* Menghitung Persen Kenaikan Pengeluaran
                     * */
                    oldpeng = newpeng;
                    newpeng = sum.pengeluaran;

                    oldKenaikanPeng = kenaikanPeng;
                    kenaikanPeng    = ((double)newpeng / (double)oldpeng) * 100 / 100;
                    if (kenaikanPeng.ToString() == "∞" || kenaikanPeng.ToString() == "NaN")
                    {
                        kenaikanPeng = 0;
                    }

                    if (oldpeng > newpeng)
                    {
                        //Kenaikan turun
                        statusKenaikanPeng = "⏬ " + String.Format("{0:0.0}", kenaikanPeng) + "%";
                        isUpPeng           = false;
                    }
                    else
                    {
                        //Kenaikan naik
                        statusKenaikanPeng = "⏫ " + String.Format("{0:0.0}", kenaikanPeng) + "%";
                        isUpPeng           = true;
                    }

                    string dates = ConvertToDates(sum.tahunbulan);
                    GridPembukuan.Rows.Add(new object[]
                    {
                        dates,
                        sum.pemasukan.ToString("N0"),
                        statusKenaikanPem,
                        sum.pengeluaran.ToString("N0"),
                        statusKenaikanPeng
                    });


                    //Change kenaikan perubahan color
                    if (isUpPem)
                    {
                        GridPembukuan.Rows[rows].Cells[2].Style.ForeColor = Color.SeaGreen;
                    }
                    else
                    {
                        GridPembukuan.Rows[rows].Cells[2].Style.ForeColor = Color.Red;
                    }

                    //Change kenaikan perubahan color
                    if (isUpPeng)
                    {
                        GridPembukuan.Rows[rows].Cells[4].Style.ForeColor = Color.Red;
                    }
                    else
                    {
                        GridPembukuan.Rows[rows].Cells[4].Style.ForeColor = Color.SeaGreen;
                    }

                    rows++;
                }
            }
            else if (selected == "Tahunan")
            {
                summary = new Summary(string.Empty);
                Task <List <Summary> > getDetail = new Task <List <Summary> >(() => summary.GetPembukuanTahunan());
                getDetail.Start();

                int rows = 0;
                foreach (Summary sum in await getDetail)
                {
                    bool isUpPem  = false;
                    bool isUpPeng = false;

                    oldpem = newpem;
                    newpem = sum.pemasukan;

                    oldKenaikanPem = kenaikanPem;
                    kenaikanPem    = ((double)newpem / (double)oldpem) * 100 / 100;
                    if (kenaikanPem.ToString() == "∞" || kenaikanPem.ToString() == "NaN")
                    {
                        kenaikanPem = 0;
                    }

                    if (oldpem > newpem)
                    {
                        //Kenaikan turun
                        statusKenaikanPem = "⏬ " + String.Format("{0:0.0}", kenaikanPem) + "%";
                        isUpPem           = false;
                    }
                    else
                    {
                        //Kenaikan naik
                        statusKenaikanPem = "⏫ " + String.Format("{0:0.0}", kenaikanPem) + "%";
                        isUpPem           = true;
                    }

                    /* Menghitung Persen Kenaikan Pengeluaran
                     * */
                    oldpeng = newpeng;
                    newpeng = sum.pengeluaran;

                    oldKenaikanPeng = kenaikanPeng;
                    kenaikanPeng    = ((double)newpeng / (double)oldpeng) * 100 / 100;
                    if (kenaikanPeng.ToString() == "∞" || kenaikanPeng.ToString() == "NaN")
                    {
                        kenaikanPeng = 0;
                    }

                    if (oldpeng > newpeng)
                    {
                        //Kenaikan turun
                        statusKenaikanPeng = "⏬ " + String.Format("{0:0.0}", kenaikanPeng) + "%";
                        isUpPeng           = false;
                    }
                    else
                    {
                        //Kenaikan naik
                        statusKenaikanPeng = "⏫ " + String.Format("{0:0.0}", kenaikanPeng) + "%";
                        isUpPeng           = true;
                    }

                    GridPembukuan.Rows.Add(new object[]
                    {
                        sum.tahunbulan,
                        sum.pemasukan.ToString("N0"),
                        statusKenaikanPem,
                        sum.pengeluaran.ToString("N0"),
                        statusKenaikanPeng
                    });


                    //Change kenaikan perubahan color
                    if (isUpPem)
                    {
                        GridPembukuan.Rows[rows].Cells[2].Style.ForeColor = Color.SeaGreen;
                    }
                    else
                    {
                        GridPembukuan.Rows[rows].Cells[2].Style.ForeColor = Color.Red;
                    }

                    //Change kenaikan perubahan color
                    if (isUpPeng)
                    {
                        GridPembukuan.Rows[rows].Cells[4].Style.ForeColor = Color.Red;
                    }
                    else
                    {
                        GridPembukuan.Rows[rows].Cells[4].Style.ForeColor = Color.SeaGreen;
                    }

                    rows++;
                }
            }
        }
    /// <summary>
    /// get Summary
    /// </summary>
    /// <param name="id"></param>
    /// <param name="sort"></param>
    /// <returns></returns>
    public List<Summary> getSummary(int id, string sort)
    {
        using (var context = new PetoEntities())
        {
            List<Summary> summary = new List<Summary>();
            // non chargeable
            List<NonChargeable> list1 = (from x in context.NonChargeables
                                         where x.TimeSheetId == id
                                         select x).ToList();

            // non chargeable data
            foreach (NonChargeable item in list1)
            {
                Summary s = new Summary();
                s.TimeSheetId = item.TimeSheetId;
                s.NonChargeableId = item.NonChargeId;

                s.TypeExpense = item.TypeExpense;
                s.TypeHours = item.TypeHours;

                s.Hours = item.Hours;

                if (item.Distance.HasValue)
                {
                    s.Distance = item.Distance.Value;
                }
                if (item.TruckDistance.HasValue)
                {
                    s.TruckDistance = item.TruckDistance.Value;
                }
                if (item.Misc.HasValue)
                {
                    s.Misc = item.Misc.Value;
                }
                if (item.Accomodation != null)
                {
                    s.Accom = item.Accomodation.Value;
                }
                s.Day = item.Day;

                s.Remarks = item.Remarks;

                summary.Add(s);
            }
            // chargeable data
            List<ChargeableJob> list2 = (from x in context.ChargeableJobs
                                         where x.TimeSheetId == id
                                         select x).ToList();

            foreach (ChargeableJob item in list2)
            {
                Summary s = new Summary();

                s.TimeSheetId = item.TimeSheetId;
                s.ChargeableId = item.ChargeableId;

                s.Hours = item.EmpHours;

                if (item.Accomodations.HasValue)
                {
                    s.Accom = item.Accomodations.Value;
                }
                if (item.TravelDistance.HasValue)
                {
                    s.Distance = item.TravelDistance.Value;
                }
                if (item.TruckDistance.HasValue)
                {
                    s.TruckDistance = item.TruckDistance.Value;
                }
                if (item.Misc.HasValue)
                {
                    s.Misc = item.Misc.Value;
                }
                s.Day = item.Day;
                s.Classification = item.Classification;
                s.Activity = item.Activity;
                s.ProjectId = item.ProjectId.Value;
                s.ProjectNum = context.Projects.FirstOrDefault(x => x.ProjectId == item.ProjectId.Value).ProjectNo;
                s.ProjectName = context.Projects.FirstOrDefault(x => x.ProjectId == item.ProjectId.Value).ProjectName;
                s.Remarks = item.Remarks;

                summary.Add(s);
            }
            // Lab Test data
            List<EmpTest> Tests = (from x in context.EmpTests
                                   where x.TimeSheetId == id
                                   select x).ToList();

            foreach (EmpTest item in Tests)
            {
                Summary s = new Summary();

                s.Day = item.Day;
                s.TestId = item.TestId;
                s.TimeSheetId = item.TimeSheetId;
                if (item.DensityTest.HasValue)
                {
                    s.DensityTest = item.DensityTest.Value;
                }
                if (item.LabTest.HasValue)
                {
                    s.labTest = item.LabTest.Value;
                }

                summary.Add(s);
            }
            // sort the list
            switch (sort)
            {
                case "Hours":
                    return summary.OrderBy(x => x.Hours).ToList();
                case "Distance":
                    return summary.OrderBy(x => x.Distance).ToList();
                case "DensityTest":
                    return summary.OrderBy(x => x.DensityTest).ToList();
                case "Classification":
                    return summary.OrderBy(x => x.Classification).ToList();
                case "Misc":
                    return summary.OrderBy(x => x.Misc).ToList();
                case "TypeExpense":
                    return summary.OrderBy(x => x.TypeExpense).ToList();
                case "TypeHours":
                    return summary.OrderBy(x => x.TypeHours).ToList();
                case "Remarks":
                    return summary.OrderBy(x => x.Remarks).ToList();
                case "Activity":
                    return summary.OrderBy(x => x.Activity).ToList();
                case "Day":
                    return sortDayOfWeek(summary);
                case "ProjectNum":
                    return summary.OrderBy(x => x.ProjectNum).ToList();
                case "ProjectName":
                    return summary.OrderBy(x => x.ProjectName).ToList();
                case "LabTest":
                    return summary.OrderBy(x => x.labTest).ToList();
                case "TruckDistance":
                    return summary.OrderBy(x => x.TruckDistance).ToList();
                case "Accom":
                    return summary.OrderBy(x => x.Accom).ToList();
                default:
                    return sortDayOfWeek(summary);
            }
        }
    }
        private void OnCLEMInitialiseActivity(object sender, EventArgs e)
        {
            // create local version of max breeders so we can modify without affecting user set value
            maxBreeders = Math.Max(this.MaximumBreedersKept, this.MinimumBreedersKept);

            this.InitialiseHerd(false, true);
            breedParams = Resources.GetResourceItem(this, typeof(RuminantHerd), this.PredictedHerdName, OnMissingResourceActionTypes.ReportErrorAndStop, OnMissingResourceActionTypes.ReportErrorAndStop) as RuminantType;

            decimal breederHerdSize = 0;

            if (AdjustBreedingFemalesAtStartup)
            {
                RuminantHerd    herd    = Resources.RuminantHerd();
                List <Ruminant> rumHerd = this.CurrentHerd(false);
                if (rumHerd != null && rumHerd.Count() > 0)
                {
                    int                    numberAdded = 0;
                    RuminantType           breedParams = rumHerd.FirstOrDefault().BreedParams;
                    RuminantInitialCohorts cohorts     = Apsim.Children(rumHerd.FirstOrDefault().BreedParams, typeof(RuminantInitialCohorts)).FirstOrDefault() as RuminantInitialCohorts;

                    if (cohorts != null)
                    {
                        List <RuminantTypeCohort> cohortList = Apsim.Children(cohorts, typeof(RuminantTypeCohort)).Cast <RuminantTypeCohort>().Where(a => a.Gender == Sex.Female && (a.Age >= breedParams.MinimumAge1stMating & a.Age <= this.MaximumBreederAge)).ToList();
                        int initialBreeders = Convert.ToInt32(cohortList.Sum(a => a.Number));
                        if (initialBreeders < this.MinimumBreedersKept)
                        {
                            double scaleFactor = this.MinimumBreedersKept / Convert.ToDouble(initialBreeders);
                            // add new individuals
                            foreach (var item in cohortList)
                            {
                                int numberToAdd = Convert.ToInt32(Math.Round(item.Number * scaleFactor) - item.Number);
                                foreach (var newind in item.CreateIndividuals(numberToAdd))
                                {
                                    newind.SaleFlag = HerdChangeReason.FillInitialHerd;
                                    herd.AddRuminant(newind, this);
                                    numberAdded++;
                                }
                            }
                            if (numberAdded == 0)
                            {
                                throw new ApsimXException(this, $"Unable to scale breeding female population up to the maximum breeders kept at startup\nNo cohorts representing breeders were found in the initial herd structure [r=InitialCohorts] for [r={breedParams.Name}]\nAdd at least one initial cohort that meets the breeder criteria of age at first mating and max age kept");
                            }
                            breederHerdSize = initialBreeders + numberAdded;
                        }
                        else if (initialBreeders > maxBreeders)
                        {
                            int reduceBy = Math.Max(0, initialBreeders - maxBreeders);
                            // reduce initial herd size
                            // randomly select the individuals to remove form the breeder herd
                            List <Ruminant> breeders = rumHerd.Where(a => a.Gender == Sex.Female && a.Age > breedParams.MinimumAge1stMating && a.Age < this.MaximumBreederAge).OrderBy(x => Guid.NewGuid()).Take(reduceBy).ToList();
                            foreach (var item in breeders)
                            {
                                item.SaleFlag = HerdChangeReason.ReduceInitialHerd;
                                herd.RemoveRuminant(item, this);
                                reduceBy--;
                            }

                            if (reduceBy > 0)
                            {
                                // add warning
                                string warn = $"Unable to reduce breeders at the start of the simulation to number required [{maxBreeders}] using [a={this.Name}]";
                                if (!Warnings.Exists(warn))
                                {
                                    Summary.WriteWarning(this, warn);
                                    Warnings.Add(warn);
                                }
                            }
                            breederHerdSize = maxBreeders;
                        }
                    }
                    else
                    {
                        throw new ApsimXException(this, $"Unable to adjust breeding female population to the maximum breeders kept at startup\nNo initial herd structure [r=InitialCohorts] has been provided in [r={breedParams.Name}]");
                    }
                }
            }

            // max sires
            if (MaximumSiresKept < 1 & MaximumSiresKept > 0)
            {
                SiresKept = Convert.ToInt32(Math.Ceiling(maxBreeders * breederHerdSize), CultureInfo.InvariantCulture);
            }
            else
            {
                SiresKept = Convert.ToInt32(Math.Truncate(MaximumSiresKept), CultureInfo.InvariantCulture);
            }

            if (AdjustBreedingMalesAtStartup)
            {
                RuminantHerd herd = Resources.RuminantHerd();
                if (herd != null)
                {
                    // get number in herd
                    List <Ruminant> rumHerd       = this.CurrentHerd(false);
                    int             numberPresent = rumHerd.Where(a => a.Gender == Sex.Male).Cast <RuminantMale>().Where(a => a.BreedingSire).Count();
                    if (numberPresent < SiresKept)
                    {
                        // fill to number needed
                        for (int i = numberPresent; i < SiresKept; i++)
                        {
                            RuminantMale newSire = new RuminantMale(SireAgeAtPurchase, Sex.Male, 0, breedParams)
                            {
                                Breed        = this.PredictedHerdBreed,
                                HerdName     = this.PredictedHerdName,
                                BreedingSire = true,
                                ID           = herd.NextUniqueID,
                                SaleFlag     = HerdChangeReason.FillInitialHerd
                            };
                            herd.AddRuminant(newSire, this);
                        }
                    }
                    else if (numberPresent > SiresKept)
                    {
                        // reduce initial herd.
                        int reduceBy = Math.Max(0, numberPresent - SiresKept);
                        // reduce initial sire herd size
                        // randomly select the individuals to remove form the breeder herd
                        List <RuminantMale> sires = rumHerd.Where(a => a.Gender == Sex.Male).Cast <RuminantMale>().Where(a => a.BreedingSire).OrderBy(x => Guid.NewGuid()).Take(reduceBy).ToList();
                        foreach (var item in sires)
                        {
                            item.SaleFlag = HerdChangeReason.ReduceInitialHerd;
                            herd.RemoveRuminant(item, this);
                            reduceBy--;
                        }

                        if (reduceBy > 0)
                        {
                            // add warning
                            string warn = $"Unable to reduce breeding sires at the start of the simulation to number required [{SiresKept}] using [a={this.Name}]";
                            if (!Warnings.Exists(warn))
                            {
                                Summary.WriteWarning(this, warn);
                                Warnings.Add(warn);
                            }
                        }
                    }
                }
            }

            // check GrazeFoodStoreExists for breeders
            grazeStoreBreeders = "";
            if (GrazeFoodStoreNameBreeders != null && !GrazeFoodStoreNameBreeders.StartsWith("Not specified"))
            {
                grazeStoreBreeders = GrazeFoodStoreNameBreeders.Split('.').Last();
                foodStoreBreeders  = Resources.GetResourceItem(this, GrazeFoodStoreNameBreeders, OnMissingResourceActionTypes.ReportErrorAndStop, OnMissingResourceActionTypes.ReportErrorAndStop) as GrazeFoodStoreType;
            }

            // check for managed paddocks and warn if breeders placed in yards.
            if (grazeStoreBreeders == "" && this.MaximumProportionBreedersPerPurchase > 0)
            {
                var ah = Apsim.Find(this, typeof(ActivitiesHolder));
                if (Apsim.ChildrenRecursively(ah, typeof(PastureActivityManage)).Count() != 0)
                {
                    Summary.WriteWarning(this, String.Format("Breeders purchased by [a={0}] are currently placed in [Not specified - general yards] while a managed pasture is available. These animals will not graze until mustered and will require feeding while in yards.\nSolution: Set the [GrazeFoodStore to place purchase in] located in the properties [General].[PastureDetails]", this.Name));
                }
            }

            // check GrazeFoodStoreExists for sires
            grazeStoreSires = "";
            if (GrazeFoodStoreNameSires != null && !GrazeFoodStoreNameSires.StartsWith("Not specified"))
            {
                grazeStoreSires = GrazeFoodStoreNameSires.Split('.').Last();
                foodStoreSires  = Resources.GetResourceItem(this, GrazeFoodStoreNameSires, OnMissingResourceActionTypes.ReportErrorAndStop, OnMissingResourceActionTypes.ReportErrorAndStop) as GrazeFoodStoreType;
            }

            // check for managed paddocks and warn if sires placed in yards.
            if (grazeStoreBreeders == "" && this.SiresKept > 0)
            {
                var ah = Apsim.Find(this, typeof(ActivitiesHolder));
                if (Apsim.ChildrenRecursively(ah, typeof(PastureActivityManage)).Count() != 0)
                {
                    Summary.WriteWarning(this, String.Format("Sires purchased by [a={0}] are currently placed in [Not specified - general yards] while a managed pasture is available. These animals will not graze until mustered and will require feeding while in yards.\nSolution: Set the [GrazeFoodStore to place purchase in] located in the properties [General].[PastureDetails]", this.Name));
                }
            }
        }
        /// <summary>
        /// Get value of a specific individual with special requirements check (e.g. breeding sire or draught purchase)
        /// </summary>
        /// <returns>value</returns>
        public double ValueofIndividual(Ruminant ind, PurchaseOrSalePricingStyleType purchaseStyle, RuminantFilterParameters property, string value)
        {
            double price = 0;

            if (PricingAvailable())
            {
                string          criteria   = property.ToString().ToUpper() + ":" + value.ToUpper();
                List <Ruminant> animalList = new List <Ruminant>()
                {
                    ind
                };

                //find first pricing entry matching specific criteria
                AnimalPriceGroup matchIndividual = null;
                AnimalPriceGroup matchCriteria   = null;
                foreach (AnimalPriceGroup item in PriceList.FindAllChildren <AnimalPriceGroup>().Cast <AnimalPriceGroup>().Where(a => a.PurchaseOrSale == purchaseStyle || a.PurchaseOrSale == PurchaseOrSalePricingStyleType.Both))
                {
                    if (animalList.Filter(item).Count() == 1 && matchIndividual == null)
                    {
                        matchIndividual = item;
                    }

                    // check that pricing item meets the specified criteria.
                    if (item.FindAllChildren <RuminantFilter>().Cast <RuminantFilter>().Where(a => (a.Parameter.ToString().ToUpper() == property.ToString().ToUpper() && a.Value.ToUpper() == value.ToUpper())).Count() > 0)
                    {
                        if (matchCriteria == null)
                        {
                            matchCriteria = item;
                        }
                        else
                        {
                            // multiple price entries were found. using first. value = xxx.
                            if (!WarningsMultipleEntry.Contains(criteria))
                            {
                                WarningsMultipleEntry.Add(criteria);
                                Summary.WriteWarning(this, "Multiple specific [" + purchaseStyle.ToString() + "] price entries were found for [r=" + ind.Breed + "] where [" + property + "]" + (value.ToUpper() != "TRUE" ? " = [" + value + "]." : ".") + "\nOnly the first entry will be used. Price [" + matchCriteria.Value.ToString("#,##0.##") + "] [" + matchCriteria.PricingStyle.ToString() + "].");
                            }
                        }
                    }
                }

                if (matchCriteria == null)
                {
                    // report specific criteria not found in price list
                    string warningString = "No [" + purchaseStyle.ToString() + "] price entry was found for [r=" + ind.Breed + "] meeting the required criteria [" + property + "]" + (value.ToUpper() != "TRUE" ? " = [" + value + "]." : ".");

                    if (matchIndividual != null)
                    {
                        // add using the best pricing available for [][] purchases of xx per head
                        warningString += "\nThe best available price [" + matchIndividual.Value.ToString("#,##0.##") + "] [" + matchIndividual.PricingStyle.ToString() + "] will be used.";
                        price          = matchIndividual.Value * ((matchIndividual.PricingStyle == PricingStyleType.perKg) ? ind.Weight : 1.0);
                    }
                    else
                    {
                        warningString += "\nNo alternate price for individuals could be found for the individuals. Add a new [r=AnimalPriceGroup] entry in the [r=AnimalPricing] for [" + ind.Breed + "]";
                    }
                    if (!WarningsNotFound.Contains(criteria))
                    {
                        WarningsNotFound.Add(criteria);
                        Summary.WriteWarning(this, warningString);
                    }
                }
                else
                {
                    price = matchCriteria.Value * ((matchCriteria.PricingStyle == PricingStyleType.perKg) ? ind.Weight : 1.0);
                }
            }
            return(price);
        }
        private void OnCLEMAnimalManage(object sender, EventArgs e)
        {
            this.Status = ActivityStatus.NoTask;
            RuminantHerd ruminantHerd = Resources.RuminantHerd();

            // remove only the individuals that are affected by this activity.
            // these are old purchases that were not made. This list will be regenerated in this method.
            ruminantHerd.PurchaseIndividuals.RemoveAll(a => a.Breed == this.PredictedHerdBreed);

            List <Ruminant> herd = this.CurrentHerd(true);

            // can sell off males any month as per NABSA
            // if we don't need this monthly, then it goes into next if statement with herd declaration
            // NABSA MALES - weaners, 1-2, 2-3 and 3-4 yo, we check for any male weaned and not a breeding sire.
            // check for sell age/weight of young males
            // if SellYoungFemalesLikeMales then all apply to both sexes else only males.
            // SellFemalesLikeMales will grow out excess heifers until age/weight rather than sell immediately.
            if (this.TimingOK || ContinuousMaleSales)
            {
                this.Status = ActivityStatus.NotNeeded;
                foreach (var ind in herd.Where(a => a.Weaned && (SellFemalesLikeMales ? true : (a.Gender == Sex.Male)) && (a.Age >= MaleSellingAge || a.Weight >= MaleSellingWeight)))
                {
                    bool sell = true;
                    if (ind.GetType() == typeof(RuminantMale))
                    {
                        // don't sell breeding sires.
                        sell = !((ind as RuminantMale).BreedingSire);
                    }
                    else
                    {
                        // only sell females that were marked as excess
                        sell = ind.Tags.Contains("GrowHeifer");
                    }

                    if (sell)
                    {
                        this.Status  = ActivityStatus.Success;
                        ind.SaleFlag = HerdChangeReason.AgeWeightSale;
                    }
                }
            }

            // if management month
            if (this.TimingOK)
            {
                this.Status = ActivityStatus.NotNeeded;
                // ensure pasture limits are ok before purchases
                bool sufficientFoodBreeders = true;
                bool sufficientFoodSires    = true;
                if (foodStoreBreeders != null)
                {
                    sufficientFoodBreeders = (foodStoreBreeders.TonnesPerHectare * 1000) >= MinimumPastureBeforeRestock;
                }
                if (foodStoreSires != null)
                {
                    sufficientFoodSires = (foodStoreSires.TonnesPerHectare * 1000) >= MinimumPastureBeforeRestock;
                }

                // check for maximum age (females and males have different cutoffs)
                foreach (var ind in herd.Where(a => a.Age >= ((a.Gender == Sex.Female) ? MaximumBreederAge : MaximumSireAge)))
                {
                    ind.SaleFlag = HerdChangeReason.MaxAgeSale;

                    // ensure females are not pregnant and add warning if pregnant old females found.
                    if (ind.Gender == Sex.Female && (ind as RuminantFemale).IsPregnant)
                    {
                        string warning = "Some females sold at maximum age in [a=" + this.Name + "] were pregnant.\nConsider changing the MaximumBreederAge in [a=RuminantActivityManage] or ensure [r=RuminantType.MaxAgeMating] is less than or equal to the MaximumBreederAge to avoid selling pregnant individuals.";
                        if (!Warnings.Exists(warning))
                        {
                            Warnings.Add(warning);
                            Summary.WriteWarning(this, warning);
                        }
                    }
                }

                // MALES
                // check for sires after sale of old individuals and buy/sell
                int numberMaleSiresInHerd = herd.Where(a => a.Gender == Sex.Male && a.SaleFlag == HerdChangeReason.None).Cast <RuminantMale>().Where(a => a.BreedingSire).Count();

                // Number of females
                int numberFemaleBreedingInHerd = herd.Where(a => a.Gender == Sex.Female && a.Age >= a.BreedParams.MinimumAge1stMating && a.SaleFlag == HerdChangeReason.None).Count();
                int numberFemaleTotalInHerd    = herd.Where(a => a.Gender == Sex.Female && a.SaleFlag == HerdChangeReason.None).Count();

                // these are females that will exceed max age and be sold in next 12 months
                int numberFemaleOldInHerd = herd.Where(a => a.Gender == Sex.Female && (a.Age + 12 >= MaximumBreederAge) && a.SaleFlag == HerdChangeReason.None).Count();

                // defined heifers here as weaned and will be a breeder in the next year
                int numberFemaleHeifersInHerd = herd.Where(a => a.Gender == Sex.Female && a.Weaned && ((a.Age - a.BreedParams.MinimumAge1stMating < 0) && (a.Age - a.BreedParams.MinimumAge1stMating > -12)) && a.SaleFlag == HerdChangeReason.None).Count();

                if (numberMaleSiresInHerd > SiresKept)
                {
                    // sell sires
                    // What rule? oldest first as they may be lost soonest?
                    int numberToRemove = numberMaleSiresInHerd - SiresKept;
                    if (numberToRemove > 0)
                    {
                        foreach (var male in herd.Where(a => a.Gender == Sex.Male).Cast <RuminantMale>().Where(a => a.BreedingSire).OrderByDescending(a => a.Age).Take(numberToRemove))
                        {
                            male.Location = grazeStoreSires;
                            male.SaleFlag = HerdChangeReason.ExcessSireSale;
                            this.Status   = ActivityStatus.Success;
                            numberToRemove--;
                            if (numberToRemove == 0)
                            {
                                break;
                            }
                        }
                    }
                }
                else if (numberMaleSiresInHerd < SiresKept)
                {
                    if ((foodStoreSires == null) || (sufficientFoodSires))
                    {
                        if (AllowSireReplacement)
                        {
                            // remove young sires from sale herd to replace breed sires (not those sold because too old)
                            foreach (RuminantMale male in herd.Where(a => a.Gender == Sex.Male && a.SaleFlag == HerdChangeReason.AgeWeightSale).OrderByDescending(a => a.Weight))
                            {
                                male.Location     = grazeStoreSires;
                                male.SaleFlag     = HerdChangeReason.None;
                                male.BreedingSire = true;
                                numberMaleSiresInHerd++;
                                if (numberMaleSiresInHerd >= SiresKept)
                                {
                                    break;
                                }
                            }
                            // if still insufficent, look into current herd for replacement
                            // remaining males assumed to be too small, so await next time-step
                        }

                        // if still insufficient buy sires.
                        if (numberMaleSiresInHerd < SiresKept && (MaximumSiresPerPurchase > 0))
                        {
                            // limit by breeders as proportion of max breeders so we don't spend alot on sires when building the herd and females more valuable
                            double propOfBreeders = (double)numberFemaleBreedingInHerd / (double)maxBreeders;
                            propOfBreeders = 1;

                            int sires       = Convert.ToInt32(Math.Ceiling(SiresKept * propOfBreeders), CultureInfo.InvariantCulture);
                            int numberToBuy = Math.Min(MaximumSiresPerPurchase, Math.Max(0, sires - numberMaleSiresInHerd));

                            for (int i = 0; i < numberToBuy; i++)
                            {
                                if (i < MaximumSiresPerPurchase)
                                {
                                    this.Status = ActivityStatus.Success;

                                    RuminantMale newSire = new RuminantMale(SireAgeAtPurchase, Sex.Male, 0, breedParams)
                                    {
                                        Location     = grazeStoreSires,
                                        Breed        = this.PredictedHerdBreed,
                                        HerdName     = this.PredictedHerdName,
                                        BreedingSire = true,
                                        Gender       = Sex.Male,
                                        ID           = 0, // Next unique ide will be assigned when added
                                        SaleFlag     = HerdChangeReason.SirePurchase
                                    };

                                    // add to purchase request list and await purchase in Buy/Sell
                                    ruminantHerd.PurchaseIndividuals.Add(newSire);
                                }
                            }
                        }
                    }
                }

                // FEMALES
                // Breeding herd sold as heifers only, purchased as breeders (>= minAge1stMating)
                // Feb2020 - Added ability to provide desticking groups to try and sell non heifer breeders before reverting to heifer sales.
                int excessBreeders = 0;

                // get the mortality rate for the herd if available or assume zero
                double mortalityRate = breedParams.MortalityBase;

                // shortfall between actual and desired numbers of breeders (-ve for shortfall)
                excessBreeders = numberFemaleBreedingInHerd - maxBreeders;
                // IAT-NABSA removes adjusts to account for the old animals that will be sold in the next year
                // This is not required in CLEM as they have been sold in this method, and it wont be until this method is called again that the next lot are sold.
                // Like IAT-NABSA we will account for mortality losses in the next year in our breeder purchases
                // Account for whole individuals only.
                int numberDyingInNextYear = Convert.ToInt32(Math.Floor(numberFemaleBreedingInHerd * mortalityRate), CultureInfo.InvariantCulture);
                // adjust for future mortality
                excessBreeders -= numberDyingInNextYear;

                // account for heifers already in the herd
                // These are the next cohort that will become breeders in the next 12 months (before this method is called again)
                excessBreeders += numberFemaleHeifersInHerd;

                // if negative - i.e. purchases needed limit to min breeders kept not max breeders kept
                if (excessBreeders < 0)
                {
                    excessBreeders = Math.Min(0, numberFemaleBreedingInHerd - MinimumBreedersKept - numberDyingInNextYear + numberFemaleHeifersInHerd);
                }

                if (excessBreeders > 0) // surplus heifers to sell
                {
                    this.Status = ActivityStatus.Success;

                    // go through any ruminant filter groups and try and sell herd
                    // this allows the user to sell old females over young breeders and heifers if required.
                    // must be female (check that males not included in validation)
                    // remove individuals to sale as specified by destock groups
                    foreach (RuminantDestockGroup item in this.Children.Where(a => a.GetType() == typeof(RuminantDestockGroup)))
                    {
                        // works with current filtered herd to obey filtering.
                        List <Ruminant> herdToSell = herd.Filter(item);
                        int             cnt        = 0;
                        while (cnt < herdToSell.Count() && excessBreeders > 0)
                        {
                            if (herd[cnt].SaleFlag != HerdChangeReason.ExcessBreederSale)
                            {
                                herd[cnt].SaleFlag = HerdChangeReason.ExcessBreederSale;
                                excessBreeders--;
                            }
                            cnt++;
                        }
                    }

                    // now need to manage heifers to herd size or make for sale like males.
                    foreach (var female in herd.Where(a => a.Gender == Sex.Female && (a as RuminantFemale).IsHeifer).Take(excessBreeders))
                    {
                        // if sell like males tag for grow out otherwise mark for sale
                        if (SellFemalesLikeMales)
                        {
                            if (!female.Tags.Contains("GrowHeifer"))
                            {
                                female.Tags.Add("GrowHeifer");
                            }
                        }
                        else
                        {
                            // tag for sale.
                            female.SaleFlag = HerdChangeReason.ExcessHeiferSale;
                        }
                        excessBreeders--;
                        if (excessBreeders == 0)
                        {
                            break;
                        }
                    }
                }
                else if (excessBreeders < 0) // shortfall breeders to buy
                {
                    double minBreedAge = breedParams.MinimumAge1stMating;
                    excessBreeders *= -1;
                    if ((foodStoreBreeders == null) || (sufficientFoodBreeders))
                    {
                        // remove grow out heifers from grow out herd to replace breeders
                        if (SellFemalesLikeMales)
                        {
                            foreach (Ruminant female in herd.Where(a => a.Tags.Contains("GrowHeifer")).OrderByDescending(a => a.Age))
                            {
                                female.Tags.Remove("GrowHeifer");
                                excessBreeders--;
                                if (excessBreeders == 0)
                                {
                                    break;
                                }
                            }
                        }

                        // remove young females from sale herd to replace breeders (not those sold because too old)
                        foreach (RuminantFemale female in herd.Where(a => a.Gender == Sex.Female && (a.SaleFlag == HerdChangeReason.AgeWeightSale || a.SaleFlag == HerdChangeReason.ExcessHeiferSale)).OrderByDescending(a => a.Age))
                        {
                            female.SaleFlag = HerdChangeReason.None;
                            excessBreeders--;
                            if (excessBreeders == 0)
                            {
                                break;
                            }
                        }

                        // if still insufficient buy breeders.
                        if (excessBreeders > 0 && (MaximumProportionBreedersPerPurchase > 0))
                        {
                            int ageOfBreeder = 0;

                            // IAT-NABSA had buy mortality base% more to account for deaths before these individuals grow to breeding age
                            // These individuals are already of breeding age so we will ignore this in CLEM
                            // minimum of (max kept x prop in single purchase) and (the number needed + annual mortality)
                            int numberToBuy             = Math.Min(excessBreeders, Convert.ToInt32(Math.Ceiling(MaximumProportionBreedersPerPurchase * MinimumBreedersKept), CultureInfo.InvariantCulture));
                            int numberPerPurchaseCohort = Convert.ToInt32(Math.Ceiling(numberToBuy / Convert.ToDouble(NumberOfBreederPurchaseAgeClasses, CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture);

                            int numberBought = 0;
                            while (numberBought < numberToBuy)
                            {
                                this.Status = ActivityStatus.Success;

                                int breederClass = Convert.ToInt32(numberBought / numberPerPurchaseCohort, CultureInfo.InvariantCulture);
                                ageOfBreeder = Convert.ToInt32(minBreedAge + (breederClass * 12), CultureInfo.InvariantCulture);

                                RuminantFemale newBreeder = new RuminantFemale(ageOfBreeder, Sex.Female, 0, breedParams)
                                {
                                    Location    = grazeStoreBreeders,
                                    Breed       = this.PredictedHerdBreed,
                                    HerdName    = this.PredictedHerdName,
                                    BreedParams = breedParams,
                                    Gender      = Sex.Female,
                                    ID          = 0,
                                    SaleFlag    = HerdChangeReason.BreederPurchase
                                };
                                // weight will be set to normalised weight as it was assigned 0 at initialisation
                                newBreeder.PreviousWeight = newBreeder.Weight;

                                // this individual must be weaned to be permitted to start breeding.
                                newBreeder.Wean(false, "Initial");
                                // add to purchase request list and await purchase in Buy/Sell
                                ruminantHerd.PurchaseIndividuals.Add(newBreeder);
                                numberBought++;
                            }
                        }
                    }
                }
                // Breeders themselves don't get sold unless specified in destocking groups below this activity. Sales is with Heifers
                // Breeders can be sold in seasonal and ENSO destocking.
                // sell breeders
                // What rule? oldest first as they may be lost soonest
                // should keep pregnant females... and young...
                // this will currently remove pregnant females and females with suckling calf
            }
        }
Exemple #37
0
        public void TestSummaryConcurrency(int n)
        {
            var random    = new Random(42);
            int mutations = (n % 10000) + 10000;
            int concLevel = (n % 5) + 1;
            int total     = mutations * concLevel;

            var sum = new Summary(new SummaryConfiguration("test_summary", "helpless", Array.Empty <string>(), false), Array.Empty <string>());

            var    allVars   = new double[total];
            double sampleSum = 0;
            var    tasks     = new List <Task>();

            for (int i = 0; i < concLevel; i++)
            {
                var vals = new double[mutations];
                for (int j = 0; j < mutations; j++)
                {
                    double v = random.NormDouble();
                    vals[j] = v;
                    allVars[(i * mutations) + j] = v;
                    sampleSum += v;
                }

                tasks.Add(Task.Run(() =>
                {
                    foreach (double v in vals)
                    {
                        sum.Observe(v);
                    }
                }));
            }

            Task.WaitAll(tasks.ToArray());

            Array.Sort(allVars);

            var m = sum.Value;

            Assert.Equal(mutations * concLevel, (int)m.Count);

            double got  = m.Sum;
            double want = sampleSum;

            Assert.True(Math.Abs(got - want) / want <= 0.001);

            var objectives = SummaryConfiguration.DefaultObjectives.Select(_ => _.Quantile).ToArray();

            Array.Sort(objectives);

            for (int i = 0; i < objectives.Length; i++)
            {
                var    wantQ   = SummaryConfiguration.DefaultObjectives.ElementAt(i);
                double epsilon = wantQ.Epsilon;
                double gotQ    = m.Quantiles[i].Key;
                double gotV    = m.Quantiles[i].Value;
                var    minMax  = GetBounds(allVars, wantQ.Quantile, epsilon);

                Assert.False(double.IsNaN(gotQ));
                Assert.False(double.IsNaN(gotV));
                Assert.False(double.IsNaN(minMax.Item1));
                Assert.False(double.IsNaN(minMax.Item2));

                Assert.Equal(wantQ.Quantile, gotQ);
                Assert.True(gotV >= minMax.Item1);
                Assert.True(gotV <= minMax.Item2);
            }
        }
        public void TestSummaryConcurrency(int n)
        {
            var random    = new Random(42);
            var mutations = n % 10000 + 10000L;
            var concLevel = (n / 10000) % 5 + 1;
            var total     = mutations * concLevel;

            var    sum       = new Summary("test_summary", "helpless", new string[0]);
            var    allVars   = new double[total];
            double sampleSum = 0;
            var    tasks     = new List <Task>();

            for (var i = 0; i < concLevel; i++)
            {
                var vals = new double[mutations];
                for (var j = 0; j < mutations; j++)
                {
                    var v = random.NormDouble();
                    vals[j] = v;
                    allVars[i * mutations + j] = v;
                    sampleSum += v;
                }

                tasks.Add(Task.Factory.StartNew(() =>
                {
                    foreach (var v in vals)
                    {
                        sum.Observe(v);
                    }
                }));
            }

            Task.WaitAll(tasks.ToArray());

            Array.Sort(allVars);

            var m = sum.Collect().Single().metric.Single().summary;

            Assert.AreEqual((ulong)(mutations * concLevel), m.sample_count);

            var got  = m.sample_sum;
            var want = sampleSum;

            Assert.IsTrue(Math.Abs(got - want) / want <= 0.001);

            var objectives = Summary.DefObjectives.Select(_ => _.Quantile).ToArray();

            Array.Sort(objectives);

            for (var i = 0; i < objectives.Length; i++)
            {
                var wantQ   = Summary.DefObjectives.ElementAt(i);
                var epsilon = wantQ.Epsilon;
                var gotQ    = m.quantile[i].quantile;
                var gotV    = m.quantile[i].value;
                var minMax  = GetBounds(allVars, wantQ.Quantile, epsilon);

                Assert.IsFalse(double.IsNaN(gotQ));
                Assert.IsFalse(double.IsNaN(gotV));
                Assert.IsFalse(double.IsNaN(minMax.Item1));
                Assert.IsFalse(double.IsNaN(minMax.Item2));

                Assert.AreEqual(wantQ.Quantile, gotQ);
                Assert.IsTrue(gotV >= minMax.Item1);
                Assert.IsTrue(gotV <= minMax.Item2);
            }
        }
        /// <summary>
        /// Create the individual ruminant animals using the Cohort parameterisations.
        /// </summary>
        /// <returns></returns>
        public List <Ruminant> CreateIndividuals()
        {
            List <Ruminant> individuals = new List <Ruminant>();

            RuminantType parent = Apsim.Parent(this, typeof(RuminantType)) as RuminantType;

            // get Ruminant Herd resource for unique ids
            RuminantHerd ruminantHerd = Resources.RuminantHerd();

            if (Number > 0)
            {
                for (int i = 1; i <= Number; i++)
                {
                    double u1            = ZoneCLEM.RandomGenerator.NextDouble();
                    double u2            = ZoneCLEM.RandomGenerator.NextDouble();
                    double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
                                           Math.Sin(2.0 * Math.PI * u2);
                    double weight = Weight + WeightSD * randStdNormal;
                    object ruminantBase;
                    if (this.Gender == Sex.Male)
                    {
                        ruminantBase = new RuminantMale(Age, Gender, weight, parent);
                    }
                    else
                    {
                        ruminantBase = new RuminantFemale(Age, Gender, weight, parent);
                    }

                    Ruminant ruminant = ruminantBase as Ruminant;
                    ruminant.ID       = ruminantHerd.NextUniqueID;
                    ruminant.Breed    = parent.Breed;
                    ruminant.HerdName = parent.Name;
                    ruminant.SaleFlag = HerdChangeReason.None;
                    if (Suckling)
                    {
                        ruminant.SetUnweaned();
                    }

                    if (Sire)
                    {
                        if (this.Gender == Sex.Male)
                        {
                            RuminantMale ruminantMale = ruminantBase as RuminantMale;
                            ruminantMale.BreedingSire = true;
                        }
                        else
                        {
                            Summary.WriteWarning(this, "Breeding sire switch is not valid for individual females [r=" + parent.Name + "].[r=" + this.Parent.Name + "].[r=" + this.Name + "]");
                        }
                    }

                    // if weight not provided use normalised weight
                    ruminant.PreviousWeight = ruminant.Weight;

                    if (this.Gender == Sex.Female)
                    {
                        RuminantFemale ruminantFemale = ruminantBase as RuminantFemale;
                        ruminantFemale.DryBreeder         = true;
                        ruminantFemale.WeightAtConception = ruminant.Weight;
                        ruminantFemale.NumberOfBirths     = 0;
                    }

                    individuals.Add(ruminantBase as Ruminant);
                }
            }

            return(individuals);
        }
 public string GetValue(Summary summary, Benchmark benchmark) => valueProvider(benchmark);
Exemple #41
0
 public virtual void VisitSummary(Summary summary)
 {
     VisitElements(summary);
 }
 public bool IsAvailable(Summary summary) => true;
Exemple #43
0
 public override void VisitSummary(Summary summary)
 {
     base.VisitSummary(summary);
       this.WriteLine("\r\n\r\n");
 }
 public bool IsDefault(Summary summary, Benchmark benchmark) => false;
        /// <summary>
        /// Deletes the object.
        /// </summary>
        public virtual void Delete(Summary deleteObject)
        {
            // create a new instance of the connection
            SqlConnection cnn = new SqlConnection(Summary.GetConnectionString());
            // create local variable array for the sql parameters
            SqlParameterHash sqlparams = null;

            try
            {
                // discover the parameters
                sqlparams =  SqlHelperParameterCache.GetSpParameterSet(Summary.GetConnectionString(), "gsp_DeleteSummary");

                // Store the parameter for the Id attribute.
                sqlparams["@id"].Value = deleteObject.Id;

                using (cnn)
                {
                    // open the connection
                    cnn.Open();

                    // Execute the stored proc to perform the delete on the instance.
                    SqlHelper.ExecuteNonQuery(cnn, CommandType.StoredProcedure, "gsp_DeleteSummary", sqlparams);

                    // close the connection after usage
                    cnn.Close();
                }

                // nullify the connection var
                cnn = null;
            }
            catch (SqlException sqlex)
            {
                throw sqlex;
            }

            // nullify the reference
            deleteObject = null;
        }
Exemple #46
0
        /// <summary>
        ///   Returns a graph of MDP States from the States matrices and Action label vector.
        /// </summary>
        /// <param name="states">State matrix.</param>
        /// <param name="actions">Action label vector.</param>
        /// <param name="statesP">Transition states matrix.</param>
        /// <param name="reward">Reward value vector.</param>
        /// <param name="properties">Feature properties from the original set.</param>
        /// <param name="discretizer">Discretization function for generating unique state identifiers.</param>
        /// <returns>IEnumerable&lt;IMDPState&gt;</returns>
        public static IEnumerable <MDPState> GetStates(
            Matrix states,
            Vector actions,
            Matrix statesP,
            Vector reward,
            Summary properties,
            IDiscretizer discretizer)
        {
            var summary = properties ?? Summary.Summarize(states);

            discretizer.Initialize(states, summary);

            var sdist   = new Dictionary <double, MDPState>();
            var adist   = new Dictionary <string, double>();
            var results = new Dictionary <double, MDPState>();

            for (var i = 0; i < states.Rows; i++)
            {
                var sid = discretizer.Discretize(states[i], summary);

                if (!sdist.ContainsKey(sid))
                {
                    sdist.Add(sid, GetState(states[i], summary, discretizer));
                    results.Add(sid, sdist[sid]);
                }

                var tsid   = discretizer.Discretize(statesP[i], summary);
                var tstate = sdist.ContainsKey(tsid) ? sdist[tsid] : GetState(statesP[i], summary, discretizer);

                if (!sdist.ContainsKey(tsid))
                {
                    sdist.Add(tsid, tstate);
                }

                var key = GetActionKey((int)sid, (int)tsid);

                if (!adist.ContainsKey(key))
                {
                    adist.Add(key, 1);
                }
                else
                {
                    adist[key]++;
                }

                sdist[sid].Successors.Add(
                    new MDPSuccessorState(GetAction(actions[i], (int)sid, (int)tsid), 0, tstate, reward[i]));

                if (results.ContainsKey(tsid))
                {
                    results.Remove(tsid);
                }
            }

            foreach (var state in sdist.Values)
            {
                var sum = state.Successors.Sum(s => adist[GetActionKey(state.Id, s.State.Id)]);
                foreach (var successor in state.Successors)
                {
                    var key = GetActionKey(state.Id, successor.State.Id);
                    ((Action)successor.Action).Probability = adist[key] / sum;
                }
            }

            // return starting states
            return(results.Values);
        }
 /// <summary>
 /// Persists the object.
 /// </summary>
 public virtual void Persist(Summary persistObject)
 {
     // Make a call to the overloaded method with a null transaction
     Persist(persistObject, null);
 }
Exemple #48
0
        Summary GetBestSetting(x360ce.Engine.SearchResult sr)
        {
            var sum = new Summary();

            for (int i = 0; i < sr.Settings.Length; i++)
            {
                // Look inside user settings.
                var s = sr.Settings[sr.Settings.Length - i - 1];
                for (int f = 0; f < _sp.Count; f++)
                {
                    // if instance, file name and file product name is match then...
                    if (s.InstanceGuid.Equals(_di.InstanceGuid) && _sp[f].FileName == s.FileName && _sp[f].FileProductName == s.FileProductName)
                    {
                        sum.DateUpdated        = s.DateUpdated;
                        sum.FileName           = GetTitle(s.FileName, s.FileProductName);
                        sum.PadSettingChecksum = s.PadSettingChecksum;
                        return(sum);
                    }
                }
                for (int f = 0; f < _sp.Count; f++)
                {
                    // if instance and file name match then...
                    if (s.InstanceGuid.Equals(_di.InstanceGuid) && _sp[f].FileName == s.FileName)
                    {
                        sum.DateUpdated        = s.DateUpdated;
                        sum.FileName           = GetTitle(s.FileName, s.FileProductName);
                        sum.PadSettingChecksum = s.PadSettingChecksum;
                        return(sum);
                    }
                }
                for (int f = 0; f < _sp.Count; f++)
                {
                    // if only instance match then...
                    if (s.InstanceGuid.Equals(_di.InstanceGuid))
                    {
                        sum.DateUpdated        = s.DateUpdated;
                        sum.FileName           = GetTitle(s.FileName, s.FileProductName);
                        sum.PadSettingChecksum = s.PadSettingChecksum;
                        return(sum);
                    }
                }
            }
            // Order so non empty names and most popular record will come first.
            var summaries = sr.Summaries.OrderByDescending(x => x.ProductName).ThenByDescending(x => x.FileName).ThenByDescending(x => x.FileProductName).ThenByDescending(x => x.Users).ToArray();

            for (int i = 0; i < summaries.Length; i++)
            {
                var s2 = summaries[i];
                // Look inside global settings.
                for (int f = 0; f < _sp.Count; f++)
                {
                    // if instance, file name and file product name is match then...
                    if (s2.ProductGuid.Equals(_di.ProductGuid) && _sp[f].FileName == s2.FileName && _sp[f].FileProductName == s2.FileProductName)
                    {
                        sum.DateUpdated        = s2.DateUpdated;
                        sum.FileName           = GetTitle(s2.FileName, s2.FileProductName);
                        sum.PadSettingChecksum = s2.PadSettingChecksum;
                        return(sum);
                    }
                }
                for (int f = 0; f < _sp.Count; f++)
                {
                    // if instance and file name match then...
                    if (s2.ProductGuid.Equals(_di.ProductGuid) && _sp[f].FileName == s2.FileName)
                    {
                        sum.DateUpdated        = s2.DateUpdated;
                        sum.FileName           = GetTitle(s2.FileName, s2.FileProductName);
                        sum.PadSettingChecksum = s2.PadSettingChecksum;
                        return(sum);
                    }
                }
                for (int f = 0; f < _sp.Count; f++)
                {
                    // if only instance match then...
                    if (s2.ProductGuid.Equals(_di.ProductGuid))
                    {
                        sum.DateUpdated        = s2.DateUpdated;
                        sum.FileName           = GetTitle(s2.FileName, s2.FileProductName);
                        sum.PadSettingChecksum = s2.PadSettingChecksum;
                        return(sum);
                    }
                }
            }
            return(null);
        }
Exemple #49
0
		/// <summary>
		/// GetRoomからのみ呼ばれる想定です。
		/// </summary>
		/// <param name="summary"></param>
		/// <param name="messages"></param>
		private void NewMessage(Summary summary, IEnumerable<Message> messages) {
			foreach (var message in messages) {
				if (message.IsAuth && String.IsNullOrWhiteSpace(message.Name) == false) {
					// アカウント情報を更新
					var account = Model.Account.GetAccount(message.Name);
					if (account == null) {
						account = new Model.Account {
							AccountName = message.Name,
						};
						Model.Account.UpdateAccount(account);
					}
				}

				if (String.IsNullOrWhiteSpace(message.ListenerId) == false) {
					// リスナーが存在しなければ追加します。
					var listener = Model.Listener.GetListener(message.ListenerId);
					if (listener == null || (String.IsNullOrWhiteSpace(listener.ListenerId) == false && message.IsAuth)) {
						listener = new Model.Listener {
							ListenerId = message.ListenerId,
							Name = String.IsNullOrWhiteSpace(message.Name) == false ? message.Name : null,
							Author = summary.Author,
							AccountName = message.IsAuth ? message.Name : null,
						};
						Model.Listener.UpdateListener(listener);
					}
				}
			}

			// DBのコメント情報を更新します。
			var dbMessage = messages.Select(message => new Model.Message {
				RoomId = summary.RoomId,
				Number = message.Number,
				Name = message.Name,
				Comment = message.Comment,
				IsAuth = message.IsAuth,
				IsBan = message.IsBan,
				PostTime = message.PostTime,
				ListenerId = message.ListenerId,
			});
			Model.Message.UpdateMessage(dbMessage);
		}
Exemple #50
0
        /// <summary>
        /// Finds the closest Value of categorised lookup values form the database
        /// This applies to Stocking rates, Grass Basal Area (or use GBA) and Land Condition
        /// The Pasture database does not have every stocking rate, grass basal area or land condition.
        /// It will find the category with the next largest value to the actual value supplied.
        /// So if the value is 0 the category with the next largest value will normally be the first entry
        /// </summary>
        /// <param name="category">The name of the distict categories to use</param>
        /// <param name="value">The value to search for</param>
        /// <returns></returns>
        private double FindClosestCategory(string category, double value)
        {
            double[] valuesToUse;
            switch (category)
            {
            case "StockingRate":
                valuesToUse = distinctStkRates;
                if (valuesToUse.Max() > 100 | valuesToUse.Min() < 0)
                {
                    // add warning
                    string warn = $"Suspicious values for [{category}] found in pasture database [x={this.Name}]";
                    if (!Warnings.Exists(warn))
                    {
                        string warnfull = $"Suspicious values for [{category}] found in pasture database [x={this.Name}]\nValues in database: [{string.Join("],[", valuesToUse.Select(a => a.ToString()).ToArray())}]\nExpecting values between 1 and 100";
                        Summary.WriteWarning(this, warnfull);
                        Warnings.Add(warn);
                    }
                }
                break;

            case "GrassBasalArea":
            case "GBA":
                valuesToUse = distinctGBAs;
                if (valuesToUse.Max() > 10 | valuesToUse.Min() < 0)
                {
                    // add warning
                    string warn = $"Suspicious values for [{category}] found in pasture database [x={this.Name}]";
                    if (!Warnings.Exists(warn))
                    {
                        string warnfull = $"Suspicious values for [{category}] found in pasture database [x={this.Name}]\nValues in database: [{string.Join("],[", valuesToUse.Select(a => a.ToString()).ToArray())}]\nExpecting values between 0 and 10";
                        Summary.WriteWarning(this, warnfull);
                        Warnings.Add(warn);
                    }
                }
                break;

            case "LandCondition":
                valuesToUse = distinctLandConditions;
                if (valuesToUse.Max() > 11 | valuesToUse.Min() < 0)
                {
                    // add warning
                    string warn = $"Suspicious values for [{category}] found in pasture database [x={this.Name}]";
                    if (!Warnings.Exists(warn))
                    {
                        string warnfull = $"Suspicious values for [{category}] found in pasture database [x={this.Name}]\nValues in database: [{string.Join("],[", valuesToUse.Select(a => a.ToString()).ToArray())}]\nExpecting values between 1 and 11";
                        Summary.WriteWarning(this, warnfull);
                        Warnings.Add(warn);
                    }
                }
                break;

            default:
                throw new ApsimXException(this, $"Unknown pasture data category [{category}] used in code behind [x={this.Name}]");
            }

            if (valuesToUse.Count() == 0)
            {
                throw new ApsimXException(this, $"Unable to find any values for [{category}] in [x={this.Name}]");
            }

            int index = Array.BinarySearch(valuesToUse, value);

            if (~index >= valuesToUse.Count())
            {
                // add warning
                string warn = $"Unable to find a [{category}] value greater than the specified value in pasture database [x={this.Name}]";
                if (!Warnings.Exists(warn))
                {
                    string warnfull = $"Unable to find a [{category}] value greater than the specified [{value:0.##}] in pasture database [x={this.Name}]\nKnown values in database: [{string.Join("],[", valuesToUse.Select(a => a.ToString()).ToArray())}]\nUsed: [{valuesToUse.Last()}]\nFix: Ensure the pasture database includes a [{category}] greater than values produced in this simulation for optimal results.";
                    Summary.WriteWarning(this, warnfull);
                    Warnings.Add(warn);
                }
                index = valuesToUse.Count() - 1;
            }
            return((index < 0) ? valuesToUse[~index] : valuesToUse[index]);
        }
Exemple #51
0
 public string GetValue(Summary summary, Benchmark benchmark)
 => Results.TryGetValue(benchmark, out var stats) && stats.Counters.ContainsKey(Counter)
         ? (stats.Counters[Counter].Count / (ulong)stats.TotalOperations).ToString()
         : "-";
Exemple #52
0
        /// <summary>
        /// Queries the the Pasture SQLite database using the specified parameters.
        /// </summary>
        /// <param name="region"></param>
        /// <param name="soil"></param>
        /// <param name="grassBasalArea"></param>
        /// <param name="landCondition"></param>
        /// <param name="stockingRate"></param>
        /// <param name="ecolCalculationDate"></param>
        /// <param name="ecolCalculationInterval"></param>
        /// <returns></returns>
        public List <PastureDataType> GetIntervalsPastureData(int region, string soil, double grassBasalArea, double landCondition, double stockingRate,
                                                              DateTime ecolCalculationDate, int ecolCalculationInterval)
        {
            List <PastureDataType> pastureDetails = new List <PastureDataType>();

            if (validationResults.Count > 0 | ecolCalculationDate > clock.EndDate)
            {
                return(pastureDetails);
            }

            int      startYear  = ecolCalculationDate.Year;
            int      startMonth = ecolCalculationDate.Month;
            DateTime endDate    = ecolCalculationDate.AddMonths(ecolCalculationInterval + 1);

            if (endDate > clock.EndDate)
            {
                endDate = clock.EndDate;
            }
            int endYear  = endDate.Year;
            int endMonth = endDate.Month;

            double stkRateCategory        = FindClosestCategory("StockingRate", stockingRate);
            double grassBasalAreaCategory = FindClosestCategory("GBA", grassBasalArea);
            double landConditionCategory  = FindClosestCategory("LandCondition", landCondition);

            string sqlQuery = "SELECT " +
                              YearColumnName + ", " +
                              MonthColumnName + "," +
                              GrowthColumnName;

            if (ErosionColumnName != null && ErosionColumnName != "")
            {
                sqlQuery += "," + ErosionColumnName;
            }
            if (RunoffColumnName != null || RunoffColumnName != "")
            {
                sqlQuery += "," + RunoffColumnName;
            }
            if (RainfallColumnName != null || RainfallColumnName != "")
            {
                sqlQuery += "," + RainfallColumnName;
            }
            if (CoverColumnName != null || CoverColumnName != "")
            {
                sqlQuery += "," + CoverColumnName;
            }
            if (TBAColumnName != null || TBAColumnName != "")
            {
                sqlQuery += "," + TBAColumnName;
            }

            sqlQuery += " FROM " + TableName +
                        " WHERE " + RegionColumnName + " = " + region +
                        " AND " + LandIdColumnName + " = " + soil +
                        " AND " + GrassBAColumnName + " = " + grassBasalAreaCategory +
                        " AND " + LandConColumnName + " = " + landConditionCategory +
                        " AND " + StkRateColumnName + " = " + stkRateCategory;

            if (shuffler != null)
            {
                int shuffleStartYear = shuffler.ShuffledYears.Where(a => a.Year == startYear).FirstOrDefault().RandomYear;
                int shuffleEndYear   = shuffler.ShuffledYears.Where(a => a.Year == endYear).FirstOrDefault().RandomYear;

                // first year
                sqlQuery += " AND (( " + YearColumnName + " = " + shuffleStartYear + " AND " + MonthColumnName + " >= " + startMonth + ")";

                // any middle years
                for (int i = startYear + 1; i < endYear; i++)
                {
                    sqlQuery += " OR ( " + YearColumnName + " = " + shuffler.ShuffledYears[i] + ")";
                }

                //last year
                sqlQuery += " OR ( " + YearColumnName + " = " + shuffleEndYear + " AND " + MonthColumnName + " <= " + endMonth + "))";
            }
            else
            {
                if (startYear == endYear)
                {
                    sqlQuery += " AND (( " + YearColumnName + " = " + startYear + " AND " + MonthColumnName + " >= " + startMonth + " AND " + MonthColumnName + " < " + endMonth + ")"
                                + ")";
                }
                else
                {
                    sqlQuery += " AND (( " + YearColumnName + " = " + startYear + " AND " + MonthColumnName + " >= " + startMonth + ")"
                                + " OR  ( " + YearColumnName + " > " + startYear + " AND " + YearColumnName + " < " + endYear + ")"
                                + " OR  ( " + YearColumnName + " = " + endYear + " AND " + MonthColumnName + " < " + endMonth + ")"
                                + ")";
                }
            }

            DataTable results = SQLiteReader.ExecuteQuery(sqlQuery);

            if (results.Rows.Count == 0)
            {
                switch (MissingDataAction)
                {
                case OnMissingResourceActionTypes.ReportWarning:
                    // this is no longer an error to allow situations where there is no pasture production reported in a given period
                    string warn = $"No pasture production for was found for [{startMonth}/{startYear}] by [x={this.Name}]";
                    if (!Warnings.Exists(warn))
                    {
                        Summary.WriteWarning(this, warn + $"\nGiven Region id: [{region}], Land id: [{soil}], Grass Basal Area: [{grassBasalAreaCategory}], Land Condition: [{landConditionCategory}] & Stocking Rate: [{stkRateCategory}]");
                        Warnings.Add(warn);
                    }
                    break;

                default:
                    break;
                }
                return(null);
            }

            // re-label shuffled years
            if (shuffler != null)
            {
                foreach (DataRow row in results.Rows)
                {
                    row["Year"] = shuffler.ShuffledYears.Where(a => a.RandomYear == Convert.ToInt32(row["Year"])).FirstOrDefault().Year;
                }
            }

            results.DefaultView.Sort = YearColumnName + ", " + MonthColumnName;

            foreach (DataRowView row in results.DefaultView)
            {
                pastureDetails.Add(DataRow2PastureDataType(row));
            }

            CheckAllMonthsWereRetrieved(pastureDetails, ecolCalculationDate, endDate,
                                        region, soil, grassBasalAreaCategory, landConditionCategory, stkRateCategory);

            return(pastureDetails);
        }
 public override void VisitSummary(Summary summary)
 {
     _builder.AppendLine();
     base.VisitSummary(summary);
     _builder.AppendLine();
     _builder.AppendLine();
 }
Exemple #54
0
        public ActionResult Index()
        {
            var summary = new Summary();

            return(View(summary));
        }
 public override void ReadFragmentFrom(IMwsReader reader)
 {
     _marketplaceID = reader.ReadAttribute<string>("MarketplaceID");
     _asin = reader.ReadAttribute<string>("ASIN");
     _itemCondition = reader.ReadAttribute<string>("ItemCondition");
     _status = reader.ReadAttribute<string>("status");
     _identifier = reader.Read<GetLowestPricedOffersAsinIdentifier>("Identifier");
     _summary = reader.Read<Summary>("Summary");
     _offers = reader.Read<ASINOfferDetailList>("Offers");
 }
Exemple #56
0
 protected override IEnumerable <Conclusion> AnalyseReport(BenchmarkReport report, Summary summary)
 {
     if (report.BenchmarkCase.Descriptor.Type.GetTypeInfo().Assembly.IsJitOptimizationDisabled().IsTrue())
     {
         yield return(CreateWarning("Benchmark was built without optimization enabled (most probably a DEBUG configuration). Please, build it in RELEASE.", report));
     }
 }
        public Summary CreateSummary(string name, string help, params string[] labelNames)
        {
            var metric = new Summary(name, help, labelNames);

            return((Summary)_registry.GetOrAdd(metric));
        }
Exemple #58
0
 /// <summary>Gets competition options columns.</summary>
 /// <param name="summary">The summary.</param>
 /// <returns>The competition options columns</returns>
 public IEnumerable <IColumn> GetColumns(Summary summary) => CompetitionCharacteristicColumn.AllColumns;
Exemple #59
0
        public Summary GetSummary()
        {
            var summary = new Summary();

            summary.TotalTimeTaken = wrex.TotalTimeTaken;
            summary.SampleResponse = wrex.SampleResponse;
            summary.FastestTime = TimeSpan.FromTicks(wrex.Results.Min(x => x.TimeTaken.Ticks));
            summary.SlowestTime = TimeSpan.FromTicks(wrex.Results.Max(x => x.TimeTaken.Ticks));
            summary.AverageTime = TimeSpan.FromTicks((long)wrex.Results.Average(x => x.TimeTaken.Ticks));
            summary.RequestsPerSecond =
                (int)(wrex.Options.NumberOfRequests / ((double)wrex.TotalTimeTaken.Ticks / TimeSpan.TicksPerSecond));

            summary.TotalDataReceivedInBytes = wrex.TotalTransferedBytes;

            return summary;
        }
Exemple #60
0
 public IEnumerable <IColumn> GetColumns(Summary summary)
 {
     yield return(new RankColumn(NumeralSystem.Arabic));
 }