diff --git a/VECTO/GUI/F_MAINForm.Designer.vb b/VECTO/GUI/F_MAINForm.Designer.vb index 62f9303d3a4a50e3fa4064f149a251e592e497cd..f3b413ecaebe7c87e340052e7c5f2446f69ada84 100644 --- a/VECTO/GUI/F_MAINForm.Designer.vb +++ b/VECTO/GUI/F_MAINForm.Designer.vb @@ -40,7 +40,7 @@ Partial Class F_MAINForm Me.ToolStripProgBarOverall = New System.Windows.Forms.ToolStripProgressBar() Me.TabControl1 = New System.Windows.Forms.TabControl() Me.TabPageGEN = New System.Windows.Forms.TabPage() - Me.Button2 = New System.Windows.Forms.Button() + Me.btStartV3 = New System.Windows.Forms.Button() Me.LbDecl = New System.Windows.Forms.Label() Me.PictureBox1 = New System.Windows.Forms.PictureBox() Me.BtGENdown = New System.Windows.Forms.Button() @@ -204,7 +204,7 @@ Partial Class F_MAINForm ' 'TabPageGEN ' - Me.TabPageGEN.Controls.Add(Me.Button2) + Me.TabPageGEN.Controls.Add(Me.btStartV3) Me.TabPageGEN.Controls.Add(Me.LbDecl) Me.TabPageGEN.Controls.Add(Me.PictureBox1) Me.TabPageGEN.Controls.Add(Me.BtGENdown) @@ -224,17 +224,17 @@ Partial Class F_MAINForm Me.TabPageGEN.Text = "Job Files" Me.TabPageGEN.UseVisualStyleBackColor = True ' - 'Button2 + 'btStartV3 ' - Me.Button2.Image = Global.VECTO.My.Resources.Resources.Play_icon - Me.Button2.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft - Me.Button2.Location = New System.Drawing.Point(6, 100) - Me.Button2.Name = "Button2" - Me.Button2.Size = New System.Drawing.Size(105, 41) - Me.Button2.TabIndex = 20 - Me.Button2.Text = "START V3" - Me.Button2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText - Me.Button2.UseVisualStyleBackColor = True + Me.btStartV3.Image = Global.VECTO.My.Resources.Resources.Play_icon + Me.btStartV3.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft + Me.btStartV3.Location = New System.Drawing.Point(6, 100) + Me.btStartV3.Name = "btStartV3" + Me.btStartV3.Size = New System.Drawing.Size(105, 41) + Me.btStartV3.TabIndex = 20 + Me.btStartV3.Text = "START V3" + Me.btStartV3.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText + Me.btStartV3.UseVisualStyleBackColor = True ' 'LbDecl ' @@ -1163,6 +1163,6 @@ Partial Class F_MAINForm Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents ReportBugViaCITnetToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem - Friend WithEvents Button2 As System.Windows.Forms.Button + Friend WithEvents btStartV3 As System.Windows.Forms.Button End Class diff --git a/VECTO/GUI/F_MAINForm.vb b/VECTO/GUI/F_MAINForm.vb index ab7e7f0d95187cf81effa2d17f7d4c9693150c06..1fdbbb85400ba2ed1f19c317534d8546ec5915cb 100644 --- a/VECTO/GUI/F_MAINForm.vb +++ b/VECTO/GUI/F_MAINForm.vb @@ -19,6 +19,7 @@ Imports TUGraz.VectoCore.Models.Simulation.Impl Imports TUGraz.VectoCore Imports TUGraz.VectoCore.Configuration Imports TUGraz.VectoCore.Models.Simulation +Imports System.Reflection ''' <summary> ''' Main application form. Loads at application start. Closing form ends application. @@ -88,11 +89,11 @@ Imports TUGraz.VectoCore.Models.Simulation Private Sub FB_Initialize() FB_Init = False - Try - VECTO_Global.COREvers = Assembly.LoadFrom("VectoCore.dll").GetName().Version.ToString() - Catch ex As Exception - LogFile.WriteToLog(tMsgID.Err, ex.StackTrace) - End Try + Try + VECTO_Global.COREvers = Assembly.LoadFrom("VectoCore.dll").GetName().Version.ToString() + Catch ex As Exception + LogFile.WriteToLog(tMsgID.Err, ex.StackTrace) + End Try fbFolder = New cFileBrowser("WorkDir", True) @@ -245,7 +246,7 @@ Imports TUGraz.VectoCore.Models.Simulation Me.ChBoxAllDRI.Enabled = Not Lock Button1.Enabled = Not Lock - Button2.Enabled = Not Lock + btStartV3.Enabled = Not Lock If DEV.Enabled Then Me.LvDEVoptions.Enabled = Not Lock @@ -486,9 +487,9 @@ Imports TUGraz.VectoCore.Models.Simulation LoadOptions() 'Resize columns ... after Loading the @file-lists - Me.LvGEN.Columns(1).Width = -2 - Me.LvDRI.Columns(1).Width = -2 - Me.LvMsg.Columns(2).Width = -2 + Me.LvGEN.Columns(1).Width = - 2 + Me.LvDRI.Columns(1).Width = - 2 + Me.LvMsg.Columns(2).Width = - 2 'Initialize BackgroundWorker VECTOworker = Me.BackgroundWorker1 @@ -508,7 +509,7 @@ Imports TUGraz.VectoCore.Models.Simulation ModeUpdate() 'License check - If Not Lic.LICcheck() Then + If False And Not Lic.LICcheck() Then MsgBox("License File invalid!" & vbCrLf & vbCrLf & Lic.FailMsg) If Lic.CreateActFile(MyAppPath & "ActivationCode.dat") Then MsgBox("Activation File created.") @@ -860,7 +861,7 @@ Imports TUGraz.VectoCore.Models.Simulation lastindx = LvGEN.SelectedIndices(LvGEN.SelectedItems.Count - 1) - For i = UBound(SelIx) To 0 Step -1 + For i = UBound(SelIx) To 0 Step - 1 LvGEN.Items.RemoveAt(SelIx(i)) Next @@ -920,7 +921,7 @@ Imports TUGraz.VectoCore.Models.Simulation Dim p As Int16 Dim f As Int16 Dim fList As String() - Dim fListDim As Int16 = -1 + Dim fListDim As Int16 = - 1 Dim ListViewItem0 As ListViewItem 'If VECTO runs: Cancel operation (because Mode-change during calculation is not very clever) @@ -975,7 +976,7 @@ Imports TUGraz.VectoCore.Models.Simulation ListViewItem0.Selected = True Me.LvGEN.Items.Add(ListViewItem0) ListViewItem0.EnsureVisible() -lbFound: + lbFound: Next Me.LvGEN.EndUpdate() @@ -1139,7 +1140,7 @@ lbFound: lastindx = LvDRI.SelectedIndices(LvDRI.SelectedItems.Count - 1) - For i = UBound(SelIx) To 0 Step -1 + For i = UBound(SelIx) To 0 Step - 1 LvDRI.Items.RemoveAt(SelIx(i)) Next @@ -1197,7 +1198,7 @@ lbFound: ListViewItem0.SubItems.Add(" ") ListViewItem0.Checked = True Me.LvDRI.Items.Add(ListViewItem0) -lbFound: + lbFound: Next Me.LvDRI.EndUpdate() @@ -1509,7 +1510,7 @@ lbFound: End If End Sub - Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click + Private Sub btStartV3_Click(sender As Object, e As EventArgs) Handles btStartV3.Click If Not VECTOworkerV3.IsBusy Then 'Save Lists for Crash SaveFileLists() @@ -1530,9 +1531,9 @@ lbFound: ClearMSG() LockGUI(True) - Button2.Enabled = True - Button2.Text = "STOP" - Button2.Image = My.Resources.Stop_icon + btStartV3.Enabled = True + btStartV3.Text = "STOP" + btStartV3.Image = My.Resources.Stop_icon ToolStripProgBarOverall.Value = 0 ToolStripProgBarOverall.Style = ProgressBarStyle.Continuous @@ -1540,9 +1541,9 @@ lbFound: VECTOworkerV3.RunWorkerAsync() Else - Button2.Enabled = False - Button2.Text = "Aborting..." - Button2.Image = My.Resources.Play_icon_gray + btStartV3.Enabled = False + btStartV3.Text = "Aborting..." + btStartV3.Image = My.Resources.Play_icon_gray VECTOworkerV3.CancelAsync() End If End Sub @@ -1550,7 +1551,8 @@ lbFound: Private Sub VectoWorkerV3_OnDoWork(sender As BackgroundWorker, e As DoWorkEventArgs) AllowSleepOFF() - Dim sumFileName As String = Path.Combine(Path.GetDirectoryName(JobFileList(0)), Path.GetFileNameWithoutExtension(JobFileList(0)) + ".v3" + Constants.FileExtensions.SumFile) + Dim sumFileName As String = Path.Combine(Path.GetDirectoryName(JobFileList(0)), + Path.GetFileNameWithoutExtension(JobFileList(0)) + ".v3" + Constants.FileExtensions.SumFile) Dim sumWriter As SummaryFileWriter = New SummaryFileWriter(sumFileName) Dim jobContainer As JobContainer = New JobContainer(sumWriter) @@ -1578,6 +1580,8 @@ lbFound: jobContainer.Execute(True) Dim start As DateTime = DateTime.Now() + Dim doneProcesses As List(Of String) = New List(Of String) + While Not jobContainer.AllCompleted If sender.CancellationPending Then jobContainer.Cancel() @@ -1588,16 +1592,44 @@ lbFound: Dim sumProgress As Double = progress.Sum(Function(pair) pair.Value.Progress) Dim duration As Double = (DateTime.Now() - start).TotalSeconds - sender.ReportProgress(Int((sumProgress * 100.0) / progress.Count), + sender.ReportProgress(Int((sumProgress*100.0)/progress.Count), New With {.Target = "Status", .Message = _ - String.Format("Duration: {0:0}s, Current Progress: {1:P} ({2})", duration, sumProgress / progress.Count, + String.Format("Duration: {0:0}s, Current Progress: {1:P} ({2})", duration, sumProgress/progress.Count, String.Join(", ", progress.Select(Function(pair) String.Format("{0,4:P}", pair.Value.Progress))))}) - Thread.Sleep(1000) + + For Each p As KeyValuePair(Of String, JobContainer.ProgressEntry) In progress + If p.Value.Done And Not doneProcesses.Contains(p.Key) Then + sender.ReportProgress(0, New With {.Target = "ListBox", .Message = String.Format("Finished Run {0}", p.Key)}) + 'If Not Cfg.DeclMode Then + sender.ReportProgress(0, New With {.Target = "ListBox", + .Message = String.Format("Run {0}: Modal Results written to {1}", p.Key, p.Value.ModFileName), + .Link = p.Value.ModFileName}) + 'End If + doneProcesses.Add(p.Key) + End If + Next + Thread.Sleep(500) End While + sender.ReportProgress(100, + New _ + With {.Target = "ListBox", .Message = String.Format("Sum File written to {0}", jobContainer.SumFileName), + .Link = jobContainer.SumFileName}) + + If Cfg.DeclMode Then + For Each job As String In JobFileList + Dim report As String = Path.Combine(Path.GetDirectoryName(job), Path.GetFileNameWithoutExtension(job) + ".pdf") + sender.ReportProgress(100, + New With {.Target = "ListBox", .Message = String.Format("PDF Report written to {0}", report), .Link = report}) + Next + End If + + For Each progressEntry As KeyValuePair(Of String, JobContainer.ProgressEntry) In jobContainer.GetProgress() - sender.ReportProgress(100, New With {.Target = "ListBox", .Message = String.Format("{0,-60} {1,8:P} {2,10:F2}s - {3}", _ - progressEntry.Key, progressEntry.Value.Progress, progressEntry.Value.ExecTime / 1000.0, IIf(progressEntry.Value.Success, "Success", "Aborted"))}) + sender.ReportProgress(100, + New With {.Target = "ListBox", .Message = String.Format("{0,-60} {1,8:P} {2,10:F2}s - {3}", + progressEntry.Key, progressEntry.Value.Progress, progressEntry.Value.ExecTime/1000.0, + IIf(progressEntry.Value.Success, "Success", "Aborted"))}) If (Not progressEntry.Value.Success) Then sender.ReportProgress(100, New With {.Target = "ListBox", .Message = progressEntry.Value.Error.Message}) End If @@ -1609,11 +1641,16 @@ lbFound: Private Sub VectoWorkerV3_OnProgressChanged(sender As Object, e As ProgressChangedEventArgs) ToolStripProgBarOverall.Value = e.ProgressPercentage - If e.UserState.Target = "ListBox" Then - MSGtoForm(tMsgID.Normal, e.UserState.Message, "", "") - ElseIf e.UserState.Target = "Status" Then - Status(e.UserState.Message) - End If + Select Case e.UserState.Target + Case "ListBox" + If e.UserState.GetType().GetProperty("Link") Is Nothing Then + MSGtoForm(tMsgID.Normal, e.UserState.Message, "", "") + Else + MSGtoForm(tMsgID.Normal, e.UserState.Message, "", e.UserState.Link) + End If + Case "Status" + Status(e.UserState.Message) + End Select End Sub Private Sub VectoWorkerV3_OnRunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) @@ -1638,8 +1675,8 @@ lbFound: 'Options enable / GUI reset LockGUI(False) - Button2.Text = "START V3" - Button2.Image = My.Resources.Play_icon + btStartV3.Text = "START V3" + btStartV3.Image = My.Resources.Play_icon Status(LastModeName & " Mode") 'SLEEP reactivate diff --git a/VectoCore/Models/Declaration/DeclarationReport.cs b/VectoCore/Models/Declaration/DeclarationReport.cs index 79fbd2bb229fe7a9b95c8168084e069bf2a2527e..512bfcfc6b5a7d0186192718c240a5f00f130b03 100644 --- a/VectoCore/Models/Declaration/DeclarationReport.cs +++ b/VectoCore/Models/Declaration/DeclarationReport.cs @@ -9,7 +9,6 @@ using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Windows.Forms.DataVisualization.Charting; -using NLog; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Utils; @@ -29,32 +28,37 @@ namespace TUGraz.VectoCore.Models.Declaration /// </summary> private class ResultContainer { + /// <summary> + /// The mission + /// </summary> public Mission Mission; + + /// <summary> + /// Dictionary of LoadingTypes and their resulting Modal Data + /// </summary> public Dictionary<LoadingType, IModalDataWriter> ModData; } /// <summary> - /// Data Dictionary for all missions. + /// Dictionary of MissionTypes and their corresponding results. /// </summary> private readonly Dictionary<MissionType, ResultContainer> _missions = new Dictionary<MissionType, ResultContainer>(); /// <summary> /// The full load curve. /// </summary> - private readonly FullLoadCurve _flc; + private readonly FullLoadCurve _fullLoadCurve; /// <summary> /// The declaration segment from the segment table /// </summary> private readonly Segment _segment; - /// <summary> /// The creator name for the report. /// </summary> private readonly string _creator; - /// <summary> /// The engine model string from engine file. /// </summary> @@ -93,7 +97,7 @@ namespace TUGraz.VectoCore.Models.Declaration /// <summary> /// Initializes a new instance of the <see cref="DeclarationReport"/> class. /// </summary> - /// <param name="flc">The full load curve.</param> + /// <param name="fullLoadCurve">The full load curve.</param> /// <param name="segment">The segment of the current vehicle from the segment table.</param> /// <param name="creator">The creator name.</param> /// <param name="engineModel">The engine model.</param> @@ -103,10 +107,11 @@ namespace TUGraz.VectoCore.Models.Declaration /// <param name="basePath">The base path.</param> /// <param name="jobFile">The name of the job file.</param> /// <param name="resultCount">The result count which defines after how many finished results the report gets written.</param> - public DeclarationReport(FullLoadCurve flc, Segment segment, string creator, string engineModel, string engineStr, + public DeclarationReport(FullLoadCurve fullLoadCurve, Segment segment, string creator, string engineModel, + string engineStr, string gearboxModel, string gearboxStr, string basePath, string jobFile, int resultCount) { - _flc = flc; + _fullLoadCurve = fullLoadCurve; _segment = segment; _creator = creator; _engineModel = engineModel; @@ -151,7 +156,9 @@ namespace TUGraz.VectoCore.Models.Declaration var titlePage = CreateTitlePage(_missions); var cyclePages = _missions.OrderBy(m => m.Key).Select((m, i) => CreateCyclePage(m.Value, i + 2, _missions.Count + 1)); - MergeDocuments(titlePage, cyclePages, Path.Combine(_basePath, _jobFile + ".pdf")); + var pages = titlePage.ToEnumerable().Concat(cyclePages); + + WritePagesToFile(pages, Path.Combine(_basePath, _jobFile + ".pdf")); } @@ -296,7 +303,8 @@ namespace TUGraz.VectoCore.Models.Declaration img.SetAbsolutePosition(17, 270); content.AddImage(img); - img = Image.GetInstance(DrawOperatingPointsChart(results.ModData[LoadingType.ReferenceLoad], _flc), BaseColor.WHITE); + img = Image.GetInstance(DrawOperatingPointsChart(results.ModData[LoadingType.ReferenceLoad], _fullLoadCurve), + BaseColor.WHITE); img.ScaleAbsolute(420, 178); img.SetAbsolutePosition(375, 75); content.AddImage(img); @@ -311,20 +319,16 @@ namespace TUGraz.VectoCore.Models.Declaration /// <summary> /// Merges the given stream to one document and writes it to a file on disk. /// </summary> - /// <param name="titlePage">The title page.</param> - /// <param name="cyclePages">The cycle pages.</param> + /// <param name="pages">The pages.</param> /// <param name="outputFileName">Name of the output file.</param> - private static void MergeDocuments(Stream titlePage, IEnumerable<Stream> cyclePages, string outputFileName) + private static void WritePagesToFile(IEnumerable<Stream> pages, string outputFileName) { var document = new Document(PageSize.A4.Rotate(), 12, 12, 12, 12); var writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create)); document.Open(); - titlePage.Position = 0; - document.Add(Image.GetInstance(writer.GetImportedPage(new PdfReader(titlePage), 1))); - - foreach (var cyclePage in cyclePages) { + foreach (var cyclePage in pages) { cyclePage.Position = 0; document.Add(Image.GetInstance(writer.GetImportedPage(new PdfReader(cyclePage), 1))); } diff --git a/VectoCore/Models/Simulation/Data/IModalDataWriter.cs b/VectoCore/Models/Simulation/Data/IModalDataWriter.cs index 3f225287bff78a0549f6c320410c8fa15a8fad61..f4036469d6fdc84329363408942253c74db76c27 100644 --- a/VectoCore/Models/Simulation/Data/IModalDataWriter.cs +++ b/VectoCore/Models/Simulation/Data/IModalDataWriter.cs @@ -16,6 +16,8 @@ namespace TUGraz.VectoCore.Models.Simulation.Data /// <returns></returns> object this[ModalResultField key] { get; set; } + string ModFileName { get; } + /// <summary> /// Indexer for auxiliary fields of the DataWriter. /// </summary> diff --git a/VectoCore/Models/Simulation/Data/ModalDataWriter.cs b/VectoCore/Models/Simulation/Data/ModalDataWriter.cs index 89cb858be6a8572875bc5e9528120af69f0265de..6f115ba991a39ee3b9d006c8d5ad466ff6530acc 100644 --- a/VectoCore/Models/Simulation/Data/ModalDataWriter.cs +++ b/VectoCore/Models/Simulation/Data/ModalDataWriter.cs @@ -13,7 +13,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data private readonly Action<ModalDataWriter> _addReportResult; private ModalResults Data { get; set; } private DataRow CurrentRow { get; set; } - private string ModFileName { get; set; } + public string ModFileName { get; protected set; } public bool WriteModalResults { get; set; } diff --git a/VectoCore/Models/Simulation/Data/SummaryFileWriter.cs b/VectoCore/Models/Simulation/Data/SummaryFileWriter.cs index 63ee0db2724161e67b20bc3363ccf13fa533b519..cd355ebc560051bbf0aa6d4b3f4c96a5509d104d 100644 --- a/VectoCore/Models/Simulation/Data/SummaryFileWriter.cs +++ b/VectoCore/Models/Simulation/Data/SummaryFileWriter.cs @@ -64,8 +64,10 @@ namespace TUGraz.VectoCore.Models.Simulation.Data private readonly string _sumFileName; private bool _engineOnly = true; + public string SumFileName{get { return _sumFileName; }} + protected SummaryFileWriter() {} - + private readonly IList<string> _auxColumns = new List<string>(); /// <summary> diff --git a/VectoCore/Models/Simulation/IVehicleContainer.cs b/VectoCore/Models/Simulation/IVehicleContainer.cs index 9f12971f3211bafe0e510a57fa4de4e5a6891923..3aa3a4974371537547abeff477ed7aa1b0bb68d8 100644 --- a/VectoCore/Models/Simulation/IVehicleContainer.cs +++ b/VectoCore/Models/Simulation/IVehicleContainer.cs @@ -31,5 +31,7 @@ namespace TUGraz.VectoCore.Models.Simulation void FinishSimulation(); VectoRun.Status RunStatus { get; set; } + + string ModFileName { get; } } } \ No newline at end of file diff --git a/VectoCore/Models/Simulation/Impl/JobContainer.cs b/VectoCore/Models/Simulation/Impl/JobContainer.cs index 8d7c748dbe18a2e1e4b6aeb5ecb651b009a37c0e..b3ee6d503d6b47ca8b90ab12e049cba2c456ff73 100644 --- a/VectoCore/Models/Simulation/Impl/JobContainer.cs +++ b/VectoCore/Models/Simulation/Impl/JobContainer.cs @@ -8,191 +8,189 @@ using TUGraz.VectoCore.Models.Simulation.Data; namespace TUGraz.VectoCore.Models.Simulation.Impl { - /// <summary> - /// Container for simulation jobs. - /// </summary> - public class JobContainer : LoggingObject - { - internal readonly List<JobEntry> Runs = new List<JobEntry>(); - private readonly SummaryFileWriter _sumWriter; - - private static int _jobNumber; - - /// <summary> - /// Initializes a new empty instance of the <see cref="JobContainer"/> class. - /// </summary> - /// <param name="sumWriter">The sum writer.</param> - public JobContainer(SummaryFileWriter sumWriter) - { - _sumWriter = sumWriter; - } - - public void AddRun(IVectoRun run) - { - _jobNumber++; - Runs.Add(new JobEntry() { - Run = run, - Container = this, - }); - } - - public void AddRuns(IEnumerable<IVectoRun> runs) - { - _jobNumber++; - //Runs.AddRange(runs); - foreach (var run in runs) { - Runs.Add(new JobEntry() { - Run = run, - Container = this, - }); - } - } - - public void AddRuns(SimulatorFactory factory) - { - factory.SumWriter = _sumWriter; - factory.JobNumber = _jobNumber++; - AddRuns(factory.SimulationRuns()); - } - - /// <summary> - /// Execute all runs, waits until finished. - /// </summary> - public void Execute(bool multithreaded = true) - { - Log.Info("VectoRun started running. Executing Runs."); - - foreach (var job in Runs) { - job.Worker = new BackgroundWorker() { - WorkerSupportsCancellation = true, - WorkerReportsProgress = true, - }; - job.Worker.DoWork += job.DoWork; - job.Worker.ProgressChanged += job.ProgressChanged; - job.Worker.RunWorkerCompleted += job.RunWorkerCompleted; - if (multithreaded) { - job.Started = true; - job.Worker.RunWorkerAsync(); - } - } - if (!multithreaded) { - var entry = Runs.First(); - entry.Started = true; - entry.Worker.RunWorkerAsync(); - } - //Task.WaitAll(_runs.Select(r => Task.Factory.StartNew(r.Run)).ToArray()); - - //_sumWriter.Finish(); - } - - public void Cancel() - { - foreach (var job in Runs) { - if (job.Worker != null && job.Worker.WorkerSupportsCancellation) { - job.Worker.CancelAsync(); - } - } - } - - public void CancelCurrent() - { - foreach (var job in Runs) { - if (job.Worker != null && job.Worker.IsBusy && job.Worker.WorkerSupportsCancellation) { - job.Worker.CancelAsync(); - } - } - } - - private static AutoResetEvent resetEvent = new AutoResetEvent(false); - - public void WaitFinished() - { - resetEvent.WaitOne(); - } - - - private void JobCompleted(JobEntry jobEntry) - { - var next = Runs.FirstOrDefault(x => x.Started == false); - if (next != null) { - next.Started = true; - next.Worker.RunWorkerAsync(); - } - if (Runs.Count(x => x.Done == true) == Runs.Count()) { - _sumWriter.Finish(); - resetEvent.Set(); - } - } - - public Dictionary<string, ProgressEntry> GetProgress() - { - return Runs.ToDictionary(jobEntry => jobEntry.Run.Name, entry => new ProgressEntry() { - Progress = entry.Progress, - Done = entry.Done, - ExecTime = entry.ExecTime, - Success = entry.Success, - Canceled = entry.Canceled, - Error = entry.ExecException - }); - } - - public bool AllCompleted - { - get { return (Runs.Count(x => x.Done == true) == Runs.Count()); } - } - - public class ProgressEntry - { - public double Progress; - public double ExecTime; - public Exception Error; - public bool Canceled; - public bool Success; - public bool Done; - } - - internal class JobEntry : LoggingObject - { - public IVectoRun Run; - public JobContainer Container; - public double Progress; - public bool Done; - public bool Started; - public bool Success; - public bool Canceled; - public double ExecTime; - public Exception ExecException; - - public BackgroundWorker Worker; - - public void DoWork(object sender, DoWorkEventArgs e) - { - var stopWatch = new Stopwatch(); - stopWatch.Start(); - var worker = sender as BackgroundWorker; - try { - Run.Run(worker); - } catch (Exception ex) { - Log.Error(ex, "Error during simulation run!"); - ExecException = ex; - } - if (worker != null && worker.CancellationPending) { - e.Cancel = true; - Canceled = true; - } - stopWatch.Stop(); - Success = Run.FinishedWithoutErrors; - Done = true; - ExecTime = stopWatch.Elapsed.TotalMilliseconds; - Container.JobCompleted(this); - } - - public void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {} - - public void ProgressChanged(object sender, ProgressChangedEventArgs e) - { - Progress = e.ProgressPercentage / 10000.0; - } - } - } + /// <summary> + /// Container for simulation jobs. + /// </summary> + public class JobContainer : LoggingObject + { + internal readonly List<RunEntry> Runs = new List<RunEntry>(); + private readonly SummaryFileWriter _sumWriter; + + private static int _jobNumber; + + /// <summary> + /// Initializes a new empty instance of the <see cref="JobContainer"/> class. + /// </summary> + /// <param name="sumWriter">The sum writer.</param> + public JobContainer(SummaryFileWriter sumWriter) + { + _sumWriter = sumWriter; + } + + public string SumFileName + { + get { return _sumWriter.SumFileName; } + } + + public void AddRun(IVectoRun run) + { + _jobNumber++; + Runs.Add(new RunEntry { Run = run, Container = this }); + } + + public void AddRuns(IEnumerable<IVectoRun> runs) + { + _jobNumber++; + //Runs.AddRange(runs); + foreach (var run in runs) { + Runs.Add(new RunEntry { Run = run, Container = this }); + } + } + + public void AddRuns(SimulatorFactory factory) + { + factory.SumWriter = _sumWriter; + factory.JobNumber = _jobNumber++; + AddRuns(factory.SimulationRuns()); + } + + /// <summary> + /// Execute all runs, waits until finished. + /// </summary> + public void Execute(bool multithreaded = true) + { + Log.Info("VectoRun started running. Executing Runs."); + + foreach (var job in Runs) { + job.Worker = new BackgroundWorker() { + WorkerSupportsCancellation = true, + WorkerReportsProgress = true, + }; + job.Worker.DoWork += job.DoWork; + job.Worker.ProgressChanged += job.ProgressChanged; + job.Worker.RunWorkerCompleted += job.RunWorkerCompleted; + if (multithreaded) { + job.Started = true; + job.Worker.RunWorkerAsync(); + } + } + if (!multithreaded) { + var entry = Runs.First(); + entry.Started = true; + entry.Worker.RunWorkerAsync(); + } + } + + public void Cancel() + { + foreach (var job in Runs) { + if (job.Worker != null && job.Worker.WorkerSupportsCancellation) { + job.Worker.CancelAsync(); + } + } + } + + public void CancelCurrent() + { + foreach (var job in Runs) { + if (job.Worker != null && job.Worker.IsBusy && job.Worker.WorkerSupportsCancellation) { + job.Worker.CancelAsync(); + } + } + } + + private static readonly AutoResetEvent resetEvent = new AutoResetEvent(false); + + public void WaitFinished() + { + resetEvent.WaitOne(); + } + + + private void JobCompleted(RunEntry runEntry) + { + var next = Runs.FirstOrDefault(x => x.Started == false); + if (next != null) { + next.Started = true; + next.Worker.RunWorkerAsync(); + } + if (AllCompleted) { + _sumWriter.Finish(); + resetEvent.Set(); + } + } + + public Dictionary<string, ProgressEntry> GetProgress() + { + return Runs.ToDictionary(jobEntry => jobEntry.Run.Name, entry => new ProgressEntry { + Progress = entry.Progress, + Done = entry.Done, + ExecTime = entry.ExecTime, + Success = entry.Success, + Canceled = entry.Canceled, + Error = entry.ExecException, + ModFileName = entry.Run.GetContainer().ModFileName + }); + } + + public bool AllCompleted + { + get { return Runs.All(x => x.Done); } + } + + public class ProgressEntry + { + public double Progress; + public double ExecTime; + public Exception Error; + public bool Canceled; + public bool Success; + public bool Done; + public string ModFileName; + } + + internal class RunEntry : LoggingObject + { + public IVectoRun Run; + public JobContainer Container; + public double Progress; + public bool Done; + public bool Started; + public bool Success; + public bool Canceled; + public double ExecTime; + public Exception ExecException; + + public BackgroundWorker Worker; + + public void DoWork(object sender, DoWorkEventArgs e) + { + var stopWatch = new Stopwatch(); + stopWatch.Start(); + var worker = sender as BackgroundWorker; + try { + Run.Run(worker); + } catch (Exception ex) { + Log.Error(ex, "Error during simulation run!"); + ExecException = ex; + } + if (worker != null && worker.CancellationPending) { + e.Cancel = true; + Canceled = true; + } + stopWatch.Stop(); + Success = Run.FinishedWithoutErrors; + Done = true; + ExecTime = stopWatch.Elapsed.TotalMilliseconds; + Container.JobCompleted(this); + } + + public void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {} + + public void ProgressChanged(object sender, ProgressChangedEventArgs e) + { + Progress = e.ProgressPercentage / 10000.0; + } + } + } } \ No newline at end of file diff --git a/VectoCore/Models/Simulation/Impl/VehicleContainer.cs b/VectoCore/Models/Simulation/Impl/VehicleContainer.cs index 9a5751d8fd2aed7fe40a2d2ec160331133928032..ee1fc5d51ce697c4bff4c718694a3437458e3acd 100644 --- a/VectoCore/Models/Simulation/Impl/VehicleContainer.cs +++ b/VectoCore/Models/Simulation/Impl/VehicleContainer.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using TUGraz.VectoCore.Exceptions; @@ -106,6 +105,11 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl #endregion + public string ModFileName + { + get { return DataWriter.ModFileName; } + } + #region IVehicleCockpit public MeterPerSecond VehicleSpeed diff --git a/VectoCoreTest/Utils/MockModalDataWriter.cs b/VectoCoreTest/Utils/MockModalDataWriter.cs index aae84d3008e33be35b2b33f2311c1c9fa7fb7ea3..9e42f743662ea1b748dc648a5d44e95aae05aed6 100644 --- a/VectoCoreTest/Utils/MockModalDataWriter.cs +++ b/VectoCoreTest/Utils/MockModalDataWriter.cs @@ -22,6 +22,11 @@ namespace TUGraz.VectoCore.Tests.Utils public ModalResults Data { get; set; } public DataRow CurrentRow { get; set; } + public string ModFileName + { + get { return ""; } + } + public object this[string auxId] { get { return CurrentRow[Auxiliaries[auxId]]; }