public string[] GetSlideSource() { if (!String.IsNullOrEmpty(Comment)) { if (MonthlyData.Any()) { return new[] { "comments", String.Format("monthly{0}.pptx", !String.IsNullOrEmpty(InvestmentDetails) ? "_inv" : String.Empty) } } ; if (TotalData.Any()) { return new[] { "comments", String.Format("total{0}.pptx", !String.IsNullOrEmpty(InvestmentDetails) ? "_inv" : String.Empty) } } ; return(new[] { "comments", String.Format("none{0}.pptx", !String.IsNullOrEmpty(InvestmentDetails) ? "_inv" : String.Empty) }); } else { if (MonthlyData.Any()) { return new[] { "no_comments", String.Format("monthly{0}.pptx", !String.IsNullOrEmpty(InvestmentDetails) ? "_inv" : String.Empty) } } ; if (TotalData.Any()) { return new[] { "no_comments", String.Format("total{0}.pptx", !String.IsNullOrEmpty(InvestmentDetails) ? "_inv" : String.Empty) } } ; return(new[] { "no_comments", String.Format("none{0}.pptx", !String.IsNullOrEmpty(InvestmentDetails) ? "_inv" : String.Empty) }); } }
public void StoreData(string userId, string teamId, MonthlyData data) { using (var connection = new SqliteConnection(connectionString)) { connection.Execute(@"replace into MonthlyData (UserId, TeamId, Month, TotalHa, AvgMaxalt, AvgAleve) values (@userId, @teamId, @month, @total, @avgMaxalt, @avgAleve", new { userId, teamId, month = data.Month, total = data.TotalHa, avgMaxalt = data.AvgMaxalt, avgAleve = data.AvgAleve }); } }
private FrameworkElement getMonthDataChart(DateTime yearMonth, MonthlyData data) { if (monthlyDataChartCache.ContainsKey(yearMonth)) { return(monthlyDataChartCache[yearMonth]); } var re = (FrameworkElement)((DataTemplate)Resources["ChartTemplate"]).LoadContent(); re.DataContext = getMonthData(yearMonth, data); monthlyDataChartCache[yearMonth] = re; return(re); }
private List <CalendarEvent> BuildDays(string userName, DateTime startDate) { var metrics = new MonthlyData(userName, startDate); var daysOfMonth = new List <CalendarEvent>(); int startOffset = (int)startDate.DayOfWeek; //Sunday = 0 for (int i = 0; i < startOffset; i++) { daysOfMonth.Add(new CalendarEvent()); //Blanks to pad before the first starts } //Actual days in the month var endDate = startDate.AddMonths(1).AddDays(-1); for (int i = 1; i <= endDate.Day; i++) { var dayEvents = new CalendarEvent { Day = i, Events = new List <TimelineEvent>() }; var day = i; var daysActivities = metrics.Activities.Where(e => e.Date.Date == new DateTime(startDate.Year, startDate.Month, day).Date); foreach (var activity in daysActivities) { var myEvent = new TimelineEvent(); var speed = Math.Round((activity.Duration.ToMinutes() / activity.Distance.ToMiles(activity.Unit.Name)), 2); myEvent.Pace = speed.ToDuration(); myEvent.Time = activity.Duration; myEvent.Distance = activity.Distance.ToMiles(activity.Unit.Name).ToFriendlyDistance(); myEvent.Race = activity.Title; myEvent.Notes = activity.Notes; dayEvents.Events.Add(myEvent); } daysOfMonth.Add(dayEvents); } //Pad any extra spaces to multiples of 7 for (int i = 0; i < daysOfMonth.Count % 7; i++) { daysOfMonth.Add(new CalendarEvent()); } return(daysOfMonth); }
/// <summary> /// Whenever we change the "selected" month (by clicking on one of the Total Cashflow chart /// items), we need to update some variables and some UI stuff. /// </summary> /// <param name="monthlyData"></param> private void UpdateMonthlyDetailsUI(MonthlyData monthlyData) { // Set the SelectedIndex. This is the currently-selected month. This index is used // to show the highlights on the top chart(s) and also in the Overview charts for // Inflow and Outflow. // this.SelectedIndex = DataManager.MonthlyData.IndexOf(monthlyData); // Update the Inflow and Outflow sections on the bottom. This tells them to update // the scroll position and highlight drawing on the Overview charts. // this.cfdInflow.UpdateData(this.selectedIndex, this.crtMonthlyTotals.WindowPositionHorizontal); this.cfdOutflow.UpdateData(this.selectedIndex, this.crtMonthlyTotals.WindowPositionHorizontal); }
/// <summary> /// This method is called when a new month is selected in the TotalCashflow chart on the /// main form. /// </summary> /// <param name="selectedIndex">The index of the "selected" month. This is so we can select the same month in the Overview chart.</param> /// <param name="scrollPositionOfOverviewChart">The scroll position of the TotalCashflowChart so we can synchronize the scrolling of the Overview chart.</param> public void UpdateData(int selectedIndex, double scrollPositionOfOverviewChart) { // Set the SelectedIndex. We need to store this here so that we can draw an overlay // on the selected item when the Overview chart paints. this.SelectedIndex = selectedIndex; // Get the month data for the current month, previous month, and previous year and // cache these values. this.currentMonthData = DataManager.MonthlyData[this.SelectedIndex]; DateTime current = new DateTime(currentMonthData.Year, currentMonthData.Month, 1); DateTime previousMonth = current.AddMonths(-1); this.lastMonthData = DataManager.GetMonthlyData(previousMonth.Month, previousMonth.Year); DateTime previousYear = current.AddYears(-1); this.lastYearData = DataManager.GetMonthlyData(previousYear.Month, previousYear.Year); // Check to see if the MonthlyData.Activities have changed. if (this.grdCashflowSources.DataSource != currentMonthData.Activities) { // Bind the grid to the Activities of the current month data. this.grdCashflowSources.SetDataBinding(currentMonthData.Activities, null); // Autosize the grid columns so that all of the data fits. this.grdCashflowSources.DisplayLayout.PerformAutoResizeColumns(false, PerformAutoSizeType.AllRowsInBand, AutoResizeColumnWidthOptions.All); // Create a BindingList that contains last year, the current month, and last months data. // This will be used as the DataSource for the chart so we can show one stack for each. BindingList <MonthlyData> monthlyDatas = new BindingList <MonthlyData>() { this.lastYearData, this.currentMonthData, this.lastMonthData }; // Update the data source of the Category Chart Y Axis and StackedBarSeries. this.categoryChartChartCategoryY.DataSource = monthlyDatas; this.categoryChartStackedBarSeries.DataSource = monthlyDatas; // Set the scroll position of the Overview chart. this.crtOverview.WindowPositionHorizontal = scrollPositionOfOverviewChart; } // Force the overview chart to refresh. this.ForceOverviewChartRefresh(); }
/// <summary> /// Handles the MouseUp event for all three of the chart that make up the TotalCashflow chart. /// Clicking on any one of these chart will "select" that month. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void crtTtalCashflow_MouseUp(object sender, MouseEventArgs e) { // Determine which item was clicked var series = crtEndingCash.Series.OfType <CategorySeries>().First(); var index = series.GetExactItemIndexFromSeriesPixel(new Infragistics.Win.DataVisualization.Point(e.X, 0)); index = Math.Round(index); // Set the selected month. this.SelectedIndex = (int)index; // Update the monthly details UI. MonthlyData monthlyData = DataManager.MonthlyData[this.SelectedIndex]; if (null != monthlyData) { this.UpdateMonthlyDetailsUI(monthlyData); } }
public static List<MonthlyData> GetOrderMonthlyCount(string SalonId, string queryYear) { _listMonthlyData.Clear(); int nSalonId = int.Parse(SalonId); int nYear = int.Parse(queryYear); string[] LastDate; if ((nYear % 4 == 0 && nYear % 100 != 0) || (nYear % 400 == 0)) { LastDate = new string[12] { "31", "29", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31" }; } else { LastDate = new string[12] {"31","28","31","30","31","30","31","31","30","31","30","31"}; } string[] Month = new string[12] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" }; //DateTime startDate = Convert.ToDateTime(queryYear+"-01-01"); //DateTime endDate = Convert.ToDateTime(queryYear + "-12-31"); for (int k = 0; k < LastDate.Length; k++) { string sStartDate = "", sEndDate = ""; sStartDate = queryYear + "-" + Month[k]+"-01"; sEndDate = queryYear + "-" + Month[k] + "-"+LastDate[k]; string sqlcmd = "SELECT COUNT(DetailID) FROM " + DBName1 + ".ezOrderDetail WHERE Status = 1 AND BookingDate >= " + "'" + sStartDate + "'" + " AND BookingDate <= " + "'" + sEndDate + "'" + " AND SalonID = " + nSalonId; DataTable dt1 = DBOperate.SelectFromTable(DBconnect, sqlcmd); MonthlyData mData = new MonthlyData(); mData.monthID = k+1; DataRow dr = dt1.Rows[0]; mData.orderCount = (int)dr.ItemArray[0]; _listMonthlyData.Add(mData); } return _listMonthlyData; }
public async Task <IActionResult> Index() { var model = new IndexViewModel(); //当前用户 var userId = UserIdentifier.UserId; //用于过滤导入数据的时间界限 var setupTime = DateTime.Parse("2020-05-21 00:00:00"); #region 参数设置 // 今日起始时间 var startTime = DateTime.Now.Date; // 今日结束时间 var endTime = startTime.AddDays(1); // 本月起始时间 var thisMonthStartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM")); // 本月结束时间 var thisMonthEndTime = thisMonthStartTime.AddMonths(1); int dayOfWeek = (int)DateTime.Now.DayOfWeek; // 本周起始时间 var thisWeekStartTime = DateTime.Now.Date.AddDays(1 - dayOfWeek); var thisWeekEndTime = DateTime.Now.Date.AddDays(8 - dayOfWeek); // 今年 var thisYearStartTime = new DateTime(DateTime.Now.Year, 1, 1); var thisYeasEndTime = thisYearStartTime.AddYears(1); #endregion #region 统计数据 var monthlyIncreaseData = new MonthlyIncreaseData(); var todayResumeData = new TodayResumeData(); var todayInvestigationData = new TodayInvestigationData(); // 简历 var yearlyResumes = await _resumeQuerier.GetStatisticResumesAsync(thisYearStartTime, thisYeasEndTime, null); // 个人月简历总数量/月全部简历数量 monthlyIncreaseData.NewResumeCount = yearlyResumes.Where(w => w.CreationTime >= thisMonthStartTime && w.CreationTime < thisMonthEndTime).Count(w => w.CreatorUserId == userId); monthlyIncreaseData.NewResumeTotalCount = yearlyResumes.Where(w => w.CreationTime >= thisMonthStartTime && w.CreationTime < thisMonthEndTime).Count(); // 简历审核情况统计 if (CustomSetting.DefaultOnlySeeMyselfData) { var todayResumes = yearlyResumes.Where(w => w.CreatorUserId == userId && w.CreationTime >= startTime && w.CreationTime <= endTime).ToList(); todayResumeData.PassedCount = todayResumes.Count(w => w.AuditStatus == AuditStatus.Complete); todayResumeData.UnhandledCount = todayResumes.Count(w => w.AuditStatus == AuditStatus.NoStart || w.AuditStatus == AuditStatus.Ongoing); todayResumeData.UnpassedCount = todayResumes.Count - todayResumeData.PassedCount - todayResumeData.UnhandledCount; } else { var todayResumes = yearlyResumes.Where(w => w.CreationTime >= startTime && w.CreationTime <= endTime).ToList(); todayResumeData.PassedCount = todayResumes.Count(w => w.AuditStatus == AuditStatus.Complete); todayResumeData.UnhandledCount = todayResumes.Count(w => w.AuditStatus == AuditStatus.NoStart || w.AuditStatus == AuditStatus.Ongoing); todayResumeData.UnpassedCount = todayResumes.Count - todayResumeData.PassedCount - todayResumeData.UnhandledCount; } // 调查 var yearlyInvestigations = await _investigationQuerier.GetStatisticInvestigationsAsync(thisYearStartTime, thisYeasEndTime); // 个人月调查总数量/月全部调查数量 monthlyIncreaseData.NewInvestigationCount = yearlyInvestigations.Where(w => w.CreationTime >= thisMonthStartTime && w.CreationTime < thisMonthEndTime).Count(w => w.OwnerUserId == userId); monthlyIncreaseData.NewInvestigationTotalCount = yearlyInvestigations.Where(w => w.CreationTime >= thisMonthStartTime && w.CreationTime < thisMonthEndTime).Count(); // 调查情况统计 if (CustomSetting.DefaultOnlySeeMyselfData) { var todayInvestigations = yearlyInvestigations.Where(w => w.OwnerUserId == userId && w.CreationTime >= startTime && w.CreationTime <= endTime).ToList(); todayInvestigationData.AcceptCount = todayInvestigations.Count(w => w.AcceptTravelStatus == AcceptTravelStatus.Accept); todayInvestigationData.RefuseCount = todayInvestigations.Count(w => w.AcceptTravelStatus == AcceptTravelStatus.Refuse); todayInvestigationData.ConsiderCount = todayInvestigations.Count(w => w.AcceptTravelStatus == AcceptTravelStatus.Consider); todayInvestigationData.MissedCount = todayInvestigations.Count(w => w.IsConnected == false); } else { var todayInvestigations = yearlyInvestigations.Where(w => w.CreationTime >= startTime && w.CreationTime <= endTime).ToList(); todayInvestigationData.AcceptCount = todayInvestigations.Count(w => w.AcceptTravelStatus == AcceptTravelStatus.Accept); todayInvestigationData.RefuseCount = todayInvestigations.Count(w => w.AcceptTravelStatus == AcceptTravelStatus.Refuse); todayInvestigationData.ConsiderCount = todayInvestigations.Count(w => w.AcceptTravelStatus == AcceptTravelStatus.Consider); todayInvestigationData.MissedCount = todayInvestigations.Count(w => w.IsConnected == false); } model.MonthlyIncreaseData = monthlyIncreaseData; model.TodayResumeData = todayResumeData; model.TodayInvestigationData = todayInvestigationData; // 预约 var monthlyInterviews = await _interviewQuerier.GetStatisticInterviewsAsync(thisMonthStartTime, thisMonthEndTime); // 个人月预约总数量/月全部预约数量 monthlyIncreaseData.NewInterviewCount = monthlyInterviews.Count(w => w.CreatorUserId == userId); monthlyIncreaseData.NewInterviewTotalCount = monthlyInterviews.Count; // 月简历统计图 var monthlyResumes = yearlyResumes.Where(w => w.CreationTime > thisMonthStartTime && w.CreationTime <= thisMonthEndTime); var resumeMonthlyData = new MonthlyData() { Labels = new List <string>(), Datasets = new List <StatisticsModel>() }; var dayCount = (thisMonthEndTime - thisMonthStartTime).TotalDays; for (int i = 0; i < dayCount; i++) { resumeMonthlyData.Labels.Add(thisMonthStartTime.AddDays(i).ToString("yyyy-MM-dd")); } var createdNameMonthlyResumesResumeGroups = monthlyResumes.GroupBy(g => g.CreatorUserName); foreach (var group in createdNameMonthlyResumesResumeGroups) { var resumesByGroup = monthlyResumes.Where(w => w.CreatorUserName == group.Key).ToList(); var values = new List <int>(); for (int i = 0; i < dayCount; i++) { DateTime s = thisMonthStartTime.AddDays(i), e = thisMonthStartTime.AddDays(i + 1); var count = resumesByGroup.Count(w => w.CreationTime >= s && w.CreationTime < e); values.Add(count); } resumeMonthlyData.Datasets.Add(new StatisticsModel() { Label = group.Key, Values = values }); } model.ResumeMonthlyData = resumeMonthlyData; // 月调查统计图 var handledNameMonthlyInvestigations = yearlyInvestigations.Where(w => w.CreationTime > thisMonthStartTime && w.CreationTime <= thisMonthEndTime); var investigationMonthlyData = new MonthlyData() { Labels = new List <string>(), Datasets = new List <StatisticsModel>() }; for (int i = 0; i < dayCount; i++) { investigationMonthlyData.Labels.Add(thisMonthStartTime.AddDays(i).ToString("yyyy-MM-dd")); } var handledNameMonthlyInvestigationGroups = handledNameMonthlyInvestigations.GroupBy(g => g.OwnerUserName); foreach (var group in handledNameMonthlyInvestigationGroups) { var investigationByGroup = handledNameMonthlyInvestigations.Where(w => w.OwnerUserName == group.Key).ToList(); var values = new List <int>(); for (int i = 0; i < dayCount; i++) { DateTime s = thisMonthStartTime.AddDays(i), e = thisMonthStartTime.AddDays(i + 1); var count = investigationByGroup.Count(w => w.CreationTime >= s && w.CreationTime < e); values.Add(count); } investigationMonthlyData.Datasets.Add(new StatisticsModel() { Label = group.Key, Values = values }); } model.InvestigaionMonthlyData = investigationMonthlyData; // 简历排行榜 var resumeRankData = new RankData() { YearlyUserRanks = new List <UserRankData>(), MonthlyUserRanks = new List <UserRankData>(), WeekUserRanks = new List <UserRankData>(), DayUserRanks = new List <UserRankData>() }; var creatorYearlyResumesResumeGroups = yearlyResumes.GroupBy(g => g.CreatorUserName); foreach (var group in creatorYearlyResumesResumeGroups) { string photo = string.Empty; if (group.First() != null) { photo = group.First()?.CreatorUserPhoto; } //年 var yearlyResumesByGroup = yearlyResumes.Where(w => w.CreatorUserName == group.Key).ToList(); if (yearlyResumesByGroup.Count > 0) { resumeRankData.YearlyUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = yearlyResumesByGroup.Count, QualifiedCount = yearlyResumesByGroup.Count(c => c.AuditStatus == AuditStatus.Complete), Photo = photo }); } // 月 var mothlyResumesByGroup = yearlyResumes.Where(w => w.CreatorUserName == group.Key && w.CreationTime >= thisMonthStartTime && w.CreationTime < thisMonthEndTime).ToList(); if (mothlyResumesByGroup.Count > 0) { resumeRankData.MonthlyUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = mothlyResumesByGroup.Count, QualifiedCount = mothlyResumesByGroup.Count(c => c.AuditStatus == AuditStatus.Complete), Photo = photo }); } // 周 var weekResumesByGroup = yearlyResumes.Where(w => w.CreatorUserName == group.Key && w.CreationTime >= thisWeekStartTime && w.CreationTime < thisWeekEndTime).ToList(); if (weekResumesByGroup.Count > 0) { resumeRankData.WeekUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = weekResumesByGroup.Count, QualifiedCount = weekResumesByGroup.Count(c => c.AuditStatus == AuditStatus.Complete), Photo = photo }); } // 天 var dayResumesByGroup = yearlyResumes.Where(w => w.CreatorUserName == group.Key && w.CreationTime >= startTime && w.CreationTime < endTime).ToList(); if (dayResumesByGroup.Count > 0) { resumeRankData.DayUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = dayResumesByGroup.Count, QualifiedCount = dayResumesByGroup.Count(c => c.AuditStatus == AuditStatus.Complete), Photo = photo }); } } model.ResumeRankData = resumeRankData; // 调查排行榜 var investigationRankData = new RankData() { YearlyUserRanks = new List <UserRankData>(), MonthlyUserRanks = new List <UserRankData>(), WeekUserRanks = new List <UserRankData>(), DayUserRanks = new List <UserRankData>() }; var ownerYearlyInvestigationGroups = yearlyInvestigations.GroupBy(g => g.OwnerUserName); foreach (var group in ownerYearlyInvestigationGroups) { string photo = string.Empty; if (group.First() != null) { photo = group.First()?.OwnerUserPhoto; } // 年 var yearlyInvestigationsByGroup = yearlyInvestigations.Where(w => w.OwnerUserName == group.Key).ToList(); if (yearlyInvestigationsByGroup.Count > 0) { investigationRankData.YearlyUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = yearlyInvestigationsByGroup.Count, QualifiedCount = yearlyInvestigationsByGroup.Count(c => c.AcceptTravelStatus == AcceptTravelStatus.Accept), Photo = photo }); } // 月 var mothlyInvestigationsByGroup = yearlyInvestigations.Where(w => w.OwnerUserName == group.Key && w.CreationTime >= thisMonthStartTime && w.CreationTime < thisMonthEndTime).ToList(); if (mothlyInvestigationsByGroup.Count > 0) { investigationRankData.MonthlyUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = mothlyInvestigationsByGroup.Count, QualifiedCount = mothlyInvestigationsByGroup.Count(c => c.AcceptTravelStatus == AcceptTravelStatus.Accept), Photo = photo }); } // 周 var weekInvestigationsByGroup = yearlyInvestigations.Where(w => w.OwnerUserName == group.Key && w.CreationTime >= thisWeekStartTime && w.CreationTime < thisWeekEndTime).ToList(); if (weekInvestigationsByGroup.Count > 0) { investigationRankData.WeekUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = weekInvestigationsByGroup.Count, QualifiedCount = weekInvestigationsByGroup.Count(c => c.AcceptTravelStatus == AcceptTravelStatus.Accept), Photo = photo }); } // 天 var dayInvestigationsByGroup = yearlyInvestigations.Where(w => w.OwnerUserName == group.Key && w.CreationTime >= startTime && w.CreationTime < endTime).ToList(); if (dayInvestigationsByGroup.Count > 0) { investigationRankData.DayUserRanks.Add(new UserRankData() { FullName = group.Key, TotalCount = dayInvestigationsByGroup.Count, QualifiedCount = dayInvestigationsByGroup.Count(c => c.AcceptTravelStatus == AcceptTravelStatus.Accept), Photo = photo }); } } model.InvestigaionRankData = investigationRankData; #endregion #region 待处理任务 if (CustomSetting.DefaultOnlySeeMyselfData) { var todoTasks = await _resumeQuerier.GetUncompleteResumesAsync(userId); model.TodoTasks = todoTasks; } else { var todoTasks = await _resumeQuerier.GetUncompleteResumesAsync(null); model.TodoTasks = todoTasks; } #endregion #region 预约中 if (CustomSetting.DefaultOnlySeeMyselfData) { var todoTasks = await _interviewQuerier.GetUnfinshInterviewsAsync(userId); model.InterviewTasks = todoTasks; } else { var todoTasks = await _interviewQuerier.GetUnfinshInterviewsAsync(null); model.InterviewTasks = todoTasks; } // 过期预约 var expriedInterviewCount = model.InterviewTasks.Count(w => w.AppointmentTime < DateTime.Now & w.CreatorUserId == userId); if (expriedInterviewCount > 0) { Notifier.Error($"你有{expriedInterviewCount}条面试预约记录超过预约时间,请及时处理。"); } #endregion return(View(model)); }
//int statusidfortrials = 9; //public int StatusIDforTrials //{ // get { return statusidfortrials; } // set { SetField(ref statusidfortrials, value); } //} public void ClearActivities() { MonthlyData?.Clear(); }
private void writeAdjustedForcingFilesVICorDHSVM(string forcingFile, ForcingFormat format) { findMonthlyValues(format); for (int range = 0; range < dates.Count - 1; range++) { var output = new List <string> [ensembles.Length]; for (int i = 0; i < output.Length; i++) { output[i] = new List <string>(); } int index = 0; MonthlyData monthData = monthlyData[0]; foreach (KeyValuePair <DateTime, double[]> pair in forcingData) { if (format == ForcingFormat.VIC) { if (pair.Key.Day == 1) { monthData = monthlyData[index++]; } //value in vic = Precip, MaxTemp, MinTemp, Wind, AvgTemp; monthData.changeFactors = future date ranges * ensembles * precip, temp for (int ensemble = 0; ensemble < ensembles.Length; ensemble++) { double precip = pair.Value[0]; if (monthData.changeFactors[range, ensemble, 0] != 0)//multiply precip value by change factor if factor is not 0, change factor will be 0 sometimes with summer only { precip *= monthData.changeFactors[range, ensemble, 0]; } output[ensemble].Add(precip.ToString("F04") + "\t" + (pair.Value[1] + monthData.changeFactors[range, ensemble, 1]).ToString("F04") + "\t" + (pair.Value[2] + monthData.changeFactors[range, ensemble, 1]).ToString("F04") + "\t" + pair.Value[3].ToString("F04")); } } else if (format == ForcingFormat.DHSVM) { if (pair.Key.Day == 1 && pair.Key.Hour == 0) { monthData = monthlyData[index++]; } string date = pair.Key.ToString("MM/dd/yyyy-HH"); string glacier = "";//if the DHSVM file has 9 columns, the last column has something to do with glacier lapse rates if (pair.Value.Length == 8) { glacier = pair.Value[7].ToString("F08"); } //value = temp, ?, ?, ?, ?, precip, ?, ?, monthData.changeFactors = future date ranges * ensembles * precip, temp for (int ensemble = 0; ensemble < ensembles.Length; ensemble++) { double precip = pair.Value[5]; if (monthData.changeFactors[range, ensemble, 0] != 0)//multiply precip value by change factor if factor is not 0, change factor will be 0 sometimes with summer only { precip *= monthData.changeFactors[range, ensemble, 0]; } output[ensemble].Add(date + " " + (pair.Value[0] + monthData.changeFactors[range, ensemble, 1]).ToString("F04") + " " + pair.Value[1].ToString("F04") + " " + pair.Value[2].ToString("F04") + " " + pair.Value[3].ToString("F04") + " " + pair.Value[4].ToString("F04") + " " + precip.ToString("F07") + " " + pair.Value[6].ToString("F08") + " " + glacier); } } } for (int ensemble = 0; ensemble < output.Length; ensemble++) { var fname = outputFolderName + "/" + makeValidFileName(ensembles[ensemble].ensembleName) + "_" + dates[range + 1].ToStringWithUnderscores() + "_" + Path.GetFileName(forcingFile); using (TextWriter fileTW = new StreamWriter(fname)) { fileTW.NewLine = "\n"; for (int i = 0; i < output[ensemble].Count; i++) { fileTW.WriteLine(output[ensemble][i]); } } } } }
private void writeAdjustedForcingFilesGSFLOW(string forcingFile, ForcingFormat format) { for (int range = 0; range < dates.Count - 1; range++) { var output = new List <KeyValuePair <DateTime, Dictionary <string, double[]> > > [ensembles.Length]; for (int i = 0; i < ensembles.Length; i++) { output[i] = copyForcingDataGSFLOW(); } //use precip as surrogate for number of grid points to adjust for (int i = 0; i < varsGSFLOW["precip"]; i++) { forcingData = getVIClikeGSFLOWforcingData(i); findMonthlyValues(format); int monthIdx = 0; MonthlyData monthData = monthlyData[0]; int dateIdx = 0; foreach (KeyValuePair <DateTime, double[]> pair in forcingData) { if (pair.Key.Day == 1) { monthData = monthlyData[monthIdx++]; } //values = precip, tmax, tmin, tavg monthData.changeFactors = future date ranges * ensembles * precip, temp for (int ensemble = 0; ensemble < ensembles.Length; ensemble++) { double precip = pair.Value[0]; double precipFactor = monthData.changeFactors[range, ensemble, 0]; double tempFactor = monthData.changeFactors[range, ensemble, 1]; if (precipFactor != 0) //multiply precip value by change factor if factor is not 0, change factor will be 0 sometimes with summer only { precip *= precipFactor; } output[ensemble][dateIdx].Value["precip"][i] = precip; output[ensemble][dateIdx].Value["tmax"][i] = pair.Value[1] + tempFactor; output[ensemble][dateIdx].Value["tmin"][i] = pair.Value[2] + tempFactor; } dateIdx++; } } //write output files to GSFLOW format for (int ensemble = 0; ensemble < ensembles.Length; ensemble++) { var fname = outputFolderName + "/" + makeValidFileName(ensembles[ensemble].ensembleName) + "_" + dates[range + 1].ToStringWithUnderscores() + "_" + Path.GetFileName(forcingFile); using (TextWriter fileTW = new StreamWriter(fname)) { fileTW.NewLine = "\n"; //write header foreach (var line in headerGSFLOW) { fileTW.WriteLine(line); } for (int i = 0; i < output[ensemble].Count; i++) { //write date fileTW.Write(output[ensemble][i].Key.ToString("yyyy M d H m s") + " "); //write each var var numVars = varsOrderedGSFLOW.Count; for (int j = 0; j < numVars; j++) { var var = varsOrderedGSFLOW[j]; var line = string.Join(" ", output[ensemble][i].Value[var].Select(x => x.ToString("F02")).ToArray()); fileTW.Write(line); if (j < numVars - 1) { fileTW.Write(" "); } } fileTW.WriteLine(""); } } } } }
private List <KeyValuePair <double, Size> > getMonthData(DateTime yearMonth, MonthlyData data) { if (monthlyDataCache.ContainsKey(yearMonth)) { return(monthlyDataCache[yearMonth]); } var delta = 1E-9; Func <DateTime, MonthlyData, List <KeyValuePair <double, Size> > > loadDataPrevious = (t, d) => { var dataContext = new List <KeyValuePair <double, Size> >(); var sum = Size.MinValue; var day = t; var dayMax = DateTime.DaysInMonth(day.Year, day.Month); for (double i = 1; i <= dayMax; i++) { try { sum += d[day]; } catch (KeyNotFoundException) { } dataContext.Add(new KeyValuePair <double, Size>(i - delta, sum)); dataContext.Add(new KeyValuePair <double, Size>(i, new Size())); dataContext.Add(new KeyValuePair <double, Size>(i + delta, sum)); day = day.AddDays(1); } return(dataContext); }, loadDataCurrent = (t, d) => { var dataContext = new List <KeyValuePair <double, Size> >(); var sum = Size.MinValue; var day = t; var dayMax = DateTime.DaysInMonth(day.Year, day.Month); var dayNow = DateTime.Now.Day; var predictIncrease = d.Sum / dayNow; double i; for (i = 1d; i <= dayNow; i++) { try { sum += d[day]; } catch (KeyNotFoundException) { } dataContext.Add(new KeyValuePair <double, Size>(i - delta, sum)); dataContext.Add(new KeyValuePair <double, Size>(i, new Size())); dataContext.Add(new KeyValuePair <double, Size>(i + delta, sum)); day = day.AddDays(1); } dataContext.Add(new KeyValuePair <double, Size>(i - 1 + 2 * delta, new Size())); for (; i <= dayMax; i++) { sum += predictIncrease; dataContext.Add(new KeyValuePair <double, Size>(i - delta, new Size())); dataContext.Add(new KeyValuePair <double, Size>(i, sum)); dataContext.Add(new KeyValuePair <double, Size>(i + delta, new Size())); } return(dataContext); }; var re = (yearMonth.Month == DateTime.Now.Month && yearMonth.Year == DateTime.Now.Year) ? loadDataCurrent(yearMonth, data) : loadDataPrevious(yearMonth, data); monthlyDataCache.Add(yearMonth, re); return(re); }