diff --git a/VECTO/GUI/F_MAINForm.vb b/VECTO/GUI/F_MAINForm.vb index 880d7d42660c7f7061c2be78146fc35c4d68a9e7..ad57998c88aaae3fe57811858a9dc908a46ab18f 100644 --- a/VECTO/GUI/F_MAINForm.vb +++ b/VECTO/GUI/F_MAINForm.vb @@ -15,18 +15,19 @@ Imports System.IO Imports System.Linq Imports System.Reflection Imports System.Threading -Imports TUGraz.VectoCore.Models.Simulation.Data Imports TUGraz.VectoCore.Models.Simulation.Impl -Imports TUGraz.VectoCore Imports TUGraz.VectoCore.Configuration -Imports TUGraz.VectoCore.Models.Simulation +Imports TUGraz.VectoCore.InputData +Imports TUGraz.VectoCore.InputData.FileIO.JSON +Imports TUGraz.VectoCore.OutputData +Imports TUGraz.VectoCore.OutputData.FileIO ''' <summary> ''' Main application form. Loads at application start. Closing form ends application. ''' </summary> ''' <remarks></remarks> - Public Class F_MAINForm +Public Class F_MAINForm Private JobListView As cFileListView Private CycleListView As cFileListView @@ -60,7 +61,7 @@ Imports TUGraz.VectoCore.Models.Simulation #Region "SLEEP Control - Prevent sleep while VECTO is running" - Private Declare Function SetThreadExecutionState Lib "kernel32"(ByVal esFlags As Long) As Long + Private Declare Function SetThreadExecutionState Lib "kernel32" (ByVal esFlags As Long) As Long Private Sub AllowSleepOFF() #If Not PLATFORM = "x86" Then @@ -89,11 +90,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) @@ -175,11 +176,11 @@ Imports TUGraz.VectoCore.Models.Simulation Me.LvGEN.SelectedItems.Clear() 'If more than 100 calculations, ask whether to write by-second results - If Cfg.BatchMode And ((Me.LvGEN.CheckedItems.Count)*(Me.LvDRI.CheckedItems.Count) > 100) And Me.ChBoxModOut.Checked _ + If Cfg.BatchMode And ((Me.LvGEN.CheckedItems.Count) * (Me.LvDRI.CheckedItems.Count) > 100) And Me.ChBoxModOut.Checked _ Then Select Case _ MsgBox( - "You are about to run Batch Mode with " & (Me.LvGEN.CheckedItems.Count)*(Me.LvDRI.CheckedItems.Count) & + "You are about to run Batch Mode with " & (Me.LvGEN.CheckedItems.Count) * (Me.LvDRI.CheckedItems.Count) & " calculations!" & ChrW(10) & "Do you still want to write modal results?", MsgBoxStyle.YesNoCancel) Case MsgBoxResult.No Me.ChBoxModOut.Checked = False @@ -261,7 +262,7 @@ Imports TUGraz.VectoCore.Models.Simulation JobFileList.Clear() CheckedItems.Clear() - x = - 1 + x = -1 For Each LV0 In Me.LvGEN.CheckedItems x += 1 LV0.SubItems(1).Text = "" @@ -1551,8 +1552,9 @@ 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 sumWriter As SummaryFileWriter = New SummaryFileWriter(sumFileName) + 'Dim sumFileName As String = Path.Combine(Path.GetDirectoryName(JobFileList(0)), Path.GetFileNameWithoutExtension(JobFileList(0)) + ".v3" + Constants.FileExtensions.SumFile) + Dim fileWriter As FileOutputWriter = New FileOutputWriter(Path.GetFileNameWithoutExtension(JobFileList(0)), Path.GetDirectoryName(JobFileList(0))) + Dim sumWriter As SummaryDataContainer = New SummaryDataContainer(fileWriter) Dim jobContainer As JobContainer = New JobContainer(sumWriter) Dim mode As SimulatorFactory.FactoryMode @@ -1565,7 +1567,8 @@ lbFound: For Each jobFile As String In JobFileList sender.ReportProgress(0, New With {.Target = "ListBox", .Message = "Reading File " + jobFile}) - Dim runsFactory As SimulatorFactory = New SimulatorFactory(mode, jobFile) + Dim dataProvider As IInputDataProvider = JSONInputDataFactory.ReadJsonJob(jobFile) + Dim runsFactory As SimulatorFactory = New SimulatorFactory(mode, dataProvider, fileWriter) runsFactory.WriteModalResults = Cfg.ModOut jobContainer.AddRuns(runsFactory) sender.ReportProgress(0, New With {.Target = "ListBox", .Message = "Finished Reading File " + jobFile}) @@ -1906,9 +1909,9 @@ lbFound: Me.ToolStripProgBarJob.Value = .ProgJobInt - If .ProgOverallStartInt > - 1 Then + If .ProgOverallStartInt > -1 Then Me.ToolStripProgBarOverall.Value = - CInt(.ProgOverallStartInt + (.PgroOverallEndInt - .ProgOverallStartInt)*.ProgJobInt/100) + CInt(.ProgOverallStartInt + (.PgroOverallEndInt - .ProgOverallStartInt) * .ProgJobInt / 100) End If End With @@ -1924,7 +1927,7 @@ lbFound: Me.ChBoxCyclDistCor.Checked = Cfg.DistCorr Me.ChBoxUseGears.Checked = Cfg.GnUfromCycle Me.ChBoxModOut.Checked = Cfg.ModOut - CbBOmode.SelectedIndex = - 1 + CbBOmode.SelectedIndex = -1 Select Case UCase(Cfg.BATCHoutpath) Case sKey.JobPath CbBOmode.SelectedIndex = 0 @@ -2000,7 +2003,7 @@ lbFound: Me.LvDEVoptions.Items.Clear() - i = - 1 + i = -1 For Each Config0 In DEV.Options i += 1 @@ -2063,7 +2066,7 @@ lbFound: CmDEV.Items.Clear() - i = - 1 + i = -1 For Each str In Config0.Modes i += 1 CmDEV.Items.Add("(" & i & ") " & str) @@ -2385,7 +2388,7 @@ lbFound: MyForm.LvMsg.Items.Insert(RowLim - 4, Space(ColLim - 30) & " " & Space(10) & "*| |*") End Select Exit Sub - LbRace: +LbRace: PRbAlt = Not PRbAlt @@ -2413,17 +2416,17 @@ lbFound: sAbort() Exit Sub End If - Scr += 5*DiffLvl + Scr += 5 * DiffLvl End If Scr += DiffLvl DiffC += 1 'Erhöhe Schwierigkeitsgrad - If DiffC = (DiffLvl + 3)*4 Then + If DiffC = (DiffLvl + 3) * 4 Then DiffC = 0 DiffLvl += 1 - If DiffLvl > 2 And DiffLvl < 7 Then MyForm.TmProgSec.Interval = 300 - (DiffLvl)*30 + If DiffLvl > 2 And DiffLvl < 7 Then MyForm.TmProgSec.Interval = 300 - (DiffLvl) * 30 Scr += 100 Select Case DiffLvl Case 3 @@ -2507,10 +2510,10 @@ lbFound: Ctrls(RowLim + 1) = 0 CtrlC += 1 If CtrlC < CtrlCL Then Exit Sub - Select Case CInt(Int((CtrlRnd*Rnd()) + 1)) + Select Case CInt(Int((CtrlRnd * Rnd()) + 1)) Case 1, 2 CtrlC = 0 - x = CInt(Int((7*Rnd()) + 1)) + x = CInt(Int((7 * Rnd()) + 1)) Ctrls(RowLim + 1) = x Case Else End Select @@ -2554,7 +2557,7 @@ lbFound: s = s.Insert(Ctrls(RowLim + 1) + 1, "X") End If Select Case xPanel - Pnls(RowLim) - Case - 1 + Case -1 s = Replace(s, "|", "\") Case 1 s = Replace(s, "|", "/") @@ -2566,15 +2569,15 @@ lbFound: PnDirC += 1 If PnDirC < PnDirCL Then GoTo Lb1 PnDirC = 0 - Select Case CInt(Int((PnDirRnd*Rnd()) + 1)) + Select Case CInt(Int((PnDirRnd * Rnd()) + 1)) Case 1 PnDir = 1 Case 2 - PnDir = - 1 + PnDir = -1 Case Else PnDir = 0 End Select - Lb1: +Lb1: xPanel += PnDir If xPanel > ColLim Then xPanel = ColLim diff --git a/VectoConsole/Program.cs b/VectoConsole/Program.cs index fe029ee98c518b7cf81d96760b99c72eb616bc5f..ea23e4f5e2508117bd11d6be580376db0b009c92 100644 --- a/VectoConsole/Program.cs +++ b/VectoConsole/Program.cs @@ -9,19 +9,22 @@ using System.Threading; using NLog; using NLog.Config; using TUGraz.VectoCore.Configuration; +using TUGraz.VectoCore.InputData.FileIO.JSON; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; +using TUGraz.VectoCore.OutputData; +using TUGraz.VectoCore.OutputData.FileIO; namespace VectoConsole { - internal static class Program - { - private static int NumLines; - private static int ProgessCounter { get; set; } + internal static class Program + { + private static int NumLines; + private static int ProgessCounter { get; set; } - private const string USAGE = @"Usage: vecto.exe [-h] [-v] FILE1.vecto [FILE2.vecto ...]"; + private const string USAGE = @"Usage: vecto.exe [-h] [-v] FILE1.vecto [FILE2.vecto ...]"; - private const string HELP = @" + private const string HELP = @" Commandline Interface for Vecto. Synopsis: @@ -50,178 +53,181 @@ Examples: vecto.exe -h "; - private static JobContainer jobContainer; - - private static int Main(string[] args) - { - try { - // on -h display help and terminate. - if (args.Contains("-h")) { - ShowVersionInformation(); - Console.Write(HELP); - return 0; - } - - // on -v: activate verbose console logger - var logLevel = LogLevel.Fatal; - - // Fatal > Error > Warn > Info > Debug > Trace - var debugEnabled = false; - - if (args.Contains("-v")) { - // display errors, warnings - logLevel = LogLevel.Warn; - debugEnabled = true; - } else if (args.Contains("-vv")) { - // also display info - logLevel = LogLevel.Info; - debugEnabled = true; - } else if (args.Contains("-vvv")) { - // display debug messages - logLevel = LogLevel.Debug; - debugEnabled = true; - } else if (args.Contains("-vvvv")) { - // display everything! - logLevel = LogLevel.Trace; - debugEnabled = true; - } - - var config = LogManager.Configuration; - //config.LoggingRules.Add(new LoggingRule("*", logLevel, config.FindTargetByName("ConsoleLogger"))); - config.LoggingRules.Add(new LoggingRule("*", logLevel, config.FindTargetByName("LogFile"))); - LogManager.Configuration = config; - Trace.Listeners.Add(new ConsoleTraceListener(true)); - - if (args.Contains("-V") || debugEnabled) { - ShowVersionInformation(); - } - - var fileList = args.Except(new[] { "-v", "-vv", "-vvv", "-vvvv", "-V", "-mod", "-eng", "-t" }).ToArray(); - - // if no other arguments given: display usage and terminate - if (!args.Any()) { - Console.Write(USAGE); - return 1; - } - - var stopWatch = new Stopwatch(); - var timings = new Dictionary<string, double>(); - - // process the file list and start simulation - var sumFileName = Path.Combine(Path.GetDirectoryName(fileList.First()) ?? "", - Path.GetFileNameWithoutExtension(fileList.First()) + Constants.FileExtensions.SumFile); - var sumWriter = new SummaryFileWriter(sumFileName); - jobContainer = new JobContainer(sumWriter); - - var mode = SimulatorFactory.FactoryMode.DeclarationMode; - if (args.Contains("-eng")) { - mode = SimulatorFactory.FactoryMode.EngineeringMode; - Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine( - "Switching to Engineering Mode. Make sure the job-file is saved in engineering mode!"); - Console.ResetColor(); - } - - Console.WriteLine("Reading Job Files"); - stopWatch.Start(); - foreach (var file in fileList.Where(f => Path.GetExtension(f) == Constants.FileExtensions.VectoJobFile)) { - var runsFactory = new SimulatorFactory(mode, file); - if (args.Contains("-mod")) { - runsFactory.WriteModalResults = true; - } - jobContainer.AddRuns(runsFactory); - } - stopWatch.Stop(); - timings.Add("Reading input files", stopWatch.Elapsed.TotalMilliseconds); - stopWatch.Reset(); - - Console.WriteLine("Starting simulation runs"); - if (debugEnabled) { - Console.ForegroundColor = ConsoleColor.White; - Console.WriteLine("Debug-Output is enabled, executing simulation runs sequentially"); - Console.ResetColor(); - } - Console.WriteLine(); - stopWatch.Start(); - jobContainer.Execute(!debugEnabled); - - Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { - var isCtrlC = e.SpecialKey == ConsoleSpecialKey.ControlC; - var isCtrlBreak = e.SpecialKey == ConsoleSpecialKey.ControlBreak; - - if (!isCtrlC) { - return; - } - //Console.WriteLine("Canceling simulation!"); - e.Cancel = true; - Program.jobContainer.CancelCurrent(); - }; - - //var x = Console.CursorLeft; - while (!jobContainer.AllCompleted) { - PrintProgress(jobContainer.GetProgress()); - Thread.Sleep(250); - } - stopWatch.Stop(); - timings.Add("Simulation runs", stopWatch.Elapsed.TotalMilliseconds); - - PrintProgress(jobContainer.GetProgress(), args.Contains("-t")); - if (args.Contains("-t")) { - PrintTimings(timings); - } - } catch (Exception e) { - Console.Error.WriteLine(e.Message); - //Trace.TraceError(e.ToString()); - Console.ForegroundColor = ConsoleColor.Red; - Console.Error.WriteLine("Please see log-file for further details (logs/log.txt)"); - Console.ResetColor(); - Environment.ExitCode = Environment.ExitCode != 0 ? Environment.ExitCode : 1; - } - return Environment.ExitCode; - } - - private static void ShowVersionInformation() - { - var vectodll = AssemblyName.GetAssemblyName("VectoCore.dll"); - Console.WriteLine("VectoConsole: {0}", Assembly.GetExecutingAssembly().GetName().Version); - Console.WriteLine("VectoCore: {0}", vectodll.Version); - } - - private static void PrintProgress(Dictionary<string, JobContainer.ProgressEntry> progessData, - bool showTiming = true) - { - Console.SetCursorPosition(0, Console.CursorTop - NumLines); - NumLines = 0; - var sumProgress = 0.0; - foreach (var progressEntry in progessData) { - if (progressEntry.Value.Success) { - Console.ForegroundColor = ConsoleColor.Green; - } else if (progressEntry.Value.Error != null) { - Console.ForegroundColor = ConsoleColor.Red; - } - var timingString = ""; - if (showTiming && progressEntry.Value.ExecTime > 0) { - timingString = string.Format("{0,9:F2}s", progressEntry.Value.ExecTime / 1000.0); - } - Console.WriteLine("{0,-60} {1,8:P}{2}", progressEntry.Key, progressEntry.Value.Progress, timingString); - Console.ResetColor(); - sumProgress += progressEntry.Value.Progress; - NumLines++; - } - sumProgress /= NumLines; - var spinner = "/-\\|"[ProgessCounter++ % 4]; - var bar = new string('#', (int)(sumProgress * 100.0 / 2)); - Console.WriteLine(string.Format(" {2} [{1,-50}] [{0,7:P}]", sumProgress, bar, spinner)); - NumLines++; - } - - private static void PrintTimings(Dictionary<string, double> timings) - { - Console.WriteLine(); - Console.WriteLine("---- timing information ----"); - foreach (var timing in timings) { - Console.WriteLine("{0,-20}: {1:F2}s", timing.Key, timing.Value / 1000); - } - } - } + private static JobContainer jobContainer; + + private static int Main(string[] args) + { + try { + // on -h display help and terminate. + if (args.Contains("-h")) { + ShowVersionInformation(); + Console.Write(HELP); + return 0; + } + + // on -v: activate verbose console logger + var logLevel = LogLevel.Fatal; + + // Fatal > Error > Warn > Info > Debug > Trace + var debugEnabled = false; + + if (args.Contains("-v")) { + // display errors, warnings + logLevel = LogLevel.Warn; + debugEnabled = true; + } else if (args.Contains("-vv")) { + // also display info + logLevel = LogLevel.Info; + debugEnabled = true; + } else if (args.Contains("-vvv")) { + // display debug messages + logLevel = LogLevel.Debug; + debugEnabled = true; + } else if (args.Contains("-vvvv")) { + // display everything! + logLevel = LogLevel.Trace; + debugEnabled = true; + } + + var config = LogManager.Configuration; + //config.LoggingRules.Add(new LoggingRule("*", logLevel, config.FindTargetByName("ConsoleLogger"))); + config.LoggingRules.Add(new LoggingRule("*", logLevel, config.FindTargetByName("LogFile"))); + LogManager.Configuration = config; + Trace.Listeners.Add(new ConsoleTraceListener(true)); + + if (args.Contains("-V") || debugEnabled) { + ShowVersionInformation(); + } + + var fileList = args.Except(new[] { "-v", "-vv", "-vvv", "-vvvv", "-V", "-mod", "-eng", "-t" }).ToArray(); + + // if no other arguments given: display usage and terminate + if (!args.Any()) { + Console.Write(USAGE); + return 1; + } + + var stopWatch = new Stopwatch(); + var timings = new Dictionary<string, double>(); + + // process the file list and start simulation + //var sumFileName = Path.Combine(Path.GetDirectoryName(fileList.First()) ?? "", + // Path.GetFileNameWithoutExtension(fileList.First()) + Constants.FileExtensions.SumFile); + var fileWriter = new FileOutputWriter(Path.GetFileNameWithoutExtension(fileList.First()), + Path.GetDirectoryName(fileList.First() ?? "")); + var sumWriter = new SummaryDataContainer(fileWriter); + jobContainer = new JobContainer(sumWriter); + + var mode = SimulatorFactory.FactoryMode.DeclarationMode; + if (args.Contains("-eng")) { + mode = SimulatorFactory.FactoryMode.EngineeringMode; + Console.ForegroundColor = ConsoleColor.White; + Console.WriteLine( + "Switching to Engineering Mode. Make sure the job-file is saved in engineering mode!"); + Console.ResetColor(); + } + + Console.WriteLine("Reading Job Files"); + stopWatch.Start(); + foreach (var file in fileList.Where(f => Path.GetExtension(f) == Constants.FileExtensions.VectoJobFile)) { + var dataProvider = JSONInputDataFactory.ReadJsonJob(file); + var runsFactory = new SimulatorFactory(mode, dataProvider, fileWriter) { ModWriter = fileWriter }; + if (args.Contains("-mod")) { + runsFactory.WriteModalResults = true; + } + jobContainer.AddRuns(runsFactory); + } + stopWatch.Stop(); + timings.Add("Reading input files", stopWatch.Elapsed.TotalMilliseconds); + stopWatch.Reset(); + + Console.WriteLine("Starting simulation runs"); + if (debugEnabled) { + Console.ForegroundColor = ConsoleColor.White; + Console.WriteLine("Debug-Output is enabled, executing simulation runs sequentially"); + Console.ResetColor(); + } + Console.WriteLine(); + stopWatch.Start(); + jobContainer.Execute(!debugEnabled); + + Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { + var isCtrlC = e.SpecialKey == ConsoleSpecialKey.ControlC; + var isCtrlBreak = e.SpecialKey == ConsoleSpecialKey.ControlBreak; + + if (!isCtrlC) { + return; + } + //Console.WriteLine("Canceling simulation!"); + e.Cancel = true; + Program.jobContainer.CancelCurrent(); + }; + + //var x = Console.CursorLeft; + while (!jobContainer.AllCompleted) { + PrintProgress(jobContainer.GetProgress()); + Thread.Sleep(250); + } + stopWatch.Stop(); + timings.Add("Simulation runs", stopWatch.Elapsed.TotalMilliseconds); + + PrintProgress(jobContainer.GetProgress(), args.Contains("-t")); + if (args.Contains("-t")) { + PrintTimings(timings); + } + } catch (Exception e) { + Console.Error.WriteLine(e.Message); + //Trace.TraceError(e.ToString()); + Console.ForegroundColor = ConsoleColor.Red; + Console.Error.WriteLine("Please see log-file for further details (logs/log.txt)"); + Console.ResetColor(); + Environment.ExitCode = Environment.ExitCode != 0 ? Environment.ExitCode : 1; + } + return Environment.ExitCode; + } + + private static void ShowVersionInformation() + { + var vectodll = AssemblyName.GetAssemblyName("VectoCore.dll"); + Console.WriteLine("VectoConsole: {0}", Assembly.GetExecutingAssembly().GetName().Version); + Console.WriteLine("VectoCore: {0}", vectodll.Version); + } + + private static void PrintProgress(Dictionary<string, JobContainer.ProgressEntry> progessData, + bool showTiming = true) + { + Console.SetCursorPosition(0, Console.CursorTop - NumLines); + NumLines = 0; + var sumProgress = 0.0; + foreach (var progressEntry in progessData) { + if (progressEntry.Value.Success) { + Console.ForegroundColor = ConsoleColor.Green; + } else if (progressEntry.Value.Error != null) { + Console.ForegroundColor = ConsoleColor.Red; + } + var timingString = ""; + if (showTiming && progressEntry.Value.ExecTime > 0) { + timingString = string.Format("{0,9:F2}s", progressEntry.Value.ExecTime / 1000.0); + } + Console.WriteLine("{0,-60} {1,8:P}{2}", progressEntry.Key, progressEntry.Value.Progress, timingString); + Console.ResetColor(); + sumProgress += progressEntry.Value.Progress; + NumLines++; + } + sumProgress /= NumLines; + var spinner = "/-\\|"[ProgessCounter++ % 4]; + var bar = new string('#', (int)(sumProgress * 100.0 / 2)); + Console.WriteLine(string.Format(" {2} [{1,-50}] [{0,7:P}]", sumProgress, bar, spinner)); + NumLines++; + } + + private static void PrintTimings(Dictionary<string, double> timings) + { + Console.WriteLine(); + Console.WriteLine("---- timing information ----"); + foreach (var timing in timings) { + Console.WriteLine("{0,-20}: {1:F2}s", timing.Key, timing.Value / 1000); + } + } + } } \ No newline at end of file diff --git a/VectoCore/InputData/FileIO/JSON/JSONInputData.cs b/VectoCore/InputData/FileIO/JSON/JSONInputData.cs index 868a77ec40cea1de43c71a474c46d8698aca79d3..9a7a4bde2a35352730252c778e7af3e9df9d6b0d 100644 --- a/VectoCore/InputData/FileIO/JSON/JSONInputData.cs +++ b/VectoCore/InputData/FileIO/JSON/JSONInputData.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; +using System.Text; using Newtonsoft.Json.Linq; using TUGraz.VectoCore.Exceptions; +using TUGraz.VectoCore.InputData.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Utils; @@ -52,7 +54,7 @@ namespace TUGraz.VectoCore.InputData.FileIO.JSON } } - public class JSONInputDataV2 : JSONFile, IInputDataProvider, IJobInputData, IDriverInputData + public class JSONInputDataV2 : JSONFile, IInputDataProvider, IJobInputData, IDriverInputData, IAuxiliariesInputData { protected IGearboxInputData Gearbox; @@ -112,9 +114,9 @@ namespace TUGraz.VectoCore.InputData.FileIO.JSON get { return Engine; } } - public IList<IAuxiliaryInputData> AuxiliaryInputData() + public IAuxiliariesInputData AuxiliaryInputData() { - return null; + return this; } public IRetarderInputData RetarderInputData @@ -136,13 +138,14 @@ namespace TUGraz.VectoCore.InputData.FileIO.JSON get { return VehicleData; } } - public IList<DataTable> Cycles + public IList<ICycleData> Cycles { get { - return - Body[JsonKeys.Job_Cycles].Select(cycle => VectoCSVFile.Read(Path.Combine(BasePath, cycle.Value<string>()))) - .ToList(); + return Body[JsonKeys.Job_Cycles].Select(cycle => new CycleInputData() { + Name = cycle.Value<string>(), + CycleData = VectoCSVFile.Read(Path.Combine(BasePath, cycle.Value<string>())) + }).Cast<ICycleData>().ToList(); } } @@ -164,7 +167,7 @@ namespace TUGraz.VectoCore.InputData.FileIO.JSON { get { - return new JSONStartStop() { + return new StartStopInputData() { Enabled = Body[JsonKeys.DriverData_StartStop][JsonKeys.DriverData_StartStop_Enabled].Value<bool>(), Delay = Body[JsonKeys.DriverData_StartStop][JsonKeys.DriverData_StartStop_Delay].Value<double>().SI<Second>(), MaxSpeed = @@ -178,7 +181,7 @@ namespace TUGraz.VectoCore.InputData.FileIO.JSON { get { - return new JSONLookaheadCoasting() { + return new LookAheadCoastingInputData() { Enabled = Body[JsonKeys.DriverData_LookaheadCoasting][JsonKeys.DriverData_Lookahead_Enabled].Value<bool>(), Deceleration = Body[JsonKeys.DriverData_LookaheadCoasting][JsonKeys.DriverData_Lookahead_Deceleration].Value<double>() @@ -194,7 +197,7 @@ namespace TUGraz.VectoCore.InputData.FileIO.JSON { get { - return new JSONOverSpeedEcoRoll() { + return new OverSpeedEcoRollInputData() { Mode = DriverData.ParseDriverMode( Body[JsonKeys.DriverData_OverspeedEcoRoll][JsonKeys.DriverData_OverspeedEcoRoll_Mode].Value<string>()), @@ -217,36 +220,26 @@ namespace TUGraz.VectoCore.InputData.FileIO.JSON } #endregion - } - - public class JSONStartStop : IStartStopInputData - { - public bool Enabled { get; internal set; } - - public MeterPerSecond MaxSpeed { get; internal set; } - - public Second MinTime { get; internal set; } - public Second Delay { get; internal set; } - } - - public class JSONLookaheadCoasting : ILookaheadCoastingInputData - { - public bool Enabled { get; internal set; } - - public MeterPerSquareSecond Deceleration { get; internal set; } - - public MeterPerSecond MinSpeed { get; internal set; } - } - - public class JSONOverSpeedEcoRoll : IOverspeedEcoRollInputData - { - public DriverData.DriverMode Mode { get; internal set; } - - public MeterPerSecond MinSpeed { get; internal set; } - - public MeterPerSecond OverSpeed { get; internal set; } - - public MeterPerSecond UnderSpeed { get; internal set; } + public IList<IAuxiliaryInputData> Auxiliaries + { + get + { + var retVal = new List<IAuxiliaryInputData>(); + foreach (var aux in Body["Aux"]) { + var auxData = new AuxiliaryDataInputData(); + var stream = new StreamReader(aux["Path"].Value<string>()); + stream.ReadLine(); // skip header "Transmission ration to engine rpm [-]" + auxData.TransmissionRatio = stream.ReadLine().IndulgentParse(); + stream.ReadLine(); // skip header "Efficiency to engine [-]" + auxData.EfficiencyToEngine = stream.ReadLine().IndulgentParse(); + stream.ReadLine(); // skip header "Efficiency auxiliary to supply [-]" + auxData.EfficiencyToSupply = stream.ReadLine().IndulgentParse(); + auxData.DemandMap = VectoCSVFile.ReadStream(new MemoryStream(Encoding.UTF8.GetBytes(stream.ReadToEnd()))); + retVal.Add(auxData); + } + return retVal; + } + } } } \ No newline at end of file diff --git a/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/AbstractSimulationDataAdapter.cs b/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/AbstractSimulationDataAdapter.cs index 0c54797ebf5d12860596f151622b0682b02a5c9e..531fca73892fc381907c007eb2a7a24a82c7dfbf 100644 --- a/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/AbstractSimulationDataAdapter.cs +++ b/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/AbstractSimulationDataAdapter.cs @@ -2,6 +2,7 @@ using System.IO; using System.Linq; using TUGraz.VectoCore.InputData.FileIO.DeclarationFile; +using TUGraz.VectoCore.Models; using TUGraz.VectoCore.Models.Declaration; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data.Engine; @@ -10,7 +11,7 @@ using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper { - public abstract class AbstractSimulationDataAdapter + public abstract class AbstractSimulationDataAdapter : LoggingObject { // ========================= diff --git a/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/DeclarationDataAdapter.cs b/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/DeclarationDataAdapter.cs index 34446d29c79b4c4d2ac1cb584b80aaf5dc328886..24efa1a9569f6d66e0c07a3ac9ff7c01b6b4dd5a 100644 --- a/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/DeclarationDataAdapter.cs +++ b/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/DeclarationDataAdapter.cs @@ -17,6 +17,9 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper { public DriverData CreateDriverData(IDriverInputData data) { + if (!data.SavedInDeclarationMode) { + WarnDeclarationMode("DriverData"); + } var lookAheadData = new DriverData.LACData { Enabled = DeclarationData.Driver.LookAhead.Enabled, Deceleration = DeclarationData.Driver.LookAhead.Deceleration, @@ -46,9 +49,12 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper return retVal; } - internal VehicleData CreateVehicleData(IVehicleInputData data, Mission mission, Kilogram loading) { + if (!data.SavedInDeclarationMode) { + WarnDeclarationMode("VehicleData"); + } + var retVal = SetCommonVehicleData(data); retVal.GrossVehicleMassRating = data.GrossVehicleMassRating; @@ -95,6 +101,10 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper internal CombustionEngineData CreateEngineData(IEngineInputData engine) { + if (!engine.SavedInDeclarationMode) { + WarnDeclarationMode("EngineData"); + } + var retVal = SetCommonCombustionEngineData(engine); retVal.Inertia = DeclarationData.Engine.EngineInertia(retVal.Displacement); retVal.FullLoadCurve = EngineFullLoadCurve.Create(engine.FullLoadCurve, true); @@ -104,6 +114,9 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper internal GearboxData CreateGearboxData(IGearboxInputData gearbox, CombustionEngineData engine) { + if (!gearbox.SavedInDeclarationMode) { + WarnDeclarationMode("GearboxData"); + } var retVal = SetCommonGearboxData(gearbox); switch (retVal.Type) { case GearboxType.AT: @@ -152,11 +165,14 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper } - public IList<VectoRunData.AuxData> CreateAuxiliaryData(IEnumerable<IAuxiliaryInputData> auxList, + public IList<VectoRunData.AuxData> CreateAuxiliaryData(IAuxiliariesInputData auxInputData, MissionType mission, VehicleClass hvdClass) { + if (!auxInputData.SavedInDeclarationMode) { + WarnDeclarationMode("AuxiliariesData"); + } var retVal = new List<VectoRunData.AuxData>(); - foreach (var auxData in auxList) { + foreach (var auxData in auxInputData.Auxiliaries) { var aux = new VectoRunData.AuxData { DemandType = AuxiliaryDemandType.Constant }; switch (auxData.Type) { @@ -187,5 +203,10 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper } return retVal; } + + private void WarnDeclarationMode(string inputData) + { + Log.Warn("{0} not in Declaration Mode!", inputData); + } } } \ No newline at end of file diff --git a/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/EngineeringDataAdapter.cs b/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/EngineeringDataAdapter.cs index 871846d2a8757c7ca58fda76e7395afc8eede589..2d90464818d61595f7d48e83845169befd67c2a4 100644 --- a/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/EngineeringDataAdapter.cs +++ b/VectoCore/InputData/FileIO/Reader/DataObjectAdaper/EngineeringDataAdapter.cs @@ -8,15 +8,19 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data.Engine; using TUGraz.VectoCore.Models.SimulationComponent.Data.Gearbox; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper { public class EngineeringDataAdapter : AbstractSimulationDataAdapter { - internal VehicleData CreateVehicleData(IVehicleInputData data, Mission mission, - Kilogram loading) + internal VehicleData CreateVehicleData(IVehicleInputData data) { + if (data.SavedInDeclarationMode) { + WarnEngineeringMode("VehicleData"); + } + var retVal = SetCommonVehicleData(data); retVal.CurbWeigthExtra = data.CurbWeightExtra; @@ -38,8 +42,17 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper return retVal; } + private void WarnEngineeringMode(string msg) + { + Log.Warn("{0} is in Declaration Mode but is used for Engineering Mode!", msg); + } + internal CombustionEngineData CreateEngineData(IEngineInputData engine) { + if (engine.SavedInDeclarationMode) { + WarnEngineeringMode("EngineData"); + } + var retVal = SetCommonCombustionEngineData(engine); retVal.Inertia = engine.Inertia; retVal.FullLoadCurve = EngineFullLoadCurve.Create(engine.FullLoadCurve); @@ -49,6 +62,10 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper internal GearboxData CreateGearboxData(IGearboxInputData gearbox, CombustionEngineData engineData) { + if (gearbox.SavedInDeclarationMode) { + WarnEngineeringMode("GearboxData"); + } + var retVal = SetCommonGearboxData(gearbox); var gears = gearbox.Gears; @@ -92,8 +109,27 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper return retVal; } + public IList<VectoRunData.AuxData> CreateAuxiliaryData(IAuxiliariesInputData auxInputData) + { + if (auxInputData.SavedInDeclarationMode) { + WarnEngineeringMode("AuxData"); + } + + return auxInputData.Auxiliaries.Select(a => new VectoRunData.AuxData { + ID = a.ID, + Technology = a.Technology, + TechList = a.TechList.DefaultIfNull(Enumerable.Empty<string>()).ToArray(), + DemandType = AuxiliaryDemandType.Mapping, + Data = new AuxiliaryData(a) //AuxiliaryData.Create(a.DemandMap) + }).Concat(new VectoRunData.AuxData { ID = "", DemandType = AuxiliaryDemandType.Direct }.ToEnumerable()).ToList(); + } + internal DriverData CreateDriverData(IDriverInputData driver) { + if (driver.SavedInDeclarationMode) { + WarnEngineeringMode("DriverData"); + } + AccelerationCurveData accelerationData = null; if (driver.AccelerationCurve != null) { accelerationData = AccelerationCurveData.Create(driver.AccelerationCurve); diff --git a/VectoCore/InputData/FileIO/Reader/DrivingCycleDataReader.cs b/VectoCore/InputData/FileIO/Reader/DrivingCycleDataReader.cs index b851ad5503ad48583fdd58ec264c82d2ba64c8ed..e2c2e55a37893af917b94a873de0d7a91415ab57 100644 --- a/VectoCore/InputData/FileIO/Reader/DrivingCycleDataReader.cs +++ b/VectoCore/InputData/FileIO/Reader/DrivingCycleDataReader.cs @@ -41,6 +41,14 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader return retVal; } + + public static DrivingCycleData Create(DataTable cycle, string name, CycleType type) + { + var retVal = DoReadCycleData(type, cycle); + retVal.Name = name; + return retVal; + } + private static DrivingCycleData DoReadCycleData(CycleType type, DataTable data) { var parser = CreateDataParser(type); diff --git a/VectoCore/InputData/FileIO/Reader/Impl/DeclarationModeVectoRunDataFactory.cs b/VectoCore/InputData/FileIO/Reader/Impl/DeclarationModeVectoRunDataFactory.cs index 60cca9b973cd4691f9fde56ec43318994ef407c2..a3c2f24cffbd988d5429e0b52c8e913f64f65e41 100644 --- a/VectoCore/InputData/FileIO/Reader/Impl/DeclarationModeVectoRunDataFactory.cs +++ b/VectoCore/InputData/FileIO/Reader/Impl/DeclarationModeVectoRunDataFactory.cs @@ -1,17 +1,12 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Security.Principal; -using Newtonsoft.Json; -using TUGraz.VectoCore.Exceptions; -using TUGraz.VectoCore.InputData.FileIO.DeclarationFile; using TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper; using TUGraz.VectoCore.Models; using TUGraz.VectoCore.Models.Declaration; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; -using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData.PDF; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl @@ -68,7 +63,9 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl VehicleData = dao.CreateVehicleData(InputDataProvider.VehicleInputData, mission, loading.Value), EngineData = engineData, GearboxData = dao.CreateGearboxData(InputDataProvider.GearboxInputData, engineData), - Aux = dao.CreateAuxiliaryData(InputDataProvider.AuxiliaryInputData(), mission.MissionType, segment.VehicleClass), + Aux = + dao.CreateAuxiliaryData(InputDataProvider.AuxiliaryInputData(), mission.MissionType, + segment.VehicleClass), Cycle = cycle, DriverData = driverdata, IsEngineOnly = false, // InputDataProvider.JobInputData().EngineOnlyMode, @@ -101,7 +98,6 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl Report.GearboxStr = string.Format("{0}-Speed {1}", gearboxData.Gears.Count, gearboxData.Type); Report.Segment = segment; Report.ResultCount = segment.Missions.Sum(m => m.Loadings.Count); - ; } internal Segment GetVehicleClassification(VehicleCategory category, AxleConfiguration axles, Kilogram grossMassRating, @@ -236,21 +232,5 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl // { // get { return false; } // } - - /// <summary> - /// Create gearboxdata instance directly from a file - /// </summary> - /// <param name="gearBoxFile"></param> - /// <param name="engineFile"></param> - /// <returns>GearboxData instance</returns> - public static GearboxData CreateGearboxDataFromFile(string gearBoxFile, string engineFile) - { - //var reader = new DeclarationModeVectoRunDataFactory(); - //var engine = reader.ReadEngine(engineFile); - //var gearbox = reader.ReadGearbox(gearBoxFile); - //var dao = new DeclarationDataAdapter(); - //var engineData = dao.CreateEngineData(engine); - //return dao.CreateGearboxData(gearbox, engineData); - } } } \ No newline at end of file diff --git a/VectoCore/InputData/FileIO/Reader/Impl/EngineOnlyVectoRunDataFactory.cs b/VectoCore/InputData/FileIO/Reader/Impl/EngineOnlyVectoRunDataFactory.cs index b36326f4107015832720ca82df55922cb5c8f012..0b285ec17d15cafde26f600a594037a3c4d631cb 100644 --- a/VectoCore/InputData/FileIO/Reader/Impl/EngineOnlyVectoRunDataFactory.cs +++ b/VectoCore/InputData/FileIO/Reader/Impl/EngineOnlyVectoRunDataFactory.cs @@ -4,25 +4,27 @@ using TUGraz.VectoCore.Exceptions; using TUGraz.VectoCore.InputData.FileIO.EngineeringFile; using TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper; using TUGraz.VectoCore.Models.Simulation.Data; +using TUGraz.VectoCore.Models.SimulationComponent.Data; namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl { public class EngineOnlyVectoRunDataFactory : EngineeringModeVectoRunDataFactory { - public override IEnumerable<VectoRunData> NextRun() + internal EngineOnlyVectoRunDataFactory(IInputDataProvider dataProvider) : base(dataProvider) {} + + public new IEnumerable<VectoRunData> NextRun() { - var job = Job as VectoJobFileV2Engineering; - if (job == null) { - Log.Warn("Job-file is null or unsupported version"); + if (InputDataProvider == null) { + Log.Warn("No valid data provider given"); yield break; } var dao = new EngineeringDataAdapter(); - foreach (var cycle in job.Body.Cycles) { + foreach (var cycle in InputDataProvider.JobInputData().Cycles) { var simulationRunData = new VectoRunData { - BasePath = job.BasePath, - JobName = job.JobFile, - EngineData = dao.CreateEngineData(Engine), - Cycle = DrivingCycleDataReader.ReadFromFileEngineOnly(Path.Combine(job.BasePath, cycle)), + //BasePath = job.BasePath, + JobName = InputDataProvider.JobInputData().JobName, + EngineData = dao.CreateEngineData(InputDataProvider.EngineInputData), + Cycle = DrivingCycleDataReader.Create(cycle.CycleData, cycle.Name, CycleType.EngineOnly), IsEngineOnly = IsEngineOnly }; yield return simulationRunData; @@ -40,7 +42,7 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl // Engine = ReadEngine(Path.Combine(job.BasePath, job.Body.EngineFile)); //} - public override bool IsEngineOnly + public bool IsEngineOnly { get { return true; } } diff --git a/VectoCore/InputData/FileIO/Reader/Impl/EngineeringModeVectoRunDataFactory.cs b/VectoCore/InputData/FileIO/Reader/Impl/EngineeringModeVectoRunDataFactory.cs index 4959bdf3622bbdc1fe4c9acd938f0df16b904e9c..efc3932b5560dbf167abf5bd7a847a2da2318aab 100644 --- a/VectoCore/InputData/FileIO/Reader/Impl/EngineeringModeVectoRunDataFactory.cs +++ b/VectoCore/InputData/FileIO/Reader/Impl/EngineeringModeVectoRunDataFactory.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; @@ -19,7 +20,12 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl { protected DriverData Driver; - internal EngineeringModeVectoRunDataFactory() {} + protected IInputDataProvider InputDataProvider; + + internal EngineeringModeVectoRunDataFactory(IInputDataProvider dataProvider) + { + InputDataProvider = dataProvider; + } //protected static void CheckForEngineeringMode(VersionInfo info, string msg) @@ -90,27 +96,23 @@ namespace TUGraz.VectoCore.InputData.FileIO.Reader.Impl /// <returns>VectoRunData instance for initializing the powertrain.</returns> public IEnumerable<VectoRunData> NextRun() { - var job = Job as VectoJobFileV2Engineering; - if (job == null) { - Log.Warn("Job-file is null or unsupported version"); - yield break; - } var dao = new EngineeringDataAdapter(); - var driver = dao.CreateDriverData(job); - var engineData = dao.CreateEngineData(Engine); - foreach (var cycle in job.Body.Cycles) { + var driver = dao.CreateDriverData(InputDataProvider.DriverInputData); + var engineData = dao.CreateEngineData(InputDataProvider.EngineInputData); + + foreach (var cycle in InputDataProvider.JobInputData().Cycles) { var simulationRunData = new VectoRunData { - BasePath = job.BasePath, - JobName = job.JobFile, + //BasePath = job.BasePath, + JobName = InputDataProvider.JobInputData().JobName, EngineData = engineData, - GearboxData = dao.CreateGearboxData(Gearbox, engineData), - VehicleData = dao.CreateVehicleData(Vehicle), + GearboxData = dao.CreateGearboxData(InputDataProvider.GearboxInputData, engineData), + VehicleData = dao.CreateVehicleData(InputDataProvider.VehicleInputData), DriverData = driver, - Aux = Aux, + Aux = dao.CreateAuxiliaryData(InputDataProvider.AuxiliaryInputData()), // TODO: distance or time-based cycle! Cycle = - DrivingCycleDataReader.ReadFromFile(Path.Combine(job.BasePath, cycle), CycleType.DistanceBased), - IsEngineOnly = IsEngineOnly + DrivingCycleDataReader.Create(cycle.CycleData, cycle.Name, CycleType.DistanceBased), + IsEngineOnly = InputDataProvider.JobInputData().EngineOnlyMode }; yield return simulationRunData; } diff --git a/VectoCore/InputData/IInputDataProvider.cs b/VectoCore/InputData/IInputDataProvider.cs index 0099066f8910e4f519390c24d98085b9e89c593d..f955659a6e234ce581022d9187b4e35c5555b091 100644 --- a/VectoCore/InputData/IInputDataProvider.cs +++ b/VectoCore/InputData/IInputDataProvider.cs @@ -15,7 +15,7 @@ namespace TUGraz.VectoCore.InputData IEngineInputData EngineInputData { get; } - IList<IAuxiliaryInputData> AuxiliaryInputData(); + IAuxiliariesInputData AuxiliaryInputData(); IRetarderInputData RetarderInputData { get; } diff --git a/VectoCore/InputData/Impl/InputData.cs b/VectoCore/InputData/Impl/InputData.cs new file mode 100644 index 0000000000000000000000000000000000000000..95bb700367fd26542374d01d6911cb9077c3a41b --- /dev/null +++ b/VectoCore/InputData/Impl/InputData.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.Data; +using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.Utils; + +namespace TUGraz.VectoCore.InputData.Impl +{ + public class CycleInputData : ICycleData + { + public string Name { get; internal set; } + + public DataTable CycleData { get; internal set; } + } + + public class StartStopInputData : IStartStopInputData + { + public bool Enabled { get; internal set; } + + public MeterPerSecond MaxSpeed { get; internal set; } + + public Second MinTime { get; internal set; } + + public Second Delay { get; internal set; } + } + + public class LookAheadCoastingInputData : ILookaheadCoastingInputData + { + public bool Enabled { get; internal set; } + + public MeterPerSquareSecond Deceleration { get; internal set; } + + public MeterPerSecond MinSpeed { get; internal set; } + } + + public class OverSpeedEcoRollInputData : IOverspeedEcoRollInputData + { + public DriverData.DriverMode Mode { get; internal set; } + + public MeterPerSecond MinSpeed { get; internal set; } + + public MeterPerSecond OverSpeed { get; internal set; } + + public MeterPerSecond UnderSpeed { get; internal set; } + } + + public class AuxiliaryDataInputData : IAuxiliaryInputData + { + public bool SavedInDeclarationMode { get; internal set; } + + public string ID { get; internal set; } + + public AuxiliaryType Type { get; internal set; } + + public string Technology { get; internal set; } + + public IList<string> TechList { get; internal set; } + + public double TransmissionRatio { get; internal set; } + + public double EfficiencyToEngine { get; internal set; } + + public double EfficiencyToSupply { get; internal set; } + + public DataTable DemandMap { get; internal set; } + } +} \ No newline at end of file diff --git a/VectoCore/InputData/InputData.cs b/VectoCore/InputData/InputData.cs index 39867ddcf90133b6b2216fb8d92c1f28866a2b33..2263d24cf09d3b51b50b076bb89cc987380754c1 100644 --- a/VectoCore/InputData/InputData.cs +++ b/VectoCore/InputData/InputData.cs @@ -15,9 +15,11 @@ namespace TUGraz.VectoCore.InputData { public interface IJobInputData { + bool SavedInDeclarationMode { get; } + IVehicleInputData Vehicle { get; } - IList<DataTable> Cycles { get; } + IList<ICycleData> Cycles { get; } bool EngineOnlyMode { get; } @@ -56,6 +58,8 @@ namespace TUGraz.VectoCore.InputData public interface IRetarderInputData { + bool SavedInDeclarationMode { get; } + RetarderData.RetarderType Type { get; } double Ratio { get; } @@ -163,8 +167,23 @@ namespace TUGraz.VectoCore.InputData KilogramPerWattSecond WHTCUrban { get; } } + public interface IAuxiliariesInputData + { + bool SavedInDeclarationMode { get; } + + IList<IAuxiliaryInputData> Auxiliaries { get; } + } + + public interface ICycleData + { + string Name { get; } + DataTable CycleData { get; } + } + public interface IDriverInputData { + bool SavedInDeclarationMode { get; } + IStartStopInputData StartStop { get; } ILookaheadCoastingInputData Lookahead { get; } IOverspeedEcoRollInputData OverspeedEcoRoll { get; } @@ -195,15 +214,24 @@ namespace TUGraz.VectoCore.InputData Second Delay { get; } } - public interface IAuxiliaryInputData { bool SavedInDeclarationMode { get; } + string ID { get; } + AuxiliaryType Type { get; } string Technology { get; } IList<string> TechList { get; } + + double TransmissionRatio { get; } + + double EfficiencyToEngine { get; } + + double EfficiencyToSupply { get; } + + DataTable DemandMap { get; } } } \ No newline at end of file diff --git a/VectoCore/JsonKeys.resx b/VectoCore/JsonKeys.resx index 4e250b2c3c9814310745ba450775adc955a4a44f..eccdda35b3481e71e2852c7fde1a34487a7b60f3 100644 --- a/VectoCore/JsonKeys.resx +++ b/VectoCore/JsonKeys.resx @@ -313,5 +313,14 @@ </data> <data name="DriverData_AccelerationCurve" xml:space="preserve"> <value>VACC</value> + </data> + <data name="Vehicle_CurbWeightExtra" xml:space="preserve"> + <value>CurbWeightExtra</value> + </data> + <data name="Vehicle_Loading" xml:space="preserve"> + <value>Loading</value> + </data> + <data name="Vehicle_DynamicTyreRadius" xml:space="preserve"> + <value>rdyn</value> </data> </root> \ No newline at end of file diff --git a/VectoCore/Models/Simulation/Data/VectoRunData.cs b/VectoCore/Models/Simulation/Data/VectoRunData.cs index 502fabeae0c90dd4eb9af6fb1de4e1f9f238c311..f90590c16ffb6820e7df0ceff79d5588fcef5ce8 100644 --- a/VectoCore/Models/Simulation/Data/VectoRunData.cs +++ b/VectoCore/Models/Simulation/Data/VectoRunData.cs @@ -1,7 +1,9 @@ using System.Collections.Generic; using System.Runtime.Serialization; +using System.Security.Permissions; using TUGraz.VectoCore.Models.Declaration; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData.PDF; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.Simulation.Data @@ -15,6 +17,8 @@ namespace TUGraz.VectoCore.Models.Simulation.Data public GearboxData GearboxData { get; internal set; } + public AxleGearData AxleGearData { get; internal set; } + public DrivingCycleData Cycle { get; internal set; } public IEnumerable<AuxData> Aux { get; internal set; } diff --git a/VectoCore/Models/Simulation/Impl/JobContainer.cs b/VectoCore/Models/Simulation/Impl/JobContainer.cs index 8d7c748dbe18a2e1e4b6aeb5ecb651b009a37c0e..36736cac686fd1f493013114e57bba53b7eeb87a 100644 --- a/VectoCore/Models/Simulation/Impl/JobContainer.cs +++ b/VectoCore/Models/Simulation/Impl/JobContainer.cs @@ -5,194 +5,195 @@ using System.Diagnostics; using System.Linq; using System.Threading; using TUGraz.VectoCore.Models.Simulation.Data; +using TUGraz.VectoCore.OutputData; 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()); + /// <summary> + /// Container for simulation jobs. + /// </summary> + public class JobContainer : LoggingObject + { + internal readonly List<JobEntry> Runs = new List<JobEntry>(); + private readonly SummaryDataContainer _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(SummaryDataContainer 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.SumData = _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; - } - } - } + } + + 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; + } + } + } } \ No newline at end of file diff --git a/VectoCore/Models/Simulation/Impl/PowertrainBuilder.cs b/VectoCore/Models/Simulation/Impl/PowertrainBuilder.cs index 2075d3242abc3a051b8cdf5602889b0070624c81..464f23e2f21de88f514af16ff206301678b9046d 100644 --- a/VectoCore/Models/Simulation/Impl/PowertrainBuilder.cs +++ b/VectoCore/Models/Simulation/Impl/PowertrainBuilder.cs @@ -4,6 +4,7 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; namespace TUGraz.VectoCore.Models.Simulation.Impl { @@ -14,14 +15,14 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl { private readonly bool _engineOnly; private readonly VehicleContainer _container; - private readonly IModalDataWriter _dataWriter; + private readonly IModalDataContainer _modData; - public PowertrainBuilder(IModalDataWriter dataWriter, bool engineOnly, WriteSumData sumWriter = null) + public PowertrainBuilder(IModalDataContainer modData, bool engineOnly, WriteSumData sumWriter = null) { _engineOnly = engineOnly; - _dataWriter = dataWriter; - _container = new VehicleContainer(dataWriter, sumWriter); + _modData = modData; + _container = new VehicleContainer(modData, sumWriter); } public VehicleContainer Build(VectoRunData data) @@ -49,16 +50,16 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl var vehicle = AddComponent(driver, new Vehicle(_container, data.VehicleData)); var wheels = AddComponent(vehicle, new Wheels(_container, data.VehicleData.DynamicTyreRadius)); var brakes = AddComponent(wheels, new Brakes(_container)); - var tmp = AddComponent(brakes, new AxleGear(_container, data.GearboxData.AxleGearData)); + var tmp = AddComponent(brakes, new AxleGear(_container, data.AxleGearData)); - switch (data.VehicleData.Retarder.Type) { + switch (data.Retarder.Type) { case RetarderData.RetarderType.Primary: - tmp = AddComponent(tmp, new Retarder(_container, data.VehicleData.Retarder.LossMap)); + tmp = AddComponent(tmp, new Retarder(_container, data.Retarder.LossMap)); tmp = AddComponent(tmp, GetGearbox(_container, data.GearboxData)); break; case RetarderData.RetarderType.Secondary: tmp = AddComponent(tmp, GetGearbox(_container, data.GearboxData)); - tmp = AddComponent(tmp, new Retarder(_container, data.VehicleData.Retarder.LossMap)); + tmp = AddComponent(tmp, new Retarder(_container, data.Retarder.LossMap)); break; case RetarderData.RetarderType.None: tmp = AddComponent(tmp, GetGearbox(_container, data.GearboxData)); @@ -90,7 +91,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl aux.AddMapping(auxData.ID, cycle, auxData.Data); break; } - _dataWriter.AddAuxiliary(auxData.ID); + _modData.AddAuxiliary(auxData.ID); } tmp = AddComponent(tmp, aux); } diff --git a/VectoCore/Models/Simulation/Impl/SimulatorFactory.cs b/VectoCore/Models/Simulation/Impl/SimulatorFactory.cs index d01de32a7fb3c136a8ce80af62982bbb97b33fae..b6b838ae6668bb639a0822aeb00149935ca9c8fb 100644 --- a/VectoCore/Models/Simulation/Impl/SimulatorFactory.cs +++ b/VectoCore/Models/Simulation/Impl/SimulatorFactory.cs @@ -10,6 +10,8 @@ using TUGraz.VectoCore.InputData.FileIO.Reader; using TUGraz.VectoCore.InputData.FileIO.Reader.Impl; using TUGraz.VectoCore.Models.Declaration; using TUGraz.VectoCore.Models.Simulation.Data; +using TUGraz.VectoCore.OutputData; +using TUGraz.VectoCore.OutputData.PDF; namespace TUGraz.VectoCore.Models.Simulation.Impl { @@ -26,7 +28,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl private FactoryMode _mode; - public SimulatorFactory(FactoryMode mode, string jobFile) + public SimulatorFactory(FactoryMode mode, IInputDataProvider dataProvider, IReportWriter writer) { Log.Fatal("########## VectoCore Version {0} ##########", Assembly.GetExecutingAssembly().GetName().Version); JobNumber = Interlocked.Increment(ref _jobNumberCounter); @@ -34,25 +36,28 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl switch (mode) { case FactoryMode.DeclarationMode: var report = new DeclarationReport(WindowsIdentity.GetCurrent().Name, - Path.GetDirectoryName(jobFile), Path.GetFileNameWithoutExtension(jobFile)); + dataProvider.JobInputData().JobName, writer); - DataReader = new DeclarationModeVectoRunDataFactory(); + DataReader = new DeclarationModeVectoRunDataFactory(dataProvider, report); break; case FactoryMode.EngineeringMode: - DataReader = new EngineeringModeVectoRunDataFactory(); + DataReader = new EngineeringModeVectoRunDataFactory(dataProvider); break; case FactoryMode.EngineOnlyMode: - DataReader = new EngineOnlyVectoRunDataFactory(); + DataReader = new EngineOnlyVectoRunDataFactory(dataProvider); break; default: throw new VectoException("Unkown factory mode in SimulatorFactory: {0}", mode); } - DataReader.SetJobFile(jobFile); + //DataReader.SetJobFile(jobFile); } public IVectoRunDataFactory DataReader { get; private set; } - public SummaryFileWriter SumWriter { get; set; } + public SummaryDataContainer SumData { get; set; } + + public IModalDataWriter ModWriter { get; set; } + public int JobNumber { get; set; } @@ -66,17 +71,22 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl { var i = 0; foreach (var data in DataReader.NextRun()) { - var modFileName = Path.Combine(data.BasePath, - data.JobName.Replace(Constants.FileExtensions.VectoJobFile, "") + "_{0}{1}" + - Constants.FileExtensions.ModDataFile); + //var modFileName = Path.Combine(data.BasePath, + // data.JobName.Replace(Constants.FileExtensions.VectoJobFile, "") + "_{0}{1}" + + // Constants.FileExtensions.ModDataFile); + // -> string.Format(modFileName, data.Cycle.Name, data.ModFileSuffix ?? "") var d = data; - IModalDataWriter modWriter = - new ModalDataWriter(string.Format(modFileName, data.Cycle.Name, data.ModFileSuffix ?? ""), - writer => d.Report.AddResult(d.Loading, d.Mission, writer), _mode); - modWriter.WriteModalResults = WriteModalResults; - var builder = new PowertrainBuilder(modWriter, - DataReader.IsEngineOnly, (writer, mass, loading) => - SumWriter.Write(d.IsEngineOnly, modWriter, d.JobName, string.Format("{0}-{1}", JobNumber, i++), + IModalDataContainer modContainer = + new ModalDataContainer(data, ModWriter, + writer => { + if (d.Report != null) { + d.Report.AddResult(d.Loading, d.Mission, writer); + } + }, _mode); + modContainer.WriteModalResults = WriteModalResults; + var builder = new PowertrainBuilder(modContainer, + data.IsEngineOnly, (writer, mass, loading) => + SumData.Write(d.IsEngineOnly, modContainer, d.JobName, string.Format("{0}-{1}", JobNumber, i++), d.Cycle.Name + ".vdri", mass, loading)); diff --git a/VectoCore/Models/Simulation/Impl/VectoRun.cs b/VectoCore/Models/Simulation/Impl/VectoRun.cs index b570be7764ec04d7bd881b513ec528a305b55ea5..401ac8985be442dba661abbd714de0eebd4d6bae 100644 --- a/VectoCore/Models/Simulation/Impl/VectoRun.cs +++ b/VectoCore/Models/Simulation/Impl/VectoRun.cs @@ -4,6 +4,7 @@ using TUGraz.VectoCore.Exceptions; using TUGraz.VectoCore.Models.Connector.Ports; using TUGraz.VectoCore.Models.Connector.Ports.Impl; using TUGraz.VectoCore.Models.Simulation.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.Simulation.Impl @@ -17,7 +18,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl protected Second AbsTime = 0.SI<Second>(); protected Second dt = 1.SI<Second>(); - protected SummaryFileWriter SumWriter { get; set; } + protected SummaryDataContainer SumWriter { get; set; } protected string JobFileName { get; set; } protected string JobName { get; set; } protected ISimulationOutPort CyclePort { get; set; } diff --git a/VectoCore/Models/Simulation/Impl/VehicleContainer.cs b/VectoCore/Models/Simulation/Impl/VehicleContainer.cs index 9a5751d8fd2aed7fe40a2d2ec160331133928032..cf5887e45b65248e9bf18bceec10869945efdf57 100644 --- a/VectoCore/Models/Simulation/Impl/VehicleContainer.cs +++ b/VectoCore/Models/Simulation/Impl/VehicleContainer.cs @@ -8,6 +8,7 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.Simulation.Impl @@ -29,7 +30,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl internal ISimulationOutPort Cycle; - internal IModalDataWriter DataWriter; + internal IModalDataContainer ModData; internal WriteSumData WriteSumData; #region IGearCockpit @@ -130,9 +131,9 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl #endregion - public VehicleContainer(IModalDataWriter dataWriter = null, WriteSumData writeSumData = null) + public VehicleContainer(IModalDataContainer modData = null, WriteSumData writeSumData = null) { - DataWriter = dataWriter; + ModData = modData; WriteSumData = writeSumData ?? delegate {}; } @@ -198,22 +199,22 @@ namespace TUGraz.VectoCore.Models.Simulation.Impl { Log.Info("VehicleContainer committing simulation. time: {0}, dist: {1}, speed: {2}", time, Distance, VehicleSpeed); foreach (var component in Components) { - component.CommitSimulationStep(DataWriter); + component.CommitSimulationStep(ModData); } - if (DataWriter != null) { - DataWriter[ModalResultField.time] = time + simulationInterval / 2; - DataWriter[ModalResultField.simulationInterval] = simulationInterval; - DataWriter.CommitSimulationStep(); + if (ModData != null) { + ModData[ModalResultField.time] = time + simulationInterval / 2; + ModData[ModalResultField.simulationInterval] = simulationInterval; + ModData.CommitSimulationStep(); } } public void FinishSimulation() { Log.Info("VehicleContainer finishing simulation."); - DataWriter.Finish(RunStatus); + ModData.Finish(RunStatus); - WriteSumData(DataWriter, VehicleMass, VehicleLoading); + WriteSumData(ModData, VehicleMass, VehicleLoading); } public VectoRun.Status RunStatus { get; set; } diff --git a/VectoCore/Models/SimulationComponent/Data/AuxiliaryData.cs b/VectoCore/Models/SimulationComponent/Data/AuxiliaryData.cs index 041efbe45c23cea1a791e0b55a75e8fb534d4325..a2ac067cd4e4d835d07fee2a7a6def7605696c37 100644 --- a/VectoCore/Models/SimulationComponent/Data/AuxiliaryData.cs +++ b/VectoCore/Models/SimulationComponent/Data/AuxiliaryData.cs @@ -4,89 +4,107 @@ using System.IO; using System.Linq; using System.Text; using TUGraz.VectoCore.Exceptions; +using TUGraz.VectoCore.InputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Data { - public class AuxiliaryData - { - public double EfficiencyToSupply { get; set; } - public double TransitionRatio { get; set; } - public double EfficiencyToEngine { get; set; } - - private readonly DelauneyMap _map = new DelauneyMap(); - - public Watt GetPowerDemand(PerSecond nAuxiliary, Watt powerAuxOut) - { - return _map.Interpolate(nAuxiliary.Value(), powerAuxOut.Value()).SI<Watt>(); - } - - public static AuxiliaryData ReadFromFile(string fileName) - { - var auxData = new AuxiliaryData(); - - try { - var stream = new StreamReader(fileName); - stream.ReadLine(); // skip header "Transmission ration to engine rpm [-]" - auxData.TransitionRatio = stream.ReadLine().IndulgentParse(); - stream.ReadLine(); // skip header "Efficiency to engine [-]" - auxData.EfficiencyToEngine = stream.ReadLine().IndulgentParse(); - stream.ReadLine(); // skip header "Efficiency auxiliary to supply [-]" - auxData.EfficiencyToSupply = stream.ReadLine().IndulgentParse(); - - var m = new MemoryStream(Encoding.UTF8.GetBytes(stream.ReadToEnd())); - var table = VectoCSVFile.ReadStream(m); - - // todo: @@@ check for valid header columns, otherwise use index - if (HeaderIsValid(table.Columns)) { - FillFromColumnNames(table, auxData._map); - } else { - FillFromColumnIndizes(table, auxData._map); - } - - auxData._map.Triangulate(); - - return auxData; - } catch (FileNotFoundException e) { - throw new VectoException("Auxiliary file not found: " + fileName, e); - } - } - - private static void FillFromColumnIndizes(DataTable table, DelauneyMap map) - { - var data = table.Rows.Cast<DataRow>().Select(row => new { - AuxiliarySpeed = row.ParseDouble(0).RPMtoRad(), - MechanicalPower = row.ParseDouble(1).SI().Kilo.Watt.Cast<Watt>(), - SupplyPower = row.ParseDouble(2).SI().Kilo.Watt.Cast<Watt>() - }); - foreach (var d in data) { - map.AddPoint(d.AuxiliarySpeed.Value(), d.SupplyPower.Value(), d.MechanicalPower.Value()); - } - } - - private static void FillFromColumnNames(DataTable table, DelauneyMap map) - { - var data = table.Rows.Cast<DataRow>().Select(row => new { - AuxiliarySpeed = row.ParseDouble(Fields.AuxSpeed).RPMtoRad(), - MechanicalPower = row.ParseDouble(Fields.MechPower).SI().Kilo.Watt.Cast<Watt>(), - SupplyPower = row.ParseDouble(Fields.SupplyPower).SI().Kilo.Watt.Cast<Watt>() - }); - foreach (var d in data) { - map.AddPoint(d.AuxiliarySpeed.Value(), d.SupplyPower.Value(), d.MechanicalPower.Value()); - } - } - - private static bool HeaderIsValid(DataColumnCollection columns) - { - return columns.Contains(Fields.AuxSpeed) && columns.Contains(Fields.MechPower) && - columns.Contains(Fields.SupplyPower); - } - - private static class Fields - { - public const string AuxSpeed = "Auxiliary speed"; - public const string MechPower = "Mechanical power"; - public const string SupplyPower = "Supply power"; - } - } + public class AuxiliaryData + { + public double EfficiencyToSupply { get; set; } + public double TransmissionRatio { get; set; } + public double EfficiencyToEngine { get; set; } + + private readonly DelauneyMap _map = new DelauneyMap(); + + public Watt GetPowerDemand(PerSecond nAuxiliary, Watt powerAuxOut) + { + return _map.Interpolate(nAuxiliary.Value(), powerAuxOut.Value()).SI<Watt>(); + } + + + public static AuxiliaryData ReadFromFile(string fileName) + { + var auxData = new AuxiliaryData(); + + try { + var stream = new StreamReader(fileName); + stream.ReadLine(); // skip header "Transmission ration to engine rpm [-]" + auxData.TransmissionRatio = stream.ReadLine().IndulgentParse(); + stream.ReadLine(); // skip header "Efficiency to engine [-]" + auxData.EfficiencyToEngine = stream.ReadLine().IndulgentParse(); + stream.ReadLine(); // skip header "Efficiency auxiliary to supply [-]" + auxData.EfficiencyToSupply = stream.ReadLine().IndulgentParse(); + + var m = new MemoryStream(Encoding.UTF8.GetBytes(stream.ReadToEnd())); + var table = VectoCSVFile.ReadStream(m); + + // todo: @@@ check for valid header columns, otherwise use index + if (HeaderIsValid(table.Columns)) { + FillFromColumnNames(table, auxData._map); + } else { + FillFromColumnIndizes(table, auxData._map); + } + + auxData._map.Triangulate(); + + return auxData; + } catch (FileNotFoundException e) { + throw new VectoException("Auxiliary file not found: " + fileName, e); + } + } + + private static void FillFromColumnIndizes(DataTable table, DelauneyMap map) + { + var data = table.Rows.Cast<DataRow>().Select(row => new { + AuxiliarySpeed = row.ParseDouble(0).RPMtoRad(), + MechanicalPower = row.ParseDouble(1).SI().Kilo.Watt.Cast<Watt>(), + SupplyPower = row.ParseDouble(2).SI().Kilo.Watt.Cast<Watt>() + }); + foreach (var d in data) { + map.AddPoint(d.AuxiliarySpeed.Value(), d.SupplyPower.Value(), d.MechanicalPower.Value()); + } + } + + private static void FillFromColumnNames(DataTable table, DelauneyMap map) + { + var data = table.Rows.Cast<DataRow>().Select(row => new { + AuxiliarySpeed = row.ParseDouble(Fields.AuxSpeed).RPMtoRad(), + MechanicalPower = row.ParseDouble(Fields.MechPower).SI().Kilo.Watt.Cast<Watt>(), + SupplyPower = row.ParseDouble(Fields.SupplyPower).SI().Kilo.Watt.Cast<Watt>() + }); + foreach (var d in data) { + map.AddPoint(d.AuxiliarySpeed.Value(), d.SupplyPower.Value(), d.MechanicalPower.Value()); + } + } + + internal AuxiliaryData(IAuxiliaryInputData data) + { + TransmissionRatio = data.TransmissionRatio; + EfficiencyToEngine = data.EfficiencyToEngine; + EfficiencyToSupply = data.EfficiencyToSupply; + if (HeaderIsValid(data.DemandMap.Columns)) { + FillFromColumnNames(data.DemandMap, _map); + } else { + FillFromColumnIndizes(data.DemandMap, _map); + } + + _map.Triangulate(); + } + + private AuxiliaryData() {} + + private static bool HeaderIsValid(DataColumnCollection columns) + { + return columns.Contains(Fields.AuxSpeed) && columns.Contains(Fields.MechPower) && + columns.Contains(Fields.SupplyPower); + } + + private static class Fields + { + public const string AuxSpeed = "Auxiliary speed"; + public const string MechPower = "Mechanical power"; + public const string SupplyPower = "Supply power"; + } + } } \ No newline at end of file diff --git a/VectoCore/Models/SimulationComponent/Impl/Auxiliary.cs b/VectoCore/Models/SimulationComponent/Impl/Auxiliary.cs index a9305a7974cf123a053ed4f1b9c344ffc1758c46..e1caf6cdb3cf93e9eef9b19eecc97c53f1575bea 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Auxiliary.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Auxiliary.cs @@ -5,6 +5,7 @@ using TUGraz.VectoCore.Models.Connector.Ports; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -83,17 +84,17 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { var sum = 0.SI<Watt>(); foreach (var kv in _powerDemands) { sum += kv.Value; // todo: aux write directauxiliary somewhere to moddata .... probably Padd column?? if (!string.IsNullOrWhiteSpace(kv.Key)) { - writer[kv.Key] = kv.Value; + container[kv.Key] = kv.Value; } } - writer[ModalResultField.Paux] = sum; + container[ModalResultField.Paux] = sum; } protected override void DoCommitSimulationStep() {} @@ -120,7 +121,7 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl _auxDict[auxId] = speed => { var powerSupply = cycle.CycleData().LeftSample.AuxiliarySupplyPower["Aux_" + auxId]; - var nAuxiliary = speed * data.TransitionRatio; + var nAuxiliary = speed * data.TransmissionRatio; var powerAuxOut = powerSupply / data.EfficiencyToSupply; var powerAuxIn = data.GetPowerDemand(nAuxiliary, powerAuxOut); return powerAuxIn / data.EfficiencyToEngine; diff --git a/VectoCore/Models/SimulationComponent/Impl/AxleGear.cs b/VectoCore/Models/SimulationComponent/Impl/AxleGear.cs index fa7b4d1130fb8a3ef6e064b757d070db44e08f51..f78ee69691b4c893dad1b55a88fc3c9ba70aa266 100644 --- a/VectoCore/Models/SimulationComponent/Impl/AxleGear.cs +++ b/VectoCore/Models/SimulationComponent/Impl/AxleGear.cs @@ -2,6 +2,7 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data.Gearbox; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -59,9 +60,9 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl return NextComponent.Initialize(inTorque, inAngularVelocity); } - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.PlossDiff] = Loss; + container[ModalResultField.PlossDiff] = Loss; } protected override void DoCommitSimulationStep() diff --git a/VectoCore/Models/SimulationComponent/Impl/Brakes.cs b/VectoCore/Models/SimulationComponent/Impl/Brakes.cs index 6ab0edf518a93614b02a66319a873539cae637a6..9cf63f6f1073d27743c0ca566f8efdce367a0e37 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Brakes.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Brakes.cs @@ -3,6 +3,7 @@ using TUGraz.VectoCore.Exceptions; using TUGraz.VectoCore.Models.Connector.Ports; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -58,9 +59,9 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl NextComponent = other; } - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.Pbrake] = BrakePower; + container[ModalResultField.Pbrake] = BrakePower; } protected override void DoCommitSimulationStep() diff --git a/VectoCore/Models/SimulationComponent/Impl/Clutch.cs b/VectoCore/Models/SimulationComponent/Impl/Clutch.cs index 84fb25be735210df14604d1892d48093b40ee8af..d7727ea0b447935adf6944d04d56587fa55eeb57 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Clutch.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Clutch.cs @@ -3,6 +3,7 @@ using TUGraz.VectoCore.Models.Connector.Ports; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -34,10 +35,10 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl return _clutchState; } - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.Pe_clutch] = _RequiredPower; - writer[ModalResultField.Tq_clutch] = _RequiredTorque; + container[ModalResultField.Pe_clutch] = _RequiredPower; + container[ModalResultField.Tq_clutch] = _RequiredTorque; } protected override void DoCommitSimulationStep() diff --git a/VectoCore/Models/SimulationComponent/Impl/CombustionEngine.cs b/VectoCore/Models/SimulationComponent/Impl/CombustionEngine.cs index 0ae4c257d05e5b1a7843e7aa4753a42bb0c770b3..86128825b0cc87d22d7e698398924a1d883d33ee 100644 --- a/VectoCore/Models/SimulationComponent/Impl/CombustionEngine.cs +++ b/VectoCore/Models/SimulationComponent/Impl/CombustionEngine.cs @@ -11,6 +11,7 @@ using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -202,30 +203,30 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.PaEng] = CurrentState.EnginePowerLoss; - writer[ModalResultField.Pe_drag] = CurrentState.FullDragPower; - writer[ModalResultField.Pe_full] = CurrentState.DynamicFullLoadPower; - writer[ModalResultField.Pe_eng] = CurrentState.EnginePower; + container[ModalResultField.PaEng] = CurrentState.EnginePowerLoss; + container[ModalResultField.Pe_drag] = CurrentState.FullDragPower; + container[ModalResultField.Pe_full] = CurrentState.DynamicFullLoadPower; + container[ModalResultField.Pe_eng] = CurrentState.EnginePower; - writer[ModalResultField.Tq_drag] = CurrentState.FullDragTorque; - writer[ModalResultField.Tq_full] = CurrentState.DynamicFullLoadTorque; - writer[ModalResultField.Tq_eng] = CurrentState.EngineTorque; - writer[ModalResultField.n] = CurrentState.EngineSpeed; + container[ModalResultField.Tq_drag] = CurrentState.FullDragTorque; + container[ModalResultField.Tq_full] = CurrentState.DynamicFullLoadTorque; + container[ModalResultField.Tq_eng] = CurrentState.EngineTorque; + container[ModalResultField.n] = CurrentState.EngineSpeed; try { var fc = Data.ConsumptionMap.GetFuelConsumption(CurrentState.EngineTorque, CurrentState.EngineSpeed); - writer[ModalResultField.FCMap] = fc; + container[ModalResultField.FCMap] = fc; //todo (MK, 2015-11-11): calculate aux start stop correction when start stop functionality is implemented in v3 var fcaux = fc; - writer[ModalResultField.FCAUXc] = fcaux; - writer[ModalResultField.FCWHTCc] = fcaux * Data.WHTCCorrectionFactor; + container[ModalResultField.FCAUXc] = fcaux; + container[ModalResultField.FCWHTCc] = fcaux * Data.WHTCCorrectionFactor; } catch (VectoException ex) { Log.Warn("t: {0} - {1} n: {2} Tq: {3}", CurrentState.AbsTime, ex.Message, CurrentState.EngineSpeed, CurrentState.EngineTorque); - writer[ModalResultField.FCMap] = double.NaN.SI<KilogramPerSecond>(); + container[ModalResultField.FCMap] = double.NaN.SI<KilogramPerSecond>(); } } diff --git a/VectoCore/Models/SimulationComponent/Impl/DistanceBasedDrivingCycle.cs b/VectoCore/Models/SimulationComponent/Impl/DistanceBasedDrivingCycle.cs index c8143ba76a049f8171dce496e50bddb508125d4c..00645585b51e20dc45423ad62a249424ce0845cb 100644 --- a/VectoCore/Models/SimulationComponent/Impl/DistanceBasedDrivingCycle.cs +++ b/VectoCore/Models/SimulationComponent/Impl/DistanceBasedDrivingCycle.cs @@ -9,6 +9,7 @@ using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -249,13 +250,13 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.dist] = CurrentState.Distance; - writer[ModalResultField.simulationDistance] = CurrentState.SimulationDistance; - writer[ModalResultField.v_targ] = CurrentState.VehicleTargetSpeed; - writer[ModalResultField.grad] = (Math.Tan(CurrentState.Gradient.Value()) * 100).SI<Scalar>(); - writer[ModalResultField.altitude] = CurrentState.Altitude; + container[ModalResultField.dist] = CurrentState.Distance; + container[ModalResultField.simulationDistance] = CurrentState.SimulationDistance; + container[ModalResultField.v_targ] = CurrentState.VehicleTargetSpeed; + container[ModalResultField.grad] = (Math.Tan(CurrentState.Gradient.Value()) * 100).SI<Scalar>(); + container[ModalResultField.altitude] = CurrentState.Altitude; } protected override void DoCommitSimulationStep() diff --git a/VectoCore/Models/SimulationComponent/Impl/Driver.cs b/VectoCore/Models/SimulationComponent/Impl/Driver.cs index d2ee769e33823c14bc37fba04ca7ad8b7e191dda..93a301b2573005e82cc7aeac7b70c99e55f41b67 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Driver.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Driver.cs @@ -11,6 +11,7 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -788,9 +789,9 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl return this; } - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.acc] = CurrentState.Acceleration; + container[ModalResultField.acc] = CurrentState.Acceleration; } protected override void DoCommitSimulationStep() diff --git a/VectoCore/Models/SimulationComponent/Impl/EngineOnlyDrivingCycle.cs b/VectoCore/Models/SimulationComponent/Impl/EngineOnlyDrivingCycle.cs index e21d22d6f5a8aa1616d80bca032e4f8e25021b09..a220da6fcde9bb05a5f2e479942b0044b6fbc70c 100644 --- a/VectoCore/Models/SimulationComponent/Impl/EngineOnlyDrivingCycle.cs +++ b/VectoCore/Models/SimulationComponent/Impl/EngineOnlyDrivingCycle.cs @@ -7,6 +7,7 @@ using TUGraz.VectoCore.Models.Connector.Ports.Impl; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -102,7 +103,7 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) {} + protected override void DoWriteModalResults(IModalDataContainer container) {} protected override void DoCommitSimulationStep() { diff --git a/VectoCore/Models/SimulationComponent/Impl/EngineOnlyGearbox.cs b/VectoCore/Models/SimulationComponent/Impl/EngineOnlyGearbox.cs index 5cd48bba7beb326f779c868b7f316d44c9937af7..18588afb1eaef157798e1b7694b3ec984ba66819 100644 --- a/VectoCore/Models/SimulationComponent/Impl/EngineOnlyGearbox.cs +++ b/VectoCore/Models/SimulationComponent/Impl/EngineOnlyGearbox.cs @@ -5,6 +5,7 @@ using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -85,7 +86,7 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) {} + protected override void DoWriteModalResults(IModalDataContainer container) {} protected override void DoCommitSimulationStep() {} diff --git a/VectoCore/Models/SimulationComponent/Impl/Gearbox.cs b/VectoCore/Models/SimulationComponent/Impl/Gearbox.cs index ebb6565f850fe214f61e10198c47d79b0d090c8e..3a7bc3189315b2ba2d7015b9863a2c9e0a1d6d3a 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Gearbox.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Gearbox.cs @@ -7,6 +7,7 @@ using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -358,11 +359,11 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.Gear] = _disengaged || DataBus.VehicleStopped ? 0 : Gear; - writer[ModalResultField.PlossGB] = _powerLoss; - writer[ModalResultField.PaGB] = _powerLossInertia; + container[ModalResultField.Gear] = _disengaged || DataBus.VehicleStopped ? 0 : Gear; + container[ModalResultField.PlossGB] = _powerLoss; + container[ModalResultField.PaGB] = _powerLossInertia; } protected override void DoCommitSimulationStep() diff --git a/VectoCore/Models/SimulationComponent/Impl/Retarder.cs b/VectoCore/Models/SimulationComponent/Impl/Retarder.cs index c071013fa36a67d864b65a6bf07de08f04273a0a..ddd20e8080d6b5aef8541352733c4823639ff597 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Retarder.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Retarder.cs @@ -3,6 +3,7 @@ using TUGraz.VectoCore.Models.Connector.Ports; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -21,9 +22,9 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl _lossMap = lossMap; } - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.PlossRetarder] = _retarderLoss; + container[ModalResultField.PlossRetarder] = _retarderLoss; } protected override void DoCommitSimulationStep() {} diff --git a/VectoCore/Models/SimulationComponent/Impl/TimeBasedDrivingCycle.cs b/VectoCore/Models/SimulationComponent/Impl/TimeBasedDrivingCycle.cs index fe36885feebacd49fbb0028633e2f8dc8298d1b8..25e0500a4d578626b026da80f99ee0ff61db55b5 100644 --- a/VectoCore/Models/SimulationComponent/Impl/TimeBasedDrivingCycle.cs +++ b/VectoCore/Models/SimulationComponent/Impl/TimeBasedDrivingCycle.cs @@ -4,6 +4,7 @@ using TUGraz.VectoCore.Models.Connector.Ports.Impl; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -94,7 +95,7 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { // TODO: write data... } diff --git a/VectoCore/Models/SimulationComponent/Impl/Vehicle.cs b/VectoCore/Models/SimulationComponent/Impl/Vehicle.cs index 4402ce894926474fb208780460e22c2422e303ae..4c075534d110d744bb020eef51d4b36a574bb7a3 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Vehicle.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Vehicle.cs @@ -9,326 +9,327 @@ using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl { - public class Vehicle : VectoSimulationComponent, IVehicle, IMileageCounter, IFvInPort, IDriverDemandOutPort - { - protected IFvOutPort NextComponent; - private VehicleState _previousState; - private VehicleState _currentState; - private readonly VehicleData _data; - - private readonly Point[] _airResistanceCurve; - - public MeterPerSecond VehicleSpeed - { - get { return _previousState.Velocity; } - } - - public Kilogram VehicleMass - { - get { return _data.TotalCurbWeight(); } - } - - public Kilogram VehicleLoading - { - get { return _data.Loading; } - } - - public Kilogram TotalMass - { - get { return _data.TotalVehicleWeight(); } - } - - public Meter Distance - { - get { return _previousState.Distance; } - } - - - public Vehicle(IVehicleContainer container, VehicleData data) : base(container) - { - _data = data; - _previousState = new VehicleState { Distance = 0.SI<Meter>(), Velocity = 0.SI<MeterPerSecond>() }; - _currentState = new VehicleState { Distance = 0.SI<Meter>(), Velocity = 0.SI<MeterPerSecond>() }; - - var values = DeclarationData.AirDrag.Lookup(_data.VehicleCategory); - _airResistanceCurve = CalculateAirResistanceCurve(values); - } - - - public IFvInPort InPort() - { - return this; - } - - public IDriverDemandOutPort OutPort() - { - return this; - } - - public void Connect(IFvOutPort other) - { - NextComponent = other; - } - - public IResponse Initialize(MeterPerSecond vehicleSpeed, Radian roadGradient) - { - _previousState = new VehicleState { - Distance = DataBus.CycleStartDistance, - Velocity = vehicleSpeed, - RollingResistance = RollingResistance(roadGradient), - SlopeResistance = SlopeResistance(roadGradient) - }; - _previousState.AirDragResistance = AirDragResistance(0.SI<MeterPerSquareSecond>(), - Constants.SimulationSettings.TargetTimeInterval); - _previousState.VehicleAccelerationForce = _previousState.RollingResistance - + _previousState.AirDragResistance - + _previousState.SlopeResistance; - - _currentState = new VehicleState { - Distance = DataBus.CycleStartDistance, - Velocity = vehicleSpeed, - AirDragResistance = _previousState.AirDragResistance, - RollingResistance = _previousState.RollingResistance, - SlopeResistance = _previousState.SlopeResistance, - VehicleAccelerationForce = _previousState.VehicleAccelerationForce, - }; - - - return NextComponent.Initialize(_currentState.VehicleAccelerationForce, vehicleSpeed); - } - - public IResponse Initialize(MeterPerSecond vehicleSpeed, MeterPerSquareSecond startAcceleration, - Radian roadGradient) - { - var tmp = _previousState.Velocity; - // set vehicle speed to get accurate airdrag resistance - _previousState.Velocity = vehicleSpeed; - _currentState.Velocity = vehicleSpeed + startAcceleration * Constants.SimulationSettings.TargetTimeInterval; - var vehicleAccelerationForce = DriverAcceleration(startAcceleration) + RollingResistance(roadGradient) + - AirDragResistance(startAcceleration, - Constants.SimulationSettings.TargetTimeInterval) + - SlopeResistance(roadGradient); - - var retVal = NextComponent.Initialize(vehicleAccelerationForce, vehicleSpeed); - - _previousState.Velocity = tmp; - _currentState.Velocity = tmp; - return retVal; - } - - public IResponse Request(Second absTime, Second dt, MeterPerSquareSecond acceleration, Radian gradient, - bool dryRun = false) - { - Log.Debug("from Wheels: acceleration: {0}", acceleration); - _currentState.dt = dt; - _currentState.Acceleration = acceleration; - _currentState.Velocity = _previousState.Velocity + acceleration * dt; - if (_currentState.Velocity.IsEqual(0.SI<MeterPerSecond>(), - Constants.SimulationSettings.VehicleSpeedHaltTolerance)) { - _currentState.Velocity = 0.SI<MeterPerSecond>(); - } - _currentState.Distance = _previousState.Distance + _previousState.Velocity * dt + acceleration * dt * dt / 2; - - _currentState.DriverAcceleration = DriverAcceleration(acceleration); - _currentState.RollingResistance = RollingResistance(gradient); - _currentState.AirDragResistance = AirDragResistance(acceleration, dt); - _currentState.SlopeResistance = SlopeResistance(gradient); - - // DriverAcceleration = vehicleAccelerationForce - RollingResistance - AirDragResistance - SlopeResistance - _currentState.VehicleAccelerationForce = _currentState.DriverAcceleration - + _currentState.RollingResistance - + _currentState.AirDragResistance - + _currentState.SlopeResistance; - - var retval = NextComponent.Request(absTime, dt, _currentState.VehicleAccelerationForce, - _currentState.Velocity, - dryRun); - return retval; - } - - protected override void DoWriteModalResults(IModalDataWriter writer) - { - var averageVelocity = (_previousState.Velocity + _currentState.Velocity) / 2; - - writer[ModalResultField.v_act] = averageVelocity; - writer[ModalResultField.PaVeh] = ((_previousState.VehicleAccelerationForce * _previousState.Velocity + - _currentState.VehicleAccelerationForce * _currentState.Velocity) / 2.0) - .Cast<Watt>(); - writer[ModalResultField.Pgrad] = ((_previousState.SlopeResistance * _previousState.Velocity + - _currentState.SlopeResistance * _currentState.Velocity) / 2.0).Cast<Watt> - (); - writer[ModalResultField.Proll] = ((_previousState.RollingResistance * _previousState.Velocity + - _currentState.RollingResistance * _currentState.Velocity) / 2.0) - .Cast<Watt>(); - - writer[ModalResultField.Pair] = ComputeAirDragPowerLoss(_previousState.Velocity, _currentState.Velocity, - _currentState.dt); - - - // sanity check: is the vehicle in step with the cycle? - if (writer[ModalResultField.dist] == DBNull.Value) { - Log.Warn("distance field is not set!"); - } else { - var distance = (SI)writer[ModalResultField.dist]; - if (!distance.IsEqual(_currentState.Distance, 1e-12.SI<Meter>())) { - Log.Warn("distance diverges: {0}, distance: {1}", (distance - _currentState.Distance).Value(), - distance); - } - } - } - - - protected override void DoCommitSimulationStep() - { - _previousState = _currentState; - _currentState = new VehicleState(); - } - - protected Newton RollingResistance(Radian gradient) - { - var retVal = (Math.Cos(gradient.Value()) * _data.TotalVehicleWeight() * - Physics.GravityAccelleration * - _data.TotalRollResistanceCoefficient).Cast<Newton>(); - Log.Debug("RollingResistance: {0}", retVal); - return retVal; - } - - - protected Newton DriverAcceleration(MeterPerSquareSecond accelleration) - { - var retVal = ((_data.TotalVehicleWeight() + _data.ReducedMassWheels) * accelleration).Cast<Newton>(); - Log.Debug("DriverAcceleration: {0}", retVal); - return retVal; - } - - - protected internal Newton SlopeResistance(Radian gradient) - { - var retVal = - (_data.TotalVehicleWeight() * Physics.GravityAccelleration * Math.Sin(gradient.Value())).Cast<Newton>(); - Log.Debug("SlopeResistance: {0}", retVal); - return retVal; - } - - - protected internal Newton AirDragResistance(MeterPerSquareSecond acceleration, Second dt) - { - var vAverage = _previousState.Velocity + acceleration * dt / 2; - if (vAverage.IsEqual(0)) { - return 0.SI<Newton>(); - } - var result = - (ComputeAirDragPowerLoss(_previousState.Velocity, _previousState.Velocity + acceleration * dt, dt) / - vAverage).Cast<Newton>(); - - Log.Debug("AirDragResistance: {0}", result); - return result; - } - - private Watt ComputeAirDragPowerLoss(MeterPerSecond v1, MeterPerSecond v2, Second dt) - { - var vAverage = (v1 + v2) / 2; - var CdA = ComputeEffectiveAirDragArea(vAverage); - Watt averageAirDragPower; - if (v1.IsEqual(v2)) { - averageAirDragPower = (Physics.AirDensity / 2.0 * CdA * vAverage * vAverage * vAverage).Cast<Watt>(); - } else { - // compute the average force within the current simulation interval - // P(t) = k * v(t)^3 , v(t) = v0 + a * t // a != 0 - // => P_avg = (CdA * rho/2)/(4*a * dt) * (v2^4 - v1^4) - var acceleration = (v2 - v1) / dt; - averageAirDragPower = - (Physics.AirDensity / 2.0 * CdA * (v2 * v2 * v2 * v2 - v1 * v1 * v1 * v1) / (4 * acceleration * dt)) - .Cast<Watt>(); - } - return averageAirDragPower; - } - - protected internal SquareMeter ComputeEffectiveAirDragArea(MeterPerSecond velocity) - { - var CdA = _data.AerodynamicDragAera; - switch (_data.CrossWindCorrectionMode) { - case CrossWindCorrectionMode.NoCorrection: - break; - case CrossWindCorrectionMode.DeclarationModeCorrection: - CdA = AirDragInterpolate(velocity); - break; - default: - throw new NotImplementedException(string.Format("CrossWindcorrection {0} is not implemented", - _data.CrossWindCorrectionMode)); - } - return CdA; - } - - private SquareMeter AirDragInterpolate(MeterPerSecond x) - { - var p = _airResistanceCurve.GetSection(c => c.X < x); - - if (x < p.Item1.X || p.Item2.X < x) { - Log.Error(_data.CrossWindCorrectionMode == CrossWindCorrectionMode.VAirBetaLookupTable - ? string.Format("CdExtrapol β = {0}", x) - : string.Format("CdExtrapol v = {0}", x)); - } - - return VectoMath.Interpolate(p.Item1.X, p.Item2.X, p.Item1.Y, p.Item2.Y, x); - } - - protected Point[] CalculateAirResistanceCurve(AirDrag.AirDragEntry values) - { - var points = new List<Point> { new Point { X = 0.SI<MeterPerSecond>(), Y = 0.SI<SquareMeter>() } }; - - for (var speed = 60; speed <= 100; speed += 5) { - var vVeh = speed.KMPHtoMeterPerSecond(); - var cdASum = 0.0.SI<SquareMeter>(); - for (var alpha = 0; alpha <= 180; alpha += 10) { - var vWindX = Physics.BaseWindSpeed * Math.Cos(alpha.ToRadian()); - var vWindY = Physics.BaseWindSpeed * Math.Sin(alpha.ToRadian()); - var vAirX = vVeh + vWindX; - var vAirY = vWindY; + public class Vehicle : VectoSimulationComponent, IVehicle, IMileageCounter, IFvInPort, IDriverDemandOutPort + { + protected IFvOutPort NextComponent; + private VehicleState _previousState; + private VehicleState _currentState; + private readonly VehicleData _data; + + private readonly Point[] _airResistanceCurve; + + public MeterPerSecond VehicleSpeed + { + get { return _previousState.Velocity; } + } + + public Kilogram VehicleMass + { + get { return _data.TotalCurbWeight(); } + } + + public Kilogram VehicleLoading + { + get { return _data.Loading; } + } + + public Kilogram TotalMass + { + get { return _data.TotalVehicleWeight(); } + } + + public Meter Distance + { + get { return _previousState.Distance; } + } + + + public Vehicle(IVehicleContainer container, VehicleData data) : base(container) + { + _data = data; + _previousState = new VehicleState { Distance = 0.SI<Meter>(), Velocity = 0.SI<MeterPerSecond>() }; + _currentState = new VehicleState { Distance = 0.SI<Meter>(), Velocity = 0.SI<MeterPerSecond>() }; + + var values = DeclarationData.AirDrag.Lookup(_data.VehicleCategory); + _airResistanceCurve = CalculateAirResistanceCurve(values); + } + + + public IFvInPort InPort() + { + return this; + } + + public IDriverDemandOutPort OutPort() + { + return this; + } + + public void Connect(IFvOutPort other) + { + NextComponent = other; + } + + public IResponse Initialize(MeterPerSecond vehicleSpeed, Radian roadGradient) + { + _previousState = new VehicleState { + Distance = DataBus.CycleStartDistance, + Velocity = vehicleSpeed, + RollingResistance = RollingResistance(roadGradient), + SlopeResistance = SlopeResistance(roadGradient) + }; + _previousState.AirDragResistance = AirDragResistance(0.SI<MeterPerSquareSecond>(), + Constants.SimulationSettings.TargetTimeInterval); + _previousState.VehicleAccelerationForce = _previousState.RollingResistance + + _previousState.AirDragResistance + + _previousState.SlopeResistance; + + _currentState = new VehicleState { + Distance = DataBus.CycleStartDistance, + Velocity = vehicleSpeed, + AirDragResistance = _previousState.AirDragResistance, + RollingResistance = _previousState.RollingResistance, + SlopeResistance = _previousState.SlopeResistance, + VehicleAccelerationForce = _previousState.VehicleAccelerationForce, + }; + + + return NextComponent.Initialize(_currentState.VehicleAccelerationForce, vehicleSpeed); + } + + public IResponse Initialize(MeterPerSecond vehicleSpeed, MeterPerSquareSecond startAcceleration, + Radian roadGradient) + { + var tmp = _previousState.Velocity; + // set vehicle speed to get accurate airdrag resistance + _previousState.Velocity = vehicleSpeed; + _currentState.Velocity = vehicleSpeed + startAcceleration * Constants.SimulationSettings.TargetTimeInterval; + var vehicleAccelerationForce = DriverAcceleration(startAcceleration) + RollingResistance(roadGradient) + + AirDragResistance(startAcceleration, + Constants.SimulationSettings.TargetTimeInterval) + + SlopeResistance(roadGradient); + + var retVal = NextComponent.Initialize(vehicleAccelerationForce, vehicleSpeed); + + _previousState.Velocity = tmp; + _currentState.Velocity = tmp; + return retVal; + } + + public IResponse Request(Second absTime, Second dt, MeterPerSquareSecond acceleration, Radian gradient, + bool dryRun = false) + { + Log.Debug("from Wheels: acceleration: {0}", acceleration); + _currentState.dt = dt; + _currentState.Acceleration = acceleration; + _currentState.Velocity = _previousState.Velocity + acceleration * dt; + if (_currentState.Velocity.IsEqual(0.SI<MeterPerSecond>(), + Constants.SimulationSettings.VehicleSpeedHaltTolerance)) { + _currentState.Velocity = 0.SI<MeterPerSecond>(); + } + _currentState.Distance = _previousState.Distance + _previousState.Velocity * dt + acceleration * dt * dt / 2; + + _currentState.DriverAcceleration = DriverAcceleration(acceleration); + _currentState.RollingResistance = RollingResistance(gradient); + _currentState.AirDragResistance = AirDragResistance(acceleration, dt); + _currentState.SlopeResistance = SlopeResistance(gradient); + + // DriverAcceleration = vehicleAccelerationForce - RollingResistance - AirDragResistance - SlopeResistance + _currentState.VehicleAccelerationForce = _currentState.DriverAcceleration + + _currentState.RollingResistance + + _currentState.AirDragResistance + + _currentState.SlopeResistance; + + var retval = NextComponent.Request(absTime, dt, _currentState.VehicleAccelerationForce, + _currentState.Velocity, + dryRun); + return retval; + } + + protected override void DoWriteModalResults(IModalDataContainer container) + { + var averageVelocity = (_previousState.Velocity + _currentState.Velocity) / 2; + + container[ModalResultField.v_act] = averageVelocity; + container[ModalResultField.PaVeh] = ((_previousState.VehicleAccelerationForce * _previousState.Velocity + + _currentState.VehicleAccelerationForce * _currentState.Velocity) / 2.0) + .Cast<Watt>(); + container[ModalResultField.Pgrad] = ((_previousState.SlopeResistance * _previousState.Velocity + + _currentState.SlopeResistance * _currentState.Velocity) / 2.0).Cast<Watt> + (); + container[ModalResultField.Proll] = ((_previousState.RollingResistance * _previousState.Velocity + + _currentState.RollingResistance * _currentState.Velocity) / 2.0) + .Cast<Watt>(); + + container[ModalResultField.Pair] = ComputeAirDragPowerLoss(_previousState.Velocity, _currentState.Velocity, + _currentState.dt); + + + // sanity check: is the vehicle in step with the cycle? + if (container[ModalResultField.dist] == DBNull.Value) { + Log.Warn("distance field is not set!"); + } else { + var distance = (SI)container[ModalResultField.dist]; + if (!distance.IsEqual(_currentState.Distance, 1e-12.SI<Meter>())) { + Log.Warn("distance diverges: {0}, distance: {1}", (distance - _currentState.Distance).Value(), + distance); + } + } + } + + + protected override void DoCommitSimulationStep() + { + _previousState = _currentState; + _currentState = new VehicleState(); + } + + protected Newton RollingResistance(Radian gradient) + { + var retVal = (Math.Cos(gradient.Value()) * _data.TotalVehicleWeight() * + Physics.GravityAccelleration * + _data.TotalRollResistanceCoefficient).Cast<Newton>(); + Log.Debug("RollingResistance: {0}", retVal); + return retVal; + } + + + protected Newton DriverAcceleration(MeterPerSquareSecond accelleration) + { + var retVal = ((_data.TotalVehicleWeight() + _data.ReducedMassWheels) * accelleration).Cast<Newton>(); + Log.Debug("DriverAcceleration: {0}", retVal); + return retVal; + } + + + protected internal Newton SlopeResistance(Radian gradient) + { + var retVal = + (_data.TotalVehicleWeight() * Physics.GravityAccelleration * Math.Sin(gradient.Value())).Cast<Newton>(); + Log.Debug("SlopeResistance: {0}", retVal); + return retVal; + } + + + protected internal Newton AirDragResistance(MeterPerSquareSecond acceleration, Second dt) + { + var vAverage = _previousState.Velocity + acceleration * dt / 2; + if (vAverage.IsEqual(0)) { + return 0.SI<Newton>(); + } + var result = + (ComputeAirDragPowerLoss(_previousState.Velocity, _previousState.Velocity + acceleration * dt, dt) / + vAverage).Cast<Newton>(); + + Log.Debug("AirDragResistance: {0}", result); + return result; + } + + private Watt ComputeAirDragPowerLoss(MeterPerSecond v1, MeterPerSecond v2, Second dt) + { + var vAverage = (v1 + v2) / 2; + var CdA = ComputeEffectiveAirDragArea(vAverage); + Watt averageAirDragPower; + if (v1.IsEqual(v2)) { + averageAirDragPower = (Physics.AirDensity / 2.0 * CdA * vAverage * vAverage * vAverage).Cast<Watt>(); + } else { + // compute the average force within the current simulation interval + // P(t) = k * v(t)^3 , v(t) = v0 + a * t // a != 0 + // => P_avg = (CdA * rho/2)/(4*a * dt) * (v2^4 - v1^4) + var acceleration = (v2 - v1) / dt; + averageAirDragPower = + (Physics.AirDensity / 2.0 * CdA * (v2 * v2 * v2 * v2 - v1 * v1 * v1 * v1) / (4 * acceleration * dt)) + .Cast<Watt>(); + } + return averageAirDragPower; + } + + protected internal SquareMeter ComputeEffectiveAirDragArea(MeterPerSecond velocity) + { + var CdA = _data.AerodynamicDragAera; + switch (_data.CrossWindCorrectionMode) { + case CrossWindCorrectionMode.NoCorrection: + break; + case CrossWindCorrectionMode.DeclarationModeCorrection: + CdA = AirDragInterpolate(velocity); + break; + default: + throw new NotImplementedException(string.Format("CrossWindcorrection {0} is not implemented", + _data.CrossWindCorrectionMode)); + } + return CdA; + } + + private SquareMeter AirDragInterpolate(MeterPerSecond x) + { + var p = _airResistanceCurve.GetSection(c => c.X < x); + + if (x < p.Item1.X || p.Item2.X < x) { + Log.Error(_data.CrossWindCorrectionMode == CrossWindCorrectionMode.VAirBetaLookupTable + ? string.Format("CdExtrapol β = {0}", x) + : string.Format("CdExtrapol v = {0}", x)); + } + + return VectoMath.Interpolate(p.Item1.X, p.Item2.X, p.Item1.Y, p.Item2.Y, x); + } + + protected Point[] CalculateAirResistanceCurve(AirDrag.AirDragEntry values) + { + var points = new List<Point> { new Point { X = 0.SI<MeterPerSecond>(), Y = 0.SI<SquareMeter>() } }; + + for (var speed = 60; speed <= 100; speed += 5) { + var vVeh = speed.KMPHtoMeterPerSecond(); + var cdASum = 0.0.SI<SquareMeter>(); + for (var alpha = 0; alpha <= 180; alpha += 10) { + var vWindX = Physics.BaseWindSpeed * Math.Cos(alpha.ToRadian()); + var vWindY = Physics.BaseWindSpeed * Math.Sin(alpha.ToRadian()); + var vAirX = vVeh + vWindX; + var vAirY = vWindY; // var vAir = VectoMath.Sqrt<MeterPerSecond>(vAirX * vAirX + vAirY * vAirY); - var beta = Math.Atan((vAirY / vAirX).Value()).ToDegree(); - var deltaCdA = ComputeDeltaCd(beta, values); - var cdA = _data.AerodynamicDragAera + deltaCdA; + var beta = Math.Atan((vAirY / vAirX).Value()).ToDegree(); + var deltaCdA = ComputeDeltaCd(beta, values); + var cdA = _data.AerodynamicDragAera + deltaCdA; - var degreeShare = ((alpha != 0 && alpha != 180) ? 10.0 / 180.0 : 5.0 / 180.0); + var degreeShare = ((alpha != 0 && alpha != 180) ? 10.0 / 180.0 : 5.0 / 180.0); // cdASum += degreeShare * cdA * (vAir * vAir / (vVeh * vVeh)).Cast<Scalar>(); - cdASum += degreeShare * cdA * ((vAirX * vAirX + vAirY * vAirY) / (vVeh * vVeh)).Cast<Scalar>(); - } - points.Add(new Point { X = vVeh, Y = cdASum }); - } - - points[0].Y = points[1].Y; - return points.ToArray(); - } - - protected SquareMeter ComputeDeltaCd(double beta, AirDrag.AirDragEntry values) - { - return (values.A1 * beta + values.A2 * beta * beta + values.A3 * beta * beta * beta).SI<SquareMeter>(); - } - - public class VehicleState - { - public MeterPerSecond Velocity; - public Second dt; - public Meter Distance; - - public Newton VehicleAccelerationForce; - public Newton DriverAcceleration; - public Newton SlopeResistance; - public Newton AirDragResistance; - public Newton RollingResistance; - public MeterPerSquareSecond Acceleration { get; set; } - } - - public class Point - { - public MeterPerSecond X; - public SquareMeter Y; - } - } + cdASum += degreeShare * cdA * ((vAirX * vAirX + vAirY * vAirY) / (vVeh * vVeh)).Cast<Scalar>(); + } + points.Add(new Point { X = vVeh, Y = cdASum }); + } + + points[0].Y = points[1].Y; + return points.ToArray(); + } + + protected SquareMeter ComputeDeltaCd(double beta, AirDrag.AirDragEntry values) + { + return (values.A1 * beta + values.A2 * beta * beta + values.A3 * beta * beta * beta).SI<SquareMeter>(); + } + + public class VehicleState + { + public MeterPerSecond Velocity; + public Second dt; + public Meter Distance; + + public Newton VehicleAccelerationForce; + public Newton DriverAcceleration; + public Newton SlopeResistance; + public Newton AirDragResistance; + public Newton RollingResistance; + public MeterPerSquareSecond Acceleration { get; set; } + } + + public class Point + { + public MeterPerSecond X; + public SquareMeter Y; + } + } } \ No newline at end of file diff --git a/VectoCore/Models/SimulationComponent/Impl/Wheels.cs b/VectoCore/Models/SimulationComponent/Impl/Wheels.cs index 3f3f598399ccf41d8302e593ef53ba392c37b1cb..adb31c88d8ac1bcd260acdd2b41c788fea794d4b 100644 --- a/VectoCore/Models/SimulationComponent/Impl/Wheels.cs +++ b/VectoCore/Models/SimulationComponent/Impl/Wheels.cs @@ -2,6 +2,7 @@ using System; using TUGraz.VectoCore.Models.Connector.Ports; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Models.SimulationComponent.Impl @@ -72,9 +73,9 @@ namespace TUGraz.VectoCore.Models.SimulationComponent.Impl #region VectoSimulationComponent - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.Pwheel] = WheelsPowerRequest; + container[ModalResultField.Pwheel] = WheelsPowerRequest; } protected override void DoCommitSimulationStep() diff --git a/VectoCore/Models/SimulationComponent/VectoSimulationComponent.cs b/VectoCore/Models/SimulationComponent/VectoSimulationComponent.cs index 207bb4b4c54abd18f765c4632ad2cddcd9bccdad..ec006ff3826752891070945fe21ea0e655ff38cb 100644 --- a/VectoCore/Models/SimulationComponent/VectoSimulationComponent.cs +++ b/VectoCore/Models/SimulationComponent/VectoSimulationComponent.cs @@ -2,6 +2,7 @@ using System; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; +using TUGraz.VectoCore.OutputData; namespace TUGraz.VectoCore.Models.SimulationComponent { @@ -22,15 +23,15 @@ namespace TUGraz.VectoCore.Models.SimulationComponent dataBus.AddComponent(this); } - public void CommitSimulationStep(IModalDataWriter writer) + public void CommitSimulationStep(IModalDataContainer container) { - if (writer != null) { - DoWriteModalResults(writer); + if (container != null) { + DoWriteModalResults(container); } DoCommitSimulationStep(); } - protected abstract void DoWriteModalResults(IModalDataWriter writer); + protected abstract void DoWriteModalResults(IModalDataContainer container); /// <summary> /// Commits the simulation step. diff --git a/VectoCore/OutputData/FileIO/FileOutputWriter.cs b/VectoCore/OutputData/FileIO/FileOutputWriter.cs new file mode 100644 index 0000000000000000000000000000000000000000..7fcbfd5289a55c2f67a6d2f88674855d7ebcb9ef --- /dev/null +++ b/VectoCore/OutputData/FileIO/FileOutputWriter.cs @@ -0,0 +1,60 @@ +using System; +using System.Data; +using System.IO; +using System.Text; +using TUGraz.VectoCore.Configuration; +using TUGraz.VectoCore.Models; +using TUGraz.VectoCore.Models.Simulation.Data; +using TUGraz.VectoCore.Utils; + +namespace TUGraz.VectoCore.OutputData.FileIO +{ + public class FileOutputWriter : LoggingObject, IModalDataWriter, ISummaryWriter, IReportWriter + { + private readonly string _basePath; + private readonly string _jobName; + + public FileOutputWriter(string jobName, string basePath) + { + _jobName = jobName; + _basePath = basePath; + } + + public void WriteModData(string runName, string cycleName, string runSuffix, DataTable modData) + { + //var modFilePattern = Path.Combine(_basePath, + // runName.Replace(Constants.FileExtensions.VectoJobFile, "") + "_{0}{1}" + + // Constants.FileExtensions.ModDataFile); + //var modFileName = string.Format(modFilePattern, cycleName, runSuffix ?? ""); + var modFileName = new StringBuilder(runName); + if (!string.IsNullOrEmpty(cycleName) || !string.IsNullOrEmpty(runSuffix)) { + modFileName.Append("_"); + if (!string.IsNullOrEmpty(cycleName)) { + modFileName.Append(cycleName); + } + if (!string.IsNullOrEmpty(runSuffix)) { + modFileName.Append(cycleName); + } + } + modFileName.Append(Constants.FileExtensions.ModDataFile); + VectoCSVFile.Write(modFileName.ToString(), modData); + } + + public void WriteSumData(DataTable data) + { + var sumFile = Path.Combine(_basePath, Path.GetFileNameWithoutExtension(_jobName) + Constants.FileExtensions.SumFile); + VectoCSVFile.Write(sumFile, data); + } + + + public Stream WriterStream(ReportType type) + { + switch (type) { + case ReportType.DeclarationReportPdf: + return new FileStream(Path.Combine(_basePath, _jobName + ".pdf"), FileMode.Create); + default: + throw new ArgumentOutOfRangeException("type"); + } + } + } +} \ No newline at end of file diff --git a/VectoCore/OutputData/IDataWriter.cs b/VectoCore/OutputData/IDataWriter.cs new file mode 100644 index 0000000000000000000000000000000000000000..4e15d411b5a9396f2af71ea8a709856572da2a5a --- /dev/null +++ b/VectoCore/OutputData/IDataWriter.cs @@ -0,0 +1,27 @@ +using System.Data; +using System.IO; +using TUGraz.VectoCore.Models.Simulation.Data; + +namespace TUGraz.VectoCore.OutputData +{ + public interface IModalDataWriter + { + void WriteModData(string runName, string cycleName, string runSuffix, DataTable modData); + } + + + public interface ISummaryWriter + { + void WriteSumData(DataTable sortedAndFilteredTable); + } + + public interface IReportWriter + { + Stream WriterStream(ReportType type); + } + + public enum ReportType + { + DeclarationReportPdf + } +} \ No newline at end of file diff --git a/VectoCore/Models/Simulation/Data/IModalDataWriter.cs b/VectoCore/OutputData/IModalDataContainer.cs similarity index 78% rename from VectoCore/Models/Simulation/Data/IModalDataWriter.cs rename to VectoCore/OutputData/IModalDataContainer.cs index 3f225287bff78a0549f6c320410c8fa15a8fad61..563a260811112e99590f2a9ca90f4833fcc5eb3d 100644 --- a/VectoCore/Models/Simulation/Data/IModalDataWriter.cs +++ b/VectoCore/OutputData/IModalDataContainer.cs @@ -2,12 +2,13 @@ using System; using System.Collections.Generic; using System.Data; using System.Linq; +using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Utils; -namespace TUGraz.VectoCore.Models.Simulation.Data +namespace TUGraz.VectoCore.OutputData { - public interface IModalDataWriter + public interface IModalDataContainer { /// <summary> /// Indexer for fields of the DataWriter. Accesses the data of the current step. @@ -52,27 +53,27 @@ namespace TUGraz.VectoCore.Models.Simulation.Data public static class ModalDataWriterExtensions { - public static SI Max(this IModalDataWriter data, ModalResultField field) + public static SI Max(this IModalDataContainer data, ModalResultField field) { return data.GetValues<SI>(field).Max(); } - public static SI Min(this IModalDataWriter data, ModalResultField field) + public static SI Min(this IModalDataContainer data, ModalResultField field) { return data.GetValues<SI>(field).Min(); } - public static SI Average(this IModalDataWriter data, ModalResultField field, Func<SI, bool> filter = null) + public static SI Average(this IModalDataContainer data, ModalResultField field, Func<SI, bool> filter = null) { return data.GetValues<SI>(field).Average(filter); } - public static SI Sum(this IModalDataWriter data, ModalResultField field, Func<SI, bool> filter = null) + public static SI Sum(this IModalDataContainer data, ModalResultField field, Func<SI, bool> filter = null) { return data.GetValues<SI>(field).Where(filter ?? (x => x != null)).Sum(); } - public static SI Sum(this IModalDataWriter data, DataColumn col, Func<SI, bool> filter = null) + public static SI Sum(this IModalDataContainer data, DataColumn col, Func<SI, bool> filter = null) { return data.GetValues<SI>(col).Where(filter ?? (x => x != null)).Sum(); } @@ -93,13 +94,13 @@ namespace TUGraz.VectoCore.Models.Simulation.Data return self ?? defaultValue; } - public static MeterPerSquareSecond AccelerationsPositive3SecondAverage(this IModalDataWriter data) + public static MeterPerSquareSecond AccelerationsPositive3SecondAverage(this IModalDataContainer data) { var acceleration3SecondAverage = AccelerationPer3Seconds(data); return acceleration3SecondAverage.Where(x => x > 0.125).Average(); } - public static MeterPerSquareSecond AccelerationNoise(this IModalDataWriter data) + public static MeterPerSquareSecond AccelerationNoise(this IModalDataContainer data) { var avg = data.AccelerationAverage(); var accelerationAverages = AccelerationPerSecond(data).ToList(); @@ -107,32 +108,32 @@ namespace TUGraz.VectoCore.Models.Simulation.Data return sqareAvg.Sqrt().Cast<MeterPerSquareSecond>(); } - public static MeterPerSquareSecond AverageAccelerations3SecondNegative(this IModalDataWriter data) + public static MeterPerSquareSecond AverageAccelerations3SecondNegative(this IModalDataContainer data) { var acceleration3SecondAverage = AccelerationPer3Seconds(data); return acceleration3SecondAverage.Where(x => x < -0.125).Average(); } - public static Scalar PercentAccelerationTime(this IModalDataWriter data) + public static Scalar PercentAccelerationTime(this IModalDataContainer data) { var acceleration3SecondAverage = AccelerationPer3Seconds(data).ToList(); return 100.SI<Scalar>() * acceleration3SecondAverage.Count(x => x > 0.125) / acceleration3SecondAverage.Count; } - public static Scalar PercentDecelerationTime(this IModalDataWriter data) + public static Scalar PercentDecelerationTime(this IModalDataContainer data) { var acceleration3SecondAverage = AccelerationPer3Seconds(data).ToList(); return 100.SI<Scalar>() * acceleration3SecondAverage.Count(x => x < -0.125) / acceleration3SecondAverage.Count; } - public static Scalar PercentCruiseTime(this IModalDataWriter data) + public static Scalar PercentCruiseTime(this IModalDataContainer data) { var acceleration3SecondAverage = AccelerationPer3Seconds(data).ToList(); return 100.SI<Scalar>() * acceleration3SecondAverage.Count(x => x.IsBetween(-0.125, -0.125)) / acceleration3SecondAverage.Count; } - public static Scalar PercentStopTime(this IModalDataWriter data) + public static Scalar PercentStopTime(this IModalDataContainer data) { var stopTime = data.GetValues<MeterPerSecond>(ModalResultField.v_act) .Zip(data.SimulationIntervals(), (v, dt) => new { v, dt }) @@ -141,155 +142,155 @@ namespace TUGraz.VectoCore.Models.Simulation.Data return 100 * (stopTime / data.Duration()).Cast<Scalar>(); } - public static MeterPerSquareSecond AccelerationAverage(this IModalDataWriter data) + public static MeterPerSquareSecond AccelerationAverage(this IModalDataContainer data) { return data.TimeIntegral<MeterPerSecond>(ModalResultField.acc) / data.Duration(); } - public static Second[] SimulationIntervals(this IModalDataWriter data) + public static Second[] SimulationIntervals(this IModalDataContainer data) { return data.GetValues<Second>(ModalResultField.simulationInterval).ToArray(); } - public static Meter AltitudeDelta(this IModalDataWriter data) + public static Meter AltitudeDelta(this IModalDataContainer data) { return data.GetValues<Meter>(ModalResultField.altitude).Last() - data.GetValues<Meter>(ModalResultField.altitude).First(); } - public static WattSecond PowerAccelerations(this IModalDataWriter data) + public static WattSecond PowerAccelerations(this IModalDataContainer data) { var paEngine = data.TimeIntegral<WattSecond>(ModalResultField.PaEng); var paGearbox = data.TimeIntegral<WattSecond>(ModalResultField.PaGB); return paEngine + paGearbox; } - public static WattSecond WorkTransmission(this IModalDataWriter data) + public static WattSecond WorkTransmission(this IModalDataContainer data) { var plossdiff = data.TimeIntegral<WattSecond>(ModalResultField.PlossGB); var plossgb = data.TimeIntegral<WattSecond>(ModalResultField.PlossDiff); return plossdiff + plossgb; } - public static WattSecond WorkRetarder(this IModalDataWriter data) + public static WattSecond WorkRetarder(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.PlossRetarder); } - public static WattSecond WorkTorqueConverter(this IModalDataWriter data) + public static WattSecond WorkTorqueConverter(this IModalDataContainer data) { //TODO (MK, 2015-11-10): return torque converter work - this was currently not possible because torque converter is not implemented. return 0.SI<WattSecond>(); } - public static Second Duration(this IModalDataWriter data) + public static Second Duration(this IModalDataContainer data) { return (data.Max(ModalResultField.time) - data.Min(ModalResultField.time)).Cast<Second>(); } - public static Meter Distance(this IModalDataWriter data) + public static Meter Distance(this IModalDataContainer data) { return (data.Max(ModalResultField.dist) - data.Min(ModalResultField.dist)).Cast<Meter>(); } - public static WattSecond WorkTotalMechanicalBrake(this IModalDataWriter data) + public static WattSecond WorkTotalMechanicalBrake(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Pbrake); } - public static WattSecond WorkAuxiliaries(this IModalDataWriter data) + public static WattSecond WorkAuxiliaries(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Paux); } - public static WattSecond WorkRoadGradientResistance(this IModalDataWriter data) + public static WattSecond WorkRoadGradientResistance(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Pgrad); } - public static WattSecond WorkRollingResistance(this IModalDataWriter data) + public static WattSecond WorkRollingResistance(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Proll); } - public static WattSecond WorkAirResistance(this IModalDataWriter data) + public static WattSecond WorkAirResistance(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Pair); } - public static WattSecond EngineWorkPositive(this IModalDataWriter data) + public static WattSecond EngineWorkPositive(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Pe_eng, x => x > 0); } - public static WattSecond EngineWorkNegative(this IModalDataWriter data) + public static WattSecond EngineWorkNegative(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Pe_eng, x => x < 0); } - public static Watt PowerBrake(this IModalDataWriter data) + public static Watt PowerBrake(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Pbrake) / data.Duration(); } - public static Watt PowerWheelPositive(this IModalDataWriter data) + public static Watt PowerWheelPositive(this IModalDataContainer data) { return data.TimeIntegral<WattSecond>(ModalResultField.Pwheel, x => x > 0) / data.Duration(); } - public static KilogramPerMeter FuelConsumptionWHTCCorrected(this IModalDataWriter data) + public static KilogramPerMeter FuelConsumptionWHTCCorrected(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCWHTCc) / data.Distance(); } - public static KilogramPerSecond FuelConsumptionWHTCCorrectedPerSecond(this IModalDataWriter data) + public static KilogramPerSecond FuelConsumptionWHTCCorrectedPerSecond(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCWHTCc) / data.Duration(); } - public static KilogramPerMeter FuelConsumptionAuxStartStopCorrected(this IModalDataWriter data) + public static KilogramPerMeter FuelConsumptionAuxStartStopCorrected(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCAUXc) / data.Distance(); } - public static KilogramPerSecond FuelConsumptionAuxStartStopCorrectedPerSecond(this IModalDataWriter data) + public static KilogramPerSecond FuelConsumptionAuxStartStopCorrectedPerSecond(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCAUXc) / data.Duration(); } - public static KilogramPerMeter FuelConsumptionFinal(this IModalDataWriter data) + public static KilogramPerMeter FuelConsumptionFinal(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCWHTCc) / data.Distance(); } - public static SI FuelConsumptionFinalLiterPer100Kilometer(this IModalDataWriter data) + public static SI FuelConsumptionFinalLiterPer100Kilometer(this IModalDataContainer data) { var fcVolumePerMeter = data.FuelConsumptionFinal() / Physics.FuelDensity; return fcVolumePerMeter.ConvertTo().Cubic.Dezi.Meter * 100.SI().Kilo.Meter; } - public static KilogramPerMeter CO2PerMeter(this IModalDataWriter data) + public static KilogramPerMeter CO2PerMeter(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCMap) * Physics.CO2PerFuelWeight / data.Distance(); } - public static SI FuelConsumptionLiterPer100Kilometer(this IModalDataWriter data) + public static SI FuelConsumptionLiterPer100Kilometer(this IModalDataContainer data) { var fcVolumePerMeter = data.FuelConsumptionPerMeter() / Physics.FuelDensity; return fcVolumePerMeter.ConvertTo().Cubic.Dezi.Meter * 100.SI().Kilo.Meter; } - public static KilogramPerSecond FuelConsumptionPerSecond(this IModalDataWriter data) + public static KilogramPerSecond FuelConsumptionPerSecond(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCMap) / data.Duration(); } - public static KilogramPerMeter FuelConsumptionPerMeter(this IModalDataWriter data) + public static KilogramPerMeter FuelConsumptionPerMeter(this IModalDataContainer data) { return data.TimeIntegral<Kilogram>(ModalResultField.FCMap) / data.Distance(); } - public static Watt EnginePowerNegativeAverage(this IModalDataWriter data) + public static Watt EnginePowerNegativeAverage(this IModalDataContainer data) { var simulationIntervals = data.GetValues<Second>(ModalResultField.simulationInterval); var values = data.GetValues<Watt>(ModalResultField.Pe_eng) @@ -301,7 +302,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data return 0.SI<Watt>(); } - public static Watt EnginePowerPositiveAverage(this IModalDataWriter data) + public static Watt EnginePowerPositiveAverage(this IModalDataContainer data) { var simulationIntervals = data.GetValues<Second>(ModalResultField.simulationInterval); var values = data.GetValues<Watt>(ModalResultField.Pe_eng) @@ -313,19 +314,19 @@ namespace TUGraz.VectoCore.Models.Simulation.Data return 0.SI<Watt>(); } - public static MeterPerSecond Speed(this IModalDataWriter data) + public static MeterPerSecond Speed(this IModalDataContainer data) { return Distance(data) / Duration(data); } - public static WattSecond AuxiliaryWork(this IModalDataWriter data, DataColumn auxCol) + public static WattSecond AuxiliaryWork(this IModalDataContainer data, DataColumn auxCol) { var simulationIntervals = data.GetValues<Second>(ModalResultField.simulationInterval); return data.GetValues<Watt>(auxCol).Zip(simulationIntervals, (value, dt) => value * dt).Sum().Cast<WattSecond>(); } - private static T TimeIntegral<T>(this IModalDataWriter data, ModalResultField field, Func<SI, bool> filter = null) + private static T TimeIntegral<T>(this IModalDataContainer data, ModalResultField field, Func<SI, bool> filter = null) where T : SIBase<T> { var simulationIntervals = data.GetValues<Second>(ModalResultField.simulationInterval); @@ -338,7 +339,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data : SIBase<T>.Create(0); } - private static IEnumerable<MeterPerSquareSecond> AccelerationPer3Seconds(IModalDataWriter data) + private static IEnumerable<MeterPerSquareSecond> AccelerationPer3Seconds(IModalDataContainer data) { var accelerationAverages = AccelerationPerSecond(data).ToList(); var runningAverage = (accelerationAverages[0] + accelerationAverages[1] + accelerationAverages[2]) / 3.0; @@ -354,7 +355,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data /// <summary> /// Calculates the average acceleration for whole seconds. /// </summary> - private static IEnumerable<MeterPerSquareSecond> AccelerationPerSecond(IModalDataWriter data) + private static IEnumerable<MeterPerSquareSecond> AccelerationPerSecond(IModalDataContainer data) { var dtSum = 0.SI<Second>(); var accAvg = 0.SI<MeterPerSecond>(); diff --git a/VectoCore/Models/Simulation/Data/ModalDataWriter.cs b/VectoCore/OutputData/ModalDataContainer.cs similarity index 75% rename from VectoCore/Models/Simulation/Data/ModalDataWriter.cs rename to VectoCore/OutputData/ModalDataContainer.cs index 89cb858be6a8572875bc5e9528120af69f0265de..70835671fa73ca8f0ae6954cd642f4a00851b5bd 100644 --- a/VectoCore/Models/Simulation/Data/ModalDataWriter.cs +++ b/VectoCore/OutputData/ModalDataContainer.cs @@ -1,37 +1,56 @@ using System; using System.Collections.Generic; using System.Data; +using System.IO; using System.Linq; +using TUGraz.VectoCore.Models.Simulation; +using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Utils; -namespace TUGraz.VectoCore.Models.Simulation.Data +namespace TUGraz.VectoCore.OutputData { - public class ModalDataWriter : IModalDataWriter + public class ModalDataContainer : IModalDataContainer { private readonly SimulatorFactory.FactoryMode _mode; - private readonly Action<ModalDataWriter> _addReportResult; + private readonly Action<ModalDataContainer> _addReportResult; private ModalResults Data { get; set; } private DataRow CurrentRow { get; set; } - private string ModFileName { get; set; } + //private readonly VectoRunData _runData; + + private readonly IModalDataWriter _writer; + private string _runName; + private string _cycleName; + private string _runSuffix; public bool WriteModalResults { get; set; } public VectoRun.Status RunStatus { get; protected set; } - public ModalDataWriter(string modFileName, - SimulatorFactory.FactoryMode mode = SimulatorFactory.FactoryMode.EngineeringMode) : this(modFileName, _ => {}, mode) {} + public ModalDataContainer(string runName, IModalDataWriter writer, + SimulatorFactory.FactoryMode mode = SimulatorFactory.FactoryMode.EngineeringMode) + : this(runName, "", "", writer, _ => {}, mode) {} - public ModalDataWriter(string modFileName, Action<ModalDataWriter> addReportResult, + public ModalDataContainer(VectoRunData runData, IModalDataWriter writer, Action<ModalDataContainer> addReportResult, SimulatorFactory.FactoryMode mode = SimulatorFactory.FactoryMode.EngineeringMode) + : this(runData.JobName, runData.Cycle.Name, runData.ModFileSuffix, writer, addReportResult, mode) {} + + protected ModalDataContainer(string runName, string cycleName, string runSuffix, IModalDataWriter writer, + Action<ModalDataContainer> addReportResult, SimulatorFactory.FactoryMode mode) + { HasTorqueConverter = false; - ModFileName = modFileName; + _runName = runName; + _cycleName = cycleName; + _runSuffix = runSuffix; + _writer = writer; + + _mode = mode; + _addReportResult = addReportResult; + Data = new ModalResults(); Auxiliaries = new Dictionary<string, DataColumn>(); CurrentRow = Data.NewRow(); - _mode = mode; - _addReportResult = addReportResult; } public bool HasTorqueConverter { get; set; } @@ -103,7 +122,9 @@ namespace TUGraz.VectoCore.Models.Simulation.Data .Concat(new[] { ModalResultField.FCMap, ModalResultField.FCAUXc, ModalResultField.FCWHTCc }.Select(x => x.GetName())); if (_mode != SimulatorFactory.FactoryMode.DeclarationMode || WriteModalResults) { - VectoCSVFile.Write(ModFileName, new DataView(Data).ToTable(false, strCols.ToArray())); + //VectoCSVFile.Write(_modWriter, new DataView(Data).ToTable(false, strCols.ToArray())); + _writer.WriteModData(_runName, _cycleName, _runSuffix, + new DataView(Data).ToTable(false, strCols.ToArray())); } if (_mode == SimulatorFactory.FactoryMode.DeclarationMode) { diff --git a/VectoCore/Models/Declaration/DeclarationReport.cs b/VectoCore/OutputData/PDF/DeclarationReport.cs similarity index 93% rename from VectoCore/Models/Declaration/DeclarationReport.cs rename to VectoCore/OutputData/PDF/DeclarationReport.cs index 0186231be8db07986dacc3d99ff4d4f463b71b81..5aa798bd3898ccb375a5f952af2e4f1f9478804a 100644 --- a/VectoCore/Models/Declaration/DeclarationReport.cs +++ b/VectoCore/OutputData/PDF/DeclarationReport.cs @@ -1,6 +1,4 @@ using System; -using iTextSharp.text; -using iTextSharp.text.pdf; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; @@ -9,7 +7,10 @@ using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Windows.Forms.DataVisualization.Charting; -using NLog; +using iTextSharp.text; +using iTextSharp.text.pdf; +using Org.BouncyCastle.Crypto.IO; +using TUGraz.VectoCore.Models.Declaration; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Utils; @@ -17,7 +18,7 @@ using Font = System.Drawing.Font; using Image = iTextSharp.text.Image; using Rectangle = System.Drawing.Rectangle; -namespace TUGraz.VectoCore.Models.Declaration +namespace TUGraz.VectoCore.OutputData.PDF { /// <summary> /// Class for creating a declaration report. @@ -30,7 +31,7 @@ namespace TUGraz.VectoCore.Models.Declaration private class ResultContainer { public Mission Mission; - public Dictionary<LoadingType, IModalDataWriter> ModData; + public Dictionary<LoadingType, IModalDataContainer> ModData; } /// <summary> @@ -54,6 +55,8 @@ namespace TUGraz.VectoCore.Models.Declaration /// </summary> private readonly string _creator; + private IReportWriter _writer; + /// <summary> /// The engine model string from engine file. @@ -78,7 +81,7 @@ namespace TUGraz.VectoCore.Models.Declaration /// <summary> /// The name of the job file (report name will be the same) /// </summary> - public string JobFile { get; set; } + public string JobName { get; set; } /// <summary> /// The result count determines how many results must be given before the report gets written. @@ -88,24 +91,15 @@ namespace TUGraz.VectoCore.Models.Declaration /// <summary> /// The base path of the application /// </summary> - private readonly string _basePath; - /// <summary> /// Initializes a new instance of the <see cref="DeclarationReport"/> class. /// </summary> - /// <param name="flc">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> - /// <param name="engineStr">The engine description string.</param> - /// <param name="gearboxModel">The gearbox model.</param> - /// <param name="gearboxStr">The gearbox description string.</param> - /// <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> + /// <param name="jobName"></param> + /// <param name="writer"></param> // public DeclarationReport(FullLoadCurve flc, Segment segment, string creator, string engineModel, string engineStr, // string gearboxModel, string gearboxStr, string basePath, string jobFile, int resultCount) - public DeclarationReport(string creator, string basePath, string jobFile) + public DeclarationReport(string creator, string jobName, IReportWriter writer) { //_flc = flc; //_segment = segment; @@ -114,9 +108,10 @@ namespace TUGraz.VectoCore.Models.Declaration //_engineStr = engineStr; //_gearboxModel = gearboxModel; //_gearboxStr = gearboxStr; - JobFile = jobFile; + JobName = jobName; //_resultCount = resultCount; - _basePath = basePath; + //_basePath = basePath; + _writer = writer; } @@ -127,12 +122,12 @@ namespace TUGraz.VectoCore.Models.Declaration /// <param name="mission">The mission.</param> /// <param name="modData">The mod data.</param> [MethodImpl(MethodImplOptions.Synchronized)] - public void AddResult(LoadingType loadingType, Mission mission, IModalDataWriter modData) + public void AddResult(LoadingType loadingType, Mission mission, IModalDataContainer modData) { if (!_missions.ContainsKey(mission.MissionType)) { _missions[mission.MissionType] = new ResultContainer { Mission = mission, - ModData = new Dictionary<LoadingType, IModalDataWriter> { { loadingType, modData } } + ModData = new Dictionary<LoadingType, IModalDataContainer> { { loadingType, modData } } }; } else { _missions[mission.MissionType].ModData[loadingType] = modData; @@ -152,7 +147,7 @@ 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")); + MergeDocuments(titlePage, cyclePages, _writer.WriterStream(ReportType.DeclarationReportPdf)); } @@ -172,7 +167,7 @@ namespace TUGraz.VectoCore.Models.Declaration var pdfFields = stamper.AcroFields; pdfFields.SetField("version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); - pdfFields.SetField("Job", JobFile); + pdfFields.SetField("Job", JobName); pdfFields.SetField("Date", DateTime.Now.ToString(CultureInfo.InvariantCulture)); pdfFields.SetField("Created", _creator); pdfFields.SetField("Config", @@ -252,7 +247,7 @@ namespace TUGraz.VectoCore.Models.Declaration var pdfFields = stamper.AcroFields; pdfFields.SetField("version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); - pdfFields.SetField("Job", JobFile); + pdfFields.SetField("Job", JobName); pdfFields.SetField("Date", DateTime.Now.ToString(CultureInfo.InvariantCulture)); pdfFields.SetField("Created", _creator); pdfFields.SetField("Config", @@ -314,11 +309,11 @@ namespace TUGraz.VectoCore.Models.Declaration /// </summary> /// <param name="titlePage">The title page.</param> /// <param name="cyclePages">The cycle pages.</param> - /// <param name="outputFileName">Name of the output file.</param> - private static void MergeDocuments(Stream titlePage, IEnumerable<Stream> cyclePages, string outputFileName) + /// <param name="reportWriter"></param> + private static void MergeDocuments(Stream titlePage, IEnumerable<Stream> cyclePages, Stream reportWriter) { var document = new Document(PageSize.A4.Rotate(), 12, 12, 12, 12); - var writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create)); + var writer = PdfWriter.GetInstance(document, reportWriter); document.Open(); @@ -537,7 +532,7 @@ namespace TUGraz.VectoCore.Models.Declaration /// <param name="modData">The mod data.</param> /// <param name="flc">The FLC.</param> /// <returns></returns> - private static Bitmap DrawOperatingPointsChart(IModalDataWriter modData, FullLoadCurve flc) + private static Bitmap DrawOperatingPointsChart(IModalDataContainer modData, FullLoadCurve flc) { var operatingPointsChart = new Chart { Width = 1000, Height = 427 }; operatingPointsChart.Legends.Add(new Legend("main") { diff --git a/VectoCore/Models/Simulation/Data/SummaryFileWriter.cs b/VectoCore/OutputData/SummaryDataContainer.cs similarity index 89% rename from VectoCore/Models/Simulation/Data/SummaryFileWriter.cs rename to VectoCore/OutputData/SummaryDataContainer.cs index 63ee0db2724161e67b20bc3363ccf13fa533b519..293b03a30a6f66d1d7ac4c269bbff5d53ce1f5d3 100644 --- a/VectoCore/Models/Simulation/Data/SummaryFileWriter.cs +++ b/VectoCore/OutputData/SummaryDataContainer.cs @@ -1,17 +1,20 @@ using System.Collections.Generic; using System.Data; +using System.IO; using System.Linq; using System.Runtime.CompilerServices; +using TUGraz.VectoCore.Models; +using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Utils; -namespace TUGraz.VectoCore.Models.Simulation.Data +namespace TUGraz.VectoCore.OutputData { - public delegate void WriteSumData(IModalDataWriter data, Kilogram vehicleMass, Kilogram loading); + public delegate void WriteSumData(IModalDataContainer data, Kilogram vehicleMass, Kilogram loading); /// <summary> /// Class for the sum file in vecto. /// </summary> - public class SummaryFileWriter : LoggingObject + public class SummaryDataContainer : LoggingObject { // ReSharper disable InconsistentNaming private const string JOB = "Job [-]"; @@ -61,20 +64,20 @@ namespace TUGraz.VectoCore.Models.Simulation.Data // ReSharper restore InconsistentNaming private readonly DataTable _table; - private readonly string _sumFileName; + private readonly ISummaryWriter _sumWriter; private bool _engineOnly = true; - protected SummaryFileWriter() {} + protected SummaryDataContainer() {} private readonly IList<string> _auxColumns = new List<string>(); /// <summary> - /// Initializes a new instance of the <see cref="SummaryFileWriter"/> class. + /// Initializes a new instance of the <see cref="SummaryDataContainer"/> class. /// </summary> - /// <param name="sumFileName">Name of the sum file.</param> - public SummaryFileWriter(string sumFileName) + /// <param name="writer"></param> + public SummaryDataContainer(ISummaryWriter writer) { - _sumFileName = sumFileName; + _sumWriter = writer; _table = new DataTable(); _table.Columns.Add(JOB, typeof(string)); @@ -90,7 +93,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data }.Select(x => new DataColumn(x, typeof(SI))).ToArray()); } - public virtual void Write(bool isEngineOnly, IModalDataWriter data, string jobFileName, string jobName, + public virtual void Write(bool isEngineOnly, IModalDataContainer data, string jobFileName, string jobName, string cycleFileName, Kilogram vehicleMass, Kilogram vehicleLoading) { @@ -102,7 +105,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data } - protected internal void WriteEngineOnly(IModalDataWriter data, string jobFileName, string jobName, + protected internal void WriteEngineOnly(IModalDataContainer data, string jobFileName, string jobName, string cycleFileName) { var row = _table.NewRow(); @@ -122,7 +125,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data } - protected internal void WriteFullPowertrain(IModalDataWriter data, string jobFileName, string jobName, + protected internal void WriteFullPowertrain(IModalDataContainer data, string jobFileName, string jobName, string cycleFileName, Kilogram vehicleMass, Kilogram vehicleLoading) { _engineOnly = false; @@ -181,7 +184,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data } [MethodImpl(MethodImplOptions.Synchronized)] - private void WriteAuxiliaries(IModalDataWriter data, DataRow row) + private void WriteAuxiliaries(IModalDataContainer data, DataRow row) { foreach (var aux in data.Auxiliaries) { var colName = "Eaux_" + aux.Key + " [kWh]"; @@ -215,7 +218,7 @@ namespace TUGraz.VectoCore.Models.Simulation.Data var sortedAndFilteredTable = new DataView(_table, "", JOB, DataViewRowState.CurrentRows).ToTable(false, dataColumns.ToArray()); - VectoCSVFile.Write(_sumFileName, sortedAndFilteredTable); + _sumWriter.WriteSumData(sortedAndFilteredTable); } } } \ No newline at end of file diff --git a/VectoCore/Utils/VectoCSVFile.cs b/VectoCore/Utils/VectoCSVFile.cs index 2bfc54f5fc8a5483818dcfd6818c3f7651abf2c8..388e743c9ff28a111bc768e54feaab63e1c1c1a2 100644 --- a/VectoCore/Utils/VectoCSVFile.cs +++ b/VectoCore/Utils/VectoCSVFile.cs @@ -150,14 +150,21 @@ namespace TUGraz.VectoCore.Utils /// <param name="table">The Datatable.</param> public static void Write(string fileName, DataTable table) { - var sb = new StringBuilder(); + Write(new StreamWriter(fileName), table); + } + public static void Write(StreamWriter writer, DataTable table) + { + if (writer == null) { + return; + } var header = table.Columns.Cast<DataColumn>().Select(col => col.Caption ?? col.ColumnName); - sb.AppendLine(string.Join(Delimiter.ToString(), header)); + writer.WriteLineAsync(string.Join(Delimiter.ToString(), header)); foreach (DataRow row in table.Rows) { + var row1 = row; var formattedList = table.Columns.Cast<DataColumn>().Select(col => { - var item = row[col]; + var item = row1[col]; var decimals = (uint?)col.ExtendedProperties["decimals"]; var outputFactor = (double?)col.ExtendedProperties["outputFactor"]; var showUnit = (bool?)col.ExtendedProperties["showUnit"]; @@ -168,10 +175,8 @@ namespace TUGraz.VectoCore.Utils : string.Format(CultureInfo.InvariantCulture, "{0}", item)); }); - sb.AppendLine(string.Join(Delimiter.ToString(), formattedList)); + writer.WriteLineAsync(string.Join(Delimiter.ToString(), formattedList)); } - - File.WriteAllText(fileName, sb.ToString()); } } } \ No newline at end of file diff --git a/VectoCore/VectoCore.csproj b/VectoCore/VectoCore.csproj index 18467c8649c2e40d6e42ab5e325feb046739656d..502f85d008420c7ad2bfcc73a2000df84675f53f 100644 --- a/VectoCore/VectoCore.csproj +++ b/VectoCore/VectoCore.csproj @@ -117,6 +117,7 @@ <Compile Include="InputData\FileIO\EngineeringFile\GearboxFileEng.cs" /> <Compile Include="InputData\FileIO\EngineeringFile\JobFileEng.cs" /> <Compile Include="InputData\FileIO\EngineeringFile\VehicleFileEng.cs" /> + <Compile Include="InputData\Impl\InputData.cs" /> <Compile Include="InputData\FileIO\InputFileReader.cs" /> <Compile Include="InputData\FileIO\JsonDataHeader.cs" /> <Compile Include="InputData\FileIO\JsonInputDataProviderDEPRECATED.cs" /> @@ -148,7 +149,6 @@ <Compile Include="Models\Declaration\HVAC.cs" /> <Compile Include="Models\Declaration\PneumaticSystem.cs" /> <Compile Include="Models\Declaration\PT1.cs" /> - <Compile Include="Models\Declaration\DeclarationReport.cs" /> <Compile Include="Models\Declaration\Rims.cs" /> <Compile Include="Models\Declaration\Segments.cs" /> <Compile Include="Models\Declaration\SteeringPump.cs" /> @@ -192,6 +192,12 @@ <Compile Include="Models\Simulation\Impl\DistanceRun.cs" /> <Compile Include="Models\Simulation\Impl\PowertrainBuilder.cs" /> <Compile Include="Models\Simulation\Impl\TimeRun.cs" /> + <Compile Include="OutputData\FileIO\FileOutputWriter.cs" /> + <Compile Include="OutputData\IModalDataContainer.cs" /> + <Compile Include="OutputData\IDataWriter.cs" /> + <Compile Include="OutputData\ModalDataContainer.cs" /> + <Compile Include="OutputData\PDF\DeclarationReport.cs" /> + <Compile Include="OutputData\SummaryDataContainer.cs" /> <Compile Include="Properties\Resources.Designer.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> @@ -238,7 +244,6 @@ <Compile Include="Models\SimulationComponent\Impl\AxleGear.cs" /> <Compile Include="Models\SimulationComponent\Impl\Retarder.cs" /> <Compile Include="Models\SimulationComponent\IPowerTrainComponent.cs" /> - <Compile Include="Models\Simulation\Data\SummaryFileWriter.cs" /> <Compile Include="Models\Simulation\Data\VectoRunData.cs" /> <Compile Include="Models\SimulationComponent\Impl\Driver.cs" /> <Compile Include="Models\SimulationComponent\Data\DriverData.cs" /> @@ -261,12 +266,10 @@ <Compile Include="Models\SimulationComponent\IWheels.cs" /> <Compile Include="Models\SimulationComponent\VectoSimulationComponent.cs" /> <Compile Include="Models\SimulationComponent\Impl\EngineOnlyDrivingCycle.cs" /> - <Compile Include="Models\Simulation\Data\IModalDataWriter.cs" /> <Compile Include="Models\Simulation\Data\ModalResult.cs"> <SubType>Component</SubType> </Compile> <Compile Include="Models\Simulation\IVectoRun.cs" /> - <Compile Include="Models\Simulation\Data\ModalDataWriter.cs" /> <Compile Include="Models\Simulation\Impl\SimulatorFactory.cs" /> <Compile Include="Models\Simulation\Impl\VectoRun.cs" /> <Compile Include="Models\Simulation\Impl\JobContainer.cs" /> @@ -341,6 +344,7 @@ <ItemGroup> <Service Include="{508349B6-6B84-4DF5-91F0-309BEEBAD82D}" /> </ItemGroup> + <ItemGroup /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <PropertyGroup> <PreBuildEvent>if $(ConfigurationName) == Release forfiles /p "$(ProjectDir)." /m "*.tt" /s /c "cmd /c echo Transforming @path && \"%25CommonProgramFiles(x86)%25\Microsoft Shared\TextTemplating\12.0\TextTransform.exe\" @file"</PreBuildEvent> diff --git a/VectoCoreTest/FileIO/JsonTest.cs b/VectoCoreTest/FileIO/JsonTest.cs index a1d51637b161cd98055bf4429ee4e070906a4225..8a0f9ac16fde8541cc0fa1d8f67c8b620ec36df7 100644 --- a/VectoCoreTest/FileIO/JsonTest.cs +++ b/VectoCoreTest/FileIO/JsonTest.cs @@ -5,164 +5,164 @@ using TUGraz.VectoCore.InputData.FileIO; namespace TUGraz.VectoCore.Tests.FileIO { - [TestClass] - public class JsonTest - { - private const string jsonExpected = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""2015-11-17T11:49:03Z"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - - private const string jsonExpected2 = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""2015-01-07T11:49:03Z"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - - - [TestMethod] - public void TestJsonHeaderEquality() - { - var h1 = new JsonDataHeader { - AppVersion = "MyVecto3", - CreatedBy = "UnitTest", - Date = new DateTime(1970, 1, 1), - FileVersion = 3 - }; - var h2 = new JsonDataHeader { - AppVersion = "MyVecto3", - CreatedBy = "UnitTest", - Date = new DateTime(1970, 1, 1), - FileVersion = 3 - }; - Assert.AreEqual(h1, h1); - Assert.AreEqual(h1, h2); - Assert.AreNotEqual(h1, null); - Assert.AreNotEqual(h1, "hello world"); - } - - [TestMethod] - public void Test_Json_DateFormat_German() - { - var json = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""17.11.2015 11:49:03"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); - - Assert.AreEqual("3.0.1.320", header.AppVersion); - Assert.AreEqual(7u, header.FileVersion); - Assert.AreEqual("Michael Krisper", header.CreatedBy); - Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); - - var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); - Assert.AreEqual(jsonExpected, jsonCompare); - } - - [TestMethod] - public void Test_Json_DateFormat_German2() - { - var json = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""7.1.2015 11:49:03"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); - - Assert.AreEqual("3.0.1.320", header.AppVersion); - Assert.AreEqual(7u, header.FileVersion); - Assert.AreEqual("Michael Krisper", header.CreatedBy); - Assert.AreEqual(new DateTime(2015, 1, 7, 11, 49, 3, DateTimeKind.Utc), header.Date); - - var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); - Assert.AreEqual(jsonExpected2, jsonCompare); - } - - [TestMethod] - public void Test_Json_DateFormat_English() - { - var json = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""11/17/2015 11:49:03 AM"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); - - Assert.AreEqual("3.0.1.320", header.AppVersion); - Assert.AreEqual(7u, header.FileVersion); - Assert.AreEqual("Michael Krisper", header.CreatedBy); - Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); - - var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); - Assert.AreEqual(jsonExpected, jsonCompare); - } - - [TestMethod] - public void Test_Json_DateFormat_English2() - { - var json = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""1/7/2015 11:49:03 AM"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); - - Assert.AreEqual("3.0.1.320", header.AppVersion); - Assert.AreEqual(7u, header.FileVersion); - Assert.AreEqual("Michael Krisper", header.CreatedBy); - Assert.AreEqual(new DateTime(2015, 1, 7, 11, 49, 3, DateTimeKind.Utc), header.Date); - - var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); - Assert.AreEqual(jsonExpected2, jsonCompare); - } - - - [TestMethod] - public void Test_Json_DateFormat_ISO8601() - { - var json = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""2015-11-17T11:49:03Z"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); - - Assert.AreEqual("3.0.1.320", header.AppVersion); - Assert.AreEqual(7u, header.FileVersion); - Assert.AreEqual("Michael Krisper", header.CreatedBy); - Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); - - var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); - Assert.AreEqual(json, jsonCompare); - } - - [TestMethod] - public void Test_Json_DateFormat_ISO8601_CET() - { - var json = @"{ - ""CreatedBy"": ""Michael Krisper"", - ""Date"": ""2015-11-17T11:49:03+01:00"", - ""AppVersion"": ""3.0.1.320"", - ""FileVersion"": 7 -}"; - var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); - - Assert.AreEqual("3.0.1.320", header.AppVersion); - Assert.AreEqual(7u, header.FileVersion); - Assert.AreEqual("Michael Krisper", header.CreatedBy); - Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); - - var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); - Assert.AreEqual(json, jsonCompare); - } - } +// [TestClass] +// public class JsonTest +// { +// private const string jsonExpected = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""2015-11-17T11:49:03Z"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; + +// private const string jsonExpected2 = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""2015-01-07T11:49:03Z"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; + + +// [TestMethod] +// public void TestJsonHeaderEquality() +// { +// var h1 = new JsonDataHeader { +// AppVersion = "MyVecto3", +// CreatedBy = "UnitTest", +// Date = new DateTime(1970, 1, 1), +// FileVersion = 3 +// }; +// var h2 = new JsonDataHeader { +// AppVersion = "MyVecto3", +// CreatedBy = "UnitTest", +// Date = new DateTime(1970, 1, 1), +// FileVersion = 3 +// }; +// Assert.AreEqual(h1, h1); +// Assert.AreEqual(h1, h2); +// Assert.AreNotEqual(h1, null); +// Assert.AreNotEqual(h1, "hello world"); +// } + +// [TestMethod] +// public void Test_Json_DateFormat_German() +// { +// var json = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""17.11.2015 11:49:03"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; +// var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); + +// Assert.AreEqual("3.0.1.320", header.AppVersion); +// Assert.AreEqual(7u, header.FileVersion); +// Assert.AreEqual("Michael Krisper", header.CreatedBy); +// Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); + +// var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); +// Assert.AreEqual(jsonExpected, jsonCompare); +// } + +// [TestMethod] +// public void Test_Json_DateFormat_German2() +// { +// var json = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""7.1.2015 11:49:03"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; +// var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); + +// Assert.AreEqual("3.0.1.320", header.AppVersion); +// Assert.AreEqual(7u, header.FileVersion); +// Assert.AreEqual("Michael Krisper", header.CreatedBy); +// Assert.AreEqual(new DateTime(2015, 1, 7, 11, 49, 3, DateTimeKind.Utc), header.Date); + +// var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); +// Assert.AreEqual(jsonExpected2, jsonCompare); +// } + +// [TestMethod] +// public void Test_Json_DateFormat_English() +// { +// var json = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""11/17/2015 11:49:03 AM"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; +// var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); + +// Assert.AreEqual("3.0.1.320", header.AppVersion); +// Assert.AreEqual(7u, header.FileVersion); +// Assert.AreEqual("Michael Krisper", header.CreatedBy); +// Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); + +// var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); +// Assert.AreEqual(jsonExpected, jsonCompare); +// } + +// [TestMethod] +// public void Test_Json_DateFormat_English2() +// { +// var json = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""1/7/2015 11:49:03 AM"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; +// var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); + +// Assert.AreEqual("3.0.1.320", header.AppVersion); +// Assert.AreEqual(7u, header.FileVersion); +// Assert.AreEqual("Michael Krisper", header.CreatedBy); +// Assert.AreEqual(new DateTime(2015, 1, 7, 11, 49, 3, DateTimeKind.Utc), header.Date); + +// var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); +// Assert.AreEqual(jsonExpected2, jsonCompare); +// } + + +// [TestMethod] +// public void Test_Json_DateFormat_ISO8601() +// { +// var json = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""2015-11-17T11:49:03Z"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; +// var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); + +// Assert.AreEqual("3.0.1.320", header.AppVersion); +// Assert.AreEqual(7u, header.FileVersion); +// Assert.AreEqual("Michael Krisper", header.CreatedBy); +// Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); + +// var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); +// Assert.AreEqual(json, jsonCompare); +// } + +// [TestMethod] +// public void Test_Json_DateFormat_ISO8601_CET() +// { +// var json = @"{ +// ""CreatedBy"": ""Michael Krisper"", +// ""Date"": ""2015-11-17T11:49:03+01:00"", +// ""AppVersion"": ""3.0.1.320"", +// ""FileVersion"": 7 +//}"; +// var header = JsonConvert.DeserializeObject<JsonDataHeader>(json); + +// Assert.AreEqual("3.0.1.320", header.AppVersion); +// Assert.AreEqual(7u, header.FileVersion); +// Assert.AreEqual("Michael Krisper", header.CreatedBy); +// Assert.AreEqual(new DateTime(2015, 11, 17, 11, 49, 3, DateTimeKind.Utc), header.Date); + +// var jsonCompare = JsonConvert.SerializeObject(header, Formatting.Indented); +// Assert.AreEqual(json, jsonCompare); +// } +// } } \ No newline at end of file diff --git a/VectoCoreTest/FileIO/SimulationDataReaderTest.cs b/VectoCoreTest/FileIO/SimulationDataReaderTest.cs index b2089217cfb7f3d2e61dcaefb87f78e704d94ac8..a13ea76651f4c11c1423a0cac1157f110f5360cf 100644 --- a/VectoCoreTest/FileIO/SimulationDataReaderTest.cs +++ b/VectoCoreTest/FileIO/SimulationDataReaderTest.cs @@ -1,6 +1,7 @@ using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; +using TUGraz.VectoCore.InputData.FileIO.JSON; using TUGraz.VectoCore.InputData.FileIO.Reader.Impl; using TUGraz.VectoCore.Models.Declaration; using TUGraz.VectoCore.Models.SimulationComponent.Data; @@ -17,14 +18,15 @@ namespace TUGraz.VectoCore.Tests.FileIO [TestMethod] public void ReadDeclarationJobFile() { - var reader = new DeclarationModeSimulationDataReader(); - reader.SetJobFile(DeclarationJob); + var dataProvider = JSONInputDataFactory.ReadJsonJob(DeclarationJob); + var reader = new DeclarationModeVectoRunDataFactory(dataProvider, null); + //reader.SetJobFile(DeclarationJob); var runData = reader.NextRun().First(); Assert.AreEqual(false, runData.IsEngineOnly); - Assert.AreEqual(Path.GetFileName(DeclarationJob), runData.JobFileName); + Assert.AreEqual(Path.GetFileName(DeclarationJob), runData.JobName); Assert.AreEqual(5850, runData.VehicleData.CurbWeight.Value()); Assert.AreEqual(1900, runData.VehicleData.CurbWeigthExtra.Value()); // taken from segmentation table Assert.AreEqual(11900, runData.VehicleData.GrossVehicleMassRating.Value()); diff --git a/VectoCoreTest/Integration/CoachPowerTrain.cs b/VectoCoreTest/Integration/CoachPowerTrain.cs index 59790d858a88bdf36504f092c9d80f7e934641ca..a560f3933083a256dcf2d04d930f42067ad86e7a 100644 --- a/VectoCoreTest/Integration/CoachPowerTrain.cs +++ b/VectoCoreTest/Integration/CoachPowerTrain.cs @@ -8,6 +8,8 @@ using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data.Gearbox; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; +using TUGraz.VectoCore.OutputData.FileIO; using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; using Wheels = TUGraz.VectoCore.Models.SimulationComponent.Impl.Wheels; @@ -30,7 +32,7 @@ namespace TUGraz.VectoCore.Tests.Integration public static VectoRun CreateEngineeringRun(DrivingCycleData cycleData, string modFileName, bool overspeed = false) { - var container = CreatePowerTrain(cycleData, modFileName, overspeed); + var container = CreatePowerTrain(cycleData, modFileName.Replace(".vmod", ""), overspeed); return new DistanceRun("", container); } @@ -38,13 +40,15 @@ namespace TUGraz.VectoCore.Tests.Integration public static VehicleContainer CreatePowerTrain(DrivingCycleData cycleData, string modFileName, bool overspeed = false) { - var modalWriter = new ModalDataWriter(modFileName); - var container = new VehicleContainer(modalWriter); + var fileWriter = new FileOutputWriter(modFileName, ""); + var modData = new ModalDataContainer(modFileName, fileWriter); + var container = new VehicleContainer(modData); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var axleGearData = CreateAxleGearData(); var gearboxData = CreateGearboxData(); var vehicleData = CreateVehicleData(3300.SI<Kilogram>()); + //var retarder = new RetarderData { Type = RetarderData.RetarderType.None }; var driverData = CreateDriverData(AccelerationFile, overspeed); var cycle = new DistanceBasedDrivingCycle(container, cycleData); @@ -141,7 +145,6 @@ namespace TUGraz.VectoCore.Tests.Integration CurbWeigthExtra = 0.SI<Kilogram>(), Loading = loading, DynamicTyreRadius = 0.52.SI<Meter>(), - Retarder = new RetarderData { Type = RetarderData.RetarderType.None }, AxleData = axles, SavedInDeclarationMode = false, }; diff --git a/VectoCoreTest/Integration/DeclarationReportTest.cs b/VectoCoreTest/Integration/DeclarationReportTest.cs index f463bc88ab7189b98038ecb27d17a52bd85ccbd3..c539159d289c4e05fa8c81401b3b88891362ab37 100644 --- a/VectoCoreTest/Integration/DeclarationReportTest.cs +++ b/VectoCoreTest/Integration/DeclarationReportTest.cs @@ -1,8 +1,11 @@ using System.IO; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; +using TUGraz.VectoCore.InputData.FileIO.JSON; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; +using TUGraz.VectoCore.OutputData; +using TUGraz.VectoCore.OutputData.FileIO; namespace TUGraz.VectoCore.Tests.Integration { @@ -20,9 +23,11 @@ namespace TUGraz.VectoCore.Tests.Integration File.Delete("job-report.pdf"); } - var sumWriter = new SummaryFileWriter(@"job-report.vsum"); - var jobContainer = new JobContainer(sumWriter); - var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, @"TestData\Jobs\job-report.vecto"); + var fileWriter = new FileOutputWriter("job-report", ""); + var sumData = new SummaryDataContainer(fileWriter); + var jobContainer = new JobContainer(sumData); + var inputData = JSONInputDataFactory.ReadJsonJob(@"TestData\Jobs\job-report.vecto"); + var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, inputData, fileWriter); jobContainer.AddRuns(factory); jobContainer.Execute(); diff --git a/VectoCoreTest/Integration/EngineOnlyCycle/EngineOnlyCycleTest.cs b/VectoCoreTest/Integration/EngineOnlyCycle/EngineOnlyCycleTest.cs index 43b5a90535bbcc2ee8f1687d28a836c3c57b1020..afa8bdddfd39fb3cca414700f4fc18514523e1e8 100644 --- a/VectoCoreTest/Integration/EngineOnlyCycle/EngineOnlyCycleTest.cs +++ b/VectoCoreTest/Integration/EngineOnlyCycle/EngineOnlyCycleTest.cs @@ -8,6 +8,7 @@ using TUGraz.VectoCore.Models.Connector.Ports.Impl; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; @@ -29,7 +30,7 @@ namespace TUGraz.VectoCore.Tests.Integration.EngineOnlyCycle var cycle = new MockDrivingCycle(container, data); var vehicle = new VehicleContainer(); var engineData = - EngineeringModeSimulationDataReader.CreateEngineDataFromFile(TestContext.DataRow["EngineFile"].ToString()); + MockSimulationDataFactory.CreateEngineDataFromFile(TestContext.DataRow["EngineFile"].ToString()); var aux = new Auxiliary(vehicle); aux.AddDirect(cycle); @@ -45,7 +46,7 @@ namespace TUGraz.VectoCore.Tests.Integration.EngineOnlyCycle var dt = 1.SI<Second>(); var modFile = Path.GetRandomFileName() + ".vmod"; - var dataWriter = new ModalDataWriter(modFile, SimulatorFactory.FactoryMode.EngineOnlyMode); + var dataWriter = new ModalDataContainer(modFile, SimulatorFactory.FactoryMode.EngineOnlyMode); foreach (var cycleEntry in data.Entries) { var response = port.Request(absTime, dt, cycleEntry.EngineTorque, cycleEntry.EngineSpeed); @@ -66,13 +67,13 @@ namespace TUGraz.VectoCore.Tests.Integration.EngineOnlyCycle [TestMethod] public void AssembleEngineOnlyPowerTrain() { - var dataWriter = new MockModalDataWriter(); + var dataWriter = new MockModalDataContainer(); var vehicleContainer = new VehicleContainer(); var gearbox = new EngineOnlyGearbox(vehicleContainer); var engine = new CombustionEngine(vehicleContainer, - EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile)); + MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile)); gearbox.InPort().Connect(engine.OutPort()); diff --git a/VectoCoreTest/Integration/FullCycleDeclarationTest.cs b/VectoCoreTest/Integration/FullCycleDeclarationTest.cs index 2d5afb73e6c2247c6c139b780e77e264788dd8fe..ade23ee67a5e1df14d93e38f23845c20cef19a1e 100644 --- a/VectoCoreTest/Integration/FullCycleDeclarationTest.cs +++ b/VectoCoreTest/Integration/FullCycleDeclarationTest.cs @@ -7,6 +7,7 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Integration @@ -126,7 +127,7 @@ namespace TUGraz.VectoCore.Tests.Integration var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, TruckDeclarationJob); factory.WriteModalResults = true; var sumFileName = Path.GetFileNameWithoutExtension(TruckDeclarationJob) + Constants.FileExtensions.SumFile; - var sumWriter = new SummaryFileWriter(sumFileName); + var sumWriter = new SummaryDataContainer(sumFileName); var jobContainer = new JobContainer(sumWriter); jobContainer.AddRuns(factory); @@ -144,7 +145,7 @@ namespace TUGraz.VectoCore.Tests.Integration var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, @"c:\Users\Technik\Downloads\40t Long Haul Truck\40t_Long_Haul_Truck.vecto"); factory.WriteModalResults = true; - factory.SumWriter = new SummaryFileWriter("Test.vsum"); + factory.SumData = new SummaryDataContainer("Test.vsum"); var runs = factory.SimulationRuns().ToArray(); var run = runs[4]; @@ -160,7 +161,7 @@ namespace TUGraz.VectoCore.Tests.Integration var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, @"c:\Users\Technik\Downloads\12t Delivery Truck\12t Delivery Truck.vecto") { WriteModalResults = true, - SumWriter = new SummaryFileWriter("Test.vsum") + SumData = new SummaryDataContainer("Test.vsum") }; var runs = factory.SimulationRuns().ToArray(); @@ -177,7 +178,7 @@ namespace TUGraz.VectoCore.Tests.Integration var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, @"c:\Users\Technik\Downloads\12t Delivery Truck\12t Delivery Truck.vecto") { WriteModalResults = true, - SumWriter = new SummaryFileWriter("Test.vsum") + SumData = new SummaryDataContainer("Test.vsum") }; var runs = factory.SimulationRuns().ToArray(); diff --git a/VectoCoreTest/Integration/SimulationRuns/FullPowertrain.cs b/VectoCoreTest/Integration/SimulationRuns/FullPowertrain.cs index 5131d991854f95577ecba454ac4b09d4cacaaa80..6219663955f036026a92a959c7ccfc745249f418 100644 --- a/VectoCoreTest/Integration/SimulationRuns/FullPowertrain.cs +++ b/VectoCoreTest/Integration/SimulationRuns/FullPowertrain.cs @@ -4,6 +4,7 @@ using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using NLog; using TUGraz.VectoCore.Configuration; +using TUGraz.VectoCore.InputData.FileIO.JSON; using TUGraz.VectoCore.InputData.FileIO.Reader; using TUGraz.VectoCore.InputData.FileIO.Reader.Impl; using TUGraz.VectoCore.Models.Connector.Ports; @@ -14,6 +15,8 @@ using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data.Gearbox; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; +using TUGraz.VectoCore.OutputData.FileIO; using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; using Wheels = TUGraz.VectoCore.Models.SimulationComponent.Impl.Wheels; @@ -38,10 +41,11 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns [TestMethod] public void Test_FullPowertrain_SimpleGearbox() { - var modalWriter = new ModalDataWriter("Coach_FullPowertrain_SimpleGearbox.vmod"); - var container = new VehicleContainer(modalWriter); + var fileWriter = new FileOutputWriter("Coach_FullPowertrain_SimpleGearbox", ""); + var modData = new ModalDataContainer("Coach_FullPowertrain_SimpleGearbox", fileWriter); + var container = new VehicleContainer(modData); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var cycleData = DrivingCycleDataReader.ReadFromFileDistanceBased(CycleFile); var axleGearData = CreateAxleGearData(); var gearboxData = CreateSimpleGearboxData(); @@ -84,22 +88,23 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns : Constants.SimulationSettings.TargetTimeInterval * container.VehicleSpeed; if (cnt++ % 100 == 0) { - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); } }). Default(r => Assert.Fail("Unexpected Response: {0}", r)); } while (!(response is ResponseCycleFinished)); - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); Assert.IsInstanceOfType(response, typeof(ResponseCycleFinished)); } [TestMethod, Ignore] public void Test_FullPowertrain() { - var modalWriter = new ModalDataWriter("Coach_FullPowertrain.vmod"); - var container = new VehicleContainer(modalWriter); + var fileWriter = new FileOutputWriter("Coach_FullPowertrain", ""); + var modData = new ModalDataContainer("Coach_FullPowertrain", fileWriter); + var container = new VehicleContainer(modData); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var cycleData = DrivingCycleDataReader.ReadFromFileDistanceBased(CoachCycleFile); var axleGearData = CreateAxleGearData(); var gearboxData = CreateGearboxData(); @@ -139,7 +144,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns try { response = cyclePort.Request(absTime, ds); } catch (Exception) { - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); throw; } Log.Info("Test Got Response: {0},", response); @@ -159,22 +164,23 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns : Constants.SimulationSettings.TargetTimeInterval * container.VehicleSpeed; if (cnt++ % 100 == 0) { - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); } }). Default(r => Assert.Fail("Unexpected Response: {0}", r)); } - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); Assert.IsInstanceOfType(response, typeof(ResponseCycleFinished)); } [TestMethod] public void Test_FullPowertrain_LowSpeed() { - var modalWriter = new ModalDataWriter("Coach_FullPowertrain_LowSpeed.vmod"); - var container = new VehicleContainer(modalWriter); + var fileWriter = new FileOutputWriter("Coach_FullPowertrain_LowSpeed", ""); + var modData = new ModalDataContainer("Coach_FullPowertrain_LowSpeed", fileWriter); + var container = new VehicleContainer(modData); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var cycleData = DrivingCycleDataReader.ReadFromFileDistanceBased(CycleFile); var axleGearData = CreateAxleGearData(); var gearboxData = CreateGearboxData(); @@ -212,7 +218,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns try { response = cyclePort.Request(absTime, ds); } catch (Exception) { - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); throw; } Log.Info("Test Got Response: {0},", response); @@ -232,25 +238,27 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns : Constants.SimulationSettings.TargetTimeInterval * container.VehicleSpeed; if (cnt++ % 100 == 0) { - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); } }). Default(r => { - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); Assert.Fail("Unexpected Response: {0}", r); }); } - modalWriter.Finish(VectoRun.Status.Success); + modData.Finish(VectoRun.Status.Success); Assert.IsInstanceOfType(response, typeof(ResponseCycleFinished)); } [TestMethod] public void Test_FullPowerTrain_JobFile() { - var sumWriter = new SummaryFileWriter(@"job.vsum"); - var jobContainer = new JobContainer(sumWriter); + var fileWriter = new FileOutputWriter("job", ""); + var sumData = new SummaryDataContainer(fileWriter); + var jobContainer = new JobContainer(sumData); - var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineeringMode, @"TestData\job.vecto"); + var inputData = JSONInputDataFactory.ReadJsonJob(@"TestData\job.vecto"); + var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineeringMode, inputData, fileWriter); jobContainer.AddRuns(factory); jobContainer.Execute(); @@ -355,7 +363,6 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns CurbWeigthExtra = 0.SI<Kilogram>(), Loading = loading, DynamicTyreRadius = 0.52.SI<Meter>(), - Retarder = new RetarderData { Type = RetarderData.RetarderType.None }, AxleData = axles, SavedInDeclarationMode = false, }; diff --git a/VectoCoreTest/Integration/SimulationRuns/MinimalPowertrain.cs b/VectoCoreTest/Integration/SimulationRuns/MinimalPowertrain.cs index aa4f713b51dfdb4c048c9291a97d587f0ca68749..7108dbcf9048ce801f7890beb466f36ad60d9cd3 100644 --- a/VectoCoreTest/Integration/SimulationRuns/MinimalPowertrain.cs +++ b/VectoCoreTest/Integration/SimulationRuns/MinimalPowertrain.cs @@ -11,6 +11,7 @@ using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data.Gearbox; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; using Wheels = TUGraz.VectoCore.Models.SimulationComponent.Impl.Wheels; @@ -36,7 +37,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns [TestMethod] public void TestWheelsAndEngineInitialize() { - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var vehicleData = CreateVehicleData(3300.SI<Kilogram>()); @@ -44,7 +45,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns var driverData = CreateDriverData(AccelerationFile); - var modalWriter = new ModalDataWriter("Coach_MinimalPowertrainOverload.vmod"); //new TestModalDataWriter(); + var modalWriter = new ModalDataContainer("Coach_MinimalPowertrainOverload.vmod"); //new TestModalDataWriter(); var vehicleContainer = new VehicleContainer(modalWriter); var driver = new Driver(vehicleContainer, driverData, new DefaultDriverStrategy()); @@ -85,7 +86,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns [TestMethod] public void TestWheelsAndEngine() { - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var cycleData = DrivingCycleDataReader.ReadFromFileDistanceBased(CycleFile); var axleGearData = CreateAxleGearData(); @@ -94,7 +95,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns var driverData = CreateDriverData(AccelerationFile); - var modalWriter = new ModalDataWriter("Coach_MinimalPowertrain.vmod"); //new TestModalDataWriter(); + var modalWriter = new ModalDataContainer("Coach_MinimalPowertrain.vmod"); //new TestModalDataWriter(); var vehicleContainer = new VehicleContainer(modalWriter); var cycle = new DistanceBasedDrivingCycle(vehicleContainer, cycleData); @@ -155,7 +156,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns [TestMethod] public void TestWheelsAndEngineLookahead() { - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var cycleData = DrivingCycleDataReader.ReadFromFileDistanceBased(CycleFileStop); var axleGearData = CreateAxleGearData(); @@ -164,7 +165,7 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns var driverData = CreateDriverData(AccelerationFile2); - var modalWriter = new ModalDataWriter("Coach_MinimalPowertrainOverload.vmod", + var modalWriter = new ModalDataContainer("Coach_MinimalPowertrainOverload.vmod", SimulatorFactory.FactoryMode.EngineeringMode); var vehicleContainer = new VehicleContainer(modalWriter); @@ -254,7 +255,6 @@ namespace TUGraz.VectoCore.Tests.Integration.SimulationRuns CurbWeigthExtra = 0.SI<Kilogram>(), Loading = loading, DynamicTyreRadius = 0.52.SI<Meter>(), - Retarder = new RetarderData { Type = RetarderData.RetarderType.None }, AxleData = axles, SavedInDeclarationMode = false, }; diff --git a/VectoCoreTest/Integration/Truck40tPowerTrain.cs b/VectoCoreTest/Integration/Truck40tPowerTrain.cs index f47a7b2ac73fa8c67f80a70c07d88cbcbe8c4dc5..c3e61c1a7d196ff503cd686c797cda29f7af705f 100644 --- a/VectoCoreTest/Integration/Truck40tPowerTrain.cs +++ b/VectoCoreTest/Integration/Truck40tPowerTrain.cs @@ -8,6 +8,7 @@ using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Data.Gearbox; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; using Wheels = TUGraz.VectoCore.Models.SimulationComponent.Impl.Wheels; @@ -44,10 +45,10 @@ namespace TUGraz.VectoCore.Tests.Integration public static VehicleContainer CreatePowerTrain(DrivingCycleData cycleData, string modFileName, Kilogram massExtra, Kilogram loading, bool overspeed = false) { - var modalWriter = new ModalDataWriter(modFileName); + var modalWriter = new ModalDataContainer(modFileName); var container = new VehicleContainer(modalWriter); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var axleGearData = CreateAxleGearData(); var gearboxData = CreateGearboxData(engineData); var vehicleData = CreateVehicleData(massExtra, loading); @@ -164,7 +165,6 @@ namespace TUGraz.VectoCore.Tests.Integration CurbWeigthExtra = massExtra, Loading = loading, DynamicTyreRadius = 0.4882675.SI<Meter>(), - Retarder = new RetarderData { Type = RetarderData.RetarderType.None }, AxleData = axles, SavedInDeclarationMode = false, }; diff --git a/VectoCoreTest/Models/Simulation/AuxTests.cs b/VectoCoreTest/Models/Simulation/AuxTests.cs index 17657138cbb79aec8b391b070ff5fecd5aa487b3..af7acc1a1eb12a089336044d2120f2fca23c1ca5 100644 --- a/VectoCoreTest/Models/Simulation/AuxTests.cs +++ b/VectoCoreTest/Models/Simulation/AuxTests.cs @@ -5,319 +5,327 @@ using TUGraz.VectoCore.Models.Declaration; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; using Microsoft.VisualStudio.TestTools.UnitTesting; +using TUGraz.VectoCore.InputData.FileIO.JSON; using TUGraz.VectoCore.InputData.FileIO.Reader; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; +using TUGraz.VectoCore.OutputData.FileIO; namespace TUGraz.VectoCore.Tests.Models.Simulation { - [TestClass] - public class AuxTests - { - [TestMethod] - public void AuxWriteModFileSumFile() - { - var dataWriter = new ModalDataWriter(@"AuxWriteModFileSumFile.vmod"); - dataWriter.AddAuxiliary("FAN"); - dataWriter.AddAuxiliary("PS"); - dataWriter.AddAuxiliary("STP"); - dataWriter.AddAuxiliary("ES"); - dataWriter.AddAuxiliary("AC"); - - var sumWriter = new SummaryFileWriter(@"AuxWriteModFileSumFile.vsum"); - var container = new VehicleContainer(dataWriter, - (writer, mass, loading) => sumWriter.WriteFullPowertrain(dataWriter, "", "", "", null, null)); - var data = DrivingCycleDataReader.ReadFromFileDistanceBased(@"TestData\Cycles\LongHaul_short.vdri"); - var mockcycle = new MockDrivingCycle(container, data); - var port = new MockTnOutPort(); - - var aux = new Auxiliary(container); - aux.InPort().Connect(port); - - var hdvClass = VehicleClass.Class5; - var mission = MissionType.LongHaul; - - aux.AddConstant("FAN", - DeclarationData.Fan.Lookup(MissionType.LongHaul, "Hydraulic driven - Constant displacement pump")); - aux.AddConstant("PS", DeclarationData.PneumaticSystem.Lookup(mission, hdvClass)); - aux.AddConstant("STP", - DeclarationData.SteeringPump.Lookup(MissionType.LongHaul, hdvClass, "Variable displacement")); - aux.AddConstant("ES", DeclarationData.ElectricSystem.Lookup(mission, null)); - aux.AddConstant("AC", - DeclarationData.HeatingVentilationAirConditioning.Lookup(mission, hdvClass)); - - var speed = 1400.RPMtoRad(); - var torque = 500.SI<NewtonMeter>(); - var t = 0.SI<Second>(); - var dt = 1.SI<Second>(); - - for (var i = 0; i < 11; i++) { - aux.OutPort().Request(t, dt, torque, speed); - dataWriter[ModalResultField.dist] = i.SI<Meter>(); - dataWriter[ModalResultField.Pe_eng] = 0.SI<Watt>(); - dataWriter[ModalResultField.acc] = 0.SI<MeterPerSquareSecond>(); - container.CommitSimulationStep(t, dt); - t += dt; - } - - container.FinishSimulation(); - sumWriter.Finish(); - - //todo: add aux columns to test - var testColumns = new[] { "Paux_FAN", "Paux_STP", "Paux_AC", "Paux_ES", "Paux_PS", "Paux" }; - - ResultFileHelper.TestModFile( - @"TestData\Results\EngineOnlyCycles\40t_Long_Haul_Truck_Long_Haul_Empty Loading.vmod", - @"AuxWriteModFileSumFile.vmod", testColumns, testRowCount: false); - ResultFileHelper.TestSumFile(@"TestData\Results\EngineOnlyCycles\40t_Long_Haul_Truck.vsum", - @"AuxWriteModFileSumFile.vsum"); - } - - [TestMethod] - public void AuxConstant() - { - var dataWriter = new MockModalDataWriter(); - var container = new VehicleContainer(dataWriter); - var port = new MockTnOutPort(); - var aux = new Auxiliary(container); - aux.InPort().Connect(port); - - var constPower = 1200.SI<Watt>(); - aux.AddConstant("CONSTANT", constPower); - - var speed = 2358.RPMtoRad(); - var torque = 500.SI<NewtonMeter>(); - var t = 0.SI<Second>(); - aux.OutPort().Request(t, t, torque, speed); - Assert.AreEqual(speed, port.AngularVelocity); - var newTorque = torque + constPower / speed; - AssertHelper.AreRelativeEqual(port.Torque, newTorque); - - speed = 2358.RPMtoRad(); - torque = 1500.SI<NewtonMeter>(); - aux.OutPort().Request(t, t, torque, speed); - Assert.AreEqual(speed, port.AngularVelocity); - newTorque = torque + constPower / speed; - AssertHelper.AreRelativeEqual(port.Torque, newTorque); - - speed = 1500.RPMtoRad(); - torque = 1500.SI<NewtonMeter>(); - aux.OutPort().Request(t, t, torque, speed); - Assert.AreEqual(speed, port.AngularVelocity); - newTorque = torque + constPower / speed; - AssertHelper.AreRelativeEqual(port.Torque, newTorque); - } - - [TestMethod] - public void AuxDirect() - { - var dataWriter = new MockModalDataWriter(); - var container = new VehicleContainer(dataWriter); - var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); - var cycle = new MockDrivingCycle(container, data); - var port = new MockTnOutPort(); - var aux = new Auxiliary(container); - aux.InPort().Connect(port); - - aux.AddDirect(cycle); - - var speed = 2358.RPMtoRad(); - var torque = 500.SI<NewtonMeter>(); - - var t = 0.SI<Second>(); - - var expected = new[] { 6100, 3100, 2300, 4500, 6100 }; - foreach (var e in expected) { - aux.OutPort().Request(t, t, torque, speed); - Assert.AreEqual(speed, port.AngularVelocity); - var newTorque = torque + e.SI<Watt>() / speed; - AssertHelper.AreRelativeEqual(port.Torque, newTorque); - - cycle.CommitSimulationStep(null); - } - } - - [TestMethod] - public void AuxAllCombined() - { - var dataWriter = new MockModalDataWriter(); - dataWriter.AddAuxiliary("ALT1"); - dataWriter.AddAuxiliary("CONSTANT"); - - var container = new VehicleContainer(dataWriter); - var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); - // cycle ALT1 is set to values to equal the first few fixed points in the auxiliary file. - // ALT1.aux file: nAuxiliary speed 2358: 0, 0.38, 0.49, 0.64, ... - // ALT1 in cycle file: 0, 0.3724 (=0.38*0.96), 0.4802 (=0.49*0.96), 0.6272 (0.64*0.96), ... - - var cycle = new MockDrivingCycle(container, data); - var port = new MockTnOutPort(); - - var aux = new Auxiliary(container); - aux.InPort().Connect(port); - - var auxData = AuxiliaryData.ReadFromFile(@"TestData\Components\24t_Coach_ALT.vaux"); - // ratio = 4.078 - // efficiency_engine = 0.96 - // efficiency_supply = 0.98 - - aux.AddMapping("ALT1", cycle, auxData); - aux.AddDirect(cycle); - var constPower = 1200.SI<Watt>(); - aux.AddConstant("CONSTANT", constPower); - - var speed = 578.22461991.RPMtoRad(); // = 2358 (nAuxiliary) * ratio - var torque = 500.SI<NewtonMeter>(); - var t = 0.SI<Second>(); - var expected = new[] { - 1200 + 6100 + 72.9166666666667, - // = 1000 * 0.07 (nAuxiliary=2358 and psupply=0) / 0.98 (efficiency_supply) - 1200 + 3100 + 677.083333333333, - // = 1000 * 0.65 (nAuxiliary=2358 and psupply=0.38) / 0.98 (efficiency_supply) - 1200 + 2300 + 822.916666666667, - // = 1000 * 0.79 (nAuxiliary=2358 and psupply=0.49) / 0.98 (efficiency_supply) - 1200 + 4500 + 1031.25, // = ... - 1200 + 6100 + 1166.66666666667, - 1200 + 6100 + 1656.25, - 1200 + 6100 + 2072.91666666667, - 1200 + 6100 + 2510.41666666667, - 1200 + 6100 + 2979.16666666667, - 1200 + 6100 + 3322.91666666667, - 1200 + 6100 + 3656.25 - }; - - foreach (var e in expected) { - aux.OutPort().Request(t, t, torque, speed); - Assert.AreEqual(speed, port.AngularVelocity); - - AssertHelper.AreRelativeEqual(port.Torque, torque + e.SI<Watt>() / speed); - - cycle.CommitSimulationStep(null); - } - } - - [TestMethod] - public void AuxMapping() - { - var auxId = "ALT1"; - var dataWriter = new MockModalDataWriter(); - dataWriter.AddAuxiliary(auxId); - - var container = new VehicleContainer(dataWriter); - var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); - // cycle ALT1 is set to values to equal the first few fixed points in the auxiliary file. - // ALT1.aux file: nAuxiliary speed 2358: 0, 0.38, 0.49, 0.64, ... - // ALT1 in cycle file: 0, 0.3724 (=0.38*0.96), 0.4802 (=0.49*0.96), 0.6272 (0.64*0.96), ... - - var cycle = new MockDrivingCycle(container, data); - var port = new MockTnOutPort(); - - var aux = new Auxiliary(container); - aux.InPort().Connect(port); - - var auxData = AuxiliaryData.ReadFromFile(@"TestData\Components\24t_Coach_ALT.vaux"); - // ratio = 4.078 - // efficiency_engine = 0.96 - // efficiency_supply = 0.98 - - aux.AddMapping(auxId, cycle, auxData); - - var speed = 578.22461991.RPMtoRad(); // = 2358 (nAuxiliary) * ratio - var torque = 500.SI<NewtonMeter>(); - var t = 0.SI<Second>(); - var expected = new[] { - 72.9166666666667, - // = 1000 * 0.07 (pmech from aux file at nAuxiliary=2358 and psupply=0) / 0.98 (efficiency_supply) - 677.083333333333, // = 1000 * 0.65 (nAuxiliary=2358 and psupply=0.38) / 0.98 - 822.916666666667, // = 1000 * 0.79 (nAuxiliary=2358 and psupply=0.49) / 0.98 - 1031.25, // = ... - 1166.66666666667, - 1656.25, - 2072.91666666667, - 2510.41666666667, - 2979.16666666667, - 3322.91666666667, - 3656.25 - }; - - foreach (var e in expected) { - aux.OutPort().Request(t, t, torque, speed); - Assert.AreEqual(speed, port.AngularVelocity); - - AssertHelper.AreRelativeEqual(port.Torque, torque + e.SI<Watt>() / speed); - - cycle.CommitSimulationStep(null); - } - } - - [TestMethod] - public void AuxColumnMissing() - { - var container = new VehicleContainer(); - var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); - var cycle = new MockDrivingCycle(container, data); - - var aux = new Auxiliary(container); - AssertHelper.Exception<VectoException>(() => aux.AddMapping("NONEXISTING_AUX", cycle, null), - "driving cycle does not contain column for auxiliary: NONEXISTING_AUX"); - } - - [TestMethod] - public void AuxFileMissing() - { - AssertHelper.Exception<VectoException>(() => AuxiliaryData.ReadFromFile(@"NOT_EXISTING_AUX_FILE.vaux"), - "Auxiliary file not found: NOT_EXISTING_AUX_FILE.vaux"); - } - - [TestMethod, Ignore] - public void AuxReadJobFileDeclarationMode() - { - var sumWriter = new SummaryFileWriter(@"AuxReadJobFileDeclarationMode.vsum"); - var jobContainer = new JobContainer(sumWriter); - - var runsFactory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, - @"TestData\Jobs\40t_Long_Haul_Truck.vecto"); - - jobContainer.AddRuns(runsFactory); - jobContainer.Execute(); - - ResultFileHelper.TestSumFile(@"TestData\Results\Declaration\40t_Long_Haul_Truck.vsum", - @"AuxReadJobFileDeclarationMode.vsum"); - } - - [TestMethod, Ignore] - public void AuxReadJobFileEngineeringMode() - { - var sumWriter = new SummaryFileWriter(@"AuxReadJobFileEngineeringMode.vsum"); - var jobContainer = new JobContainer(sumWriter); - - var runsFactory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineeringMode, - @"TestData\Jobs\24t Coach.vecto"); - - jobContainer.AddRuns(runsFactory); - jobContainer.Execute(); - - ResultFileHelper.TestSumFile(@"TestData\Results\Engineering\24t Coach.vsum", - @"AuxReadJobFileEngineeringMode.vsum"); - - ResultFileHelper.TestModFile( - @"TestData\Results\Engineering\24t Coach_Coach_24t_xshort.vmod", - @"TestData\Jobs\24t Coach_Coach_24t_xshort.vmod"); - Assert.Inconclusive(); - } - - [TestMethod] - public void AuxDeclarationWrongConfiguration() - { - // test what happens if there was a wrong auxiliary configuration in declaration mode - Assert.Inconclusive(); - } - - [TestMethod] - public void AuxCycleAdditionalFieldMissing() - { - // test the case when the Padd field is missing (no direct auxiliary) - Assert.Inconclusive(); - } - } + [TestClass] + public class AuxTests + { + [TestMethod] + public void AuxWriteModFileSumFile() + { + var fileWriter = new FileOutputWriter("AuxWriteModFileSumFile", ""); + var modData = new ModalDataContainer("AuxWriteModFileSumFile", fileWriter); + modData.AddAuxiliary("FAN"); + modData.AddAuxiliary("PS"); + modData.AddAuxiliary("STP"); + modData.AddAuxiliary("ES"); + modData.AddAuxiliary("AC"); + + var sumWriter = new SummaryDataContainer(fileWriter); + var container = new VehicleContainer(modData, + (writer, mass, loading) => sumWriter.WriteFullPowertrain(modData, "", "", "", null, null)); + var data = DrivingCycleDataReader.ReadFromFileDistanceBased(@"TestData\Cycles\LongHaul_short.vdri"); + var mockcycle = new MockDrivingCycle(container, data); + var port = new MockTnOutPort(); + + var aux = new Auxiliary(container); + aux.InPort().Connect(port); + + var hdvClass = VehicleClass.Class5; + var mission = MissionType.LongHaul; + + aux.AddConstant("FAN", + DeclarationData.Fan.Lookup(MissionType.LongHaul, "Hydraulic driven - Constant displacement pump")); + aux.AddConstant("PS", DeclarationData.PneumaticSystem.Lookup(mission, hdvClass)); + aux.AddConstant("STP", + DeclarationData.SteeringPump.Lookup(MissionType.LongHaul, hdvClass, "Variable displacement")); + aux.AddConstant("ES", DeclarationData.ElectricSystem.Lookup(mission, null)); + aux.AddConstant("AC", + DeclarationData.HeatingVentilationAirConditioning.Lookup(mission, hdvClass)); + + var speed = 1400.RPMtoRad(); + var torque = 500.SI<NewtonMeter>(); + var t = 0.SI<Second>(); + var dt = 1.SI<Second>(); + + for (var i = 0; i < 11; i++) { + aux.OutPort().Request(t, dt, torque, speed); + modData[ModalResultField.dist] = i.SI<Meter>(); + modData[ModalResultField.Pe_eng] = 0.SI<Watt>(); + modData[ModalResultField.acc] = 0.SI<MeterPerSquareSecond>(); + container.CommitSimulationStep(t, dt); + t += dt; + } + + container.FinishSimulation(); + sumWriter.Finish(); + + //todo: add aux columns to test + var testColumns = new[] { "Paux_FAN", "Paux_STP", "Paux_AC", "Paux_ES", "Paux_PS", "Paux" }; + + ResultFileHelper.TestModFile( + @"TestData\Results\EngineOnlyCycles\40t_Long_Haul_Truck_Long_Haul_Empty Loading.vmod", + @"AuxWriteModFileSumFile.vmod", testColumns, testRowCount: false); + ResultFileHelper.TestSumFile(@"TestData\Results\EngineOnlyCycles\40t_Long_Haul_Truck.vsum", + @"AuxWriteModFileSumFile.vsum"); + } + + [TestMethod] + public void AuxConstant() + { + var dataWriter = new MockModalDataContainer(); + var container = new VehicleContainer(dataWriter); + var port = new MockTnOutPort(); + var aux = new Auxiliary(container); + aux.InPort().Connect(port); + + var constPower = 1200.SI<Watt>(); + aux.AddConstant("CONSTANT", constPower); + + var speed = 2358.RPMtoRad(); + var torque = 500.SI<NewtonMeter>(); + var t = 0.SI<Second>(); + aux.OutPort().Request(t, t, torque, speed); + Assert.AreEqual(speed, port.AngularVelocity); + var newTorque = torque + constPower / speed; + AssertHelper.AreRelativeEqual(port.Torque, newTorque); + + speed = 2358.RPMtoRad(); + torque = 1500.SI<NewtonMeter>(); + aux.OutPort().Request(t, t, torque, speed); + Assert.AreEqual(speed, port.AngularVelocity); + newTorque = torque + constPower / speed; + AssertHelper.AreRelativeEqual(port.Torque, newTorque); + + speed = 1500.RPMtoRad(); + torque = 1500.SI<NewtonMeter>(); + aux.OutPort().Request(t, t, torque, speed); + Assert.AreEqual(speed, port.AngularVelocity); + newTorque = torque + constPower / speed; + AssertHelper.AreRelativeEqual(port.Torque, newTorque); + } + + [TestMethod] + public void AuxDirect() + { + var dataWriter = new MockModalDataContainer(); + var container = new VehicleContainer(dataWriter); + var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); + var cycle = new MockDrivingCycle(container, data); + var port = new MockTnOutPort(); + var aux = new Auxiliary(container); + aux.InPort().Connect(port); + + aux.AddDirect(cycle); + + var speed = 2358.RPMtoRad(); + var torque = 500.SI<NewtonMeter>(); + + var t = 0.SI<Second>(); + + var expected = new[] { 6100, 3100, 2300, 4500, 6100 }; + foreach (var e in expected) { + aux.OutPort().Request(t, t, torque, speed); + Assert.AreEqual(speed, port.AngularVelocity); + var newTorque = torque + e.SI<Watt>() / speed; + AssertHelper.AreRelativeEqual(port.Torque, newTorque); + + cycle.CommitSimulationStep(null); + } + } + + [TestMethod] + public void AuxAllCombined() + { + var dataWriter = new MockModalDataContainer(); + dataWriter.AddAuxiliary("ALT1"); + dataWriter.AddAuxiliary("CONSTANT"); + + var container = new VehicleContainer(dataWriter); + var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); + // cycle ALT1 is set to values to equal the first few fixed points in the auxiliary file. + // ALT1.aux file: nAuxiliary speed 2358: 0, 0.38, 0.49, 0.64, ... + // ALT1 in cycle file: 0, 0.3724 (=0.38*0.96), 0.4802 (=0.49*0.96), 0.6272 (0.64*0.96), ... + + var cycle = new MockDrivingCycle(container, data); + var port = new MockTnOutPort(); + + var aux = new Auxiliary(container); + aux.InPort().Connect(port); + + var auxData = AuxiliaryData.ReadFromFile(@"TestData\Components\24t_Coach_ALT.vaux"); + // ratio = 4.078 + // efficiency_engine = 0.96 + // efficiency_supply = 0.98 + + aux.AddMapping("ALT1", cycle, auxData); + aux.AddDirect(cycle); + var constPower = 1200.SI<Watt>(); + aux.AddConstant("CONSTANT", constPower); + + var speed = 578.22461991.RPMtoRad(); // = 2358 (nAuxiliary) * ratio + var torque = 500.SI<NewtonMeter>(); + var t = 0.SI<Second>(); + var expected = new[] { + 1200 + 6100 + 72.9166666666667, + // = 1000 * 0.07 (nAuxiliary=2358 and psupply=0) / 0.98 (efficiency_supply) + 1200 + 3100 + 677.083333333333, + // = 1000 * 0.65 (nAuxiliary=2358 and psupply=0.38) / 0.98 (efficiency_supply) + 1200 + 2300 + 822.916666666667, + // = 1000 * 0.79 (nAuxiliary=2358 and psupply=0.49) / 0.98 (efficiency_supply) + 1200 + 4500 + 1031.25, // = ... + 1200 + 6100 + 1166.66666666667, + 1200 + 6100 + 1656.25, + 1200 + 6100 + 2072.91666666667, + 1200 + 6100 + 2510.41666666667, + 1200 + 6100 + 2979.16666666667, + 1200 + 6100 + 3322.91666666667, + 1200 + 6100 + 3656.25 + }; + + foreach (var e in expected) { + aux.OutPort().Request(t, t, torque, speed); + Assert.AreEqual(speed, port.AngularVelocity); + + AssertHelper.AreRelativeEqual(port.Torque, torque + e.SI<Watt>() / speed); + + cycle.CommitSimulationStep(null); + } + } + + [TestMethod] + public void AuxMapping() + { + var auxId = "ALT1"; + var dataWriter = new MockModalDataContainer(); + dataWriter.AddAuxiliary(auxId); + + var container = new VehicleContainer(dataWriter); + var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); + // cycle ALT1 is set to values to equal the first few fixed points in the auxiliary file. + // ALT1.aux file: nAuxiliary speed 2358: 0, 0.38, 0.49, 0.64, ... + // ALT1 in cycle file: 0, 0.3724 (=0.38*0.96), 0.4802 (=0.49*0.96), 0.6272 (0.64*0.96), ... + + var cycle = new MockDrivingCycle(container, data); + var port = new MockTnOutPort(); + + var aux = new Auxiliary(container); + aux.InPort().Connect(port); + + var auxData = AuxiliaryData.ReadFromFile(@"TestData\Components\24t_Coach_ALT.vaux"); + // ratio = 4.078 + // efficiency_engine = 0.96 + // efficiency_supply = 0.98 + + aux.AddMapping(auxId, cycle, auxData); + + var speed = 578.22461991.RPMtoRad(); // = 2358 (nAuxiliary) * ratio + var torque = 500.SI<NewtonMeter>(); + var t = 0.SI<Second>(); + var expected = new[] { + 72.9166666666667, + // = 1000 * 0.07 (pmech from aux file at nAuxiliary=2358 and psupply=0) / 0.98 (efficiency_supply) + 677.083333333333, // = 1000 * 0.65 (nAuxiliary=2358 and psupply=0.38) / 0.98 + 822.916666666667, // = 1000 * 0.79 (nAuxiliary=2358 and psupply=0.49) / 0.98 + 1031.25, // = ... + 1166.66666666667, + 1656.25, + 2072.91666666667, + 2510.41666666667, + 2979.16666666667, + 3322.91666666667, + 3656.25 + }; + + foreach (var e in expected) { + aux.OutPort().Request(t, t, torque, speed); + Assert.AreEqual(speed, port.AngularVelocity); + + AssertHelper.AreRelativeEqual(port.Torque, torque + e.SI<Watt>() / speed); + + cycle.CommitSimulationStep(null); + } + } + + [TestMethod] + public void AuxColumnMissing() + { + var container = new VehicleContainer(); + var data = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Coach time based short.vdri"); + var cycle = new MockDrivingCycle(container, data); + + var aux = new Auxiliary(container); + AssertHelper.Exception<VectoException>(() => aux.AddMapping("NONEXISTING_AUX", cycle, null), + "driving cycle does not contain column for auxiliary: NONEXISTING_AUX"); + } + + [TestMethod] + public void AuxFileMissing() + { + AssertHelper.Exception<VectoException>(() => AuxiliaryData.ReadFromFile(@"NOT_EXISTING_AUX_FILE.vaux"), + "Auxiliary file not found: NOT_EXISTING_AUX_FILE.vaux"); + } + + [TestMethod, Ignore] + public void AuxReadJobFileDeclarationMode() + { + var fileWriter = new FileOutputWriter("AuxReadJobFileDeclarationMode", ""); + var sumData = new SummaryDataContainer(fileWriter); + var jobContainer = new JobContainer(sumData); + + var inputData = JSONInputDataFactory.ReadJsonJob(@"TestData\Jobs\40t_Long_Haul_Truck.vecto"); + var runsFactory = new SimulatorFactory(SimulatorFactory.FactoryMode.DeclarationMode, + inputData, fileWriter); + + jobContainer.AddRuns(runsFactory); + jobContainer.Execute(); + + ResultFileHelper.TestSumFile(@"TestData\Results\Declaration\40t_Long_Haul_Truck.vsum", + @"AuxReadJobFileDeclarationMode.vsum"); + } + + [TestMethod, Ignore] + public void AuxReadJobFileEngineeringMode() + { + var fileWriter = new FileOutputWriter("AuxReadJobFileEngineeringMode", ""); + var sumData = new SummaryDataContainer(fileWriter); + var jobContainer = new JobContainer(sumData); + + var inputData = JSONInputDataFactory.ReadJsonJob(@"TestData\Jobs\24t Coach.vecto"); + var runsFactory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineeringMode, + inputData, fileWriter); + + jobContainer.AddRuns(runsFactory); + jobContainer.Execute(); + + ResultFileHelper.TestSumFile(@"TestData\Results\Engineering\24t Coach.vsum", + @"AuxReadJobFileEngineeringMode.vsum"); + + ResultFileHelper.TestModFile( + @"TestData\Results\Engineering\24t Coach_Coach_24t_xshort.vmod", + @"TestData\Jobs\24t Coach_Coach_24t_xshort.vmod"); + Assert.Inconclusive(); + } + + [TestMethod] + public void AuxDeclarationWrongConfiguration() + { + // test what happens if there was a wrong auxiliary configuration in declaration mode + Assert.Inconclusive(); + } + + [TestMethod] + public void AuxCycleAdditionalFieldMissing() + { + // test the case when the Padd field is missing (no direct auxiliary) + Assert.Inconclusive(); + } + } } \ No newline at end of file diff --git a/VectoCoreTest/Models/Simulation/DrivingCycleTests.cs b/VectoCoreTest/Models/Simulation/DrivingCycleTests.cs index 6f39ce3f5dbf6c680e012b65a032b195b10eb3d4..06dfba3ada35107facabe3db83be5f5e9c0471a2 100644 --- a/VectoCoreTest/Models/Simulation/DrivingCycleTests.cs +++ b/VectoCoreTest/Models/Simulation/DrivingCycleTests.cs @@ -16,7 +16,7 @@ namespace TUGraz.VectoCore.Tests.Models.Simulation [TestMethod] public void TestEngineOnly() { - var dataWriter = new MockModalDataWriter(); + var dataWriter = new MockModalDataContainer(); var container = new VehicleContainer(dataWriter); var cycleData = DrivingCycleDataReader.ReadFromFileEngineOnly(@"TestData\Cycles\Coach Engine Only.vdri"); @@ -67,7 +67,7 @@ namespace TUGraz.VectoCore.Tests.Models.Simulation response = cycle.OutPort().Request(absTime, dt); Assert.IsInstanceOfType(response, typeof(ResponseSuccess)); - var dataWriter = new MockModalDataWriter(); + var dataWriter = new MockModalDataContainer(); container.CommitSimulationStep(absTime, dt); Assert.AreEqual(absTime, outPort.AbsTime); @@ -88,7 +88,7 @@ namespace TUGraz.VectoCore.Tests.Models.Simulation response = cycle.OutPort().Request(absTime, dt); Assert.IsInstanceOfType(response, typeof(ResponseSuccess)); - dataWriter = new MockModalDataWriter(); + dataWriter = new MockModalDataContainer(); container.CommitSimulationStep(absTime, dt); Assert.AreEqual(absTime, outPort.AbsTime); @@ -132,7 +132,7 @@ namespace TUGraz.VectoCore.Tests.Models.Simulation [TestMethod] public void Test_TimeBased_TimeFieldMissing() { - var container = new VehicleContainer(new MockModalDataWriter()); + var container = new VehicleContainer(new MockModalDataContainer()); var cycleData = DrivingCycleDataReader.ReadFromFileTimeBased(@"TestData\Cycles\Cycle time field missing.vdri"); var cycle = new TimeBasedDrivingCycle(container, cycleData); @@ -144,7 +144,7 @@ namespace TUGraz.VectoCore.Tests.Models.Simulation inPort.Connect(outPort); - var dataWriter = new MockModalDataWriter(); + var dataWriter = new MockModalDataContainer(); var absTime = 0.SI<Second>(); var dt = 1.SI<Second>(); diff --git a/VectoCoreTest/Models/Simulation/PowerTrainBuilderTest.cs b/VectoCoreTest/Models/Simulation/PowerTrainBuilderTest.cs index 07cd87871ff9a97d6d7282aa1be05ac7dd55bc15..283839d01ff3fb7dfea0a10380e63edaa940bbb8 100644 --- a/VectoCoreTest/Models/Simulation/PowerTrainBuilderTest.cs +++ b/VectoCoreTest/Models/Simulation/PowerTrainBuilderTest.cs @@ -1,5 +1,6 @@ using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; +using TUGraz.VectoCore.InputData.FileIO.JSON; using TUGraz.VectoCore.InputData.FileIO.Reader.Impl; using TUGraz.VectoCore.Models.Connector.Ports; using TUGraz.VectoCore.Models.Simulation; @@ -17,11 +18,11 @@ namespace TUGraz.VectoCore.Tests.Models.Simulation [TestMethod] public void BuildFullPowerTrainTest() { - var reader = new EngineeringModeSimulationDataReader(); - reader.SetJobFile(JobFile); + var dataProvider = JSONInputDataFactory.ReadJsonJob(JobFile); + var reader = new EngineeringModeVectoRunDataFactory(dataProvider); var runData = reader.NextRun().First(); - var writer = new MockModalDataWriter(); + var writer = new MockModalDataContainer(); var builder = new PowertrainBuilder(writer, false); var powerTrain = builder.Build(runData); diff --git a/VectoCoreTest/Models/Simulation/SimulationTests.cs b/VectoCoreTest/Models/Simulation/SimulationTests.cs index a5369cf178aa04da5cc719a2edcb3712a0aeaf4d..a70511ebd30842b521a8f61e7c9b0247efc60177 100644 --- a/VectoCoreTest/Models/Simulation/SimulationTests.cs +++ b/VectoCoreTest/Models/Simulation/SimulationTests.cs @@ -4,109 +4,110 @@ using TUGraz.VectoCore.Configuration; using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Models.Simulation { - [TestClass] - public class SimulationTests - { - private const string EngineFile = @"TestData\Components\24t Coach.veng"; - private const string CycleFile = @"TestData\Cycles\Coach Engine Only short.vdri"; - - private const string EngineOnlyJob = @"TestData\Jobs\EngineOnlyJob.vecto"; - - [TestMethod] - public void TestSimulationEngineOnly() - { - var resultFileName = "TestEngineOnly-result.vmod"; - var job = CreateRun(resultFileName); - - var container = job.GetContainer(); - - Assert.AreEqual(560.RPMtoRad(), container.EngineSpeed); - Assert.AreEqual(0U, container.Gear); - } - - [TestMethod] - public void TestEngineOnly_JobRun() - { - var actual = @"TestData\Jobs\EngineOnlyJob_Coach Engine Only short.vmod"; - var expected = @"TestData\Results\EngineOnlyCycles\24tCoach_EngineOnly short.vmod"; - - var job = CreateRun(actual); - job.Run(); - - ResultFileHelper.TestModFile(expected, actual); - } - - private class MockSumWriter : SummaryFileWriter - { - public override void Write(bool isEngineOnly, IModalDataWriter data, string jobFileName, string jobName, - string cycleFileName, - Kilogram vehicleMass, Kilogram vehicleLoading) {} - - public override void Finish() {} - } - - - [TestMethod] - public void TestEngineOnly_SimulatorRun() - { - var actual = @"TestData\Jobs\EngineOnlyJob_Coach Engine Only short.vmod"; - var expected = @"TestData\Results\EngineOnlyCycles\24tCoach_EngineOnly short.vmod"; - - var run = CreateRun(actual); - - var sim = new JobContainer(new MockSumWriter()); - sim.AddRun(run); - sim.Execute(); - sim.WaitFinished(); - - ResultFileHelper.TestModFile(expected, actual); - } - - public IVectoRun CreateRun(string resultFileName) - { - var sumFileName = resultFileName.Substring(0, resultFileName.Length - 5) + Constants.FileExtensions.SumFile; - - var dataWriter = new ModalDataWriter(resultFileName, SimulatorFactory.FactoryMode.EngineOnlyMode); - var sumWriter = new SummaryFileWriter(sumFileName); - - var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineOnlyMode, EngineOnlyJob) { - SumWriter = sumWriter - }; - - return factory.SimulationRuns().First(); - } - - [TestMethod] - public void Test_VectoJob() - { - var sumWriter = new SummaryFileWriter(@"24t Coach.vsum"); - var jobContainer = new JobContainer(sumWriter); - - var runsFactory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineOnlyMode, - @"TestData\Jobs\24t Coach EngineOnly.vecto"); - - jobContainer.AddRuns(runsFactory); - jobContainer.Execute(); - - jobContainer.WaitFinished(); - - ResultFileHelper.TestSumFile(@"TestData\Results\EngineOnlyCycles\24t Coach.vsum", @"24t Coach.vsum"); - - ResultFileHelper.TestModFiles(new[] { - @"TestData\Results\EngineOnlyCycles\24t Coach_Engine Only1.vmod", - @"TestData\Results\EngineOnlyCycles\24t Coach_Engine Only2.vmod", - @"TestData\Results\EngineOnlyCycles\24t Coach_Engine Only3.vmod" - }, new[] { - @"TestData\Jobs\24t Coach EngineOnly_Engine Only1.vmod", - @"TestData\Jobs\24t Coach EngineOnly_Engine Only2.vmod", - @"TestData\Jobs\24t Coach EngineOnly_Engine Only3.vmod" - }) - ; - } - } + [TestClass] + public class SimulationTests + { + private const string EngineFile = @"TestData\Components\24t Coach.veng"; + private const string CycleFile = @"TestData\Cycles\Coach Engine Only short.vdri"; + + private const string EngineOnlyJob = @"TestData\Jobs\EngineOnlyJob.vecto"; + + [TestMethod] + public void TestSimulationEngineOnly() + { + var resultFileName = "TestEngineOnly-result.vmod"; + var job = CreateRun(resultFileName); + + var container = job.GetContainer(); + + Assert.AreEqual(560.RPMtoRad(), container.EngineSpeed); + Assert.AreEqual(0U, container.Gear); + } + + [TestMethod] + public void TestEngineOnly_JobRun() + { + var actual = @"TestData\Jobs\EngineOnlyJob_Coach Engine Only short.vmod"; + var expected = @"TestData\Results\EngineOnlyCycles\24tCoach_EngineOnly short.vmod"; + + var job = CreateRun(actual); + job.Run(); + + ResultFileHelper.TestModFile(expected, actual); + } + + private class MockSumWriter : SummaryDataContainer + { + public override void Write(bool isEngineOnly, IModalDataContainer data, string jobFileName, string jobName, + string cycleFileName, + Kilogram vehicleMass, Kilogram vehicleLoading) {} + + public override void Finish() {} + } + + + [TestMethod] + public void TestEngineOnly_SimulatorRun() + { + var actual = @"TestData\Jobs\EngineOnlyJob_Coach Engine Only short.vmod"; + var expected = @"TestData\Results\EngineOnlyCycles\24tCoach_EngineOnly short.vmod"; + + var run = CreateRun(actual); + + var sim = new JobContainer(new MockSumWriter()); + sim.AddRun(run); + sim.Execute(); + sim.WaitFinished(); + + ResultFileHelper.TestModFile(expected, actual); + } + + public IVectoRun CreateRun(string resultFileName) + { + var sumFileName = resultFileName.Substring(0, resultFileName.Length - 5) + Constants.FileExtensions.SumFile; + + var dataWriter = new ModalDataContainer(resultFileName, SimulatorFactory.FactoryMode.EngineOnlyMode); + var sumWriter = new SummaryDataContainer(sumFileName); + + var factory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineOnlyMode, EngineOnlyJob) { + SumData = sumWriter + }; + + return factory.SimulationRuns().First(); + } + + [TestMethod] + public void Test_VectoJob() + { + var sumWriter = new SummaryDataContainer(@"24t Coach.vsum"); + var jobContainer = new JobContainer(sumWriter); + + var runsFactory = new SimulatorFactory(SimulatorFactory.FactoryMode.EngineOnlyMode, + @"TestData\Jobs\24t Coach EngineOnly.vecto"); + + jobContainer.AddRuns(runsFactory); + jobContainer.Execute(); + + jobContainer.WaitFinished(); + + ResultFileHelper.TestSumFile(@"TestData\Results\EngineOnlyCycles\24t Coach.vsum", @"24t Coach.vsum"); + + ResultFileHelper.TestModFiles(new[] { + @"TestData\Results\EngineOnlyCycles\24t Coach_Engine Only1.vmod", + @"TestData\Results\EngineOnlyCycles\24t Coach_Engine Only2.vmod", + @"TestData\Results\EngineOnlyCycles\24t Coach_Engine Only3.vmod" + }, new[] { + @"TestData\Jobs\24t Coach EngineOnly_Engine Only1.vmod", + @"TestData\Jobs\24t Coach EngineOnly_Engine Only2.vmod", + @"TestData\Jobs\24t Coach EngineOnly_Engine Only3.vmod" + }) + ; + } + } } \ No newline at end of file diff --git a/VectoCoreTest/Models/Simulation/VechicleContainerTests.cs b/VectoCoreTest/Models/Simulation/VechicleContainerTests.cs index c6942b2bab30103406b5fad276c95858dd841f55..8a3146c000e285a0c0ebfedebc540ea98ebf3325 100644 --- a/VectoCoreTest/Models/Simulation/VechicleContainerTests.cs +++ b/VectoCoreTest/Models/Simulation/VechicleContainerTests.cs @@ -2,6 +2,7 @@ using TUGraz.VectoCore.InputData.FileIO.Reader.Impl; using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.Tests.Utils; namespace TUGraz.VectoCore.Tests.Models.Simulation { @@ -14,7 +15,7 @@ namespace TUGraz.VectoCore.Tests.Models.Simulation public void VechicleContainerHasEngine() { var vehicle = new VehicleContainer(); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var engine = new CombustionEngine(vehicle, engineData); Assert.IsNotNull(vehicle.EngineSpeed); diff --git a/VectoCoreTest/Models/SimulationComponent/ClutchTest.cs b/VectoCoreTest/Models/SimulationComponent/ClutchTest.cs index 19aad85a8ed03bf718521f6a9b500c51c2b84191..d2cfafe4ecf67cccb1a9254b864448c423fb0d10 100644 --- a/VectoCoreTest/Models/SimulationComponent/ClutchTest.cs +++ b/VectoCoreTest/Models/SimulationComponent/ClutchTest.cs @@ -19,7 +19,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void TestClutch() { var container = new VehicleContainer(); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(CoachEngine); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(CoachEngine); var gearbox = new MockGearbox(container); var clutch = new Clutch(container, engineData, null); diff --git a/VectoCoreTest/Models/SimulationComponent/CombustionEngineTest.cs b/VectoCoreTest/Models/SimulationComponent/CombustionEngineTest.cs index b79f59df40e4f741327406f944b32dad16e2899d..f2544549129861ef7c0fc95b43857cb15622fd8f 100644 --- a/VectoCoreTest/Models/SimulationComponent/CombustionEngineTest.cs +++ b/VectoCoreTest/Models/SimulationComponent/CombustionEngineTest.cs @@ -58,7 +58,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void TestEngineHasOutPort() { var vehicle = new VehicleContainer(); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(CoachEngine); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(CoachEngine); var engine = new CombustionEngine(vehicle, engineData); var port = engine.OutPort(); @@ -69,7 +69,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void TestOutPortRequestNotFailing() { var vehicle = new VehicleContainer(); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(CoachEngine); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(CoachEngine); var engine = new CombustionEngine(vehicle, engineData); new EngineOnlyGearbox(vehicle); @@ -88,7 +88,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void TestSimpleModalData() { var vehicle = new VehicleContainer(); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(CoachEngine); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(CoachEngine); var engine = new CombustionEngine(vehicle, engineData); var gearbox = new EngineOnlyGearbox(vehicle); var port = engine.OutPort(); @@ -98,7 +98,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var torque = 0.SI<NewtonMeter>(); var engineSpeed = 600.RPMtoRad(); - var dataWriter = new MockModalDataWriter(); + var dataWriter = new MockModalDataContainer(); for (var i = 0; i < 21; i++) { port.Request(absTime, dt, torque, engineSpeed); @@ -156,7 +156,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var vehicleContainer = new VehicleContainer(); var gearbox = new EngineOnlyGearbox(vehicleContainer); var engineData = - EngineeringModeSimulationDataReader.CreateEngineDataFromFile( + MockSimulationDataFactory.CreateEngineDataFromFile( TestContext.DataRow["EngineFile"].ToString()); var engine = new EngineOnlyCombustionEngine(vehicleContainer, engineData); @@ -167,7 +167,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var requestPort = gearbox.OutPort(); //var modalData = new ModalDataWriter(string.Format("load_jump_{0}.csv", TestContext.DataRow["TestName"].ToString())); - var modalData = new MockModalDataWriter(); + var modalData = new MockModalDataContainer(); var idlePower = double.Parse(TestContext.DataRow["initialIdleLoad"].ToString()).SI<Watt>(); @@ -209,7 +209,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent { var container = new VehicleContainer(); var gearbox = new MockGearbox(container); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(CoachEngine); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(CoachEngine); var engine = new CombustionEngine(container, engineData); var clutch = new Clutch(container, engineData, engine.IdleController); @@ -232,8 +232,8 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var requestPort = gearbox.OutPort(); //vehicleContainer.DataWriter = new ModalDataWriter("engine_idle_test.csv"); - var dataWriter = new MockModalDataWriter(); - container.DataWriter = dataWriter; + var dataWriter = new MockModalDataContainer(); + container.ModData = dataWriter; var torque = 1200.SI<NewtonMeter>(); var angularVelocity = 800.RPMtoRad(); @@ -455,7 +455,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void TestWriteToFile() { var vehicle = new VehicleContainer(); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(CoachEngine); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(CoachEngine); var engine = new CombustionEngine(vehicle, engineData); //engineData.WriteToFile("engineData test output.veng"); @@ -464,7 +464,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent [TestMethod] public void Test_EngineData() { - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(CoachEngine); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(CoachEngine); var motorway = engineData.WHTCMotorway; Assert.AreEqual(motorway.Value(), 0); Assert.IsTrue(motorway.HasEqualUnit(new SI().Kilo.Gramm.Per.Watt.Second.ConvertTo())); @@ -496,7 +496,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent { container = new VehicleContainer(); var gearbox = new MockGearbox(container); - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(engineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(engineFile); engine = new CombustionEngine(container, engineData); var clutch = new Clutch(container, engineData, engine.IdleController); @@ -519,8 +519,8 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent requestPort = gearbox.OutPort(); //vehicleContainer.DataWriter = new ModalDataWriter("engine_idle_test.csv"); - var dataWriter = new MockModalDataWriter(); - container.DataWriter = dataWriter; + var dataWriter = new MockModalDataContainer(); + container.ModData = dataWriter; } } } \ No newline at end of file diff --git a/VectoCoreTest/Models/SimulationComponent/DriverTest.cs b/VectoCoreTest/Models/SimulationComponent/DriverTest.cs index cdb889fdaa3043ef3c8f8b88fbf51395e4b199bd..05c0a7271ceeef636be62247599c1eef7835eba5 100644 --- a/VectoCoreTest/Models/SimulationComponent/DriverTest.cs +++ b/VectoCoreTest/Models/SimulationComponent/DriverTest.cs @@ -12,6 +12,7 @@ using TUGraz.VectoCore.Models.Simulation.Impl; using TUGraz.VectoCore.Models.SimulationComponent; using TUGraz.VectoCore.Models.SimulationComponent.Data; using TUGraz.VectoCore.Models.SimulationComponent.Impl; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; using Wheels = TUGraz.VectoCore.Models.SimulationComponent.Impl.Wheels; @@ -34,13 +35,13 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent [TestMethod] public void DriverCoastingTest() { - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var vehicleData = CreateVehicleData(33000.SI<Kilogram>()); var driverData = CreateDriverData(); - var modalWriter = new ModalDataWriter("Coach_MinimalPowertrain_Coasting.vmod", + var modalWriter = new ModalDataContainer("Coach_MinimalPowertrain_Coasting.vmod", SimulatorFactory.FactoryMode.EngineeringMode); //new TestModalDataWriter(); var vehicleContainer = new VehicleContainer(modalWriter); @@ -89,13 +90,13 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent [TestMethod] public void DriverCoastingTest2() { - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var vehicleData = CreateVehicleData(33000.SI<Kilogram>()); var driverData = CreateDriverData(); - var modalWriter = new ModalDataWriter("Coach_MinimalPowertrain_Coasting.vmod"); + var modalWriter = new ModalDataContainer("Coach_MinimalPowertrain_Coasting.vmod"); var vehicleContainer = new VehicleContainer(modalWriter); var driver = new Driver(vehicleContainer, driverData, new DefaultDriverStrategy()); @@ -147,13 +148,13 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent [TestMethod] public void DriverOverloadTest() { - var engineData = EngineeringModeSimulationDataReader.CreateEngineDataFromFile(EngineFile); + var engineData = MockSimulationDataFactory.CreateEngineDataFromFile(EngineFile); var vehicleData = CreateVehicleData(33000.SI<Kilogram>()); var driverData = CreateDriverData(); - var modalWriter = new ModalDataWriter("Coach_MinimalPowertrain.vmod", SimulatorFactory.FactoryMode.EngineeringMode); + var modalWriter = new ModalDataContainer("Coach_MinimalPowertrain.vmod", SimulatorFactory.FactoryMode.EngineeringMode); var vehicleContainer = new VehicleContainer(modalWriter); var cycle = new MockDrivingCycle(vehicleContainer, null); @@ -201,7 +202,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var vehicleContainer = new VehicleContainer(); var vehicle = new MockVehicle(vehicleContainer); - var driverData = EngineeringModeSimulationDataReader.CreateDriverDataFromFile(JobFile); + var driverData = MockSimulationDataFactory.CreateDriverDataFromFile(JobFile); var driver = new Driver(vehicleContainer, driverData, new DefaultDriverStrategy()); var cycle = new MockDrivingCycle(vehicleContainer, null); @@ -270,7 +271,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var vehicleContainer = new VehicleContainer(); var vehicle = new MockVehicle(vehicleContainer); - var driverData = EngineeringModeSimulationDataReader.CreateDriverDataFromFile(JobFile); + var driverData = MockSimulationDataFactory.CreateDriverDataFromFile(JobFile); var driver = new Driver(vehicleContainer, driverData, new DefaultDriverStrategy()); var cycle = new MockDrivingCycle(vehicleContainer, null); @@ -362,7 +363,6 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent CurbWeigthExtra = 0.SI<Kilogram>(), Loading = loading, DynamicTyreRadius = 0.52.SI<Meter>(), - Retarder = new RetarderData { Type = RetarderData.RetarderType.None }, AxleData = axles, SavedInDeclarationMode = false, }; diff --git a/VectoCoreTest/Models/SimulationComponent/GearboxTest.cs b/VectoCoreTest/Models/SimulationComponent/GearboxTest.cs index dd53a1499aa6255e39f4b01d1da8cf495311ffe4..3b56f72e028c74266e93370879720faed969ff7f 100644 --- a/VectoCoreTest/Models/SimulationComponent/GearboxTest.cs +++ b/VectoCoreTest/Models/SimulationComponent/GearboxTest.cs @@ -65,9 +65,9 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void AxleGearTest() { var vehicle = new VehicleContainer(); - var gbxData = EngineeringModeSimulationDataReader.CreateGearboxDataFromFile(GearboxDataFile); + var axleGearData = MockSimulationDataFactory.CreateAxleGearDataFromFile(GearboxDataFile); //Gears gearData = new Gears(); - var axleGear = new AxleGear(vehicle, gbxData.AxleGearData); + var axleGear = new AxleGear(vehicle, axleGearData); var mockPort = new MockTnOutPort(); axleGear.InPort().Connect(mockPort); @@ -90,9 +90,9 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var loss = 9401.44062.SI<Watt>(); - Assert.AreEqual(Formulas.PowerToTorque(PvD + loss, angSpeed * gbxData.AxleGearData.Ratio).Value(), + Assert.AreEqual(Formulas.PowerToTorque(PvD + loss, angSpeed * axleGearData.Ratio).Value(), mockPort.Torque.Value(), 0.01, "Torque Engine Side"); - Assert.AreEqual((angSpeed * gbxData.AxleGearData.Ratio).Value(), mockPort.AngularVelocity.Value(), 0.01, + Assert.AreEqual((angSpeed * axleGearData.Ratio).Value(), mockPort.AngularVelocity.Value(), 0.01, "Torque Engine Side"); } @@ -106,14 +106,14 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent { var wrongFile = @"TestData\Components\24t Coach LessThanTwoGears.vgbx"; AssertHelper.Exception<VectoSimulationException>( - () => DeclarationModeSimulationDataReader.CreateGearboxDataFromFile(wrongFile, EngineDataFile), + () => MockSimulationDataFactory.CreateGearboxDataFromFile(wrongFile, EngineDataFile), "At least two Gear-Entries must be defined in Gearbox: 1 Axle-Gear and at least 1 Gearbox-Gear!"); } [TestMethod] public void Gearbox_LossMapInterpolationFail() { - var gearboxData = DeclarationModeSimulationDataReader.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); + var gearboxData = MockSimulationDataFactory.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); var container = new VehicleContainer(); var gearbox = new Gearbox(container, gearboxData, new AMTShiftStrategy(gearboxData, container)); var driver = new MockDriver(container); @@ -147,7 +147,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void Gearbox_IntersectFullLoadCurves() { var container = new VehicleContainer(); - var gearboxData = DeclarationModeSimulationDataReader.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); + var gearboxData = MockSimulationDataFactory.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); var gearbox = new Gearbox(container, gearboxData, new AMTShiftStrategy(gearboxData, container)); var driver = new MockDriver(container); @@ -257,7 +257,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void Gearbox_ShiftDown() { var container = new VehicleContainer(); - var gearboxData = DeclarationModeSimulationDataReader.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); + var gearboxData = MockSimulationDataFactory.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); var gearbox = new Gearbox(container, gearboxData, new AMTShiftStrategy(gearboxData, container)); var driver = new MockDriver(container); @@ -309,7 +309,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent public void Gearbox_ShiftUp() { var container = new VehicleContainer(); - var gearboxData = DeclarationModeSimulationDataReader.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); + var gearboxData = MockSimulationDataFactory.CreateGearboxDataFromFile(GearboxDataFile, EngineDataFile); var gearbox = new Gearbox(container, gearboxData, new AMTShiftStrategy(gearboxData, container)); var driver = new MockDriver(container); var vehicle = new MockVehicle(container) { MyVehicleSpeed = 10.SI<MeterPerSecond>() }; diff --git a/VectoCoreTest/Models/SimulationComponent/VehicleTest.cs b/VectoCoreTest/Models/SimulationComponent/VehicleTest.cs index 4cde7c9338ca6aac725557d4bc7c1f65e6dd6504..0353577558c6d3f94816896eb235216c9554cb3c 100644 --- a/VectoCoreTest/Models/SimulationComponent/VehicleTest.cs +++ b/VectoCoreTest/Models/SimulationComponent/VehicleTest.cs @@ -25,7 +25,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var container = new VehicleContainer(); //var reader = new EngineeringModeSimulationDataReader(); - var vehicleData = EngineeringModeSimulationDataReader.CreateVehicleDataFromFile(VehicleDataFileCoach); + var vehicleData = MockSimulationDataFactory.CreateVehicleDataFromFile(VehicleDataFileCoach); //VehicleData.ReadFromFile(VehicleDataFile); //vehicleData.CrossWindCorrection = VehicleData.CrossWindCorrectionMode.NoCorrection; var vehicle = new Vehicle(container, vehicleData); @@ -54,7 +54,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent { var container = new VehicleContainer(); - var vehicleData = EngineeringModeSimulationDataReader.CreateVehicleDataFromFile(VehicleDataFileTruck); + var vehicleData = MockSimulationDataFactory.CreateVehicleDataFromFile(VehicleDataFileTruck); vehicleData.AerodynamicDragAera = 6.46.SI<SquareMeter>(); var vehicle = new Vehicle(container, vehicleData); @@ -115,7 +115,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent { var container = new VehicleContainer(); - var vehicleData = EngineeringModeSimulationDataReader.CreateVehicleDataFromFile(VehicleDataFileTruck); + var vehicleData = MockSimulationDataFactory.CreateVehicleDataFromFile(VehicleDataFileTruck); vehicleData.AerodynamicDragAera = 6.2985.SI<SquareMeter>(); vehicleData.CrossWindCorrectionMode = CrossWindCorrectionMode.DeclarationModeCorrection; @@ -124,7 +124,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent var mockPort = new MockFvOutPort(); vehicle.InPort().Connect(mockPort); - var writer = new MockModalDataWriter(); + var writer = new MockModalDataContainer(); vehicle.Initialize(80.KMPHtoMeterPerSecond(), 0.SI<Radian>()); var absTime = 0.SI<Second>(); diff --git a/VectoCoreTest/Models/SimulationComponent/WheelsTest.cs b/VectoCoreTest/Models/SimulationComponent/WheelsTest.cs index 775a968c09f06828569b210a9fed6e71d17b14ea..f6dce7b18e7868546171b8841ef4056d7dd2be0a 100644 --- a/VectoCoreTest/Models/SimulationComponent/WheelsTest.cs +++ b/VectoCoreTest/Models/SimulationComponent/WheelsTest.cs @@ -19,7 +19,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponent { var container = new VehicleContainer(); //var reader = new EngineeringModeSimulationDataReader(); - var vehicleData = EngineeringModeSimulationDataReader.CreateVehicleDataFromFile(VehicleDataFile); + var vehicleData = MockSimulationDataFactory.CreateVehicleDataFromFile(VehicleDataFile); IWheels wheels = new Wheels(container, vehicleData.DynamicTyreRadius); var mockPort = new MockTnOutPort(); diff --git a/VectoCoreTest/Models/SimulationComponentData/GearboxDataTest.cs b/VectoCoreTest/Models/SimulationComponentData/GearboxDataTest.cs index 8104a8117e48e6db8ad2e3b9a428f58425e27990..668c1c1f3ebccb4b531d783dcfac1d6fbdebee4d 100644 --- a/VectoCoreTest/Models/SimulationComponentData/GearboxDataTest.cs +++ b/VectoCoreTest/Models/SimulationComponentData/GearboxDataTest.cs @@ -3,6 +3,7 @@ using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; using TUGraz.VectoCore.InputData.FileIO.Reader.Impl; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.Tests.Utils; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Models.SimulationComponentData @@ -14,16 +15,18 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponentData protected const string GearboxFile = @"Testdata\Components\24t Coach.vgbx"; + protected const string EngineFile = @"TestData\Components\24t Coach.veng"; + [TestMethod] public void TestGearboxDataReadTest() { - var gbxData = EngineeringModeSimulationDataReader.CreateGearboxDataFromFile(GearboxFile); + var gbxData = MockSimulationDataFactory.CreateGearboxDataFromFile(GearboxFile, EngineFile); Assert.AreEqual(GearboxType.AMT, gbxData.Type); Assert.AreEqual(1.0, gbxData.TractionInterruption.Value(), 0.0001); Assert.AreEqual(8, gbxData.Gears.Count); - Assert.AreEqual(3.240355, gbxData.AxleGearData.Ratio, 0.0001); + // Todo: Assert.AreEqual(3.240355, gbxData.AxleGearData.Ratio, 0.0001); Assert.AreEqual(1.0, gbxData.Gears[7].Ratio, 0.0001); Assert.AreEqual(-400, gbxData.Gears[1].ShiftPolygon.Downshift[0].Torque.Value(), 0.0001); @@ -44,18 +47,18 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponentData var rdyn = double.Parse(TestContext.DataRow["rDyn"].ToString(), CultureInfo.InvariantCulture); var speed = double.Parse(TestContext.DataRow["v"].ToString(), CultureInfo.InvariantCulture); - var gbxData = - EngineeringModeSimulationDataReader.CreateGearboxDataFromFile(TestContext.DataRow["GearboxDataFile"].ToString()); - + var gbxData = MockSimulationDataFactory.CreateGearboxDataFromFile(TestContext.DataRow["GearboxDataFile"].ToString(), + EngineFile); + var axleData = MockSimulationDataFactory.CreateAxleGearDataFromFile(TestContext.DataRow["GearboxDataFile"].ToString()); var PvD = double.Parse(TestContext.DataRow["PowerGbxOut"].ToString(), CultureInfo.InvariantCulture).SI<Watt>(); var torqueToWheels = Formulas.PowerToTorque(PvD, SpeedToAngularSpeed(speed, rdyn)); var torqueFromEngine = 0.SI<NewtonMeter>(); - var angSpeed = SpeedToAngularSpeed(speed, rdyn) * gbxData.AxleGearData.Ratio; + var angSpeed = SpeedToAngularSpeed(speed, rdyn) * axleData.Ratio; if (TestContext.DataRow["Gear"].ToString() == "A") { - torqueFromEngine = gbxData.AxleGearData.LossMap.GearboxInTorque(angSpeed, torqueToWheels); + torqueFromEngine = axleData.LossMap.GearboxInTorque(angSpeed, torqueToWheels); } var powerEngine = Formulas.TorqueToPower(torqueFromEngine, angSpeed); @@ -69,7 +72,7 @@ namespace TUGraz.VectoCore.Tests.Models.SimulationComponentData [TestMethod] public void TestInputOutOfRange() { - var gbxData = EngineeringModeSimulationDataReader.CreateGearboxDataFromFile(GearboxFile); + var gbxData = MockSimulationDataFactory.CreateGearboxDataFromFile(GearboxFile, EngineFile); Assert.Inconclusive("test another file which is not correct"); } diff --git a/VectoCoreTest/Reports/SumWriterTest.cs b/VectoCoreTest/Reports/SumWriterTest.cs index 6c5e7dde3fcec03f197e4e317e4c3803b9dd0369..39f5d842127a270133cdab5de621bb922833e83c 100644 --- a/VectoCoreTest/Reports/SumWriterTest.cs +++ b/VectoCoreTest/Reports/SumWriterTest.cs @@ -2,106 +2,110 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; +using TUGraz.VectoCore.OutputData; +using TUGraz.VectoCore.OutputData.FileIO; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Reports { - [TestClass] - public class SumWriterTest - { - [TestMethod] - public void TestSumCalcFixedTime() - { - var sumWriter = new SummaryFileWriter("testsumcalc_fixed.vsum"); - - var modData = new ModalDataWriter("testsumcalc_fixed.vmod"); - modData.AddAuxiliary("FAN"); - - for (var i = 0; i < 500; i++) { - modData[ModalResultField.simulationInterval] = 1.SI<Second>(); - modData[ModalResultField.time] = i.SI<Second>(); - modData[ModalResultField.dist] = i.SI<Meter>(); - modData["FAN"] = 3000.SI<Watt>(); - modData[ModalResultField.Pair] = 3000.SI<Watt>(); - modData[ModalResultField.Proll] = 3000.SI<Watt>(); - modData[ModalResultField.Pgrad] = 3000.SI<Watt>(); - modData[ModalResultField.Paux] = 3000.SI<Watt>(); - modData[ModalResultField.Pbrake] = 3000.SI<Watt>(); - - modData[ModalResultField.FCMap] = 1e-4.SI<KilogramPerSecond>(); - - modData[ModalResultField.altitude] = 0.SI<Meter>(); - modData[ModalResultField.acc] = 0.SI<MeterPerSquareSecond>(); - modData[ModalResultField.Pe_eng] = (i % 2 == 0 ? 1 : -1) * 3000.SI<Watt>(); - - modData.CommitSimulationStep(); - } - - sumWriter.WriteFullPowertrain(modData, "testSumCalc", "--", "--", 0.SI<Kilogram>(), 0.SI<Kilogram>()); - - modData.Finish(VectoRun.Status.Success); - sumWriter.Finish(); - - var sumData = VectoCSVFile.Read("testsumcalc_fixed.vsum", false, true); - - // 3kW * 500s => to kWh - Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eair [kWh]"), 1e-3); - Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eaux_FAN [kWh]"), 1e-3); - Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eroll [kWh]"), 1e-3); - Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Egrad [kWh]"), 1e-3); - Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eaux [kWh]"), 1e-3); - Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Ebrake [kWh]"), 1e-3); - - // 500s * 1e-4 kg/s = 0.05kg => 0.05kg / 499s => to g/h - Assert.AreEqual((500.0 * 1e-4) * 1000 * 3600 / 499.0, sumData.Rows[0].ParseDouble("FC-Map [g/h]"), 1e-3); - // 500s * 1e-4 kg/s = 0.05kg => 0.05kg / 499m => to g/km - Assert.AreEqual((500.0 * 1e-4) * 1000 * 1000 / 499.0, sumData.Rows[0].ParseDouble("FC-Map [g/km]"), 1e-3); - } - - [TestMethod] - public void TestSumCalcVariableTime() - { - var sumWriter = new SummaryFileWriter("testsumcalc_var.vsum"); - - var modData = new ModalDataWriter("testsumcalc_var.vmod"); - modData.AddAuxiliary("FAN"); - - var timeSteps = new[] - { 0.5.SI<Second>(), 0.3.SI<Second>(), 1.2.SI<Second>(), 12.SI<Second>(), 0.1.SI<Second>() }; - var powerDemand = new[] - { 1000.SI<Watt>(), 1500.SI<Watt>(), 2000.SI<Watt>(), 2500.SI<Watt>(), 3000.SI<Watt>() }; - - for (var i = 0; i < 500; i++) { - modData[ModalResultField.simulationInterval] = timeSteps[i % timeSteps.Count()]; - modData[ModalResultField.time] = i.SI<Second>(); - modData[ModalResultField.dist] = i.SI<Meter>(); - modData["FAN"] = powerDemand[i % powerDemand.Count()]; - modData[ModalResultField.Pair] = powerDemand[i % powerDemand.Count()]; - modData[ModalResultField.Proll] = powerDemand[i % powerDemand.Count()]; - modData[ModalResultField.Pgrad] = powerDemand[i % powerDemand.Count()]; - modData[ModalResultField.Paux] = powerDemand[i % powerDemand.Count()]; - modData[ModalResultField.Pbrake] = powerDemand[i % powerDemand.Count()]; - - modData[ModalResultField.altitude] = 0.SI<Meter>(); - modData[ModalResultField.acc] = 0.SI<MeterPerSquareSecond>(); - modData[ModalResultField.Pe_eng] = (i % 2 == 0 ? 1 : -1) * powerDemand[i % powerDemand.Count()]; - modData.CommitSimulationStep(); - } - - sumWriter.WriteFullPowertrain(modData, "testSumCalc", "--", "--", 0.SI<Kilogram>(), 0.SI<Kilogram>()); - - modData.Finish(VectoRun.Status.Success); - sumWriter.Finish(); - - var sumData = VectoCSVFile.Read("testsumcalc_var.vsum", false, true); - - // sum(dt * p) => to kWh - Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eair [kWh]"), 1e-3); - Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eaux_FAN [kWh]"), 1e-3); - Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eroll [kWh]"), 1e-3); - Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Egrad [kWh]"), 1e-3); - Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eaux [kWh]"), 1e-3); - Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Ebrake [kWh]"), 1e-3); - } - } + [TestClass] + public class SumWriterTest + { + [TestMethod] + public void TestSumCalcFixedTime() + { + var writer = new FileOutputWriter("testsumcalc_fixed", ""); + var sumWriter = new SummaryDataContainer(writer); + + var modData = new ModalDataContainer("testsumcalc_fixed", writer); //("testsumcalc_fixed.vmod"); + modData.AddAuxiliary("FAN"); + + for (var i = 0; i < 500; i++) { + modData[ModalResultField.simulationInterval] = 1.SI<Second>(); + modData[ModalResultField.time] = i.SI<Second>(); + modData[ModalResultField.dist] = i.SI<Meter>(); + modData["FAN"] = 3000.SI<Watt>(); + modData[ModalResultField.Pair] = 3000.SI<Watt>(); + modData[ModalResultField.Proll] = 3000.SI<Watt>(); + modData[ModalResultField.Pgrad] = 3000.SI<Watt>(); + modData[ModalResultField.Paux] = 3000.SI<Watt>(); + modData[ModalResultField.Pbrake] = 3000.SI<Watt>(); + + modData[ModalResultField.FCMap] = 1e-4.SI<KilogramPerSecond>(); + + modData[ModalResultField.altitude] = 0.SI<Meter>(); + modData[ModalResultField.acc] = 0.SI<MeterPerSquareSecond>(); + modData[ModalResultField.Pe_eng] = (i % 2 == 0 ? 1 : -1) * 3000.SI<Watt>(); + + modData.CommitSimulationStep(); + } + + sumWriter.WriteFullPowertrain(modData, "testSumCalc", "--", "--", 0.SI<Kilogram>(), 0.SI<Kilogram>()); + + modData.Finish(VectoRun.Status.Success); + sumWriter.Finish(); + + var sumData = VectoCSVFile.Read("testsumcalc_fixed.vsum", false, true); + + // 3kW * 500s => to kWh + Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eair [kWh]"), 1e-3); + Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eaux_FAN [kWh]"), 1e-3); + Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eroll [kWh]"), 1e-3); + Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Egrad [kWh]"), 1e-3); + Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Eaux [kWh]"), 1e-3); + Assert.AreEqual(500.0 * 3000.0 / 1000 / 3600, sumData.Rows[0].ParseDouble("Ebrake [kWh]"), 1e-3); + + // 500s * 1e-4 kg/s = 0.05kg => 0.05kg / 499s => to g/h + Assert.AreEqual((500.0 * 1e-4) * 1000 * 3600 / 499.0, sumData.Rows[0].ParseDouble("FC-Map [g/h]"), 1e-3); + // 500s * 1e-4 kg/s = 0.05kg => 0.05kg / 499m => to g/km + Assert.AreEqual((500.0 * 1e-4) * 1000 * 1000 / 499.0, sumData.Rows[0].ParseDouble("FC-Map [g/km]"), 1e-3); + } + + [TestMethod] + public void TestSumCalcVariableTime() + { + var writer = new FileOutputWriter("testsumcalc_var", ""); + var sumWriter = new SummaryDataContainer(writer); + + var modData = new ModalDataContainer("testsumcalc_var", writer); + modData.AddAuxiliary("FAN"); + + var timeSteps = new[] + { 0.5.SI<Second>(), 0.3.SI<Second>(), 1.2.SI<Second>(), 12.SI<Second>(), 0.1.SI<Second>() }; + var powerDemand = new[] + { 1000.SI<Watt>(), 1500.SI<Watt>(), 2000.SI<Watt>(), 2500.SI<Watt>(), 3000.SI<Watt>() }; + + for (var i = 0; i < 500; i++) { + modData[ModalResultField.simulationInterval] = timeSteps[i % timeSteps.Count()]; + modData[ModalResultField.time] = i.SI<Second>(); + modData[ModalResultField.dist] = i.SI<Meter>(); + modData["FAN"] = powerDemand[i % powerDemand.Count()]; + modData[ModalResultField.Pair] = powerDemand[i % powerDemand.Count()]; + modData[ModalResultField.Proll] = powerDemand[i % powerDemand.Count()]; + modData[ModalResultField.Pgrad] = powerDemand[i % powerDemand.Count()]; + modData[ModalResultField.Paux] = powerDemand[i % powerDemand.Count()]; + modData[ModalResultField.Pbrake] = powerDemand[i % powerDemand.Count()]; + + modData[ModalResultField.altitude] = 0.SI<Meter>(); + modData[ModalResultField.acc] = 0.SI<MeterPerSquareSecond>(); + modData[ModalResultField.Pe_eng] = (i % 2 == 0 ? 1 : -1) * powerDemand[i % powerDemand.Count()]; + modData.CommitSimulationStep(); + } + + sumWriter.WriteFullPowertrain(modData, "testSumCalc", "--", "--", 0.SI<Kilogram>(), 0.SI<Kilogram>()); + + modData.Finish(VectoRun.Status.Success); + sumWriter.Finish(); + + var sumData = VectoCSVFile.Read("testsumcalc_var.vsum", false, true); + + // sum(dt * p) => to kWh + Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eair [kWh]"), 1e-3); + Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eaux_FAN [kWh]"), 1e-3); + Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eroll [kWh]"), 1e-3); + Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Egrad [kWh]"), 1e-3); + Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Eaux [kWh]"), 1e-3); + Assert.AreEqual(0.934722222, sumData.Rows[0].ParseDouble("Ebrake [kWh]"), 1e-3); + } + } } \ No newline at end of file diff --git a/VectoCoreTest/Utils/MockAuxiliaryDemand.cs b/VectoCoreTest/Utils/MockAuxiliaryDemand.cs index be93826a2034e534091f1c6f552a83cbfa1686b7..e78499ceea525e55fdd99644a90e2bcab94c0395 100644 --- a/VectoCoreTest/Utils/MockAuxiliaryDemand.cs +++ b/VectoCoreTest/Utils/MockAuxiliaryDemand.cs @@ -6,6 +6,7 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Utils @@ -40,12 +41,12 @@ namespace TUGraz.VectoCore.Tests.Utils }; } - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { - writer[ModalResultField.dist] = 0.SI<Meter>(); - writer[ModalResultField.v_targ] = 0.KMPHtoMeterPerSecond(); - writer[ModalResultField.grad] = 0.SI<Scalar>(); - writer[ModalResultField.altitude] = 0.SI<Meter>(); + container[ModalResultField.dist] = 0.SI<Meter>(); + container[ModalResultField.v_targ] = 0.KMPHtoMeterPerSecond(); + container[ModalResultField.grad] = 0.SI<Scalar>(); + container[ModalResultField.altitude] = 0.SI<Meter>(); } protected override void DoCommitSimulationStep() diff --git a/VectoCoreTest/Utils/MockDriver.cs b/VectoCoreTest/Utils/MockDriver.cs index 10183c6a3048401df165403935c958208235a784..9f89e5b33ac1809dd892337c4a3075960d10bb04 100644 --- a/VectoCoreTest/Utils/MockDriver.cs +++ b/VectoCoreTest/Utils/MockDriver.cs @@ -6,6 +6,7 @@ using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Utils @@ -18,7 +19,7 @@ namespace TUGraz.VectoCore.Tests.Utils public MockDriver(IVehicleContainer container) : base(container) {} - protected override void DoWriteModalResults(IModalDataWriter writer) {} + protected override void DoWriteModalResults(IModalDataContainer container) {} protected override void DoCommitSimulationStep() {} diff --git a/VectoCoreTest/Utils/MockGearbox.cs b/VectoCoreTest/Utils/MockGearbox.cs index ed9e7f6f2c7152586a5ff83dc5de7720f4c15961..80907914f7ba1353f012037a829a6a74279ef16f 100644 --- a/VectoCoreTest/Utils/MockGearbox.cs +++ b/VectoCoreTest/Utils/MockGearbox.cs @@ -5,6 +5,7 @@ using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent; using TUGraz.VectoCore.Models.SimulationComponent.Data; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Utils @@ -68,7 +69,7 @@ namespace TUGraz.VectoCore.Tests.Utils } - protected override void DoWriteModalResults(IModalDataWriter writer) + protected override void DoWriteModalResults(IModalDataContainer container) { // nothing to write } diff --git a/VectoCoreTest/Utils/MockModalDataWriter.cs b/VectoCoreTest/Utils/MockModalDataContainer.cs similarity index 93% rename from VectoCoreTest/Utils/MockModalDataWriter.cs rename to VectoCoreTest/Utils/MockModalDataContainer.cs index aae84d3008e33be35b2b33f2311c1c9fa7fb7ea3..dbcb3d35a41f0c0a200ebfe5d460bf1a3efee999 100644 --- a/VectoCoreTest/Utils/MockModalDataWriter.cs +++ b/VectoCoreTest/Utils/MockModalDataContainer.cs @@ -3,6 +3,7 @@ using System.Data; using System.Linq; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.Impl; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Utils @@ -10,9 +11,9 @@ namespace TUGraz.VectoCore.Tests.Utils /// <summary> /// Fake Data Writer Class for Tests. /// </summary> - internal class MockModalDataWriter : IModalDataWriter + internal class MockModalDataContainer : IModalDataContainer { - public MockModalDataWriter() + public MockModalDataContainer() { Data = new ModalResults(); CurrentRow = Data.NewRow(); diff --git a/VectoCoreTest/Utils/MockSimulationDataFactory.cs b/VectoCoreTest/Utils/MockSimulationDataFactory.cs new file mode 100644 index 0000000000000000000000000000000000000000..d7d9ed40bd19540ac7a9b8a313fd445827e0853f --- /dev/null +++ b/VectoCoreTest/Utils/MockSimulationDataFactory.cs @@ -0,0 +1,53 @@ +using TUGraz.VectoCore.InputData; +using TUGraz.VectoCore.InputData.FileIO.JSON; +using TUGraz.VectoCore.InputData.FileIO.Reader.DataObjectAdaper; +using TUGraz.VectoCore.Models.SimulationComponent.Data; + +namespace TUGraz.VectoCore.Tests.Utils +{ + public class MockSimulationDataFactory + { + /// <summary> + /// Create gearboxdata instance directly from a file + /// </summary> + /// <param name="gearBoxFile"></param> + /// <param name="engineFile"></param> + /// <returns>GearboxData instance</returns> + public static GearboxData CreateGearboxDataFromFile(string gearBoxFile, string engineFile) + { + var gearboxInput = JSONInputDataFactory.ReadGearbox(gearBoxFile); + var engineInput = JSONInputDataFactory.ReadEngine(engineFile); + var dao = new DeclarationDataAdapter(); + var engineData = dao.CreateEngineData(engineInput); + return dao.CreateGearboxData(gearboxInput, engineData); + } + + public static AxleGearData CreateAxleGearDataFromFile(string axleGearFile) + { + var dao = new DeclarationDataAdapter(); + var axleGearInput = JSONInputDataFactory.ReadGearbox(axleGearFile); + return dao.CreateAxleGearData((IAxleGearInputData)axleGearInput); + } + + public static CombustionEngineData CreateEngineDataFromFile(string engineFile) + { + var dao = new EngineeringDataAdapter(); + var engineInput = JSONInputDataFactory.ReadEngine(engineFile); + return dao.CreateEngineData(engineInput); + } + + public static VehicleData CreateVehicleDataFromFile(string vehicleDataFile) + { + var dao = new EngineeringDataAdapter(); + var vehicleInput = JSONInputDataFactory.ReadJsonVehicle(vehicleDataFile); + return dao.CreateVehicleData(vehicleInput); + } + + public static DriverData CreateDriverDataFromFile(string driverDataFile) + { + var jobInput = JSONInputDataFactory.ReadJsonJob(driverDataFile); + var dao = new EngineeringDataAdapter(); + return dao.CreateDriverData(jobInput.DriverInputData); + } + } +} \ No newline at end of file diff --git a/VectoCoreTest/Utils/MockVehicle.cs b/VectoCoreTest/Utils/MockVehicle.cs index c30b292f07de0445bad895ba618f18cef7b2da19..0d489794655702eed21044b4ccdb2d3aebec4f4d 100644 --- a/VectoCoreTest/Utils/MockVehicle.cs +++ b/VectoCoreTest/Utils/MockVehicle.cs @@ -5,6 +5,7 @@ using TUGraz.VectoCore.Models.Simulation; using TUGraz.VectoCore.Models.Simulation.Data; using TUGraz.VectoCore.Models.Simulation.DataBus; using TUGraz.VectoCore.Models.SimulationComponent; +using TUGraz.VectoCore.OutputData; using TUGraz.VectoCore.Utils; namespace TUGraz.VectoCore.Tests.Utils @@ -17,7 +18,7 @@ namespace TUGraz.VectoCore.Tests.Utils internal RequestData LastRequest = new RequestData(); public MockVehicle(IVehicleContainer cockpit) : base(cockpit) {} - protected override void DoWriteModalResults(IModalDataWriter writer) {} + protected override void DoWriteModalResults(IModalDataContainer container) {} protected override void DoCommitSimulationStep() {} diff --git a/VectoCoreTest/VectoCoreTest.csproj b/VectoCoreTest/VectoCoreTest.csproj index 176794c9104fde36ab3cfb424eb0c3d6dc31b827..1b2af8674c3c86ea1833d95ee1f825f2df26fe9e 100644 --- a/VectoCoreTest/VectoCoreTest.csproj +++ b/VectoCoreTest/VectoCoreTest.csproj @@ -83,6 +83,7 @@ <Compile Include="Integration\SimulationRuns\FullPowertrain.cs" /> <Compile Include="Integration\Truck40tPowerTrain.cs" /> <Compile Include="Models\SimulationComponent\GearboxPowertrainTest.cs" /> + <Compile Include="Utils\MockSimulationDataFactory.cs" /> <Compile Include="Utils\Port.cs" /> <Compile Include="Models\SimulationComponentData\AuxiliaryTypeHelperTest.cs" /> <Compile Include="Models\Simulation\AuxTests.cs" /> @@ -121,7 +122,7 @@ <Compile Include="Utils\MockGearbox.cs" /> <Compile Include="Utils\SITest.cs" /> <Compile Include="Utils\DelauneyMapTest.cs" /> - <Compile Include="Utils\MockModalDataWriter.cs" /> + <Compile Include="Utils\MockModalDataContainer.cs" /> <Compile Include="Utils\DoubleExtensionMethodTest.cs" /> <Compile Include="Utils\VectoMathTest.cs" /> </ItemGroup>