Code development platform for open source projects from the European Union institutions :large_blue_circle: EU Login authentication by SMS has been phased out. To see alternatives please check here

Skip to content
Snippets Groups Projects
Commit ada40c3f authored by Markus Quaritsch's avatar Markus Quaritsch
Browse files

deleting no longer needed .vb files

parent 20078236
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 3184 deletions
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Public Class cDelaunayMap
Public ptDim As Integer
Public ptList As List(Of dPoint)
Private lDT As List(Of dTriangle)
Private planes As List(Of Double())
Public DualMode As Boolean
Private ptListXZ As List(Of dPoint)
Private planesXZ As List(Of Double())
Private lDTXZ As List(Of dTriangle)
Public ExtrapolError As Boolean
Public Sub New()
ptList = New List(Of dPoint)
ptListXZ = New List(Of dPoint)
DualMode = False
End Sub
Public Sub AddPoints(ByVal X As Double, ByVal Y As Double, ByVal Z As Double)
ptList.Add(New dPoint(X, Y, Z))
If DualMode Then ptListXZ.Add(New dPoint(X, Z, Y))
End Sub
Public Function Triangulate() As Boolean
Dim tr As dTriangle
Dim DT As dTriangulation
ptDim = ptList.Count - 1
'XY-triangulation
Try
DT = New dTriangulation
lDT = DT.Triangulate(ptList)
Catch ex As Exception
Return False
End Try
planes = New List(Of Double())
For Each tr In lDT
planes.Add(GetPlane(tr))
Next
'#If DEBUG Then
' Dim i As Int16
' Debug.Print("#,x1,y1,z1,x2,y2,z2")
' i = -1
' For Each tr In lDT
' i += 1
' Debug.Print(i & "," & tr.P1.X & "," & tr.P1.Y & "," & tr.P1.Z & "," & tr.P2.X & "," & tr.P2.Y & "," & tr.P2.Z)
' Debug.Print(i & "," & tr.P3.X & "," & tr.P3.Y & "," & tr.P3.Z & "," & tr.P2.X & "," & tr.P2.Y & "," & tr.P2.Z)
' Debug.Print(i & "," & tr.P1.X & "," & tr.P1.Y & "," & tr.P1.Z & "," & tr.P3.X & "," & tr.P3.Y & "," & tr.P3.Z)
' Next
'#End If
'XZ-triangulation
If DualMode Then
If ptDim <> ptListXZ.Count - 1 Then Return False
Try
DT = New dTriangulation
lDTXZ = DT.Triangulate(ptListXZ)
Catch ex As Exception
Return False
End Try
planesXZ = New List(Of Double())
For Each tr In lDTXZ
planesXZ.Add(GetPlane(tr))
Next
End If
Return True
End Function
'XY => Z Interpolation
Public Function Intpol(ByVal x As Double, ByVal y As Double) As Double
Dim j As Integer
Dim l0 As Double()
Dim tr As dTriangle
ExtrapolError = False
'Try exact solution for IsInside()
j = -1
For Each tr In lDT
j += 1
If IsInside(tr, x, y, True) Then
l0 = planes(j)
Return (l0(3) - x * l0(0) - y * l0(1)) / l0(2)
End If
Next
'Try approx. solution (fixes rounding errors when points lies exactly on an edge of a triangle)
j = -1
For Each tr In lDT
j += 1
If IsInside(tr, x, y, False) Then
l0 = planes(j)
Return (l0(3) - x * l0(0) - y * l0(1)) / l0(2)
End If
Next
'ERROR: Extrapolation
ExtrapolError = True
Return Nothing
End Function
'XZ => Y Interpolation
Public Function IntpolXZ(ByVal x As Double, ByVal z As Double) As Double
Dim j As Integer
Dim l0 As Double()
Dim tr As dTriangle
ExtrapolError = False
If DualMode Then
j = -1
'Try exact solution for IsInside()
For Each tr In lDTXZ
j += 1
If IsInside(tr, x, z, True) Then
l0 = planesXZ(j)
Return (l0(3) - x * l0(0) - z * l0(1)) / l0(2)
End If
Next
'Try approx. solution (fixes rounding errors when points lies exactly on an edge of a triangle)
j = -1
For Each tr In lDTXZ
j += 1
If IsInside(tr, x, z, False) Then
l0 = planesXZ(j)
Return (l0(3) - x * l0(0) - z * l0(1)) / l0(2)
End If
Next
'ERROR: Extrapolation
ExtrapolError = True
Return Nothing
Else
'ERROR: Extrapolation
ExtrapolError = True
Return Nothing
End If
End Function
Private Function GetPlane(ByRef tr As dTriangle) As Double()
Dim AB As dPoint
Dim AC As dPoint
Dim cross As dPoint
Dim l(3) As Double
Dim pt1 As dPoint
Dim pt2 As dPoint
Dim pt3 As dPoint
pt1 = tr.P1
pt2 = tr.P2
pt3 = tr.P3
AB = New dPoint(pt2.X - pt1.X, pt2.Y - pt1.Y, pt2.Z - pt1.Z)
AC = New dPoint(pt3.X - pt1.X, pt3.Y - pt1.Y, pt3.Z - pt1.Z)
cross = New dPoint(AB.Y * AC.Z - AB.Z * AC.Y, AB.Z * AC.X - AB.X * AC.Z, AB.X * AC.Y - AB.Y * AC.X)
l(0) = cross.X
l(1) = cross.Y
l(2) = cross.Z
l(3) = pt1.X * cross.X + pt1.Y * cross.Y + pt1.Z * cross.Z
Return l
End Function
Private Function IsInside(ByRef tr As dTriangle, ByVal xges As Double, ByVal yges As Double, ByVal Exact As Boolean) _
As Boolean
Dim v0(1) As Double
Dim v1(1) As Double
Dim v2(1) As Double
Dim dot00 As Double
Dim dot01 As Double
Dim dot02 As Double
Dim dot11 As Double
Dim dot12 As Double
Dim invDenom As Double
Dim u As Double
Dim v As Double
Dim pt1 As dPoint
Dim pt2 As dPoint
Dim pt3 As dPoint
pt1 = tr.P1
pt2 = tr.P2
pt3 = tr.P3
'Quelle: http://www.blackpawn.com/texts/pointinpoly/default.html (Barycentric Technique)
' Compute vectors
v0(0) = pt3.X - pt1.X
v0(1) = pt3.Y - pt1.Y
v1(0) = pt2.X - pt1.X
v1(1) = pt2.Y - pt1.Y
v2(0) = xges - pt1.X
v2(1) = yges - pt1.Y
' Compute dot products
dot00 = v0(0) * v0(0) + v0(1) * v0(1)
dot01 = v0(0) * v1(0) + v0(1) * v1(1)
dot02 = v0(0) * v2(0) + v0(1) * v2(1)
dot11 = v1(0) * v1(0) + v1(1) * v1(1)
dot12 = v1(0) * v2(0) + v1(1) * v2(1)
' Compute barycentric coordinates
invDenom = 1 / (dot00 * dot11 - dot01 * dot01)
u = (dot11 * dot02 - dot01 * dot12) * invDenom
v = (dot00 * dot12 - dot01 * dot02) * invDenom
'Debug.Print(u & ", " & v & ", " & u + v)
' Check if point is in triangle
If Exact Then
Return (u >= 0) And (v >= 0) And (u + v <= 1)
Else
Return (u >= -0.001) And (v >= -0.001) And (u + v <= 1.001)
End If
End Function
Public Class dPoint
Public X As Double
Public Y As Double
Public Z As Double
Public Sub New(ByVal xd As Double, ByVal yd As Double, ByVal zd As Double)
X = xd
Y = yd
Z = zd
End Sub
Public Shared Operator =(left As dPoint, right As dPoint) As Boolean
'If DirectCast(left, Object) = DirectCast(right, Object) Then
' Return True
'End If
'If (DirectCast(left, Object) Is Nothing) OrElse (DirectCast(right, Object) Is Nothing) Then
' Return False
'End If
' Just compare x and y here...
If left.X <> right.X Then
Return False
End If
If left.Y <> right.Y Then
Return False
End If
Return True
End Operator
Public Shared Operator <>(left As dPoint, right As dPoint) As Boolean
Return Not (left = right)
End Operator
End Class
Public Class dTriangle
Public P1 As dPoint
Public P2 As dPoint
Public P3 As dPoint
Public Sub New(ByRef pp1 As dPoint, ByRef pp2 As dPoint, ByRef pp3 As dPoint)
P1 = pp1
P2 = pp2
P3 = pp3
End Sub
Public Function ContainsInCircumcircle(pt As dPoint) As Double
Dim ax As Double = Me.P1.X - pt.X
Dim ay As Double = Me.P1.Y - pt.Y
Dim bx As Double = Me.P2.X - pt.X
Dim by As Double = Me.P2.Y - pt.Y
Dim cx As Double = Me.P3.X - pt.X
Dim cy As Double = Me.P3.Y - pt.Y
Dim det_ab As Double = ax * by - bx * ay
Dim det_bc As Double = bx * cy - cx * by
Dim det_ca As Double = cx * ay - ax * cy
Dim a_squared As Double = ax * ax + ay * ay
Dim b_squared As Double = bx * bx + by * by
Dim c_squared As Double = cx * cx + cy * cy
Return a_squared * det_bc + b_squared * det_ca + c_squared * det_ab
End Function
Public Function SharesVertexWith(triangle As dTriangle) As Boolean
If Me.P1.X = triangle.P1.X AndAlso Me.P1.Y = triangle.P1.Y Then
Return True
End If
If Me.P1.X = triangle.P2.X AndAlso Me.P1.Y = triangle.P2.Y Then
Return True
End If
If Me.P1.X = triangle.P3.X AndAlso Me.P1.Y = triangle.P3.Y Then
Return True
End If
If Me.P2.X = triangle.P1.X AndAlso Me.P2.Y = triangle.P1.Y Then
Return True
End If
If Me.P2.X = triangle.P2.X AndAlso Me.P2.Y = triangle.P2.Y Then
Return True
End If
If Me.P2.X = triangle.P3.X AndAlso Me.P2.Y = triangle.P3.Y Then
Return True
End If
If Me.P3.X = triangle.P1.X AndAlso Me.P3.Y = triangle.P1.Y Then
Return True
End If
If Me.P3.X = triangle.P2.X AndAlso Me.P3.Y = triangle.P2.Y Then
Return True
End If
If Me.P3.X = triangle.P3.X AndAlso Me.P3.Y = triangle.P3.Y Then
Return True
End If
Return False
End Function
End Class
Public Class dEdge
Public StartPoint As dPoint
Public EndPoint As dPoint
Public Sub New(ByRef p1 As dPoint, ByRef p2 As dPoint)
StartPoint = p1
EndPoint = p2
End Sub
Public Shared Operator =(left As dEdge, right As dEdge) As Boolean
'If DirectCast(left, Object) = DirectCast(right, Object) Then
' Return True
'End If
'If (DirectCast(left, Object) Is Nothing) Or (DirectCast(right, Object) Is Nothing) Then
' Return False
'End If
Return _
((left.StartPoint = right.StartPoint AndAlso left.EndPoint = right.EndPoint) OrElse
(left.StartPoint = right.EndPoint AndAlso left.EndPoint = right.StartPoint))
End Operator
Public Shared Operator <>(left As dEdge, right As dEdge) As Boolean
Return Not (left = right)
End Operator
End Class
Public Class dTriangulation
Public Function Triangulate(triangulationPoints As List(Of dPoint)) As List(Of dTriangle)
If triangulationPoints.Count < 3 Then
Throw New ArgumentException("Can not triangulate less than three vertices!")
End If
' The triangle list
Dim triangles As New List(Of dTriangle)()
' The "supertriangle" which encompasses all triangulation points.
' This triangle initializes the algorithm and will be removed later.
Dim superTriangle As dTriangle = Me.SuperTriangle(triangulationPoints)
triangles.Add(superTriangle)
' Include each point one at a time into the existing triangulation
For i As Integer = 0 To triangulationPoints.Count - 1
' Initialize the edge buffer.
Dim EdgeBuffer As New List(Of dEdge)()
' If the actual vertex lies inside the circumcircle, then the three edges of the
' triangle are added to the edge buffer and the triangle is removed from list.
For j As Integer = triangles.Count - 1 To 0 Step -1
Dim t As dTriangle = triangles(j)
If t.ContainsInCircumcircle(triangulationPoints(i)) > 0 Then
EdgeBuffer.Add(New dEdge(t.P1, t.P2))
EdgeBuffer.Add(New dEdge(t.P2, t.P3))
EdgeBuffer.Add(New dEdge(t.P3, t.P1))
triangles.RemoveAt(j)
End If
Next
' Remove duplicate edges. This leaves the convex hull of the edges.
' The edges in this convex hull are oriented counterclockwise!
For j As Integer = EdgeBuffer.Count - 2 To 0 Step -1
For k As Integer = EdgeBuffer.Count - 1 To j + 1 Step -1
If EdgeBuffer(j) = EdgeBuffer(k) Then
EdgeBuffer.RemoveAt(k)
EdgeBuffer.RemoveAt(j)
k -= 1
Continue For
End If
Next
Next
' Generate new counterclockwise oriented triangles filling the "hole" in
' the existing triangulation. These triangles all share the actual vertex.
For j As Integer = 0 To EdgeBuffer.Count - 1
triangles.Add(New dTriangle(EdgeBuffer(j).StartPoint, EdgeBuffer(j).EndPoint, triangulationPoints(i)))
Next
Next
' We don't want the supertriangle in the triangulation, so
' remove all triangles sharing a vertex with the supertriangle.
For i As Integer = triangles.Count - 1 To 0 Step -1
If triangles(i).SharesVertexWith(superTriangle) Then
triangles.RemoveAt(i)
End If
Next
' Return the triangles
Return triangles
End Function
Private Function SuperTriangle(triangulationPoints As List(Of dPoint)) As dTriangle
Dim M As Double = triangulationPoints(0).X
' get the extremal x and y coordinates
For i As Integer = 1 To triangulationPoints.Count - 1
Dim xAbs As Double = Math.Abs(triangulationPoints(i).X)
Dim yAbs As Double = Math.Abs(triangulationPoints(i).Y)
If xAbs > M Then
M = xAbs
End If
If yAbs > M Then
M = yAbs
End If
Next
' make a triangle
Dim sp1 As New dPoint(10 * M, 0, 0)
Dim sp2 As New dPoint(0, 10 * M, 0)
Dim sp3 As New dPoint(-10 * M, -10 * M, 0)
Return New dTriangle(sp1, sp2, sp3)
End Function
End Class
End Class
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Public Class cFile_V3
Private TxtFldParser As Microsoft.VisualBasic.FileIO.TextFieldParser
Private StrWrter As System.IO.StreamWriter
Private Mode As FileMode
Private Path As String
Private Sepp As String
Private SkipCom As Boolean
Private StopE As Boolean
Private FileOpen As Boolean
Private PreLine As String()
Private FileEnd As Boolean
'File format
private FileFormat As System.Text.Encoding = System.Text.Encoding.UTF8
Public Sub New()
Me.Reset()
End Sub
Private Sub Reset()
FileOpen = False
Mode = FileMode.Undefined
PreLine = Nothing
FileEnd = False
End Sub
Public Function OpenRead(ByVal FileName As String, Optional ByVal Separator As String = ",",
Optional ByVal SkipComment As Boolean = True, Optional ByVal StopAtE As Boolean = False) As Boolean
Me.Reset()
StopE = StopAtE
Path = FileName
Sepp = Separator
SkipCom = SkipComment
If Not (Mode = FileMode.Undefined) Then Return False
If Not IO.File.Exists(Path) Then Return False
Mode = FileMode.Read
Try
TxtFldParser = New Microsoft.VisualBasic.FileIO.TextFieldParser(Path, System.Text.Encoding.Default)
FileOpen = True
Catch ex As Exception
Return False
End Try
TxtFldParser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
TxtFldParser.Delimiters = New String() {Sepp}
'If TxtFldParser.EndOfData Then Return False
Me.ReadLine()
Return True
End Function
Public Function ReadLine() As String()
Dim line As String()
Dim line0 As String
line = PreLine
lb10:
If TxtFldParser.EndOfData Then
FileEnd = True
Else
PreLine = TxtFldParser.ReadFields
line0 = UCase(Trim(PreLine(0)))
If SkipCom Then
If Left(line0, 1) = "#" Then GoTo lb10
End If
If StopE Then FileEnd = (line0 = "E")
End If
Return line
End Function
Public Sub Close()
Select Case Mode
Case FileMode.Read
If FileOpen Then TxtFldParser.Close()
TxtFldParser = Nothing
Case FileMode.Write
If FileOpen Then StrWrter.Close()
StrWrter = Nothing
End Select
Me.Reset()
End Sub
Public ReadOnly Property EndOfFile() As Boolean
Get
Return FileEnd
End Get
End Property
Public Function OpenWrite(ByVal FileName As String, Optional ByVal Separator As String = ",",
Optional ByVal AutoFlush As Boolean = False, Optional ByVal Append As Boolean = False) As Boolean
Me.Reset()
Path = FileName
Sepp = Separator
If Not (Mode = FileMode.Undefined) Then Return False
Mode = FileMode.Write
Try
StrWrter = My.Computer.FileSystem.OpenTextFileWriter(Path, Append, FileFormat)
FileOpen = True
Catch ex As Exception
Return False
End Try
StrWrter.AutoFlush = AutoFlush
Return True
End Function
Public Sub WriteLine(ByVal ParamArray x() As Object)
Dim St As String
Dim StB As New System.Text.StringBuilder
Dim Skip As Boolean
Skip = True
For Each St In x
If Skip Then
StB.Append(St)
Skip = False
Else
StB.Append(Sepp & St)
End If
Next
StrWrter.WriteLine(StB.ToString)
StB = Nothing
End Sub
Public Sub WriteLine(ByVal x As String)
StrWrter.WriteLine(x)
End Sub
Private Enum FileMode
Undefined
Read
Write
End Enum
End Class
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Imports System.Globalization
Imports TUGraz.VectoCommon.Utils
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces
Public Class cMAP
Implements IFuelConsumptionMap
Private LnU As List(Of Single)
Private LTq As List(Of Single)
Private lFC As List(Of Single)
Private sFilePath As String
Private iMapDim As Integer
Private FuelMap As cDelaunayMap
Private Sub ResetMe()
lFC = Nothing
LTq = Nothing
LnU = Nothing
iMapDim = -1
FuelMap = New cDelaunayMap
End Sub
Public Function ReadFile(Optional ByVal ShowMsg As Boolean = True) As Boolean
Dim file As cFile_V3
Dim line As String()
Dim nU As Single
Dim MsgSrc As String
MsgSrc = "Main/ReadInp/MAP"
'Reset
ResetMe()
'Stop if there's no file
If sFilePath = "" OrElse Not IO.File.Exists(sFilePath) Then
Return False
End If
'Open file
file = New cFile_V3
If Not file.OpenRead(sFilePath) Then
file = Nothing
Return False
End If
'Skip Header
file.ReadLine()
'Initi Lists (before version check so ReadOldFormat works)
lFC = New System.Collections.Generic.List(Of Single)
LTq = New System.Collections.Generic.List(Of Single)
LnU = New System.Collections.Generic.List(Of Single)
Try
Do While Not file.EndOfFile
'Line read
line = file.ReadLine
'Line counter up (was reset in ResetMe)
iMapDim += 1
'Revolutions
nU = Single.Parse(line(0), CultureInfo.InvariantCulture)
LnU.Add(nU)
'Power
LTq.Add(Single.Parse(line(1), CultureInfo.InvariantCulture))
'FC
'Check sign
If CSng(line(2)) < 0 Then
file.Close()
Return False
End If
lFC.Add(CSng(line(2)))
Loop
Catch ex As Exception
GoTo lbEr
End Try
'Close file
file.Close()
file = Nothing
Return True
'ERROR-label for clean Abort
lbEr:
file.Close()
file = Nothing
Return False
End Function
Public Function Triangulate() As Boolean
Dim i As Integer
Dim MsgSrc As String
MsgSrc = "MAP/Norm"
'FC Delauney
For i = 0 To iMapDim
FuelMap.AddPoints(LnU(i), LTq(i), lFC(i))
Next
Return FuelMap.Triangulate()
End Function
Public Function fFCdelaunay_Intp(ByVal nU As Single, ByVal Tq As Single) As Single
Dim val As Single
val = CType(FuelMap.Intpol(nU, Tq), Single)
If FuelMap.ExtrapolError Then
Return -10000
Else
Return val
End If
End Function
#Region "Properties"
Public Property FilePath() As String
Get
Return sFilePath
End Get
Set(ByVal value As String)
sFilePath = value
End Set
End Property
Public ReadOnly Property MapDim As Integer
Get
Return iMapDim
End Get
End Property
Public ReadOnly Property Tq As List(Of Single)
Get
Return LTq
End Get
End Property
Public ReadOnly Property FC As List(Of Single)
Get
Return lFC
End Get
End Property
Public ReadOnly Property nU As List(Of Single)
Get
Return LnU
End Get
End Property
#End Region
Public Function GetFuelConsumption(torque As NewtonMeter, angularVelocity As PerSecond) As KilogramPerSecond _
Implements IFuelConsumptionMap.GetFuelConsumption
Return _
(fFCdelaunay_Intp(CType(angularVelocity.AsRPM, Single), CType(torque.Value(), Single)) / 3600.0 / 1000.0).SI(Of KilogramPerSecond)()
End Function
End Class
Option Strict On
Imports DownstreamModules.Electrics
Namespace Electrics
'Model based on CombinedALTS_V02_Editable.xlsx
Public Class Alternator
Implements IAlternator
Private signals As ICombinedAlternatorSignals
'D6
Public Property AlternatorName As String Implements IAlternator.AlternatorName
'G6
Public Property PulleyRatio As Double Implements IAlternator.PulleyRatio
'C10-D15
Public Property InputTable2000 As New List(Of AltUserInput) Implements IAlternator.InputTable2000
'F10-G15
Public Property InputTable4000 As New List(Of AltUserInput) Implements IAlternator.InputTable4000
'I10-J15
Public Property InputTable6000 As New List(Of AltUserInput) Implements IAlternator.InputTable6000
'M10-N15
Public Property RangeTable As New List(Of Table4Row) Implements IAlternator.RangeTable
'S9
Public ReadOnly Property SpindleSpeed As Double Implements IAlternator.SpindleSpeed
Get
Return signals.CrankRPM * PulleyRatio
End Get
End Property
'S10
Public ReadOnly Property Efficiency As Double Implements IAlternator.Efficiency
Get
'First build RangeTable, table 4
InitialiseRangeTable()
CalculateRangeTable()
'Calculate ( Interpolate ) Efficiency
Dim range As List(Of AltUserInput) = RangeTable.Select(Function(s) New AltUserInput(s.RPM, s.Efficiency)).ToList()
Return Alternator.Iterpolate(range, Convert.ToSingle(SpindleSpeed))
End Get
End Property
'Constructors
Sub New()
End Sub
Sub New(isignals As ICombinedAlternatorSignals, inputs As List(Of ICombinedAlternatorMapRow))
If isignals Is Nothing Then Throw New ArgumentException("Alternator - ISignals supplied is nothing")
signals = isignals
Me.AlternatorName = inputs.First().AlternatorName
Me.PulleyRatio = inputs.First().PulleyRatio
Dim values2k As Dictionary(Of Double, Double) =
inputs.Where(Function(x) x.RPM = 2000).Select(Function(x) New KeyValuePair(Of Double, Double)(x.Amps, x.Efficiency)) _
.ToDictionary(Function(x) x.Key, Function(x) x.Value)
Dim values4k As Dictionary(Of Double, Double) =
inputs.Where(Function(x) x.RPM = 4000).Select(Function(x) New KeyValuePair(Of Double, Double)(x.Amps, x.Efficiency)) _
.ToDictionary(Function(x) x.Key, Function(x) x.Value)
Dim values6k As Dictionary(Of Double, Double) =
inputs.Where(Function(x) x.RPM = 6000).Select(Function(x) New KeyValuePair(Of Double, Double)(x.Amps, x.Efficiency)) _
.ToDictionary(Function(x) x.Key, Function(x) x.Value)
BuildInputTable(values2k, InputTable2000)
BuildInputTable(values4k, InputTable4000)
BuildInputTable(values6k, InputTable6000)
CreateRangeTable()
End Sub
Public Shared Function Iterpolate(values As List(Of AltUserInput), x As Double) As Double
Dim lowestX As Double = values.Min(Function(m) m.Amps)
Dim highestX As Double = values.Max(Function(m) m.Amps)
Dim preKey, postKey, preEff, postEff, EffSlope As Double
Dim deltaX, deltaEff As Double
'Out of range, returns efficiency for lowest
If x < lowestX Then Return values.First(Function(f) f.Amps = lowestX).Eff
'Out of range, efficiency for highest
If x > highestX Then Return values.First(Function(f) f.Amps = highestX).Eff
'On Bounds check
If values.Where(Function(w) w.Amps = x).Count = 1 Then Return values.First(Function(w) w.Amps = x).Eff
'OK, we need to interpolate.
preKey = values.Last(Function(l) l.Amps < x).Amps
postKey = values.First(Function(l) l.Amps > x).Amps
preEff = values.First(Function(f) f.Amps = preKey).Eff
postEff = values.First(Function(f) f.Amps = postKey).Eff
deltaX = postKey - preKey
deltaEff = postEff - preEff
'slopes
EffSlope = deltaEff / deltaX
Dim retVal As Double = ((x - preKey) * EffSlope) + preEff
Return retVal
End Function
Private Sub CalculateRangeTable()
'M10=Row0-Rpm - N10=Row0-Eff
'M11=Row1-Rpm - N11=Row1-Eff
'M12=Row2-Rpm - N12=Row2-Eff - 2000
'M13=Row3-Rpm - N13=Row3-Eff - 4000
'M14=Row4-Rpm - N14=Row4-Eff - 6000
'M15=Row5-Rpm - N15=Row5-Eff
'M16=Row6-Rpm - N16=Row6-Eff
Dim N10, N11, N12, N13, N14, N15, N16 As Double
Dim M10, M11, M12, M13, M14, M15, M16 As Double
'EFFICIENCY
'2000
N12 = Alternator.Iterpolate(InputTable2000, signals.CurrentDemandAmps.Value())
RangeTable(2).Efficiency = N12
'4000
N13 = Alternator.Iterpolate(InputTable4000, signals.CurrentDemandAmps.Value())
RangeTable(3).Efficiency = N13
'6000
N14 = Alternator.Iterpolate(InputTable6000, signals.CurrentDemandAmps.Value())
RangeTable(4).Efficiency = N14
'Row0 & Row1 Efficiency =IF(N13>N12,0,MAX(N12:N14)) - Example Alt 1 N13=
N11 = If(N13 > N12, 0, Math.Max(Math.Max(N12, N13), N14))
RangeTable(1).Efficiency = N11
N10 = N11
RangeTable(0).Efficiency = N10
'Row 5 Efficiency
N15 = If(N13 > N14, 0, Math.Max(Math.Max(N12, N13), N14))
RangeTable(5).Efficiency = N15
'Row 6 - Efficiency
N16 = N15
RangeTable(6).Efficiency = N16
'RPM
'2000 Row 2 - RPM
M12 = 2000
RangeTable(2).RPM = M12
'4000 Row 3 - RPM
M13 = 4000
RangeTable(3).RPM = M13
'6000 Row 4 - RPM
M14 = 6000
RangeTable(4).RPM = M14
'Row 1 - RPM
'NOTE: Update to reflect CombineALternatorSchematicV02 20150429
'IF(M12=IF(N12>N13,M12-((M12-M13)/(N12-N13))*(N12-N11),M12-((M12-M13)/(N12-N13))*(N12-N11)), M12-0.01, IF(N12>N13,M12-((M12-M13)/(N12-N13))*(N12-N11),M12-((M12-M13)/(N12-N13))*(N12-N11)))
M11 =
Convert.ToSingle(
If _
(N12 - N13 = 0, 0,
If _
(M12 = If(N12 > N13, M12 - ((M12 - M13) / (N12 - N13)) * (N12 - N11), M12 - ((M12 - M13) / (N12 - N13)) * (N12 - N11)),
M12 - 0.01,
If(N12 > N13, M12 - ((M12 - M13) / (N12 - N13)) * (N12 - N11), M12 - ((M12 - M13) / (N12 - N13)) * (N12 - N11)))))
RangeTable(1).RPM = M11
'Row 0 - RPM
M10 = If(M11 < 1500, M11 - 1, 1500)
RangeTable(0).RPM = M10
'Row 5 - RPM
M15 =
Convert.ToSingle(
If _
(
M14 =
If _
((N14 = 0 OrElse N14 = N13), M14 + 1,
If(N13 > N14, ((((M14 - M13) / (N13 - N14)) * N14) + M14), ((((M14 - M13) / (N13 - N14)) * (N14 - N15)) + M14))),
M14 + 0.01,
If _
((N14 = 0 OrElse N14 = N13), M14 + 1,
If(N13 > N14, ((((M14 - M13) / (N13 - N14)) * N14) + M14), ((((M14 - M13) / (N13 - N14)) * (N14 - N15)) + M14)))))
RangeTable(5).RPM = M15
'Row 6 - RPM
M16 = If(M15 > 10000, M15 + 1, 10000)
RangeTable(6).RPM = M16
End Sub
Private Sub InitialiseRangeTable()
RangeTable(0).RPM = 0
RangeTable(0).Efficiency = 0
RangeTable(1).RPM = 0
RangeTable(0).Efficiency = 0
RangeTable(2).RPM = 2000
RangeTable(0).Efficiency = 0
RangeTable(3).RPM = 4000
RangeTable(0).Efficiency = 0
RangeTable(4).RPM = 6000
RangeTable(0).Efficiency = 0
RangeTable(5).RPM = 0
RangeTable(0).Efficiency = 0
RangeTable(6).RPM = 0
RangeTable(0).Efficiency = 0
End Sub
Private Sub CreateRangeTable()
RangeTable.Clear()
RangeTable.Add(New Table4Row(0, 0))
RangeTable.Add(New Table4Row(0, 0))
RangeTable.Add(New Table4Row(0, 0))
RangeTable.Add(New Table4Row(0, 0))
RangeTable.Add(New Table4Row(0, 0))
RangeTable.Add(New Table4Row(0, 0))
RangeTable.Add(New Table4Row(0, 0))
End Sub
Public Sub BuildInputTable(inputs As Dictionary(Of Double, Double), targetTable As List(Of AltUserInput))
Dim C11, C12, C13, C14, C15, D11, D12, D13, D14, D15 As Double
targetTable.Clear()
'Row0
targetTable.Add(New AltUserInput(0, D14))
'Row1
targetTable.Add(New AltUserInput(inputs.OrderBy(Function(x) x.Key).First.Key,
inputs.OrderBy(Function(x) x.Key).First.Value))
'Row2
targetTable.Add(New AltUserInput(inputs.OrderBy(Function(x) x.Key).Skip(1).First.Key,
inputs.OrderBy(Function(x) x.Key).Skip(1).First.Value))
'Row3
targetTable.Add(New AltUserInput(inputs.OrderBy(Function(x) x.Key).Skip(2).First.Key,
inputs.OrderBy(Function(x) x.Key).Skip(2).First.Value))
C11 = targetTable(1).Amps
C12 = targetTable(2).Amps
C13 = targetTable(3).Amps
D11 = targetTable(1).Eff
D12 = targetTable(2).Eff
D13 = targetTable(3).Eff
D14 = If(D12 > D13, 0, Math.Max(Math.Max(D11, D12), D13))
'Row4 - Eff
targetTable.Add(New AltUserInput(0, D14))
'Row4 - Amps
' Should probably refactor this into some sort of helper/extension method
Dim numarray As Double() = {D11, D12, D13}
Dim maxD11_D13 As Double = numarray.Max()
'=IF(OR(D13=0,D13=D12),C13+1,IF(D12>D13,((((C13-C12)/(D12-D13))*D13)+C13),((((C13-C12)/(D12-D13))*(D13-D14))+C13)))
C14 =
If _
((D13 = 0 OrElse D13 = D12 OrElse D13 = maxD11_D13), C13 + 1,
If(D12 > D13, ((((C13 - C12) / (D12 - D13)) * D13) + C13), ((((C13 - C12) / (D12 - D13)) * (D13 - D14)) + C13)))
targetTable(4).Amps = C14
'Row5
C15 = If(C14 > 200, C14 + 1, 200)
D15 = D14
targetTable.Add(New AltUserInput(C15, D15))
'Row0
targetTable(0).Eff = D11
End Sub
Public Function IsEqualTo(other As IAlternator) As Boolean Implements IAlternator.IsEqualTo
If Me.AlternatorName <> other.AlternatorName Then Return False
If Me.PulleyRatio <> other.PulleyRatio Then Return False
Dim i As Integer = 1
For i = 1 To 3
If Me.InputTable2000(i).Eff <> other.InputTable2000(i).Eff Then Return False
If Me.InputTable4000(i).Eff <> other.InputTable4000(i).Eff Then Return False
If Me.InputTable6000(i).Eff <> other.InputTable6000(i).Eff Then Return False
Next
Return True
End Function
End Class
End Namespace
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports DownstreamModules.Electrics
Imports TUGraz.VectoCommon.Utils
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces.DownstreamModules.Electrics
Namespace Electrics
Public Class AlternatorMap
Implements IAlternatorMap
Private ReadOnly filePath As String
Private _map As New List(Of MapPoint)
Private _yRange As List(Of Double)
Private _xRange As List(Of Double)
Private _minX, _minY, _maxX, _maxY As Double
'Required Action Test or Interpolation Type
Public Function OnBoundaryYInterpolatedX(x As Double, y As Double) As Boolean
Return _yRange.Contains(y) AndAlso Not _xRange.Contains(x)
End Function
Public Function OnBoundaryXInterpolatedY(x As Double, y As Double) As Boolean
Return Not _yRange.Contains(y) AndAlso _xRange.Contains(x)
End Function
Public Function ONBoundaryXY(x As Double, y As Double) As Boolean
Return (From sector In _map Where sector.Y = y AndAlso sector.x = x).Count = 1
End Function
'Determine Value Methods
Private Function GetOnBoundaryXY(x As Double, y As Double) As Double
Return (From sector In _map Where sector.Y = y AndAlso sector.x = x).First().v
End Function
Private Function GetOnBoundaryYInterpolatedX(x As Double, y As Double) As Double
Dim x0, x1, v0, v1, slope, dx As Double
x0 = (From p In _xRange Order By p Where p < x).Last()
x1 = (From p In _xRange Order By p Where p > x).First()
dx = x1 - x0
v0 = GetOnBoundaryXY(x0, y)
v1 = GetOnBoundaryXY(x1, y)
slope = (v1 - v0) / (x1 - x0)
Return v0 + ((x - x0) * slope)
End Function
Private Function GetOnBoundaryXInterpolatedY(x As Double, y As Double) As Double
Dim y0, y1, v0, v1, dy, v, slope As Double
y0 = (From p In _yRange Order By p Where p < y).Last()
y1 = (From p In _yRange Order By p Where p > y).First()
dy = y1 - y0
v0 = GetOnBoundaryXY(x, y0)
v1 = GetOnBoundaryXY(x, y1)
slope = (v1 - v0) / (y1 - y0)
v = v0 + ((y - y0) * slope)
Return v
End Function
Private Function GetBiLinearInterpolatedValue(x As Double, y As Double) As Double
Dim q11, q12, q21, q22, x1, x2, y1, y2, r1, r2, p As Double
y1 = (From mapSector As MapPoint In _map Where mapSector.Y < y).Last().Y
y2 = (From mapSector As MapPoint In _map Where mapSector.Y > y).First().Y
x1 = (From mapSector As MapPoint In _map Where mapSector.x < x).Last().x
x2 = (From mapSector As MapPoint In _map Where mapSector.x > x).First().x
q11 = GetOnBoundaryXY(x1, y1)
q12 = GetOnBoundaryXY(x1, y2)
q21 = GetOnBoundaryXY(x2, y1)
q22 = GetOnBoundaryXY(x2, y2)
r1 = ((x2 - x) / (x2 - x1)) * q11 + ((x - x1) / (x2 - x1)) * q21
r2 = ((x2 - x) / (x2 - x1)) * q12 + ((x - x1) / (x2 - x1)) * q22
p = ((y2 - y) / (y2 - y1)) * r1 + ((y - y1) / (y2 - y1)) * r2
Return p
End Function
'Utilities
Private Sub fillMapWithDefaults()
_map.Add(New MapPoint(10, 1500, 0.615))
_map.Add(New MapPoint(27, 1500, 0.7))
_map.Add(New MapPoint(53, 1500, 0.1947))
_map.Add(New MapPoint(63, 1500, 0.0))
_map.Add(New MapPoint(68, 1500, 0.0))
_map.Add(New MapPoint(125, 1500, 0.0))
_map.Add(New MapPoint(136, 1500, 0.0))
_map.Add(New MapPoint(10, 2000, 0.62))
_map.Add(New MapPoint(27, 2000, 0.7))
_map.Add(New MapPoint(53, 2000, 0.3))
_map.Add(New MapPoint(63, 2000, 0.1462))
_map.Add(New MapPoint(68, 2000, 0.692))
_map.Add(New MapPoint(125, 2000, 0.0))
_map.Add(New MapPoint(136, 2000, 0.0))
_map.Add(New MapPoint(10, 4000, 0.64))
_map.Add(New MapPoint(27, 4000, 0.6721))
_map.Add(New MapPoint(53, 4000, 0.7211))
_map.Add(New MapPoint(63, 4000, 0.74))
_map.Add(New MapPoint(68, 4000, 0.7352))
_map.Add(New MapPoint(125, 4000, 0.68))
_map.Add(New MapPoint(136, 4000, 0.6694))
_map.Add(New MapPoint(10, 6000, 0.53))
_map.Add(New MapPoint(27, 6000, 0.5798))
_map.Add(New MapPoint(53, 6000, 0.656))
_map.Add(New MapPoint(63, 6000, 0.6853))
_map.Add(New MapPoint(68, 6000, 0.7))
_map.Add(New MapPoint(125, 6000, 0.6329))
_map.Add(New MapPoint(136, 6000, 0.62))
_map.Add(New MapPoint(10, 7000, 0.475))
_map.Add(New MapPoint(27, 7000, 0.5337))
_map.Add(New MapPoint(53, 7000, 0.6235))
_map.Add(New MapPoint(63, 7000, 0.658))
_map.Add(New MapPoint(68, 7000, 0.6824))
_map.Add(New MapPoint(125, 7000, 0.6094))
_map.Add(New MapPoint(136, 7000, 0.5953))
End Sub
Private Sub getMapRanges()
_yRange = (From coords As MapPoint In _map Order By coords.Y Select coords.Y Distinct).ToList()
_xRange = (From coords As MapPoint In _map Order By coords.x Select coords.x Distinct).ToList()
_minX = _xRange.First
_maxX = _xRange.Last
_minY = _yRange.First
_maxY = _yRange.Last
End Sub
'Single entry point to determine Value on map
Public Function GetValue(x As Double, y As Double) As Double
If x < _minX OrElse x > _maxX OrElse y < _minY OrElse y > _maxY Then
'OnAuxiliaryEvent(String.Format("Alternator Map Limiting : RPM{0}, AMPS{1}",x,y),AdvancedAuxiliaryMessageType.Warning)
'Limiting
If x < _minX Then x = _minX
If x > _maxX Then x = _maxX
If y < _minY Then y = _minY
If y > _maxY Then y = _maxY
End If
'Satisfies both data points - non interpolated value
If ONBoundaryXY(x, y) Then Return GetOnBoundaryXY(x, y)
'Satisfies only x or y - single interpolation value
If OnBoundaryXInterpolatedY(x, y) Then Return GetOnBoundaryXInterpolatedY(x, y)
If OnBoundaryYInterpolatedX(x, y) Then Return GetOnBoundaryYInterpolatedX(x, y)
'satisfies no data points - Bi-Linear interpolation
Return GetBiLinearInterpolatedValue(x, y)
End Function
Public Function ReturnDefaultMapValueTests() As String
Dim sb As StringBuilder = New StringBuilder()
Dim x, y As Single
'All Sector Values
sb.AppendLine("All Values From Map")
sb.AppendLine("-------------------")
For Each x In _xRange
For Each y In _yRange
sb.AppendLine(String.Format("X:{0}, Y:{1}, V:{2}", x, y, GetValue(x, y)))
Next
Next
sb.AppendLine("")
sb.AppendLine("Four Corners with interpolated other")
sb.AppendLine("-------------------")
x = 1500
y = 18.5
sb.AppendLine(String.Format("X:{0}, Y:{1}, V:{2}", x, y, GetValue(x, y)))
x = 7000
y = 96.5
sb.AppendLine(String.Format("X:{0}, Y:{1}, V:{2}", x, y, GetValue(x, y)))
x = 1750
y = 10
sb.AppendLine(String.Format("X:{0}, Y:{1}, V:{2}", x, y, GetValue(x, y)))
x = 6500
y = 10
sb.AppendLine(String.Format("X:{0}, Y:{1}, V:{2}", x, y, GetValue(x, y)))
sb.AppendLine("")
sb.AppendLine("Interpolated both")
sb.AppendLine("-------------------")
Dim mx, my As Double
Dim x2, y2 As Integer
For x2 = 0 To _xRange.Count - 2
For y2 = 0 To _yRange.Count - 2
mx = _xRange(x2) + (_xRange(x2 + 1) - _xRange(x2)) / 2
my = _yRange(y2) + (_yRange(y2 + 1) - _yRange(y2)) / 2
sb.AppendLine(String.Format("X:{0}, Y:{1}, V:{2}", mx, my, GetValue(mx, my)))
Next
Next
sb.AppendLine("")
sb.AppendLine("MIKE -> 40 & 1000")
sb.AppendLine("-------------------")
x = 1000
y = 40
sb.AppendLine(String.Format("X:{0}, Y:{1}, V:{2}", x, y, GetValue(x, y)))
Return sb.ToString()
End Function
'Constructors
Public Sub New(filepath As String)
Me.filePath = filepath
Initialise()
getMapRanges()
End Sub
Private Class MapPoint
Public Y As Double
Public x As Double
Public v As Double
Public Sub New(y As Double, x As Double, v As Double)
Me.Y = y
Me.x = x
Me.v = v
End Sub
End Class
'Get Alternator Efficiency
Public Function GetEfficiency(rpm As Double, amps As Ampere) As AlternatorMapValues _
Implements IAlternatorMap.GetEfficiency
Return New AlternatorMapValues(GetValue(rpm, amps.Value()))
End Function
'Initialises the map.
Public Function Initialise() As Boolean Implements IAlternatorMap.Initialise
If File.Exists(filePath) Then
Using sr As StreamReader = New StreamReader(filePath)
'get array og lines fron csv
Dim lines() As String = sr.ReadToEnd().Split(CType(Environment.NewLine, Char()),
StringSplitOptions.RemoveEmptyEntries)
'Must have at least 2 entries in map to make it usable [dont forget the header row]
If (lines.Count() < 3) Then
Throw New ArgumentException("Insufficient rows in csv to build a usable map")
End If
_map = New List(Of MapPoint)
Dim firstline As Boolean = True
For Each line As String In lines
If Not firstline Then
'Advanced Alternator Source Check.
If line.Contains("[MODELSOURCE") Then Exit For
'split the line
Dim elements() As String = line.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
'3 entries per line required
If (elements.Length <> 3) Then
Throw New ArgumentException("Incorrect number of values in csv file")
End If
'add values to map
'Create AlternatorKey
Dim newPoint As MapPoint = New MapPoint(Single.Parse(elements(0), CultureInfo.InvariantCulture),
Single.Parse(elements(1), CultureInfo.InvariantCulture),
Single.Parse(elements(2), CultureInfo.InvariantCulture))
_map.Add(newPoint)
Else
firstline = False
End If
Next line
End Using
Return True
Else
Throw New ArgumentException("Supplied input file does not exist")
End If
End Function
'Public Events
Public Event AuxiliaryEvent(ByRef sender As Object, message As String, messageType As AdvancedAuxiliaryMessageType) _
Implements IAuxiliaryEvent.AuxiliaryEvent
Protected Sub OnAuxiliaryEvent(message As String, messageType As AdvancedAuxiliaryMessageType)
RaiseEvent AuxiliaryEvent(Me, message, messageType)
End Sub
End Class
End Namespace
Option Strict On
Imports System.Text
Imports System.IO
Imports System.Globalization
Imports DownstreamModules.Electrics
Imports TUGraz.VectoCommon.Utils
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces.DownstreamModules.Electrics
Namespace Electrics
Public Class CombinedAlternator
Implements IAlternatorMap, ICombinedAlternator
Private map As New List(Of ICombinedAlternatorMapRow)
Public Property Alternators As New List(Of IAlternator) Implements ICombinedAlternator.Alternators
Private OriginalAlternators As New List(Of IAlternator)
Private FilePath As String
Private altSignals As ICombinedAlternatorSignals
Private Signals As ISignals
Private AverageAlternatorsEfficiency As AlternatorMapValues
'Interface Implementation
Public Function GetEfficiency(ByVal CrankRPM As Double, ByVal Amps As Ampere) As AlternatorMapValues _
Implements IAlternatorMap.GetEfficiency
altSignals.CrankRPM = CrankRPM
altSignals.CurrentDemandAmps = (Amps.Value() / Alternators.Count).SI(Of Ampere)()
Dim alternatorMapValues As AlternatorMapValues = Nothing
If Signals Is Nothing OrElse Signals.RunningCalc Then
'If running calc cycle get efficiency from interpolation function
alternatorMapValues = New AlternatorMapValues(Convert.ToSingle(Alternators.Average(Function(a) a.Efficiency) / 100))
Else
'If running Pre calc cycle get an average of inputs
alternatorMapValues = AverageAlternatorsEfficiency
End If
If alternatorMapValues.Efficiency <= 0 Then
alternatorMapValues = New AlternatorMapValues(0.01)
End If
Return alternatorMapValues
End Function
Public Function Initialise() As Boolean Implements IAlternatorMap.Initialise
'From the map we construct this CombinedAlternator object and original CombinedAlternator Object
Alternators.Clear()
OriginalAlternators.Clear()
For Each alt As IEnumerable(Of ICombinedAlternatorMapRow) In map.GroupBy(Function(g) g.AlternatorName)
Dim altName As String = alt.First().AlternatorName
Dim pulleyRatio As Double = alt.First().PulleyRatio
Dim alternator As IAlternator = New Alternator(altSignals, alt.ToList())
Alternators.Add(alternator)
Next
Return True
End Function
'Constructors
Public Sub New(filePath As String, Optional signals As ISignals = Nothing)
Dim feedback As String = String.Empty
Me.Signals = signals
If Not FilePathUtils.ValidateFilePath(filePath, ".aalt", feedback) Then
Throw New ArgumentException(String.Format("Combined Alternator requires a valid .AALT filename. : {0}", feedback))
Else
Me.FilePath = filePath
End If
Me.altSignals = New CombinedAlternatorSignals()
'IF file exists then read it otherwise create a default.
If File.Exists(filePath) AndAlso InitialiseMap(filePath) Then
Initialise()
Else
'Create Default Map
CreateDefaultMap()
Initialise()
End If
' Calculate alternators average which is used only in the pre-run
Dim efficiencySum As Double
Dim efficiencyAverage As Double
For Each alt As IAlternator In Alternators
efficiencySum += alt.InputTable2000.ElementAt(1).Eff
efficiencySum += alt.InputTable2000.ElementAt(2).Eff
efficiencySum += alt.InputTable2000.ElementAt(3).Eff
efficiencySum += alt.InputTable4000.ElementAt(1).Eff
efficiencySum += alt.InputTable4000.ElementAt(2).Eff
efficiencySum += alt.InputTable4000.ElementAt(3).Eff
efficiencySum += alt.InputTable6000.ElementAt(1).Eff
efficiencySum += alt.InputTable6000.ElementAt(2).Eff
efficiencySum += alt.InputTable6000.ElementAt(3).Eff
Next
efficiencyAverage = efficiencySum / (Alternators.Count * 9)
AverageAlternatorsEfficiency = New AlternatorMapValues(efficiencyAverage / 100)
End Sub
'Helpers
Private Sub CreateDefaultMap()
map.Clear()
map.Add(New CombinedAlternatorMapRow("Alt1", 2000, 10, 62, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 2000, 27, 70, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 2000, 53, 30, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 4000, 10, 64, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 4000, 63, 74, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 4000, 125, 68, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 6000, 10, 53, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 6000, 68, 70, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt1", 6000, 136, 62, 3.6))
map.Add(New CombinedAlternatorMapRow("Alt2", 2000, 10, 62, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 2000, 27, 70, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 2000, 53, 30, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 4000, 10, 64, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 4000, 63, 74, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 4000, 125, 68, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 6000, 10, 53, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 6000, 68, 70, 3))
map.Add(New CombinedAlternatorMapRow("Alt2", 6000, 136, 62, 3))
End Sub
'Grid Management
Private Function AddNewAlternator(list As List(Of ICombinedAlternatorMapRow), ByRef feeback As String) As Boolean
Dim returnValue As Boolean = True
Dim altName As String = list.First().AlternatorName
Dim pulleyRatio As Double = list.First().PulleyRatio
'Check alt does not already exist in list
If Alternators.Where(Function(w) w.AlternatorName = altName).Count > 0 Then
feeback = "This alternator already exists in in the list, operation not completed."
Return False
End If
Dim alternator As IAlternator = New Alternator(altSignals, list.ToList())
Alternators.Add(alternator)
Return returnValue
End Function
Public Function AddAlternator(rows As List(Of ICombinedAlternatorMapRow), ByRef feedback As String) As Boolean
If Not AddNewAlternator(rows, feedback) Then
feedback = String.Format("Unable to add new alternator : {0}", feedback)
Return False
End If
Return True
End Function
Public Function DeleteAlternator(alternatorName As String, ByRef feedback As String, CountValidation As Boolean) _
As Boolean
'Is this the last alternator, if so deny the user the right to remove it.
If CountValidation AndAlso Alternators.Count < 2 Then
feedback = "There must be at least one alternator remaining, operation aborted."
Return False
End If
If Alternators.Where(Function(w) w.AlternatorName = alternatorName).Count = 0 Then
feedback = "This alternator does not exist"
Return False
End If
Dim altToRemove As IAlternator = Alternators.First(Function(w) w.AlternatorName = alternatorName)
Dim numAlternators As Integer = Alternators.Count
Alternators.Remove(altToRemove)
If Alternators.Count = numAlternators - 1 Then
Return True
Else
feedback = String.Format("The alternator {0} could not be removed : {1}", alternatorName, feedback)
Return False
End If
End Function
'Public Function UpdateAlternator( gridIndex As Integer, rows As List(Of ICombinedAlternatorMapRow), ByRef feedback As String) As Boolean
' Dim altName As String = rows.First.AlternatorName
' Dim altToUpd As IAlternator = Alternators.First(Function(w) w.AlternatorName = altName)
' If Not DeleteAlternator(altName, feedback) Then
' feedback = feedback
' Return False
' End If
' 'Re.create alternator.
' Dim replacementAlt As New Alternator(altSignals, rows)
' Alternators.Add(replacementAlt)
' Return True
'End Function
'Persistance Functions
Public Function Save(aaltPath As String) As Boolean
Dim returnValue As Boolean = True
Dim sb As New StringBuilder()
Dim row As Integer = 0
Dim amps As Double
Dim eff As Double
'write headers
sb.AppendLine("[AlternatorName],[RPM],[Amps],[Efficiency],[PulleyRatio]")
'write details
For Each alt As IAlternator In Alternators.OrderBy(Function(o) o.AlternatorName)
'2000 - IE Alt1,2000,10,50,3
For row = 1 To 3
amps = alt.InputTable2000(row).Amps
eff = alt.InputTable2000(row).Eff
sb.Append(
alt.AlternatorName + ",2000," + amps.ToString("0.000") + "," + eff.ToString("0.000") + "," +
alt.PulleyRatio.ToString("0.000"))
sb.AppendLine("")
Next
'4000 - IE Alt1,2000,10,50,3
For row = 1 To 3
amps = alt.InputTable4000(row).Amps
eff = alt.InputTable4000(row).Eff
sb.Append(
alt.AlternatorName + ",4000," + amps.ToString("0.000") + "," + eff.ToString("0.000") + "," +
alt.PulleyRatio.ToString("0.000"))
sb.AppendLine("")
Next
'6000 - IE Alt1,2000,10,50,3
For row = 1 To 3
amps = alt.InputTable6000(row).Amps
eff = alt.InputTable6000(row).Eff
sb.Append(
alt.AlternatorName + ",6000," + amps.ToString("0.000") + "," + eff.ToString("0.000") + "," +
alt.PulleyRatio.ToString("0.000"))
sb.AppendLine("")
Next
Next
'Add Model Source
sb.AppendLine("[MODELSOURCE]")
sb.Append(Me.ToString())
' Write the stream cotnents to a new file named "AllTxtFiles.txt"
Using outfile As New StreamWriter(aaltPath)
outfile.Write(sb.ToString())
End Using
Return returnValue
End Function
Private Function Load() As Boolean
If Not InitialiseMap(FilePath) Then Return False
Return True
End Function
'Initialises the map, only valid when loadingUI for first time in edit mode or always in operational mode.
Private Function InitialiseMap(filePath As String) As Boolean
Dim returnValue As Boolean = False
Dim elements As String()
If File.Exists(filePath) Then
Using sr As StreamReader = New StreamReader(filePath)
'get array og lines fron csv
Dim lines() As String = sr.ReadToEnd().Split(CType(Environment.NewLine, Char()),
StringSplitOptions.RemoveEmptyEntries)
'Must have at least 2 entries in map to make it usable [dont forget the header row]
If (lines.Count() < 10) Then
Throw New ArgumentException("Insufficient rows in csv to build a usable map")
End If
map = New List(Of ICombinedAlternatorMapRow)
Dim firstline As Boolean = True
For Each line As String In lines
If Not firstline Then
'Advanced Alternator Source Check.
If line.Contains("[MODELSOURCE") Then Exit For
'split the line
elements = line.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
'3 entries per line required
If (elements.Length <> 5) Then
Throw New ArgumentException("Incorrect number of values in csv file")
End If
'add values to map
map.Add(New CombinedAlternatorMapRow(elements(0), Single.Parse(elements(1), CultureInfo.InvariantCulture),
Single.Parse(elements(2), CultureInfo.InvariantCulture),
Single.Parse(elements(3), CultureInfo.InvariantCulture),
Single.Parse(elements(4), CultureInfo.InvariantCulture)))
Else
firstline = False
End If
Next line
End Using
Return True
Else
Throw New ArgumentException("Supplied input file does not exist")
End If
Return returnValue
End Function
'Can be used to send messages to Vecto.
Public Event AuxiliaryEvent(ByRef sender As Object, message As String, messageType As AdvancedAuxiliaryMessageType) _
Implements IAuxiliaryEvent.AuxiliaryEvent
'This is used to generate a diagnostics output which enables the user to
'Determine if they beleive the resulting map is what is expected
'Basically it is a check against the model/Spreadsheet
Public Overrides Function ToString() As String
Dim sb As New StringBuilder()
Dim a1, a2, a3, e1, e2, e3 As String
For Each alt As Alternator In Alternators.OrderBy(Function(o) o.AlternatorName)
sb.AppendLine("")
sb.AppendFormat("** {0} ** , PulleyRatio {1}", alt.AlternatorName, alt.PulleyRatio)
sb.AppendLine("")
sb.AppendLine("******************************************************************")
sb.AppendLine("")
Dim i As Integer = 1
sb.AppendLine("Table 1 (2000)" + vbTab + "Table 2 (4000)" + vbTab + "Table 3 (6000)")
sb.AppendLine("Amps" + vbTab + "Eff" + vbTab + "Amps" + vbTab + "Eff" + vbTab + "Amps" + vbTab + "Eff" + vbTab)
sb.AppendLine("")
For i = 1 To 3
a1 = alt.InputTable2000(i).Amps.ToString("0")
e1 = alt.InputTable2000(i).Eff.ToString("0.000")
a2 = alt.InputTable4000(i).Amps.ToString("0")
e2 = alt.InputTable4000(i).Eff.ToString("0.000")
a3 = alt.InputTable6000(i).Amps.ToString("0")
e3 = alt.InputTable6000(i).Eff.ToString("0.000")
sb.AppendLine(a1 + vbTab + e1 + vbTab + a2 + vbTab + e2 + vbTab + a3 + vbTab + e3 + vbTab)
Next
Next
'sb.AppendLine("")
'sb.AppendLine("********* COMBINED EFFICIENCY VALUES **************")
'sb.AppendLine("")
'sb.AppendLine(vbTab + "RPM VALUES")
'sb.AppendLine("AMPS" + vbTab + "500" + vbTab + "1500" + vbTab + "2500" + vbTab + "3500" + vbTab + "4500" + vbTab + "5500" + vbTab + "6500" + vbTab + "7500")
'For a As Single = 1 To Alternators.Count * 50
' sb.Append(a.ToString("0") + vbTab)
' For Each r As Single In {500, 1500, 2500, 3500, 4500, 5500, 6500, 7500}
' Dim eff As Single = GetEfficiency(r, a).Efficiency
' sb.Append(eff.ToString("0.000") + vbTab)
' Next
' sb.AppendLine("")
'Next
Return sb.ToString()
End Function
'Equality
Public Function IsEqualTo(other As ICombinedAlternator) As Boolean Implements ICombinedAlternator.IsEqualTo
'Count Check.
If Me.Alternators.Count <> other.Alternators.Count Then Return False
For Each alt As IAlternator In Me.Alternators
'Can we find the same alternatorName in other
If other.Alternators.Where(Function(f) f.AlternatorName = alt.AlternatorName).Count() <> 1 Then Return False
'get the alternator to compare and compare it.
If Not alt.IsEqualTo(other.Alternators.First(Function(f) f.AlternatorName = alt.AlternatorName)) Then Return False
Next
Return True
End Function
End Class
End Namespace
Imports DownstreamModules.Electrics
Namespace Electrics
'This class is reflective of the stored entries for the combined alternator
'And is used by the Combined Alternator Form and any related classes.
Public Class CombinedAlternatorMapRow
Implements ICombinedAlternatorMapRow
Public Property AlternatorName As String Implements ICombinedAlternatorMapRow.AlternatorName
Public Property RPM As Double Implements ICombinedAlternatorMapRow.RPM
Public Property Amps As Double Implements ICombinedAlternatorMapRow.Amps
Public Property Efficiency As Double Implements ICombinedAlternatorMapRow.Efficiency
Public Property PulleyRatio As Double Implements ICombinedAlternatorMapRow.PulleyRatio
'Constructors
Sub New()
End Sub
Sub New(AlternatorName As String, RPM As Single, Amps As Single, Efficiency As Single, PulleyRatio As Single)
'Sanity Check
If AlternatorName.Trim.Length = 0 Then Throw New ArgumentException("Alternator name cannot be zero length")
If Efficiency < 0 Or Efficiency > 100 Then _
Throw New ArgumentException("Alternator Efficiency must be between 0 and 100")
If PulleyRatio <= 0 Then Throw New ArgumentException("Alternator Pully ratio must be a positive number")
'Assignments
Me.AlternatorName = AlternatorName
Me.RPM = RPM
Me.Amps = Amps
Me.Efficiency = Efficiency
Me.PulleyRatio = PulleyRatio
End Sub
End Class
End Namespace

Imports DownstreamModules.Electrics
Imports TUGraz.VectoCommon.Utils
Namespace Electrics
'Used by the CombinedAlternator class and any other related classes.
Public Class CombinedAlternatorSignals
Implements ICombinedAlternatorSignals
Public Property CrankRPM As Double Implements ICombinedAlternatorSignals.CrankRPM
Public Property CurrentDemandAmps As Ampere Implements ICombinedAlternatorSignals.CurrentDemandAmps
'Number of alternators in the Combined Alternator
Public Property NumberOfAlternators As Integer Implements ICombinedAlternatorSignals.NumberOfAlternators
End Class
End Namespace
Imports System.ComponentModel
Imports DownstreamModules.Electrics
Imports TUGraz.VectoCommon.Utils
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Namespace Electrics
''' <summary>
''' Described a consumer of Alternator electrical power
''' </summary>
''' <remarks></remarks>
Public Class ElectricalConsumer
Implements IElectricalConsumer
'Fields
Private _BaseVehicle As Boolean
Private _Category As String
Private _ConsumerName As String
Private _NominalConsumptionAmps As Double
Private _NumberInActualVehicle As Integer
Private _PhaseIdle_TractionOn As Double
Private _PowerNetVoltage As Double
Private _Info As String
'Calculated
Private Property AvgConsumptionAmps As Double Implements IElectricalConsumer.AvgConsumptionAmps
'Properties
Public Property BaseVehicle As Boolean Implements IElectricalConsumer.BaseVehicle
Get
Return _BaseVehicle
End Get
Set(value As Boolean)
_BaseVehicle = value
NotifyPropertyChanged("BaseVehicle")
End Set
End Property
Public Property Category As String Implements IElectricalConsumer.Category
Get
Return _Category
End Get
Set(value As String)
_Category = value
NotifyPropertyChanged("Category")
End Set
End Property
Public Property ConsumerName As String Implements IElectricalConsumer.ConsumerName
Get
Return _ConsumerName
End Get
Set(value As String)
_ConsumerName = value
NotifyPropertyChanged("ConsumerName")
End Set
End Property
Public Property NominalConsumptionAmps As Double Implements IElectricalConsumer.NominalConsumptionAmps
Get
Return _NominalConsumptionAmps
End Get
Set(value As Double)
_NominalConsumptionAmps = value
NotifyPropertyChanged("NominalConsumptionAmps")
End Set
End Property
Public Property NumberInActualVehicle As Integer Implements IElectricalConsumer.NumberInActualVehicle
Get
Return _NumberInActualVehicle
End Get
Set(value As Integer)
_NumberInActualVehicle = value
NotifyPropertyChanged("NumberInActualVehicle")
End Set
End Property
Public Property PhaseIdle_TractionOn As Double Implements IElectricalConsumer.PhaseIdle_TractionOn
Get
Return _PhaseIdle_TractionOn
End Get
Set(value As Double)
_PhaseIdle_TractionOn = value
NotifyPropertyChanged("PhaseIdle_TractionOn")
End Set
End Property
Public Property PowerNetVoltage As Double Implements IElectricalConsumer.PowerNetVoltage
Get
Return _PowerNetVoltage
End Get
Set(value As Double)
_PowerNetVoltage = value
NotifyPropertyChanged("PowerNetVoltage")
End Set
End Property
Public Property Info As String Implements IElectricalConsumer.Info
Get
Return _Info
End Get
Set(value As String)
_Info = value
NotifyPropertyChanged("Info")
End Set
End Property
'Public class outputs
Public Function TotalAvgConumptionAmps(Optional PhaseIdle_TractionOnBasedOnCycle As Double = Nothing) As Ampere _
Implements IElectricalConsumer.TotalAvgConumptionAmps
If ConsumerName = "Doors per Door" Then
Return NominalConsumptionAmps.SI(Of Ampere)() * (NumberInActualVehicle * PhaseIdle_TractionOnBasedOnCycle)
Else
Return NominalConsumptionAmps.SI(Of Ampere)() * (NumberInActualVehicle * PhaseIdle_TractionOn)
End If
End Function
Public Function TotalAvgConsumptionInWatts(Optional PhaseIdle_TractionOnBasedOnCycle As Double = 0.0) As Watt _
Implements IElectricalConsumer.TotalAvgConsumptionInWatts
Return TotalAvgConumptionAmps(PhaseIdle_TractionOnBasedOnCycle) * PowerNetVoltage.SI(Of Volt)()
End Function
'Constructor
Public Sub New(BaseVehicle As Boolean, Category As String, ConsumerName As String, NominalConsumptionAmps As Double,
PhaseIdle_TractionOn As Double, PowerNetVoltage As Double, numberInVehicle As Integer, info As String)
'Illegal Value Check.
If Category.Trim.Length = 0 Then Throw New ArgumentException("Category Name cannot be empty")
If ConsumerName.Trim.Length = 0 Then Throw New ArgumentException("ConsumerName Name cannot be empty")
If _
PhaseIdle_TractionOn < ElectricConstants.PhaseIdleTractionOnMin Or
PhaseIdle_TractionOn > ElectricConstants.PhaseIdleTractionMax Then _
Throw New ArgumentException("PhaseIdle_TractionOn must have a value between 0 and 1")
If _
NominalConsumptionAmps < ElectricConstants.NonminalConsumerConsumptionAmpsMin Or
NominalConsumptionAmps > ElectricConstants.NominalConsumptionAmpsMax Then _
Throw New ArgumentException("NominalConsumptionAmps must have a value between 0 and 100")
If PowerNetVoltage < ElectricConstants.PowenetVoltageMin Or PowerNetVoltage > ElectricConstants.PowenetVoltageMax _
Then Throw New ArgumentException("PowerNetVoltage must have a value between 6 and 48")
If numberInVehicle < 0 Then Throw New ArgumentException("Cannot have less than 0 consumers in the vehicle")
'Good, now assign.
Me.BaseVehicle = BaseVehicle
Me.Category = Category
Me.ConsumerName = ConsumerName
Me.NominalConsumptionAmps = NominalConsumptionAmps
Me.PhaseIdle_TractionOn = PhaseIdle_TractionOn
Me.PowerNetVoltage = PowerNetVoltage
Me.NumberInActualVehicle = numberInVehicle
Me.Info = info
End Sub
'Comparison Overrides
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Nothing OrElse Not Me.GetType() Is obj.GetType() Then
Return False
End If
Dim other As IElectricalConsumer = CType(obj, IElectricalConsumer)
Return Me.ConsumerName = other.ConsumerName
End Function
<System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage>
Public Overrides Function GetHashCode() As Integer
Return 0
End Function
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(p As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(p))
End Sub
End Class
End Namespace
\ No newline at end of file
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Imports DownstreamModules.Electrics
Imports TUGraz.VectoCommon.Utils
Namespace Electrics
Public Class ElectricalConsumerList
Implements IElectricalConsumerList
Private _items As New List(Of IElectricalConsumer)
Private _powernetVoltage As Double
Private _doorDutyCycleZeroToOne As Double
'Constructor
Public Sub New(powernetVoltage As Double, doorDutyCycle_ZeroToOne As Double,
Optional createDefaultList As Boolean = False)
_powernetVoltage = powernetVoltage
If createDefaultList Then
_items = GetDefaultConsumerList()
End If
_doorDutyCycleZeroToOne = doorDutyCycle_ZeroToOne
End Sub
'Transfers the Info comments from a default set of consumables to a live set.
'This way makes the comments not dependent on saved data.
Public Sub MergeInfoData() Implements IElectricalConsumerList.MergeInfoData
If _items.Count <> GetDefaultConsumerList().Count Then Return
Dim dflt As List(Of IElectricalConsumer) = GetDefaultConsumerList()
For idx As Integer = 0 To _items.Count - 1
_items(idx).Info = dflt(idx).Info
Next
End Sub
'Initialise default set of consumers
Public Function GetDefaultConsumerList() As List(Of IElectricalConsumer)
'This populates the default settings as per engineering spreadsheet.
'Vehicle Basic Equipment' category can be added or remove by customers.
'At some time in the future, this may be removed and replace with file based consumer lists.
Dim items As New List(Of IElectricalConsumer)
Dim c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20 As IElectricalConsumer
c1 = CType(New ElectricalConsumer(False, "Doors", "Doors per Door", 3.0, 0.096339,
_powernetVoltage, 3, ""),
IElectricalConsumer)
c2 = CType(New ElectricalConsumer(True, "Veh Electronics &Engine", "Controllers,Valves etc",
25.0, 1.0,
_powernetVoltage, 1, ""),
IElectricalConsumer)
c3 = CType(New ElectricalConsumer(False, "Vehicle basic equipment", "Radio City", 2.0, 0.8,
_powernetVoltage, 1, ""),
IElectricalConsumer)
c4 = CType(New ElectricalConsumer(False, "Vehicle basic equipment", "Radio Intercity", 5.0,
0.8, _powernetVoltage,
0, ""),
IElectricalConsumer)
c5 = CType(New ElectricalConsumer(False, "Vehicle basic equipment", "Radio/Audio Tourism",
9.0, 0.8,
_powernetVoltage, 0, ""),
IElectricalConsumer)
c6 = CType(New ElectricalConsumer(False, "Vehicle basic equipment", "Fridge", 4.0, 0.5,
_powernetVoltage, 0, ""),
IElectricalConsumer)
c7 = CType(New ElectricalConsumer(False, "Vehicle basic equipment", "Kitchen Standard",
67.0, 0.05, _powernetVoltage,
0, ""),
IElectricalConsumer)
c8 = CType(New ElectricalConsumer(False, "Vehicle basic equipment",
"Interior lights City/ Intercity + Doorlights [Should be 1/m]", 1.0, 0.7,
_powernetVoltage, 12,
"1 Per metre length of bus"),
IElectricalConsumer)
c9 = CType(New ElectricalConsumer(False, "Vehicle basic equipment",
"LED Interior lights ceiling city/Intercity + door [Should be 1/m]", 0.6, 0.7,
_powernetVoltage, 0,
"1 Per metre length of bus"),
IElectricalConsumer)
c10 = CType(New ElectricalConsumer(False, "Vehicle basic equipment", "Interior lights Tourism + reading [1/m]",
1.1,
0.7, _powernetVoltage, 0, "1 Per metre length of bus"),
IElectricalConsumer)
c11 = CType(New ElectricalConsumer(False, "Vehicle basic equipment",
"LED Interior lights ceiling Tourism + LED reading [Should be 1/m]", 0.66, 0.7,
_powernetVoltage, 0,
"1 Per metre length of bus"),
IElectricalConsumer)
c12 = CType(New ElectricalConsumer(False, "Customer Specific Equipment", "External Displays Font/Side/Rear",
2.65017667844523, 1.0, _powernetVoltage, 4, ""),
IElectricalConsumer)
c13 = CType(New ElectricalConsumer(False, "Customer Specific Equipment",
"Internal display per unit ( front side rear)", 1.06007067137809, 1.0,
_powernetVoltage, 1, ""),
IElectricalConsumer)
c14 = CType(New ElectricalConsumer(False, "Customer Specific Equipment",
"CityBus Ref EBSF Table4 Devices ITS No Displays", 9.3, 1.0, _powernetVoltage, 1,
""),
IElectricalConsumer)
c15 = CType(New ElectricalConsumer(False, "Lights", "Exterior Lights BULB", 7.4, 1.0,
_powernetVoltage, 1, ""),
IElectricalConsumer)
c16 = CType(New ElectricalConsumer(False, "Lights", "Day running lights LED bonus",
-0.723, 1.0, _powernetVoltage,
1, ""),
IElectricalConsumer)
c17 = CType(New ElectricalConsumer(False, "Lights", "Antifog rear lights LED bonus",
-0.17, 1.0, _powernetVoltage,
1, ""),
IElectricalConsumer)
c18 = CType(New ElectricalConsumer(False, "Lights", "Position lights LED bonus", -1.2,
1.0, _powernetVoltage, 1,
""),
IElectricalConsumer)
c19 = CType(New ElectricalConsumer(False, "Lights", "Direction lights LED bonus", -0.3,
1.0, _powernetVoltage, 1,
""),
IElectricalConsumer)
c20 = CType(New ElectricalConsumer(False, "Lights", "Brake Lights LED bonus", -1.2, 1.0,
_powernetVoltage, 1, ""),
IElectricalConsumer)
items.Add(c1)
items.Add(c2)
items.Add(c3)
items.Add(c4)
items.Add(c5)
items.Add(c6)
items.Add(c7)
items.Add(c8)
items.Add(c9)
items.Add(c10)
items.Add(c11)
items.Add(c12)
items.Add(c13)
items.Add(c14)
items.Add(c15)
items.Add(c16)
items.Add(c17)
items.Add(c18)
items.Add(c19)
items.Add(c20)
Return items
End Function
'Interface implementation
Public Property DoorDutyCycleFraction As Double Implements IElectricalConsumerList.DoorDutyCycleFraction
Get
Return _doorDutyCycleZeroToOne
End Get
Set(value As Double)
_doorDutyCycleZeroToOne = value
End Set
End Property
Public ReadOnly Property Items As List(Of IElectricalConsumer) Implements IElectricalConsumerList.Items
Get
Return _items
End Get
End Property
Public Sub AddConsumer(consumer As IElectricalConsumer) Implements IElectricalConsumerList.AddConsumer
If Not _items.Contains(consumer) Then
_items.Add(consumer)
Else
Throw New ArgumentException("Consumer Already Present in the list")
End If
End Sub
Public Sub RemoveConsumer(consumer As IElectricalConsumer) Implements IElectricalConsumerList.RemoveConsumer
If _items.Contains(consumer) Then
_items.Remove(consumer)
Else
Throw New ArgumentException("Consumer Not In List")
End If
End Sub
Public Function GetTotalAverageDemandAmps(excludeOnBase As Boolean) As Ampere _
Implements IElectricalConsumerList.GetTotalAverageDemandAmps
Dim Amps As Ampere
If excludeOnBase Then
Amps =
Aggregate item In Items Where item.BaseVehicle = False Into Sum(item.TotalAvgConumptionAmps(DoorDutyCycleFraction))
Else
Amps = Aggregate item In Items Into Sum(item.TotalAvgConumptionAmps(DoorDutyCycleFraction))
End If
Return Amps
End Function
End Class
End Namespace
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Imports DownstreamModules.Electrics
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces.DownstreamModules.Electrics
Namespace Electrics
Public Class ElectricsUserInputsConfig
Implements IElectricsUserInputsConfig
Public Property PowerNetVoltage As Double Implements IElectricsUserInputsConfig.PowerNetVoltage
Public Property AlternatorMap As String Implements IElectricsUserInputsConfig.AlternatorMap
Public Property AlternatorGearEfficiency As Double Implements IElectricsUserInputsConfig.AlternatorGearEfficiency
Public Property ElectricalConsumers As IElectricalConsumerList _
Implements IElectricsUserInputsConfig.ElectricalConsumers
Public Property DoorActuationTimeSecond As Integer Implements IElectricsUserInputsConfig.DoorActuationTimeSecond
Public Property StoredEnergyEfficiency As Double Implements IElectricsUserInputsConfig.StoredEnergyEfficiency
Public Property ResultCardIdle As IResultCard Implements IElectricsUserInputsConfig.ResultCardIdle
Public Property ResultCardTraction As IResultCard Implements IElectricsUserInputsConfig.ResultCardTraction
Public Property ResultCardOverrun As IResultCard Implements IElectricsUserInputsConfig.ResultCardOverrun
Public Property SmartElectrical As Boolean Implements IElectricsUserInputsConfig.SmartElectrical
Public Sub New(Optional setToDefaults As Boolean = False, Optional vectoInputs As VectoInputs = Nothing)
If setToDefaults Then SetPropertiesToDefaults(vectoInputs)
End Sub
Public Sub SetPropertiesToDefaults(vectoInputs As VectoInputs)
DoorActuationTimeSecond = 4
StoredEnergyEfficiency = 0.935
AlternatorGearEfficiency = 0.92
PowerNetVoltage = vectoInputs.PowerNetVoltage.Value()
ResultCardIdle = New ResultCard(New List(Of SmartResult))
ResultCardOverrun = New ResultCard(New List(Of SmartResult))
ResultCardTraction = New ResultCard(New List(Of SmartResult))
SmartElectrical = False
AlternatorMap = String.Empty
End Sub
End Class
End Namespace
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Imports DownstreamModules.Electrics
Imports TUGraz.VectoCommon.Utils
Imports TUGraz.VectoCore.BusAuxiliaries.Interfaces.DownstreamModules.Electrics
Namespace Electrics
Public Class ResultCard
Implements IResultCard
Private _results As List(Of SmartResult)
'Constructor
Public Sub New(results As List(Of SmartResult))
If results Is Nothing Then Throw New ArgumentException("A list of smart results must be supplied.")
_results = results
End Sub
'Public class outputs
Public ReadOnly Property Results As List(Of SmartResult) Implements IResultCard.Results
Get
Return _results
End Get
End Property
Public Function GetSmartCurrentResult(ByVal Amps As Ampere) As Ampere Implements IResultCard.GetSmartCurrentResult
If _results.Count < 2 Then Return 10.SI(Of Ampere)()
Return GetOrInterpolate(Amps.Value()).SI(Of Ampere)()
End Function
'Helpers
''' <summary>
''' Gets or interpolates value (A)
''' </summary>
''' <param name="amps"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GetOrInterpolate(amps As Double) As Double
Dim pre As Double
Dim post As Double
Dim dAmps As Double
Dim dSmartAmps As Double
Dim smartAmpsSlope As Double
Dim smartAmps As Double
Dim maxKey As Double
Dim minKey As Double
maxKey = _results.Max.Amps
minKey = _results.Min.Amps
Dim compareKey As SmartResult = New SmartResult(amps, 0)
'Is on boundary check
If _results.Contains(compareKey) Then _
Return _results.OrderBy(Function(x) x.Amps).First(Function(x) x.Amps = compareKey.Amps).SmartAmps
'Is over map - Extrapolate
If amps > maxKey Then
'get the entries before and after the supplied key
pre = (From a In _results Order By a.Amps Where a.Amps < maxKey Select a).Last().Amps
post = maxKey
'get the delta values
dAmps = post - pre
dSmartAmps = (From da In _results Order By da.Amps Where da.Amps = post).First().SmartAmps -
(From da In _results Order By da.Amps Where da.Amps = pre).First().SmartAmps
'calculate the slopes
smartAmpsSlope = dSmartAmps / dAmps
'calculate the new values
smartAmps = ((amps - post) * smartAmpsSlope) +
(From da In _results Order By da.Amps Where da.Amps = post).First().SmartAmps
Return smartAmps
End If
'Is under map - Extrapolate
If amps < minKey Then
'get the entries before and after the supplied key
'Post is the first entry and pre is the penultimate to first entry
post = minKey
pre = (From k In _results Order By k.Amps Where k.Amps > minKey Select k).First().Amps
'get the delta values
dAmps = post - pre
dSmartAmps = (From da In _results Order By da.Amps Where da.Amps = post).First().SmartAmps -
(From da In _results Order By da.Amps Where da.Amps = pre).First().SmartAmps
'calculate the slopes
smartAmpsSlope = dSmartAmps / dAmps
'calculate the new values
smartAmps = ((amps - post) * smartAmpsSlope) +
(From da In _results Order By da.Amps Where da.Amps = post).First().SmartAmps
Return smartAmps
End If
'Is Inside map - Interpolate
'get the entries before and after the supplied rpm
pre = (From m In _results Order By m.Amps Where m.Amps < amps Select m).Last().Amps
post = (From m In _results Where m.Amps > amps Select m).First().Amps
'get the delta values for rpm and the map values
dAmps = post - pre
dSmartAmps = (From da In _results Order By da.Amps Where da.Amps = post).First().SmartAmps -
(From da In _results Order By da.Amps Where da.Amps = pre).First().SmartAmps
'calculate the slopes
smartAmpsSlope = dSmartAmps / dAmps
'calculate the new values
smartAmps = ((amps - post) * smartAmpsSlope) +
(From da In _results Order By da.Amps Where da.Amps = post).First().SmartAmps
Return smartAmps
End Function
End Class
End Namespace
Namespace Hvac
Public Class Bus
Implements IBus
'Private Property Backing
Private _id As Integer
Private _model As String
Private _floorType As String
Private _engineType As String
Private _lengthInMetres As Double
Private _widthInMetres As Double
Private _heightInMetres As Double
Private _registeredPassengers As Integer
Private _isDoubleDecker As Boolean
Public ReadOnly Property Id As Integer Implements IBus.Id
Get
Return _id
End Get
End Property
Public Property Model As String Implements IBus.Model
Get
Return _model
End Get
Set(value As String)
If Not ModelOK(value) Then Throw New ArgumentException("Model argument is invalid")
_model = value
End Set
End Property
Public Property FloorType As String Implements IBus.FloorType
Get
Return _floorType
End Get
Set(value As String)
If Not FloorTypeOK(value) Then Throw New ArgumentException("Model argument is invalid")
_floorType = value
End Set
End Property
Public Property EngineType As String Implements IBus.EngineType
Get
Return _engineType
End Get
Set(value As String)
If Not EngineOK(value) Then Throw New ArgumentException("EngineType argument is invalid")
_engineType = value
End Set
End Property
Public Property LengthInMetres As Double Implements IBus.LengthInMetres
Get
Return _lengthInMetres
End Get
Set(value As Double)
If Not DimensionOK(value) Then Throw New ArgumentException("Invalid Length")
_lengthInMetres = value
End Set
End Property
Public Property WidthInMetres As Double Implements IBus.WidthInMetres
Get
Return _widthInMetres
End Get
Set(value As Double)
If Not DimensionOK(value) Then Throw New ArgumentException("Invalid Width")
_widthInMetres = value
End Set
End Property
Public Property HeightInMetres As Double Implements IBus.HeightInMetres
Get
Return _heightInMetres
End Get
Set(value As Double)
If Not DimensionOK(value) Then Throw New ArgumentException("Invalid Height")
_heightInMetres = value
End Set
End Property
Public Property RegisteredPassengers As Integer Implements IBus.RegisteredPassengers
Get
Return _registeredPassengers
End Get
Set(value As Integer)
If Not PassengersOK(value) Then Throw New ArgumentException("Invalid Number Of Passengers")
_registeredPassengers = value
End Set
End Property
Public Property IsDoubleDecker As Boolean Implements IBus.IsDoubleDecker
Get
Return _isDoubleDecker
End Get
Set(ByVal value As Boolean)
_isDoubleDecker = value
End Set
End Property
'Constructors
Public Sub New(_id As Integer,
_model As String,
_floorType As String,
_engineType As String,
_lengthInMetres As Double,
_widthInMetres As Double,
_heightInMetres As Double,
_registeredPassengers As Integer,
_doubleDecker As Boolean)
'Validity checks.
If Not ModelOK(_model) Then Throw New ArgumentException("Model argument is invalid")
If Not FloorTypeOK(_floorType) Then Throw New ArgumentException("Model argument is invalid")
If Not EngineOK(_engineType) Then Throw New ArgumentException("EngineType argument is invalid")
If Not DimensionOK(_lengthInMetres) Then Throw New ArgumentException("Invalid Length")
If Not DimensionOK(_widthInMetres) Then Throw New ArgumentException("Invalid Width")
If Not DimensionOK(_heightInMetres) Then Throw New ArgumentException("Invalid Height")
If Not PassengersOK(_registeredPassengers) Then Throw New ArgumentException("Invalid Number Of Passengers")
'Set Private Members
Me._id = _id
Me._model = _model
Me._floorType = _floorType
Me._engineType = _engineType
Me._lengthInMetres = _lengthInMetres
Me._widthInMetres = _widthInMetres
Me._heightInMetres = _heightInMetres
Me._registeredPassengers = _registeredPassengers
Me._isDoubleDecker = _doubleDecker
End Sub
'Construction Validators Helpers
Private Function ModelOK(ByVal model As String) As Boolean
model = model.ToLower
If model Is Nothing OrElse model.Trim.Length = 0 Then Return False
Return True
End Function
Private Function FloorTypeOK(ByVal floorType As String) As Boolean
floorType = floorType.ToLower
If floorType Is Nothing OrElse floorType.Trim.Length = 0 Then Return False
If floorType <> "raised floor" AndAlso floorType <> "low floor" AndAlso floorType <> "semi low floor" Then _
Return False
Return True
End Function
Private Function EngineOK(ByVal engine As String) As Boolean
engine = engine.ToLower
If engine Is Nothing OrElse engine.Trim.Length = 0 Then Return False
If engine <> "diesel" AndAlso engine <> "gas" AndAlso engine <> "hybrid" Then Return False
Return True
End Function
Private Function DimensionOK(ByVal dimension As Double) As Boolean
Return dimension > 0.5
End Function
Private Function PassengersOK(ByVal registeredPassengers As Integer) As Boolean
Return registeredPassengers > 1
End Function
'To String function
Public Overrides Function ToString() As String
Return _
String.Format("{0},{1},{2},{3},{4},{5},{6},{7}", _model, _floorType, _engineType, _lengthInMetres, _widthInMetres,
_heightInMetres, _registeredPassengers, _isDoubleDecker)
End Function
End Class
End Namespace
Imports System.Globalization
Imports System.IO
Imports System.Text
Namespace Hvac
Public Class BusDatabase
Implements IBusDatabase
Private buses As New List(Of IBus)
Private selectListBuses As New List(Of IBus)
Public Function AddBus(bus As IBus) As Boolean Implements IBusDatabase.AddBus
Dim result As Boolean = True
Try
buses.Add(bus)
Catch ex As Exception
result = False
End Try
Return result
End Function
Public Function GetBuses(busModel As String, Optional AsSelectList As Boolean = False) As List(Of IBus) _
Implements IBusDatabase.GetBuses
If AsSelectList Then
selectListBuses = New List(Of IBus)
selectListBuses = buses.Where(Function(v) v.Model = "" OrElse v.Model.ToLower.Contains(busModel.ToLower)).ToList()
selectListBuses.Insert(0, New Bus(0, "<Select>", "low floor", "gas", 1, 1, 1, 2, False))
Return selectListBuses
Else
Return buses.Where(Function(v) v.Model = "" OrElse v.Model.ToLower.Contains(busModel.ToLower)).ToList()
End If
End Function
Public Function Initialise(filepath As String) As Boolean Implements IBusDatabase.Initialise
Dim returnStatus As Boolean = True
If File.Exists(filepath) Then
Using sr As StreamReader = New StreamReader(filepath)
'get array og lines fron csv
Dim lines() As String = sr.ReadToEnd().Split(CType(Environment.NewLine, Char()),
StringSplitOptions.RemoveEmptyEntries)
'Must have at least 2 entries in map to make it usable [dont forget the header row]
If (lines.Count() < 2) Then
Return False
End If
Dim firstline As Boolean = True
Dim id As Integer = 1
For Each line As String In lines
If Not firstline Then
'split the line
Dim elements() As String = line.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
'7 or 8 entries per line required
If (elements.Length <> 7 AndAlso elements.Length <> 8) Then
Throw New ArgumentException("Incorrect number of values in csv file")
End If
'Bus
Try
Dim bus As New Bus(id,
elements(0),
elements(1),
elements(2),
Double.Parse(elements(3), CultureInfo.InvariantCulture),
Double.Parse(elements(4), CultureInfo.InvariantCulture),
Double.Parse(elements(5), CultureInfo.InvariantCulture),
Integer.Parse(elements(6), CultureInfo.InvariantCulture),
If(elements.Length = 8, Boolean.Parse(elements(7)), False))
buses.Add(bus)
Catch ex As Exception
'Indicate problems
returnStatus = False
End Try
id = id + 1
Else
firstline = False
End If
Next line
End Using
Else
returnStatus = False
End If
Dim uniqueBuses As Integer = (From b In buses Select New With {Key b.Model, b} Distinct).Count()
If buses.Count <> uniqueBuses Then
returnStatus = False
End If
Return returnStatus
End Function
Public Function UpdateBus(id As Integer, bus As IBus) As Boolean Implements IBusDatabase.UpdateBus
Dim result As Boolean = True
Try
Dim existingBus As IBus = buses.Single(Function(b) b.Id = id)
existingBus.Model = bus.Model
existingBus.RegisteredPassengers = bus.RegisteredPassengers
existingBus.FloorType = bus.FloorType
existingBus.LengthInMetres = bus.LengthInMetres
existingBus.WidthInMetres = bus.WidthInMetres
existingBus.HeightInMetres = bus.HeightInMetres
existingBus.IsDoubleDecker = bus.IsDoubleDecker
Catch ex As Exception
result = False
End Try
Return result
End Function
Public Function Save(filepath As String) As Boolean Implements IBusDatabase.Save
Dim result As Boolean = True
Dim output As New StringBuilder
Try
output.AppendLine("Bus Model,Type,engine Type,length in m,wide in m,height in m,registered passengers,double decker")
For Each bus As IBus In buses
output.AppendLine(bus.ToString())
Next
File.WriteAllText(filepath, output.ToString())
Catch ex As Exception
result = False
End Try
Return result
End Function
End Class
End Namespace
Namespace Hvac
Public Enum BusEngineType
Diesal = 1
Gas = 2
Hybrid = 3
End Enum
End Namespace
Imports System.Windows.Forms
Imports System.Drawing
Public Class DeleteCell
Inherits DataGridViewButtonCell
Public Property ToolTip As String = "Delete tech benefit line"
Private del As Image = TryCast(My.Resources.ResourceManager.GetObject("Delete"), Image)
Protected Overrides Sub Paint(graphics As Graphics, clipBounds As Rectangle, cellBounds As Rectangle,
rowIndex As Integer, elementState As DataGridViewElementStates, value As Object, formattedValue As Object,
errorText As String, cellStyle As DataGridViewCellStyle, advancedBorderStyle As DataGridViewAdvancedBorderStyle,
paintParts As DataGridViewPaintParts)
advancedBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single
Me.ToolTipText = ToolTip
cellStyle.BackColor = Color.White
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts)
graphics.DrawImage(del, cellBounds)
End Sub
End Class
Public Class DeleteAlternatorCell
Inherits DataGridViewButtonCell
Public Property ToolTip As String = "Delete alternator"
Private del As Image = TryCast(My.Resources.ResourceManager.GetObject("Delete"), Image)
Protected Overrides Sub Paint(graphics As Graphics, clipBounds As Rectangle, cellBounds As Rectangle,
rowIndex As Integer, elementState As DataGridViewElementStates, value As Object, formattedValue As Object,
errorText As String, cellStyle As DataGridViewCellStyle, advancedBorderStyle As DataGridViewAdvancedBorderStyle,
paintParts As DataGridViewPaintParts)
advancedBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single
Me.ToolTipText = ToolTip
cellStyle.BackColor = Color.White
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts)
graphics.DrawImage(del, cellBounds)
End Sub
End Class
\ No newline at end of file
Imports System.Windows.Forms
Public Class DeleteColumn
Inherits DataGridViewButtonColumn
Public Sub new()
MyBase.New()
Me.CellTemplate = New DeleteCell()
End Sub
End Class
Public Class DeleteAlternatorColumn
Inherits DataGridViewButtonColumn
Public Sub new()
MyBase.New()
Me.CellTemplate = New DeleteAlternatorCell()
End Sub
End Class
\ No newline at end of file
Imports DownstreamModules.HVAC
Namespace Hvac
Public Class EnvironmentalCondition
Implements IEnvironmentalCondition
Private _temperature As Double
Private _solar As Double
Private _weight As Double
Public Sub New(temperature As Double, solar As Double, weight As Double)
_temperature = temperature
_solar = solar
_weight = weight
End Sub
Public Function GetTemperature() As Double Implements IEnvironmentalCondition.GetTemperature
Return _temperature
End Function
Public Function GetSolar() As Double Implements IEnvironmentalCondition.GetSolar
Return _solar
End Function
Public Function GetWeight() As Double Implements IEnvironmentalCondition.GetWeighting
Return _weight
End Function
Public Function GetNormalisedWeight(map As List(Of IEnvironmentalCondition)) As Double _
Implements IEnvironmentalCondition.GetNormalisedWeighting
Return _weight/map.Sum(Function(w) w.GetWeighting())
End Function
End Class
End Namespace
\ No newline at end of file
Imports System.Globalization
Imports System.IO
Imports DownstreamModules.HVAC
Namespace Hvac
Public Class EnvironmentalConditionsMap
Implements IEnvironmentalConditionsMap
Private filePath As String
Private vectoDirectory As String
Private _map As New List(Of IEnvironmentalCondition)
Public Sub New(filepath As String, vectoDirectory As String)
Me.filePath = filepath
Me.vectoDirectory = vectoDirectory
Initialise()
End Sub
Public Function Initialise() As Boolean Implements IEnvironmentalConditionsMap.Initialise
If (Not String.IsNullOrWhiteSpace(filePath)) Then
filePath = FilePathUtils.ResolveFilePath(vectoDirectory, filePath)
If File.Exists(filePath) Then
Using sr As StreamReader = New StreamReader(filePath)
'get array og lines fron csv
Dim lines() As String = sr.ReadToEnd().Split(CType(Environment.NewLine, Char()),
StringSplitOptions.RemoveEmptyEntries)
'Must have at least 1 entries to make it usable [dont forget the header row]
If (lines.Count() < 2) Then
Return False
End If
Dim firstline As Boolean = True
For Each line As String In lines
If Not firstline Then
'split the line
Dim elements() As String = line.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
'3 entries per line required
If (elements.Length <> 4) Then
Return False
End If
'Add environment condition
Dim newCondition As EnvironmentalCondition = New EnvironmentalCondition(
Double.Parse(elements(1), CultureInfo.InvariantCulture),
Double.Parse(elements(2), CultureInfo.InvariantCulture),
Double.Parse(elements(3), CultureInfo.InvariantCulture))
_map.Add(newCondition)
Else
firstline = False
End If
Next line
End Using
Else
Return False
End If
End If
Return True
End Function
Public Function GetEnvironmentalConditions() As List(Of IEnvironmentalCondition) _
Implements IEnvironmentalConditionsMap.GetEnvironmentalConditions
Return _map
End Function
End Class
End Namespace
' Copyright 2017 European Union.
' Licensed under the EUPL (the 'Licence');
'
' * You may not use this work except in compliance with the Licence.
' * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
' * Unless required by applicable law or agreed to in writing,
' software distributed under the Licence is distributed on an "AS IS" basis,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'
' See the LICENSE.txt for the specific language governing permissions and limitations.
Imports DownstreamModules.HVAC
Imports Newtonsoft.Json
Imports TUGraz.VectoCommon.Utils
Namespace Hvac
Public Class HVACConstants
Implements IHVACConstants
<JsonProperty("FuelDensity")> ReadOnly _fuelDensity As Double
<JsonProperty("DieselGCVJperGram")> ReadOnly _dieselGcvJperGram As Double = 44800
Public Sub New()
_fuelDensity = 835 '.SI(Of KilogramPerCubicMeter)()
End Sub
Public Sub New(fuelDensitySingle As KilogramPerCubicMeter)
_fuelDensity = fuelDensitySingle.Value()
End Sub
<JsonIgnore>
Public ReadOnly Property DieselGCVJperGram As JoulePerKilogramm Implements IHVACConstants.DieselGCVJperGram
Get
Return _dieselGcvJperGram.SI(Unit.SI.Joule.Per.Gramm).Cast(Of JoulePerKilogramm)()
End Get
End Property
<JsonIgnore()>
Public ReadOnly Property FuelDensity As KilogramPerCubicMeter Implements IHVACConstants.FuelDensity
Get
Return _fuelDensity.SI(Of KilogramPerCubicMeter)()
End Get
End Property
<JsonIgnore()>
Public ReadOnly Property FuelDensityAsGramPerLiter As Double Implements IHVACConstants.FuelDensityAsGramPerLiter
Get
Return _fuelDensity * 1000
End Get
End Property
End Class
End Namespace
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment