├── .gitignore ├── AUTHORS ├── res └── dbm.ico ├── img ├── aveva.png ├── dbmlogo.png ├── sample1.png ├── sample2.png ├── sample3a.png ├── sample3b.png ├── sample4a.png ├── sample4b.png ├── vitens.png └── augmented.png ├── CONTRIBUTORS ├── jobs ├── test.ps1 ├── build.ps1 └── deploy.ps1 ├── .github └── workflows │ └── build.yml ├── .gitlab-ci.yml ├── register.bat ├── sign.bat ├── src ├── dbm │ ├── DBMManifest.vb │ ├── DBMLoggerConsole.vb │ ├── DBMCorrelationPoint.vb │ ├── DBMTimeSeries.vb │ ├── DBMStrings.vb │ ├── DBMForecastItem.vb │ ├── driver │ │ ├── DBMPointDriverAVEVAPIAF.vb │ │ └── DBMPointDriverCSV.vb │ ├── DBMDataStore.vb │ ├── DBMForecast.vb │ ├── DBMAssert.vb │ ├── DBMParameters.vb │ ├── DBMLoggerAbstract.vb │ ├── DBMResult.vb │ ├── DBMInfo.vb │ ├── DBMDate.vb │ ├── DBMPoint.vb │ ├── DBMPointDriverAbstract.vb │ ├── DBMStatisticsItem.vb │ ├── DBMStatistics.vb │ ├── DBM.vb │ └── DBMMath.vb ├── DBMDataRef │ ├── DBMLoggerAFTrace.vb │ └── DBMEventSource.vb └── dbmtester │ └── DBMTester.vb ├── CODE_OF_CONDUCT.md ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | J.H. Fitié, Vitens N.V. 2 | -------------------------------------------------------------------------------- /res/dbm.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/res/dbm.ico -------------------------------------------------------------------------------- /img/aveva.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/aveva.png -------------------------------------------------------------------------------- /img/dbmlogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/dbmlogo.png -------------------------------------------------------------------------------- /img/sample1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/sample1.png -------------------------------------------------------------------------------- /img/sample2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/sample2.png -------------------------------------------------------------------------------- /img/sample3a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/sample3a.png -------------------------------------------------------------------------------- /img/sample3b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/sample3b.png -------------------------------------------------------------------------------- /img/sample4a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/sample4a.png -------------------------------------------------------------------------------- /img/sample4b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/sample4b.png -------------------------------------------------------------------------------- /img/vitens.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/vitens.png -------------------------------------------------------------------------------- /img/augmented.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/DBM/HEAD/img/augmented.png -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | E.A. Trietsch, Vitens N.V. 2 | VORtech B.V. 3 | -------------------------------------------------------------------------------- /jobs/test.ps1: -------------------------------------------------------------------------------- 1 | # Dynamic Bandwidth Monitor 2 | # Leak detection method implemented in a real-time data historian 3 | # Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | # 5 | # This file is part of DBM. 6 | # 7 | # DBM is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # DBM is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with DBM. If not, see . 19 | 20 | & "$PSScriptRoot\sign.ps1" 21 | 22 | $ErrorActionPreference = 'Stop' 23 | Add-Type -Path build\DBM.dll 24 | [Vitens.DynamicBandwidthMonitor.DBMInfo]::TestResults($true) 25 | -------------------------------------------------------------------------------- /jobs/build.ps1: -------------------------------------------------------------------------------- 1 | # Dynamic Bandwidth Monitor 2 | # Leak detection method implemented in a real-time data historian 3 | # Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | # 5 | # This file is part of DBM. 6 | # 7 | # DBM is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # DBM is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with DBM. If not, see . 19 | 20 | (Get-Content src\dbm\DBMInfo.vb) -replace 'Const GITHASH As String = ".*?"', ('Const GITHASH As String = "' + $Env:CI_COMMIT_SHA.SubString(0, 8) + '"') | Set-Content src\dbm\DBMInfo.vb 21 | .\build.bat 22 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # Dynamic Bandwidth Monitor 2 | # Leak detection method implemented in a real-time data historian 3 | # Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | # 5 | # This file is part of DBM. 6 | # 7 | # DBM is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # DBM is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with DBM. If not, see . 19 | 20 | on: push 21 | jobs: 22 | build: 23 | runs-on: windows-latest 24 | steps: 25 | - uses: actions/checkout@v2 26 | - name: build 27 | run: .\build.bat 28 | - name: test 29 | run: | 30 | Add-Type -Path build\DBM.dll 31 | [Vitens.DynamicBandwidthMonitor.DBMInfo]::TestResults() 32 | -------------------------------------------------------------------------------- /jobs/deploy.ps1: -------------------------------------------------------------------------------- 1 | # Dynamic Bandwidth Monitor 2 | # Leak detection method implemented in a real-time data historian 3 | # Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | # 5 | # This file is part of DBM. 6 | # 7 | # DBM is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # DBM is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with DBM. If not, see . 19 | 20 | & "$PSScriptRoot\test.ps1" 21 | 22 | $DeployProduction = $Env:CI_COMMIT_REF_NAME -eq $Env:CI_DEFAULT_BRANCH 23 | $DeployAcceptance = $DeployProduction -Or $Env:CI_COMMIT_REF_NAME -eq 'staging' 24 | $DeployTesting = $true 25 | 26 | if ($DeployTesting) {.\register.bat piaf-t} 27 | if ($DeployAcceptance) {.\register.bat piaf-a} 28 | if ($DeployProduction) {.\register.bat piaf} 29 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | # Dynamic Bandwidth Monitor 2 | # Leak detection method implemented in a real-time data historian 3 | # Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | # 5 | # This file is part of DBM. 6 | # 7 | # DBM is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # DBM is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU General Public License 18 | # along with DBM. If not, see . 19 | 20 | default: 21 | tags: 22 | - windows 23 | 24 | stages: 25 | - build 26 | - sign 27 | - test 28 | - deploy 29 | 30 | build: 31 | stage: build 32 | script: 33 | - jobs\build.ps1 34 | 35 | sign: 36 | stage: sign 37 | script: 38 | - jobs\sign.ps1 39 | 40 | test: 41 | stage: test 42 | script: 43 | - jobs\test.ps1 44 | 45 | deploy: 46 | stage: deploy 47 | script: 48 | - jobs\deploy.ps1 49 | -------------------------------------------------------------------------------- /register.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | rem Dynamic Bandwidth Monitor 4 | rem Leak detection method implemented in a real-time data historian 5 | rem Copyright (C) 2014-2021 J.H. Fitié, Vitens N.V. 6 | rem 7 | rem This file is part of DBM. 8 | rem 9 | rem DBM is free software: you can redistribute it and/or modify 10 | rem it under the terms of the GNU General Public License as published by 11 | rem the Free Software Foundation, either version 3 of the License, or 12 | rem (at your option) any later version. 13 | rem 14 | rem DBM is distributed in the hope that it will be useful, 15 | rem but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | rem MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | rem GNU General Public License for more details. 18 | rem 19 | rem You should have received a copy of the GNU General Public License 20 | rem along with DBM. If not, see . 21 | 22 | cd /d %~dp0 23 | 24 | rem Variables 25 | if not "%1" == "" set PIAFServer=/PISystem:%1 26 | 27 | rem Register PI AF Data Reference on AF server 28 | cd build 29 | "%PIHOME%\AF\regplugin.exe" %PIAFServer% /Unregister DBMDataRef.dll 30 | "%PIHOME%\AF\regplugin.exe" %PIAFServer% DBMDataRef.dll 31 | "%PIHOME%\AF\regplugin.exe" %PIAFServer% /Owner:DBMDataRef.dll * /Exclude:DBMDataRef.dll 32 | cd .. 33 | -------------------------------------------------------------------------------- /sign.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | rem Dynamic Bandwidth Monitor 4 | rem Leak detection method implemented in a real-time data historian 5 | rem Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 6 | rem 7 | rem This file is part of DBM. 8 | rem 9 | rem DBM is free software: you can redistribute it and/or modify 10 | rem it under the terms of the GNU General Public License as published by 11 | rem the Free Software Foundation, either version 3 of the License, or 12 | rem (at your option) any later version. 13 | rem 14 | rem DBM is distributed in the hope that it will be useful, 15 | rem but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | rem MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | rem GNU General Public License for more details. 18 | rem 19 | rem You should have received a copy of the GNU General Public License 20 | rem along with DBM. If not, see . 21 | 22 | cd /d %~dp0 23 | 24 | rem Sign 25 | rem arguments: pfx file, password(, file) 26 | set Files=%3 27 | if "%~3" == "" set Files=build\*.dll build\*.exe 28 | for %%f in (%Files%) do powershell -Command "Set-AuthenticodeSignature -Certificate (New-Object System.Security.Cryptography.X509Certificates.X509Certificate2('%1', '%2')) -TimestampServer http://timestamp.digicert.com -HashAlgorithm SHA256 -FilePath '%%~f'" 29 | -------------------------------------------------------------------------------- /src/dbm/DBMManifest.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2024 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | ' This information is shared between all DBM binaries. A summary can be 22 | ' returned using the DBM.Version function. 23 | 24 | 25 | 26 | 27 | 28 | 29 | 31 | 32 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/dbm/DBMLoggerConsole.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | 23 | 24 | Namespace Vitens.DynamicBandwidthMonitor 25 | 26 | 27 | Public Class DBMLoggerConsole 28 | Inherits DBMLoggerAbstract 29 | 30 | 31 | Public Overrides Sub Log(level As Level, message As String) 32 | 33 | Select Case level 34 | Case Level.Error 35 | Console.ForegroundColor = ConsoleColor.Red 36 | Case Level.Warning 37 | Console.ForegroundColor = ConsoleColor.Yellow 38 | Case Level.Information 39 | Console.ForegroundColor = ConsoleColor.White 40 | Case Level.Debug 41 | Console.ForegroundColor = ConsoleColor.Cyan 42 | Case Level.Trace 43 | Console.ForegroundColor = ConsoleColor.DarkGray 44 | End Select 45 | Console.WriteLine(message) 46 | Console.ResetColor 47 | 48 | End Sub 49 | 50 | 51 | End Class 52 | 53 | 54 | End Namespace 55 | -------------------------------------------------------------------------------- /src/DBMDataRef/DBMLoggerAFTrace.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports OSIsoft.AF.Diagnostics 23 | 24 | 25 | Namespace Vitens.DynamicBandwidthMonitor 26 | 27 | 28 | Public Class DBMLoggerAFTrace 29 | Inherits DBMLoggerAbstract 30 | 31 | 32 | Public Overrides Sub Log(level As Level, message As String) 33 | 34 | Select Case level 35 | Case Level.Error 36 | If AFTrace.IsTraced(AFTraceSwitchLevel.Error) Then 37 | AFTrace.TraceError(message) 38 | End If 39 | Case Level.Warning 40 | If AFTrace.IsTraced(AFTraceSwitchLevel.Warning) Then 41 | AFTrace.TraceWarning(message) 42 | End If 43 | Case Level.Information 44 | If AFTrace.IsTraced(AFTraceSwitchLevel.Information) Then 45 | AFTrace.TraceInformation(message) 46 | End If 47 | Case Level.Debug 48 | If AFTrace.IsTraced(AFTraceSwitchLevel.Detail) Then 49 | AFTrace.TraceDetail(message) 50 | End If 51 | Case Level.Trace 52 | If AFTrace.IsTraced(AFTraceSwitchLevel.Data) Then 53 | AFTrace.TraceData(message) 54 | End If 55 | End Select 56 | 57 | End Sub 58 | 59 | 60 | End Class 61 | 62 | 63 | End Namespace 64 | -------------------------------------------------------------------------------- /src/dbm/DBMCorrelationPoint.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Namespace Vitens.DynamicBandwidthMonitor 22 | 23 | 24 | Public Class DBMCorrelationPoint 25 | 26 | 27 | ' Contains a DBMPointDriverAbstract object and a boolean SubtractSelf which 28 | ' can be set to true when the input tag has to be subtracted from the 29 | ' correlation tag, for example when the correlation tag contains the input 30 | ' tag. Set to false for adjacent areas. 31 | 32 | 33 | Private _pointDriver As DBMPointDriverAbstract 34 | Private _subtractSelf As Boolean ' True if input needs to be subtracted 35 | 36 | 37 | Public Property PointDriver As DBMPointDriverAbstract 38 | Get 39 | Return _pointDriver 40 | End Get 41 | Set(value As DBMPointDriverAbstract) 42 | _pointDriver = value 43 | End Set 44 | End Property 45 | 46 | 47 | Public Property SubtractSelf As Boolean 48 | Get 49 | Return _subtractSelf 50 | End Get 51 | Set(value As Boolean) 52 | _subtractSelf = value 53 | End Set 54 | End Property 55 | 56 | 57 | Public Sub New(pointDriver As DBMPointDriverAbstract, 58 | subtractSelf As Boolean) 59 | 60 | Me.pointDriver = pointDriver 61 | Me.subtractSelf = subtractSelf 62 | 63 | End Sub 64 | 65 | 66 | End Class 67 | 68 | 69 | End Namespace 70 | -------------------------------------------------------------------------------- /src/dbm/DBMTimeSeries.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Double 23 | Imports Vitens.DynamicBandwidthMonitor.DBMMath 24 | 25 | 26 | Namespace Vitens.DynamicBandwidthMonitor 27 | 28 | 29 | Public Class DBMTimeSeries 30 | 31 | 32 | ' Contains time series functions. 33 | 34 | 35 | Public Shared Function TimeWeightedValue(value As Double, 36 | nextValue As Double, timestamp As DateTime, nextTimestamp As DateTime, 37 | Optional stepped As Boolean = True) As Double 38 | 39 | TimeWeightedValue = value 40 | 41 | ' When not stepped, using interpolation, the value to be used for the 42 | ' interval is the average value of the current value and the next value. 43 | If Not stepped Then 44 | TimeWeightedValue += nextValue 45 | TimeWeightedValue /= 2 46 | End If 47 | 48 | TimeWeightedValue *= nextTimestamp.Subtract(timestamp).TotalDays 49 | 50 | Return TimeWeightedValue 51 | 52 | End Function 53 | 54 | 55 | Public Shared Function LinearInterpolation(timestamp As DateTime, 56 | startTimestamp As DateTime, startValue As Double, 57 | endTimestamp As DateTime, endValue As Double, 58 | Optional stepped As Boolean = True) As Double 59 | 60 | If stepped Then 61 | Return startValue 62 | Else 63 | Return Lerp(startValue, endValue, 64 | (timestamp.Ticks-startTimestamp.Ticks)/ 65 | (endTimestamp.Ticks-startTimestamp.Ticks)) 66 | End If 67 | 68 | End Function 69 | 70 | 71 | End Class 72 | 73 | 74 | End Namespace 75 | -------------------------------------------------------------------------------- /src/dbm/DBMStrings.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | 23 | 24 | Namespace Vitens.DynamicBandwidthMonitor 25 | 26 | 27 | Public Class DBMStrings 28 | 29 | 30 | Public Const UnsignedAssembly As String = "Unsigned assembly" 31 | Public Const TimestampText As String = "Timestamp" 32 | Public Const FactorText As String = "Factor" 33 | Public Const MeasurementText As String = "Measurement" 34 | Public Const ForecastText As String = "Forecast" 35 | Public Const LowerControlLimitText As String = "Lower control limit" 36 | Public Const UpperControlLimitText As String = "Upper control limit" 37 | Public Const DecimalFormat As String = "G5" 38 | Public Const PercentageFormat As String = "0.0%" 39 | Public Const CSVComment As String = "# " 40 | Public Const StatisticsInsufficientData As String = 41 | "Insufficient data for calculating model calibration metrics" 42 | Public Const StatisticsBrief As String = 43 | "Calibrated: {0} (" & 44 | "n {1}; " & 45 | "Systematic error {2:" & PercentageFormat & "}; " & 46 | "Random error {3:" & PercentageFormat & "}; " & 47 | "Fit {4:" & PercentageFormat & "})" 48 | Public Const QualityTests As String = 49 | "n {0}; C {1:" & PercentageFormat & "}; " & 50 | "SE {2:" & PercentageFormat & "} (SD={3:" & PercentageFormat & "}); " & 51 | "RE {4:" & PercentageFormat & "} (SD={5:" & PercentageFormat & "}); " & 52 | "F {6:" & PercentageFormat & "} (SD={7:" & PercentageFormat & "}); " & 53 | "Score {8:" & PercentageFormat & "}" 54 | Public Const ForecastFactorAnnotation As String = 55 | FactorText & " {0:" & DecimalFormat & "}" 56 | 57 | 58 | End Class 59 | 60 | 61 | End Namespace 62 | -------------------------------------------------------------------------------- /src/dbm/DBMForecastItem.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports Vitens.DynamicBandwidthMonitor.DBMMath 23 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 24 | 25 | 26 | Namespace Vitens.DynamicBandwidthMonitor 27 | 28 | 29 | Public Class DBMForecastItem 30 | 31 | 32 | Private _measurement, _forecast, _lowerControlLimit, 33 | _upperControlLimit As Double 34 | 35 | 36 | Public Property Measurement As Double 37 | Get 38 | Return _measurement 39 | End Get 40 | Set(value As Double) 41 | _measurement = value 42 | End Set 43 | End Property 44 | 45 | 46 | Public Property Forecast As Double 47 | Get 48 | Return _forecast 49 | End Get 50 | Set(value As Double) 51 | _forecast = value 52 | End Set 53 | End Property 54 | 55 | 56 | Public Property LowerControlLimit As Double 57 | Get 58 | Return _lowerControlLimit 59 | End Get 60 | Set(value As Double) 61 | _lowerControlLimit = value 62 | End Set 63 | End Property 64 | 65 | 66 | Public Property UpperControlLimit As Double 67 | Get 68 | Return _upperControlLimit 69 | End Get 70 | Set(value As Double) 71 | _upperControlLimit = value 72 | End Set 73 | End Property 74 | 75 | 76 | Public Function Range(p As Double) As Double 77 | 78 | ' Returns the range between the control limits and forecast value scaled 79 | ' for the requested confidence interval. This function requires that the 80 | ' results have been calculated for the default range using the Forecast 81 | ' function before. Always use the full sample size and appropriate 82 | ' distribution as the calculation is run on an EMA-smoothed series of data 83 | ' and not on a single forecast result from which outliers might be 84 | ' removed. 85 | 86 | Return (Me.UpperControlLimit-Me.Forecast)/ 87 | ControlLimitRejectionCriterion(2*BandwidthCI-1, ComparePatterns-1)* 88 | ControlLimitRejectionCriterion(2*p-1, ComparePatterns-1) 89 | 90 | End Function 91 | 92 | 93 | End Class 94 | 95 | 96 | End Namespace 97 | -------------------------------------------------------------------------------- /src/dbm/driver/DBMPointDriverAVEVAPIAF.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports OSIsoft.AF.Asset 23 | Imports OSIsoft.AF.Time 24 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 25 | 26 | 27 | ' Assembly title 28 | 29 | 30 | 31 | Namespace Vitens.DynamicBandwidthMonitor 32 | 33 | 34 | Public Class DBMPointDriver 35 | Inherits DBMPointDriverAbstract 36 | 37 | 38 | ' Description: Driver for AVEVA PI Asset Framework. 39 | ' Identifier (Point): OSIsoft.AF.Asset.AFAttribute (PI AF attribute) 40 | 41 | 42 | Public Sub New(point As Object) 43 | 44 | MyBase.New(point) 45 | 46 | End Sub 47 | 48 | 49 | Public Overrides Function ToString As String 50 | 51 | Return "AVEVA PI AF driver " & DirectCast(Point, AFAttribute).GetPath 52 | 53 | End Function 54 | 55 | 56 | Public Overrides Function SnapshotTimestamp As DateTime 57 | 58 | ' Returns the snapshot timestamp from AVEVA PI AF. 59 | 60 | Return DirectCast(Point, AFAttribute).GetValue.Timestamp.LocalTime 61 | 62 | End Function 63 | 64 | 65 | Public Overrides Sub PrepareData(startTimestamp As DateTime, 66 | endTimestamp As DateTime) 67 | 68 | ' Retrieves a value for each interval in the time range from AVEVA PI AF 69 | ' and stores this in memory. The (aligned) end time itself is excluded. 70 | 71 | Dim values As AFValues 72 | Dim value As AFValue 73 | 74 | DBM.Logger.LogDebug( 75 | "startTimestamp " & startTimestamp.ToString("s") & "; " & 76 | "endTimestamp " & endTimestamp.ToString("s"), Me.ToString) 77 | 78 | values = DirectCast(Point, AFAttribute).Data.InterpolatedValues( 79 | New AFTimeRange(New AFTime(startTimestamp), 80 | New AFTime(endTimestamp.AddSeconds(-CalculationInterval))), 81 | New AFTimeSpan(0, 0, 0, 0, 0, CalculationInterval, 0), 82 | Nothing, Nothing, True) ' Get interpolated values for time range. 83 | 84 | DBM.Logger.LogTrace( 85 | "Retrieved " & values.Count.ToString & " values", Me.ToString) 86 | 87 | For Each value In values 88 | DataStore.AddData(value.Timestamp.LocalTime, value.Value) 89 | Next 90 | 91 | End Sub 92 | 93 | 94 | End Class 95 | 96 | 97 | End Namespace 98 | -------------------------------------------------------------------------------- /src/dbm/driver/DBMPointDriverCSV.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.IO 23 | 24 | 25 | ' Assembly title 26 | 27 | 28 | 29 | Namespace Vitens.DynamicBandwidthMonitor 30 | 31 | 32 | Public Class DBMPointDriver 33 | Inherits DBMPointDriverAbstract 34 | 35 | 36 | ' Description: Driver for CSV files (timestamp,value). 37 | ' Identifier (Point): String (CSV filename) 38 | ' Remarks: Data interval must be the same as the CalculationInterval 39 | ' parameter. 40 | 41 | 42 | Private _splitChars As Char() = {","c, " "c} ' Comma and tab 43 | 44 | 45 | Public Sub New(point As Object) 46 | 47 | MyBase.New(point) 48 | 49 | End Sub 50 | 51 | 52 | Public Overrides Function ToString As String 53 | 54 | Return "CSV driver " & DirectCast(Point, String) 55 | 56 | End Function 57 | 58 | 59 | Public Overrides Sub PrepareData(startTimestamp As DateTime, 60 | endTimestamp As DateTime) 61 | 62 | ' Retrieves information from a CSV file and stores this in memory. Passed 63 | ' timestamps are ignored and all data in the CSV is loaded into memory. 64 | 65 | Dim substrings() As String 66 | Dim timestamp As DateTime 67 | Dim value As Double 68 | 69 | If File.Exists(DirectCast(Point, String)) Then 70 | Using StreamReader As New StreamReader(DirectCast(Point, String)) 71 | Do While Not StreamReader.EndOfStream 72 | ' Comma and tab delimiters; split timestamp and value 73 | substrings = StreamReader.ReadLine.Split(_splitChars, 2) 74 | If substrings.Length = 2 AndAlso 75 | DateTime.TryParse(substrings(0), timestamp) AndAlso 76 | timestamp >= startTimestamp And timestamp < endTimestamp And 77 | Double.TryParse(substrings(1), value) Then 78 | DataStore.AddData(timestamp, value) 79 | End If 80 | Loop 81 | End Using ' Close CSV file 82 | Else 83 | ' If Point does not represent a valid, existing file then throw a 84 | ' File Not Found Exception. 85 | Throw New FileNotFoundException(DirectCast(Point, String)) 86 | End If 87 | 88 | End Sub 89 | 90 | 91 | End Class 92 | 93 | 94 | End Namespace 95 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at johan.fitie@vitens.nl. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /src/dbm/DBMDataStore.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Collections.Generic 23 | Imports System.Double 24 | Imports System.Threading 25 | 26 | 27 | Namespace Vitens.DynamicBandwidthMonitor 28 | 29 | 30 | Public Class DBMDataStore 31 | 32 | 33 | Private _lock As New Object ' Object for exclusive lock on critical section. 34 | Private _dataStore As New Dictionary(Of DateTime, Double) ' In-memory data 35 | 36 | 37 | Public Sub AddData(timestamp As DateTime, data As Object) 38 | 39 | ' Make sure that the retrieved data type is a Double and also that the 40 | ' timestamp is not already stored in memory (could happen because of DST 41 | ' time overlap). 42 | 43 | If TypeOf data Is Double Then 44 | 45 | Monitor.Enter(_lock) ' Block 46 | Try 47 | 48 | If Not _dataStore.ContainsKey(timestamp) Then 49 | _dataStore.Add(timestamp, DirectCast(data, Double)) 50 | End If 51 | 52 | Finally 53 | Monitor.Exit(_lock) ' Unblock 54 | End Try 55 | 56 | End If 57 | 58 | End Sub 59 | 60 | 61 | Public Sub RemoveData(timestamp As DateTime) 62 | 63 | Monitor.Enter(_lock) ' Block 64 | Try 65 | 66 | _dataStore.Remove(timestamp) 67 | 68 | Finally 69 | Monitor.Exit(_lock) ' Unblock 70 | End Try 71 | 72 | End Sub 73 | 74 | 75 | Public Sub ClearData 76 | 77 | Monitor.Enter(_lock) ' Block 78 | Try 79 | 80 | _dataStore.Clear ' Clear all 81 | 82 | Finally 83 | Monitor.Exit(_lock) ' Unblock 84 | End Try 85 | 86 | End Sub 87 | 88 | 89 | Public Function GetData(timestamp As DateTime) As Double 90 | 91 | ' Retrieves data from the DataStore dictionary. If there is no data for 92 | ' the timestamp, return Not a Number. 93 | 94 | Monitor.Enter(_lock) ' Block 95 | Try 96 | 97 | GetData = Nothing 98 | If _dataStore.TryGetValue(timestamp, GetData) Then ' In dictionary. 99 | Return GetData ' Return value from dictionary. 100 | Else 101 | Return NaN ' No data in dictionary for timestamp, return Not a Number. 102 | End If 103 | 104 | Finally 105 | Monitor.Exit(_lock) ' Unblock 106 | End Try 107 | 108 | End Function 109 | 110 | 111 | End Class 112 | 113 | 114 | End Namespace 115 | -------------------------------------------------------------------------------- /src/DBMDataRef/DBMEventSource.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Collections.Generic 23 | Imports System.DateTime 24 | Imports OSIsoft.AF.Asset 25 | Imports OSIsoft.AF.Data 26 | 27 | 28 | Namespace Vitens.DynamicBandwidthMonitor 29 | 30 | 31 | Public Class DBMEventSource 32 | Inherits AFEventSource 33 | 34 | 35 | Const UpdateSeconds As Integer = 60 ' Time limiter for update checking. 36 | 37 | 38 | Private _previousTimestamp As DateTime 39 | Private _previousSnapshots As New Dictionary(Of AFAttribute, DateTime) 40 | 41 | 42 | Protected Overrides Function GetEvents As Boolean 43 | 44 | ' The GetEvents method is designed to get data pipe events from the System 45 | ' of record. 46 | 47 | Dim attribute As AFAttribute 48 | Dim snapshot As AFValue 49 | 50 | ' Limit update checking to once every minute. 51 | If (Now-_previousTimestamp).TotalSeconds < UpdateSeconds Then Return False 52 | _previousTimestamp = Now 53 | 54 | ' Iterate over all signed up attributes in this data pipe. For some 55 | ' services signing up to many attributes, initialization might take some 56 | ' time. After data is retrieved for all attributes for the first time, 57 | ' only small amounts of new data are needed for all consequent 58 | ' evaluations, greatly speeding them up. 59 | For Each attribute In MyBase.Signups 60 | 61 | ' Check if we need to perform an action on this attribute. This is only 62 | ' needed if the attribute is an instance of an object. 63 | If attribute IsNot Nothing Then 64 | 65 | snapshot = attribute.GetValue ' Retrieve latest value. 66 | 67 | If _previousSnapshots.ContainsKey(attribute) Then 68 | ' If newer, store snapshot timestamp as previous snapshot timestamp 69 | ' for this attribute and publish new snapshot to the data pipe. 70 | If snapshot.Timestamp.LocalTime > 71 | _previousSnapshots.Item(attribute) Then 72 | _previousSnapshots.Item(attribute) = snapshot.Timestamp.LocalTime 73 | MyBase.PublishEvent(attribute, 74 | New AFDataPipeEvent(AFDataPipeAction.Add, snapshot)) 75 | End If 76 | Else 77 | ' Store the initial previous snapshot timestamp for this attribute. 78 | _previousSnapshots.Add(attribute, snapshot.Timestamp.LocalTime) 79 | End If 80 | 81 | End If 82 | 83 | Next attribute 84 | 85 | Return False ' Required. 86 | 87 | End Function 88 | 89 | 90 | Protected Overrides Sub Dispose(disposing As Boolean) 91 | End Sub 92 | 93 | 94 | End Class 95 | 96 | 97 | End Namespace 98 | -------------------------------------------------------------------------------- /src/dbm/DBMForecast.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Double 23 | Imports Vitens.DynamicBandwidthMonitor.DBMMath 24 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 25 | Imports Vitens.DynamicBandwidthMonitor.DBMStatistics 26 | 27 | 28 | Namespace Vitens.DynamicBandwidthMonitor 29 | 30 | 31 | Public Class DBMForecast 32 | 33 | 34 | Public Shared Function Forecast(values() As Double) As DBMForecastItem 35 | 36 | ' Calculates and stores forecast and control limits by removing 37 | ' outliers from the Values array and extrapolating the regression 38 | ' line by one interval. 39 | ' The result of the calculation is returned as a new object. 40 | 41 | Dim statisticsItem As New DBMStatisticsItem 42 | Dim range As Double 43 | 44 | Forecast = New DBMForecastItem 45 | 46 | With Forecast 47 | 48 | .Measurement = values(values.Length-1) 49 | 50 | ' Calculate statistics for data after removing outliers. Exclude the 51 | ' last item in the array as this is the current measured value for 52 | ' which we need to calculate a forecast and control limits. 53 | Array.Resize(values, values.Length-1) 54 | statisticsItem = Statistics(RemoveOutliers(values)) 55 | 56 | If statisticsItem.HasInsufficientData Then 57 | 58 | ' Forecast and control limits cannot be calculated if there is 59 | ' insufficient data. Return Not a Number. 60 | .Forecast = NaN 61 | .LowerControlLimit = NaN 62 | .UpperControlLimit = NaN 63 | 64 | Else 65 | 66 | ' Extrapolate regression by one interval and use this result as a 67 | ' forecast. 68 | .Forecast = 69 | ComparePatterns*statisticsItem.Slope+statisticsItem.Intercept 70 | 71 | ' Control limits are determined by using measures of process variation 72 | ' and are based on the concepts surrounding hypothesis testing and 73 | ' interval estimation. They are used to detect signals in process data 74 | ' that indicate that a process is not in control and, therefore, not 75 | ' operating predictably. 76 | range = ControlLimitRejectionCriterion(BandwidthCI, 77 | statisticsItem.Count-1)*statisticsItem.StandardError 78 | 79 | ' Set upper and lower control limits based on forecast, rejection 80 | ' criterion and standard error of the regression. 81 | .LowerControlLimit = .Forecast-range 82 | .UpperControlLimit = .Forecast+range 83 | 84 | End If 85 | 86 | End With 87 | 88 | Return Forecast 89 | 90 | End Function 91 | 92 | 93 | End Class 94 | 95 | 96 | End Namespace 97 | -------------------------------------------------------------------------------- /src/dbm/DBMAssert.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Convert 23 | Imports System.Double 24 | Imports System.Math 25 | 26 | 27 | Namespace Vitens.DynamicBandwidthMonitor 28 | 29 | 30 | Public Class DBMAssert 31 | 32 | 33 | ' In computer programming, specifically when using the imperative 34 | ' programming paradigm, an assertion is a predicate (a Boolean-valued 35 | ' function over the state space, usually expressed as a logical proposition 36 | ' using the variables of a program) connected to a point in the program, 37 | ' that always should evaluate to true at that point in code execution. 38 | ' Assertions can help a programmer read the code, help a compiler compile 39 | ' it, or help the program detect its own defects. 40 | ' For the latter, some programs check assertions by actually evaluating the 41 | ' predicate as they run. Then, if it is not in fact true - an assertion 42 | ' failure -, the program considers itself to be broken and typically 43 | ' deliberately crashes or throws an assertion failure exception. 44 | 45 | 46 | Public Shared Function Hash(values() As Double) As Double 47 | 48 | ' Simple hash function for checking array contents. 49 | 50 | Dim value As Double 51 | 52 | Hash = 1 53 | For Each value In values 54 | If Not IsNaN(value) Then 55 | Hash = (Hash+value+1)/3 56 | End If 57 | Next 58 | 59 | Return Hash 60 | 61 | End Function 62 | 63 | 64 | Public Shared Sub AssertEqual(a As Object, b As Object) 65 | 66 | If TypeOf a Is Boolean And TypeOf b Is Boolean AndAlso 67 | ToBoolean(a) = ToBoolean(b) Then Exit Sub 68 | If TypeOf a Is DateTime And TypeOf b Is DateTime AndAlso 69 | ToDateTime(a) = ToDateTime(b) Then Exit Sub 70 | If TypeOf a Is Double And TypeOf b Is Double AndAlso 71 | (IsNaN(ToDouble(a)) And IsNaN(ToDouble(b))) Then Exit Sub 72 | If (TypeOf a Is Integer Or TypeOf a Is Double Or TypeOf a Is Decimal) And 73 | (TypeOf b Is Integer Or TypeOf b Is Double Or 74 | TypeOf b Is Decimal) AndAlso 75 | ToDouble(a) = ToDouble(b) Then Exit Sub 76 | Throw New Exception("Assert failed a=" & a.ToString & " b=" & b.ToString) 77 | 78 | End Sub 79 | 80 | 81 | Public Shared Sub AssertArrayEqual(a() As Double, b() As Double) 82 | 83 | AssertEqual(Hash(a), Hash(b)) 84 | 85 | End Sub 86 | 87 | 88 | Public Shared Sub AssertAlmostEqual(a As Object, b As Object, 89 | Optional digits As Integer = 4) 90 | 91 | AssertEqual(Round(ToDouble(a), digits), Round(ToDouble(b), digits)) 92 | 93 | End Sub 94 | 95 | 96 | Public Shared Sub AssertTrue(a As Boolean) 97 | 98 | AssertEqual(a, True) 99 | 100 | End Sub 101 | 102 | 103 | Public Shared Sub AssertFalse(a As Boolean) 104 | 105 | AssertEqual(a, False) 106 | 107 | End Sub 108 | 109 | 110 | Public Shared Sub AssertNaN(a As Double) 111 | 112 | AssertEqual(a, NaN) 113 | 114 | End Sub 115 | 116 | 117 | End Class 118 | 119 | 120 | End Namespace 121 | -------------------------------------------------------------------------------- /src/dbm/DBMParameters.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System.Math 22 | Imports Vitens.DynamicBandwidthMonitor.DBMMath 23 | 24 | 25 | Namespace Vitens.DynamicBandwidthMonitor 26 | 27 | 28 | Public Class DBMParameters 29 | 30 | 31 | ' This class contains default values for several parameters which DBM uses 32 | ' for its calculations. The values for these parameters can be changed 33 | ' at runtime. 34 | 35 | ' Time interval at which the calculation is run. 36 | Private Shared _calculationInterval As Integer = 300 ' seconds, 5 minutes 37 | 38 | Public Shared Property CalculationInterval As Integer 39 | Get 40 | Return _calculationInterval 41 | End Get 42 | Set(value As Integer) 43 | _calculationInterval = value 44 | End Set 45 | End Property 46 | 47 | 48 | ' Use forecast of the previous Sunday for holidays. 49 | Private Shared _useSundayForHolidays As Boolean = True 50 | 51 | Public Shared Property UseSundayForHolidays As Boolean 52 | Get 53 | Return _useSundayForHolidays 54 | End Get 55 | Set(value As Boolean) 56 | _useSundayForHolidays = value 57 | End Set 58 | End Property 59 | 60 | 61 | ' Number of weeks to look back to forecast the current value and 62 | ' control limits. 63 | Private Shared _comparePatterns As Integer = 12 ' weeks 64 | 65 | Public Shared Property ComparePatterns As Integer 66 | Get 67 | Return _comparePatterns 68 | End Get 69 | Set(value As Integer) 70 | _comparePatterns = value 71 | End Set 72 | End Property 73 | 74 | 75 | ' Number of previous intervals used to smooth the data. 76 | Private Shared _emaPreviousPeriods As Integer = 77 | CInt(0.5*3600/DBMParameters.CalculationInterval-1) ' 5 intervals, 30 mins 78 | 79 | Public Shared Property EMAPreviousPeriods As Integer 80 | Get 81 | Return _emaPreviousPeriods 82 | End Get 83 | Set(value As Integer) 84 | _emaPreviousPeriods = value 85 | End Set 86 | End Property 87 | 88 | 89 | ' Confidence interval used for removing outliers. 90 | Private Shared _outlierCI As Double = 0.99 91 | 92 | Public Shared Property OutlierCI As Double 93 | Get 94 | Return _outlierCI 95 | End Get 96 | Set(value As Double) 97 | _outlierCI = value 98 | End Set 99 | End Property 100 | 101 | 102 | ' Confidence interval used for determining control limits. 103 | Private Shared _bandwidthCI As Double = 0.99 104 | 105 | Public Shared Property BandwidthCI As Double 106 | Get 107 | Return _bandwidthCI 108 | End Get 109 | Set(value As Double) 110 | _bandwidthCI = value 111 | End Set 112 | End Property 113 | 114 | 115 | ' Number of previous intervals used to calculate forecast error correlation 116 | ' when an event is found. 117 | Private Shared _correlationPreviousPeriods As Integer = 118 | CInt(2*3600/DBMParameters.CalculationInterval-1) ' 23 intervals, 2 hours 119 | 120 | Public Shared Property CorrelationPreviousPeriods As Integer 121 | Get 122 | Return _correlationPreviousPeriods 123 | End Get 124 | Set(value As Integer) 125 | _correlationPreviousPeriods = value 126 | End Set 127 | End Property 128 | 129 | 130 | ' Absolute correlation lower limit for detecting (anti)correlation. 131 | Private Shared _correlationThreshold As Double = Sqrt(0.7) ' 0.83666 132 | 133 | Public Shared Property CorrelationThreshold As Double 134 | Get 135 | Return _correlationThreshold 136 | End Get 137 | Set(value As Double) 138 | _correlationThreshold = value 139 | End Set 140 | End Property 141 | 142 | 143 | ' Regression angle range (around -45/+45 degrees) required when suppressing 144 | ' based on (anti)correlation. 145 | Private Shared _regressionAngleRange As Double = 146 | SlopeToAngle(2)-SlopeToAngle(1) ' 18.435 degrees, factor 2 147 | 148 | Public Shared Property RegressionAngleRange As Double 149 | Get 150 | Return _regressionAngleRange 151 | End Get 152 | Set(value As Double) 153 | _regressionAngleRange = value 154 | End Set 155 | End Property 156 | 157 | 158 | End Class 159 | 160 | 161 | End Namespace 162 | -------------------------------------------------------------------------------- /src/dbm/DBMLoggerAbstract.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.DateTime 23 | Imports System.Diagnostics 24 | Imports System.Environment 25 | Imports Vitens.DynamicBandwidthMonitor.DBMInfo 26 | 27 | 28 | Namespace Vitens.DynamicBandwidthMonitor 29 | 30 | 31 | Public MustInherit Class DBMLoggerAbstract 32 | 33 | 34 | Private _staticLogInfo As String 35 | 36 | 37 | Public Enum Level 38 | 39 | [Error] 40 | Warning 41 | Information 42 | Debug 43 | Trace 44 | 45 | End Enum 46 | 47 | 48 | Private Function EncloseBrackets(text As String) As String 49 | 50 | If text.Equals(String.Empty) Or text.Contains(" ") Then 51 | Return "[" & text & "]" 52 | Else 53 | Return text 54 | End If 55 | 56 | End Function 57 | 58 | 59 | Public Sub New 60 | 61 | With Process.GetCurrentProcess 62 | _staticLogInfo = EncloseBrackets(Environment.MachineName) & " " & 63 | EncloseBrackets(DBMInfo.ProductName) & " " & 64 | EncloseBrackets(.ProcessName) & " " & 65 | .Id.ToString & " " & 66 | EncloseBrackets(Environment.UserName) 67 | End With 68 | 69 | End Sub 70 | 71 | 72 | Public MustOverride Sub Log(level As Level, message As String) 73 | 74 | 75 | Private Function FormatLog(level As Level, entity As String, 76 | message As String) As String 77 | 78 | Dim i As Integer = 1 79 | Dim frameCount As Integer = (New StackTrace).FrameCount 80 | Dim caller As StackFrame = New StackFrame(0) 81 | Dim loggerClass As String = 82 | caller.GetMethod.DeclaringType.FullName.ToString 83 | 84 | Do While i < frameCount 85 | caller = New StackFrame(i) 86 | With caller.GetMethod 87 | ' Find the first non-constructor (instance, static) method outside of 88 | ' this class. 89 | If Not .DeclaringType.FullName.ToString.Equals(loggerClass) And 90 | Not .Name.ToString.Equals(".ctor") And 91 | Not .Name.ToString.Equals(".cctor") Then Exit Do 92 | End With 93 | i+=1 94 | Loop 95 | 96 | If message.Contains(NewLine) Then ' Multi-line message 97 | message = NewLine & " " & message.Replace(NewLine, NewLine & " ") 98 | End If 99 | 100 | With caller.GetMethod 101 | Return Now.ToString("yyyy-MM-ddTHH:mm:ss.fff") & " " & 102 | level.ToString & " " & 103 | _staticLogInfo & " " & 104 | .DeclaringType.FullName.ToString.Substring( 105 | .DeclaringType.Namespace.ToString.Length+1) & 106 | "." & .Name.ToString & " " & 107 | EncloseBrackets(entity) & " " & 108 | message 109 | End With 110 | 111 | End Function 112 | 113 | 114 | Public Sub LogError(message As String, Optional entity As String = "") 115 | 116 | ' Error messages. 117 | ' For errors and exceptions that cannot be handled. These messages 118 | ' indicate a failure in the current operation or request, not an app-wide 119 | ' failure. 120 | 121 | Log(Level.Error, FormatLog(Level.Error, entity, message)) 122 | 123 | End Sub 124 | 125 | 126 | Public Sub LogWarning(message As String, Optional entity As String = "") 127 | 128 | ' Warning messages. Encountered a recoverable error. 129 | ' For abnormal or unexpected events. Typically includes errors or 130 | ' conditions that don't cause the app to fail. 131 | 132 | Log(Level.Warning, FormatLog(Level.Warning, entity, message)) 133 | 134 | End Sub 135 | 136 | 137 | Public Sub LogInformation(message As String, Optional entity As String = "") 138 | 139 | ' Informational messages. 140 | ' Tracks the general flow of the app. May have long-term value. 141 | 142 | Log(Level.Information, FormatLog(Level.Information, entity, message)) 143 | 144 | End Sub 145 | 146 | 147 | Public Sub LogDebug(message As String, Optional entity As String = "") 148 | 149 | ' More detailed messages within a method (e.g., Sending email). 150 | ' For debugging and development. 151 | 152 | Log(Level.Debug, FormatLog(Level.Debug, entity, message)) 153 | 154 | End Sub 155 | 156 | 157 | Public Sub LogTrace(message As String, Optional entity As String = "") 158 | 159 | ' Data value messages (EmailAddress = john@invalidcompany.com). 160 | ' Contain the most detailed messages. These messages may contain 161 | ' sensitive app data. 162 | 163 | Log(Level.Trace, FormatLog(Level.Trace, entity, message)) 164 | 165 | End Sub 166 | 167 | 168 | End Class 169 | 170 | 171 | End Namespace 172 | -------------------------------------------------------------------------------- /src/dbm/DBMResult.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Double 23 | Imports System.Math 24 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 25 | 26 | 27 | Namespace Vitens.DynamicBandwidthMonitor 28 | 29 | 30 | Public Class DBMResult 31 | 32 | 33 | ' DBMResult is the object passed by DBM.GetResult and contains the final 34 | ' results for the DBM calculation. It is also used for storing intermediate 35 | ' results of (correlation) calculation results from a DBMPoint object. 36 | 37 | 38 | Private _timestamp As DateTime 39 | Private _isFutureData As Boolean 40 | Private _forecastItem As DBMForecastItem 41 | Private _factor, _absoluteErrors(), _relativeErrors() As Double 42 | 43 | 44 | Public Property Timestamp As DateTime 45 | Get 46 | Return _timestamp 47 | End Get 48 | Set(value As DateTime) 49 | _timestamp = value 50 | End Set 51 | End Property 52 | 53 | 54 | Public Property IsFutureData As Boolean 55 | Get 56 | Return _isFutureData 57 | End Get 58 | Set(value As Boolean) 59 | _isFutureData = value 60 | End Set 61 | End Property 62 | 63 | 64 | Public Property ForecastItem As DBMForecastItem 65 | Get 66 | Return _forecastItem 67 | End Get 68 | Set(value As DBMForecastItem) 69 | _forecastItem = value 70 | End Set 71 | End Property 72 | 73 | 74 | Public Property Factor As Double 75 | Get 76 | Return _factor 77 | End Get 78 | Set(value As Double) 79 | _factor = value 80 | End Set 81 | End Property 82 | 83 | 84 | Public Function GetAbsoluteErrors As Double() 85 | Return _absoluteErrors 86 | End Function 87 | 88 | 89 | Public Function GetRelativeErrors As Double() 90 | Return _relativeErrors 91 | End Function 92 | 93 | 94 | Public Sub New 95 | 96 | ' Initialize array sizes. To be filled from back to front. When a 97 | ' correlation calculation is not required (no event detected or no 98 | ' correlation points specified) only the last item in the arrays contains 99 | ' a value. 100 | 101 | ReDim _absoluteErrors(CorrelationPreviousPeriods) 102 | ReDim _relativeErrors(CorrelationPreviousPeriods) 103 | 104 | End Sub 105 | 106 | 107 | Public Function HasEvent As Boolean 108 | 109 | ' Returns true if there is an event. 110 | 111 | Return Abs(Me.Factor) > 1 112 | 113 | End Function 114 | 115 | 116 | Public Function HasSuppressedEvent As Boolean 117 | 118 | ' Returns true if there is a suppressed event. 119 | 120 | With Me.ForecastItem 121 | Return Me.Factor = 0 And 122 | (.Measurement < .LowerControlLimit Or 123 | .Measurement > .UpperControlLimit) 124 | End With 125 | 126 | End Function 127 | 128 | 129 | Public Function TimestampIsValid As Boolean 130 | 131 | ' Returns true if the timestamp is valid. When DST goes in effect, there 132 | ' is a missing hour in local time. 133 | 134 | Return Not TimeZoneInfo.Local.IsInvalidTime(Me.Timestamp) 135 | 136 | End Function 137 | 138 | 139 | Public Sub Calculate(index As Integer, measurementEMA As Double, 140 | forecastEMA As Double, lowerControlLimitEMA As Double, 141 | upperControlLimitEMA As Double) 142 | 143 | ' Calculates and stores forecast errors and initial results. 144 | 145 | ' Forecast error (for forecast error correlation calculations). 146 | _absoluteErrors(index) = forecastEMA-measurementEMA 147 | _relativeErrors(index) = forecastEMA/measurementEMA-1 148 | 149 | If Me.ForecastItem Is Nothing Then 150 | 151 | ' Store EMA results in new DBMForecastItem object for current timestamp. 152 | Me.ForecastItem = New DBMForecastItem 153 | With Me.ForecastItem 154 | .Measurement = measurementEMA 155 | .Forecast = forecastEMA 156 | .LowerControlLimit = lowerControlLimitEMA 157 | .UpperControlLimit = upperControlLimitEMA 158 | End With 159 | 160 | ' No factor if there is no valid measurement. 161 | If IsNaN(measurementEMA) Then 162 | Me.Factor = NaN 163 | End If 164 | 165 | ' Lower control limit exceeded, calculate factor. 166 | If measurementEMA < lowerControlLimitEMA Then 167 | Me.Factor = (forecastEMA-measurementEMA)/ 168 | (lowerControlLimitEMA-forecastEMA) 169 | End If 170 | 171 | ' Upper control limit exceeded, calculate factor. 172 | If measurementEMA > upperControlLimitEMA Then 173 | Me.Factor = (measurementEMA-forecastEMA)/ 174 | (upperControlLimitEMA-forecastEMA) 175 | End If 176 | 177 | End If 178 | 179 | End Sub 180 | 181 | 182 | End Class 183 | 184 | 185 | End Namespace 186 | -------------------------------------------------------------------------------- /src/dbm/DBMInfo.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.DateTime 23 | Imports System.Diagnostics 24 | Imports System.Environment 25 | Imports System.Math 26 | Imports System.Reflection 27 | Imports System.Security.Cryptography.X509Certificates 28 | Imports System.TimeSpan 29 | Imports Vitens.DynamicBandwidthMonitor.DBMStrings 30 | Imports Vitens.DynamicBandwidthMonitor.DBMTests 31 | 32 | 33 | Namespace Vitens.DynamicBandwidthMonitor 34 | 35 | 36 | Public Class DBMInfo 37 | 38 | 39 | Private Shared Function AssemblyLocation As String 40 | 41 | ' Returns assembly. 42 | 43 | Return Assembly.GetExecutingAssembly.Location 44 | 45 | End Function 46 | 47 | 48 | Private Shared Function GetFileVersionInfo As FileVersionInfo 49 | 50 | ' Returns FileVersionInfo for assembly. 51 | 52 | Return FileVersionInfo.GetVersionInfo(AssemblyLocation) 53 | 54 | End Function 55 | 56 | 57 | Private Shared Function BuildDate As DateTime 58 | 59 | ' Returns the build date based on FileBuildPart. 60 | 61 | Return New DateTime(2000, 1, 1).AddDays(GetFileVersionInfo.FileBuildPart) 62 | 63 | End Function 64 | 65 | 66 | Public Shared Function Version As String 67 | 68 | ' Returns a string containing the full version number including, if set, 69 | ' Git hash. Use Semantic Versioning Specification (SemVer). 70 | 71 | Const GITHASH As String = "#######" ' Updated by CI/CD tools. 72 | 73 | With GetFileVersionInfo 74 | Return .FileMajorPart.ToString & "." & .FileMinorPart.ToString & ".0+" & 75 | BuildDate.ToString("yyMMdd") & "." & GITHASH 76 | End With 77 | 78 | End Function 79 | 80 | 81 | Public Shared Function ProductName As String 82 | 83 | ' Returns the name of the product. 84 | 85 | Return GetFileVersionInfo.ProductName 86 | 87 | End Function 88 | 89 | 90 | Public Shared Function Application As String 91 | 92 | ' Returns the name and version of the application. 93 | 94 | Return ProductName & " v" & Version 95 | 96 | End Function 97 | 98 | 99 | Public Shared Function Product As String 100 | 101 | ' Returns the name of and information about the product. 102 | 103 | With GetFileVersionInfo 104 | Return Application & NewLine & 105 | .Comments & NewLine & 106 | .LegalCopyright 107 | End With 108 | 109 | End Function 110 | 111 | 112 | Public Shared Function LicenseNotice As String 113 | 114 | ' Returns a string containing product name, version number, copyright, 115 | ' and license notice. 116 | 117 | Return Product & NewLine & 118 | NewLine & 119 | "This program is free software: you can redistribute it and/or " & 120 | "modify it under the terms of the GNU General Public License as " & 121 | "published by the Free Software Foundation, either version 3 of the " & 122 | "License, or (at your option) any later version." & NewLine & 123 | NewLine & 124 | "This program is distributed in the hope that it will be useful, but " & 125 | "WITHOUT ANY WARRANTY; without even the implied warranty of " & 126 | "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU " & 127 | "General Public License for more details." & NewLine & 128 | NewLine & 129 | "You should have received a copy of the GNU General Public License " & 130 | "along with this program. " & 131 | "If not, see ." 132 | 133 | End Function 134 | 135 | 136 | Public Shared Function CertificateInfo( 137 | Optional required As Boolean = False) As String 138 | 139 | ' Returns a string containing the certificate Subject and Issuer, if 140 | ' available. Else returns 'Unsigned assembly'. 141 | 142 | Try 143 | With X509Certificate.CreateFromSignedFile(AssemblyLocation) 144 | Return .Subject & " (" & .Issuer & ")" 145 | End With 146 | Catch 147 | DBM.Logger.LogWarning(UnsignedAssembly & " " & AssemblyLocation) 148 | If required Then Throw 149 | Return UnsignedAssembly 150 | End Try 151 | 152 | End Function 153 | 154 | 155 | Public Shared Function TestResults( 156 | Optional certificateRequired As Boolean = False) As String 157 | 158 | ' Run unit and integration tests and return test run duration. An 159 | ' exception occurs if one of the tests fail. 160 | 161 | Dim timer As DateTime 162 | Dim utDurationMs, itDurationMs, qtDurationMs As Double 163 | Dim qtResult As String 164 | 165 | timer = Now 166 | RunUnitTests 167 | utDurationMs = (Now.Ticks-timer.Ticks)/TicksPerMillisecond 168 | 169 | timer = Now 170 | RunIntegrationTests 171 | itDurationMs = (Now.Ticks-timer.Ticks)/TicksPerMillisecond 172 | 173 | timer = Now 174 | qtResult = RunQualityTests 175 | qtDurationMs = (Now.Ticks-timer.Ticks)/TicksPerMillisecond 176 | 177 | Return "Certificate: " & CertificateInfo(certificateRequired) & NewLine & 178 | "Unit tests: " & Round(utDurationMs).ToString & " ms" & NewLine & 179 | "Integration tests: " & Round(itDurationMs).ToString & " ms" & NewLine & 180 | "Quality tests: " & Round(qtDurationMs).ToString & " ms; " & qtResult 181 | 182 | End Function 183 | 184 | 185 | End Class 186 | 187 | 188 | End Namespace 189 | -------------------------------------------------------------------------------- /src/dbmtester/DBMTester.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Collections.Generic 23 | Imports System.Environment 24 | Imports System.Globalization.CultureInfo 25 | Imports System.Text.RegularExpressions 26 | Imports System.Threading.Thread 27 | Imports Vitens.DynamicBandwidthMonitor.DBMDate 28 | Imports Vitens.DynamicBandwidthMonitor.DBMInfo 29 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 30 | Imports Vitens.DynamicBandwidthMonitor.DBMStatistics 31 | Imports Vitens.DynamicBandwidthMonitor.DBMStrings 32 | 33 | 34 | ' Assembly title 35 | 36 | 37 | 38 | Namespace Vitens.DynamicBandwidthMonitor 39 | 40 | 41 | Public Class DBMTester 42 | 43 | 44 | ' DBMTester is a command line utility that can be used to quickly 45 | ' calculate DBM results using the CSV driver. 46 | 47 | 48 | Private Shared Function Separator As String 49 | 50 | If CurrentThread.CurrentCulture Is InvariantCulture Then 51 | Return "," 52 | Else 53 | Return " " ' Tab character 54 | End If 55 | 56 | End Function 57 | 58 | 59 | Private Shared Function FormatNumber(value As Double) As String 60 | 61 | Return value.ToString(DecimalFormat) 62 | 63 | End Function 64 | 65 | 66 | Public Shared Sub Main 67 | 68 | Dim commandLineArg, substrings(), parameter, value As String 69 | Dim inputPointDriver As DBMPointDriver = Nothing 70 | Dim correlationPoints As New List(Of DBMCorrelationPoint) 71 | Dim startTimestamp, endTimestamp As DateTime 72 | Dim results As List(Of DBMResult) 73 | Dim dbm As New DBM 74 | Dim result As DBMResult 75 | 76 | ' Parse command line arguments 77 | For Each commandLineArg In GetCommandLineArgs 78 | ' Parameter=Value 79 | If Regex.IsMatch(commandLineArg, "^[-/].+=.+$") Then 80 | substrings = commandLineArg.Split(New Char(){"="c}, 2) 81 | parameter = substrings(0).Substring(1).ToLower 82 | value = substrings(1) 83 | Try 84 | If parameter.Equals("i") Then 85 | inputPointDriver = New DBMPointDriver(value) 86 | ElseIf parameter.Equals("c") Then 87 | correlationPoints.Add( 88 | New DBMCorrelationPoint(New DBMPointDriver(value), False)) 89 | ElseIf parameter.Equals("cs") Then 90 | correlationPoints.Add( 91 | New DBMCorrelationPoint(New DBMPointDriver(value), True)) 92 | ElseIf parameter.Equals("iv") Then 93 | CalculationInterval = Convert.ToInt32(value) 94 | ElseIf parameter.Equals("us") Then 95 | UseSundayForHolidays = Convert.ToBoolean(value) 96 | ElseIf parameter.Equals("p") Then 97 | ComparePatterns = Convert.ToInt32(value) 98 | ElseIf parameter.Equals("ep") Then 99 | EMAPreviousPeriods = Convert.ToInt32(value) 100 | ElseIf parameter.Equals("oi") Then 101 | OutlierCI = Convert.ToDouble(value) 102 | ElseIf parameter.Equals("bi") Then 103 | BandwidthCI = Convert.ToDouble(value) 104 | ElseIf parameter.Equals("cp") Then 105 | CorrelationPreviousPeriods = Convert.ToInt32(value) 106 | ElseIf parameter.Equals("ct") Then 107 | CorrelationThreshold = Convert.ToDouble(value) 108 | ElseIf parameter.Equals("ra") Then 109 | RegressionAngleRange = Convert.ToDouble(value) 110 | ElseIf parameter.Equals("st") Then 111 | startTimestamp = Convert.ToDateTime(value) 112 | ElseIf parameter.Equals("et") Then 113 | endTimestamp = Convert.ToDateTime(value) 114 | ElseIf parameter.Equals("f") Then 115 | If value.ToLower.Equals("intl") Then 116 | CurrentThread.CurrentCulture = InvariantCulture 117 | End If 118 | End If 119 | Catch ex As Exception 120 | DBM.Logger.LogError(ex.ToString) 121 | Exit Sub 122 | End Try 123 | End If 124 | Next commandLineArg 125 | 126 | If inputPointDriver IsNot Nothing And 127 | startTimestamp > DateTime.MinValue Then 128 | 129 | If endTimestamp = DateTime.MinValue Then 130 | ' No end timestamp, use start timestamp. 131 | endTimestamp = startTimestamp 132 | End If 133 | 134 | ' Header 135 | DBM.Logger.LogInformation( 136 | CSVComment & Product.Replace(NewLine, NewLine & CSVComment)) 137 | DBM.Logger.LogInformation( 138 | TimestampText & Separator & 139 | FactorText & Separator & 140 | MeasurementText & Separator & 141 | ForecastText & Separator & 142 | LowerControlLimitText & Separator & 143 | UpperControlLimitText, 144 | inputPointDriver.ToString) 145 | 146 | ' Get results for time range. 147 | results = dbm.GetResults(inputPointDriver, correlationPoints, 148 | startTimestamp, endTimestamp) 149 | For Each result In results 150 | 151 | With result 152 | DBM.Logger.LogInformation( 153 | .Timestamp.ToString("s") & Separator & 154 | FormatNumber(.Factor) & Separator & 155 | FormatNumber(.ForecastItem.Measurement) & Separator & 156 | FormatNumber(.ForecastItem.Forecast) & Separator & 157 | FormatNumber(.ForecastItem.LowerControlLimit) & Separator & 158 | FormatNumber(.ForecastItem.UpperControlLimit), 159 | inputPointDriver.ToString) 160 | End With 161 | 162 | Next result 163 | 164 | DBM.Logger.LogInformation( 165 | CSVComment & Statistics(results).Brief, inputPointDriver.ToString) 166 | 167 | End If 168 | 169 | End Sub 170 | 171 | 172 | End Class 173 | 174 | 175 | End Namespace 176 | -------------------------------------------------------------------------------- /src/dbm/DBMDate.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Globalization 23 | Imports System.Math 24 | Imports System.TimeSpan 25 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 26 | 27 | 28 | Namespace Vitens.DynamicBandwidthMonitor 29 | 30 | 31 | Public Class DBMDate 32 | 33 | 34 | ' Contains date and time functions. 35 | 36 | 37 | Public Shared Function PreviousInterval(timestamp As DateTime) As DateTime 38 | 39 | ' Returns a DateTime for the passed timestamp aligned on the previous 40 | ' interval. 41 | 42 | Return timestamp.AddTicks( 43 | -timestamp.Ticks Mod CalculationInterval*TicksPerSecond) 44 | 45 | End Function 46 | 47 | 48 | Public Shared Function NextInterval(timestamp As DateTime) As DateTime 49 | 50 | Return PreviousInterval(timestamp.AddSeconds(CalculationInterval)) 51 | 52 | End Function 53 | 54 | 55 | Public Shared Function IsOnInterval(timestamp As DateTime) As Boolean 56 | 57 | ' Returns true if the end timestamp is exactly on an interval boundary. 58 | 59 | Return timestamp.Equals(PreviousInterval(timestamp)) 60 | 61 | End Function 62 | 63 | 64 | Public Shared Function IntervalSeconds(numberOfValues As Integer, 65 | durationSeconds As Double) As Double 66 | 67 | ' Number of values desired. If =0, all intervals will be returned. If >0, 68 | ' that number of values will be returned. If <0, the negative value minus 69 | ' 1 number of values will be returned (f.ex. -25 over a 24 hour period 70 | ' will return an hourly value). Duration is in seconds. The first value 71 | ' returned will then be the first interval in the time range, and the last 72 | ' value returned will be the final calculation interval (f.ex. requesting 73 | ' 6 values for a duration of 60 minutes with a calculation interval of 5 74 | ' minutes will return an interval of 660 seconds which will then return 75 | ' values at :00, :11, :22, :33, :44, and :55). 76 | 77 | If numberOfValues < 0 Then numberOfValues = -numberOfValues-1 78 | If numberOfValues = 1 Then 79 | Return durationSeconds ' Return a single value 80 | Else 81 | Return Max(1, (durationSeconds/CalculationInterval-1)/ 82 | (numberOfValues-1))*CalculationInterval ' Required interval 83 | End If 84 | 85 | End Function 86 | 87 | 88 | Public Shared Function Computus(year As Integer) As DateTime 89 | 90 | ' Computus (Latin for computation) is the calculation of the date of 91 | ' Easter in the Christian calendar. The computus is used to set the time 92 | ' for ecclesiastical purposes, in particular to calculate the date of 93 | ' Easter. 94 | 95 | Dim H, i, L As Integer 96 | 97 | H = (year\100-year\400-(8*(year\100)+13)\25+19*(year Mod 19)+15) Mod 30 98 | i = H-H\28-(H\28)*(29\H+1)*(21-year Mod 19)\11 99 | L = i-(year+year\4+i+2-year\100+year\400) Mod 7 100 | 101 | Return New DateTime(year, 3+(L+40)\44, L+28-31*((172+L)\176)) 102 | 103 | End Function 104 | 105 | 106 | Public Shared Function IsHoliday(timestamp As DateTime, 107 | culture As CultureInfo) As Boolean 108 | 109 | ' Returns True if the passed date is a holiday. 110 | 111 | Dim DaysSinceEaster As Integer = 112 | timestamp.Subtract(Computus(timestamp.Year)).Days 113 | 114 | With timestamp 115 | ' For any culture, consider the following days a holiday: 116 | ' New Year's Day, Easter, Ascension Day, Pentecost, 117 | ' Christmas Day, and New Year's Eve. 118 | IsHoliday = (.Month = 1 And .Day = 1) Or 119 | {0, 39, 49}.Contains(DaysSinceEaster) Or 120 | (.Month = 12 And {25, 31}.Contains(.Day)) 121 | If culture.Name.Equals("nl-NL") Then 122 | ' For the Netherlands, consider the following days a holiday: 123 | ' 2nd day of Easter, Royal day, Liberation Day (lustrum), 124 | ' 2nd day of Pentecost, and Boxing Day 125 | IsHoliday = IsHoliday Or 126 | {1, 50}.Contains(DaysSinceEaster) Or 127 | (.Year >= 1980 And .Year < 2014 And .Month = 4 And .Day = 30) Or 128 | (.Year >= 2014 And .Month = 4 And .Day = 27) Or 129 | (.Year Mod 5 = 0 And .Month = 5 And .Day = 5) Or 130 | (.Month = 12 And .Day = 26) 131 | End If 132 | End With 133 | 134 | Return IsHoliday 135 | 136 | End Function 137 | 138 | 139 | Public Shared Function DaysSinceSunday(timestamp As DateTime) As Integer 140 | 141 | ' Return the number of days between the passed timestamp and the 142 | ' preceding Sunday. 143 | 144 | Return timestamp.DayOfWeek ' 0=Sunday, 6=Saturday 145 | 146 | End Function 147 | 148 | 149 | Public Shared Function PreviousSunday(timestamp As DateTime) As DateTime 150 | 151 | ' Returns a DateTime for the Sunday preceding the timestamp passed. 152 | 153 | Return timestamp.AddDays(-DaysSinceSunday(timestamp)) 154 | 155 | End Function 156 | 157 | 158 | Public Shared Function OffsetHoliday(timestamp As DateTime, 159 | culture As CultureInfo) As DateTime 160 | 161 | If UseSundayForHolidays And IsHoliday(timestamp, culture) Then 162 | Return PreviousSunday(timestamp) ' Offset holidays 163 | Else 164 | Return timestamp 165 | End If 166 | 167 | End Function 168 | 169 | 170 | Public Shared Function DataPreparationTimestamp( 171 | startTimestamp As DateTime) As DateTime 172 | 173 | startTimestamp = PreviousInterval(startTimestamp.AddDays( 174 | -7*ComparePatterns).AddSeconds( 175 | -(EMAPreviousPeriods+CorrelationPreviousPeriods)*CalculationInterval)) 176 | If UseSundayForHolidays Then startTimestamp = 177 | PreviousSunday(startTimestamp) 178 | 179 | Return startTimestamp 180 | 181 | End Function 182 | 183 | 184 | Public Shared Function EMATimeOffset(count As Integer) As Integer 185 | 186 | ' The use of an exponential moving average (EMA) time shifts the resulting 187 | ' calculated data. To compensate for this, an offset should be applied 188 | ' based on exponentially increasing weighting factors. The returned value 189 | ' is in seconds and is only shifted in whole intervals. 190 | 191 | ' Floor(n/2.91136) is a fast approximation of Round(n-EMA(1..n)). 192 | Return CInt(-Floor(count/2.91136)*CalculationInterval) 193 | 194 | End Function 195 | 196 | 197 | End Class 198 | 199 | 200 | End Namespace 201 | -------------------------------------------------------------------------------- /src/dbm/DBMPoint.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Collections.Generic 23 | Imports System.Globalization 24 | Imports System.Math 25 | Imports Vitens.DynamicBandwidthMonitor.DBMDate 26 | Imports Vitens.DynamicBandwidthMonitor.DBMMath 27 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 28 | Imports Vitens.DynamicBandwidthMonitor.DBMForecast 29 | 30 | 31 | Namespace Vitens.DynamicBandwidthMonitor 32 | 33 | 34 | Public Class DBMPoint 35 | 36 | 37 | Private _pointDriver As DBMPointDriverAbstract 38 | 39 | 40 | Public Property PointDriver As DBMPointDriverAbstract 41 | Get 42 | Return _pointDriver 43 | End Get 44 | Set(value As DBMPointDriverAbstract) 45 | _pointDriver = value 46 | End Set 47 | End Property 48 | 49 | 50 | Public Sub New(pointDriver As DBMPointDriverAbstract) 51 | 52 | DBM.Logger.LogDebug(pointDriver.ToString, pointDriver.ToString) 53 | Me.PointDriver = pointDriver 54 | 55 | End Sub 56 | 57 | 58 | Public Function GetResults(startTimestamp As DateTime, 59 | endTimestamp As DateTime, numberOfValues As Integer, 60 | isInputDBMPoint As Boolean, hasCorrelationDBMPoint As Boolean, 61 | subtractPoint As DBMPoint, culture As CultureInfo) As List(Of DBMResult) 62 | 63 | ' Retrieves data and calculates forecast and control limits for 64 | ' this point. Also calculates and stores (historic) forecast errors for 65 | ' correlation analysis later on. Forecast results are cached and then 66 | ' reused when possible. This is important because, due to the use of a 67 | ' moving average, previously calculated results will often need to be 68 | ' included in later calculations. 69 | 70 | Dim timeRangeInterval As Double 71 | Dim snapshotTimestamp As DateTime 72 | Dim result As DBMResult 73 | Dim correlationCounter, emaCounter, patternCounter As Integer 74 | Dim forecastTimestamp, historyTimestamp, patternTimestamp As DateTime 75 | Dim forecastItems As New Dictionary(Of DateTime, DBMForecastItem) 76 | Dim patterns(ComparePatterns), measurements(EMAPreviousPeriods), 77 | forecasts(EMAPreviousPeriods), 78 | lowerControlLimits(EMAPreviousPeriods), 79 | upperControlLimits(EMAPreviousPeriods) As Double 80 | 81 | GetResults = New List(Of DBMResult) 82 | 83 | ' Align timestamps and determine interval. 84 | startTimestamp = PreviousInterval(startTimestamp) 85 | If Not IsOnInterval(endTimestamp) Then 86 | ' Add one extra interval if the end timestamp is not exactly on an 87 | ' interval boundary. This is required for linear interpolation of 88 | ' non-stepped data to the end of the interval. 89 | endTimestamp = NextInterval(endTimestamp) 90 | End If 91 | endTimestamp = NextInterval(endTimestamp) 92 | timeRangeInterval = IntervalSeconds(numberOfValues, 93 | (endTimestamp-startTimestamp).TotalSeconds) 94 | 95 | ' Get data from data source. 96 | snapshotTimestamp = Me.PointDriver.snapshotTimestamp 97 | Me.PointDriver.RetrieveData(startTimestamp, endTimestamp) 98 | If subtractPoint IsNot Nothing Then 99 | subtractPoint.PointDriver.RetrieveData(startTimestamp, endTimestamp) 100 | End If 101 | 102 | Do While endTimestamp > startTimestamp 103 | 104 | result = New DBMResult 105 | result.Timestamp = PreviousInterval(startTimestamp) 106 | result.IsFutureData = result.Timestamp > snapshotTimestamp 107 | 108 | For correlationCounter = 0 To CorrelationPreviousPeriods ' Corr. loop. 109 | 110 | ' Retrieve data and calculate forecast. Only do this for the required 111 | ' timestamp and only process previous timestamps for calculating 112 | ' correlation results if an event was found. 113 | If result.ForecastItem Is Nothing Or (isInputDBMPoint And 114 | Abs(result.Factor) > 0 And hasCorrelationDBMPoint) Or 115 | Not isInputDBMPoint Then 116 | 117 | For emaCounter = 0 To EMAPreviousPeriods ' Filter hi freq. variation 118 | 119 | forecastTimestamp = result.Timestamp.AddSeconds( 120 | -(EMAPreviousPeriods-emaCounter+correlationCounter)* 121 | CalculationInterval) ' Timestamp for forecast results 122 | 123 | ' Calculate forecast for this timestamp if there is none yet. 124 | If Not forecastItems.ContainsKey(forecastTimestamp) Then 125 | 126 | historyTimestamp = OffsetHoliday(forecastTimestamp, culture) 127 | 128 | For patternCounter = 0 To ComparePatterns ' Data for regression. 129 | 130 | If patternCounter = ComparePatterns Then 131 | patternTimestamp = forecastTimestamp ' Last is measurement. 132 | Else 133 | patternTimestamp = historyTimestamp. 134 | AddDays(-(ComparePatterns-patternCounter)*7) ' History. 135 | End If 136 | 137 | patterns(patternCounter) = 138 | Me.PointDriver.DataStore.GetData(patternTimestamp) 139 | If subtractPoint IsNot Nothing Then ' Subtract input if req'd. 140 | patterns(patternCounter) -= 141 | subtractPoint.PointDriver.DataStore. 142 | GetData(patternTimestamp) 143 | End If 144 | 145 | Next patternCounter 146 | 147 | ' Calculate and store forecast for this timestamp. 148 | forecastItems.Add(forecastTimestamp, Forecast(patterns)) 149 | 150 | End If 151 | 152 | With forecastItems.Item(forecastTimestamp) ' To arrays for EMA. 153 | measurements(emaCounter) = .Measurement 154 | forecasts(emaCounter) = .Forecast 155 | lowerControlLimits(emaCounter) = .LowerControlLimit 156 | upperControlLimits(emaCounter) = .UpperControlLimit 157 | End With 158 | 159 | Next emaCounter 160 | 161 | ' Calculate final result using filtered calculation results. 162 | result.Calculate(CorrelationPreviousPeriods-correlationCounter, 163 | ExponentialMovingAverage(measurements), 164 | ExponentialMovingAverage(forecasts), 165 | ExponentialMovingAverage(lowerControlLimits), 166 | ExponentialMovingAverage(upperControlLimits)) 167 | 168 | End If 169 | 170 | Next correlationCounter 171 | 172 | GetResults.Add(result) ' Add timestamp results. 173 | startTimestamp = 174 | startTimestamp.AddSeconds(timeRangeInterval) ' Next interval. 175 | 176 | Loop 177 | 178 | Return GetResults 179 | 180 | End Function 181 | 182 | 183 | End Class 184 | 185 | 186 | End Namespace 187 | -------------------------------------------------------------------------------- /src/dbm/DBMPointDriverAbstract.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Threading 23 | Imports Vitens.DynamicBandwidthMonitor.DBMDate 24 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 25 | 26 | 27 | Namespace Vitens.DynamicBandwidthMonitor 28 | 29 | 30 | Public MustInherit Class DBMPointDriverAbstract 31 | 32 | 33 | ' DBM drivers should inherit from this base class. In Sub New, 34 | ' MyBase.New(point) should be called. RetrieveData is used to retrieve and 35 | ' store data in bulk from a source using the DataStore.AddData method. Use 36 | ' DataStore.GetData to fetch results from memory. 37 | 38 | 39 | Private _point As Object 40 | Private _dataStore As New DBMDataStore ' In-memory data 41 | Private _lock As New Object ' Object for exclusive lock on critical section. 42 | Private _previousStartTimestamp As DateTime = DateTime.MaxValue 43 | Private _previousEndTimestamp As DateTime 44 | 45 | 46 | Public Property Point As Object 47 | Get 48 | Return _point 49 | End Get 50 | Set(value As Object) 51 | _point = value 52 | End Set 53 | End Property 54 | 55 | 56 | Public Property DataStore As DBMDataStore 57 | Get 58 | Return _dataStore 59 | End Get 60 | Set(value As DBMDataStore) 61 | _dataStore = value 62 | End Set 63 | End Property 64 | 65 | 66 | Public Sub New(point As Object) 67 | 68 | ' When inheriting from this base class, call MyBase.New(Point) from Sub 69 | ' New to store the unique identifier in the Point object. 70 | 71 | Me.Point = point 72 | 73 | End Sub 74 | 75 | 76 | Public MustOverride Overrides Function ToString As String 77 | ' Return the name of this point as a string. 78 | 79 | 80 | Public Overridable Function SnapshotTimestamp As DateTime 81 | 82 | ' Return the latest data timestamp (snapshot) for which the source of data 83 | ' has information available. If there is no limit, return 84 | ' DateTime.MaxValue. 85 | 86 | Return DateTime.MaxValue 87 | 88 | End Function 89 | 90 | 91 | Public Function CalculationTimestamp As DateTime 92 | 93 | ' Return the latest possible calculation timestamp for which the source of 94 | ' data has information available. Compensated for exponential moving 95 | ' average (EMA) time shift. 96 | 97 | Return SnapshotTimestamp.AddSeconds(EMATimeOffset(EMAPreviousPeriods+1)) 98 | 99 | End Function 100 | 101 | 102 | Public MustOverride Sub PrepareData(startTimestamp As DateTime, 103 | endTimestamp As DateTime) 104 | ' Must retrieve and store data in bulk for the passed time range from a 105 | ' source of data, to be used in the DataStore.GetData method. Use 106 | ' DataStore.AddData to store data in memory. 107 | 108 | 109 | Public Sub RetrieveData(startTimestamp As DateTime, 110 | endTimestamp As DateTime) 111 | 112 | Dim snapshot As DateTime = SnapshotTimestamp 113 | 114 | ' Data preparation timestamps 115 | startTimestamp = DataPreparationTimestamp(startTimestamp) 116 | endTimestamp = PreviousInterval(endTimestamp) 117 | 118 | ' If set, never retrieve values beyond the snapshot time aligned to the 119 | ' next interval. 120 | If startTimestamp > snapshot Then startTimestamp = NextInterval(snapshot) 121 | If endTimestamp > snapshot Then endTimestamp = NextInterval(snapshot) 122 | 123 | ' Exit this sub if there is no data to retrieve or when the start 124 | ' timestamp is not before the end timestamp. 125 | If Not startTimestamp < endTimestamp Then Exit Sub 126 | 127 | Monitor.Enter(_lock) ' Block 128 | Try 129 | 130 | ' Determine what data stored in memory can be reused, what needs to be 131 | ' removed, and what needs to be retrieved from the data source and 132 | ' stored in memory. Here is a simplified overview of how the different 133 | ' cases (S(tart)-E(nd)) are handled, compared to the time range stored 134 | ' previously (PS-PE): 135 | ' PS*==========*PE S...PS E...PE Action 136 | ' Case 1: S==========E = = Do nothing 137 | ' Case 2: S++|==========E < = Add backward 138 | ' Case 3: ---S=======E > = Do nothing 139 | ' Case 4: S=======E--- = < Do nothing 140 | ' Case 5: S++|=======E--- < < Remove forward, add backwd 141 | ' Case 6: ---S====E--- > < Do nothing 142 | ' Case 7: S==========|++E = > Add forward 143 | ' Case 8: S++|==========|++E < > Clear all 144 | ' Case 9: ---S=======|++E > > Remove backward, add forwd 145 | ' Case 10: S==E a) or b) S==E E<=PS S>=PE Clear all 146 | If (startTimestamp < _previousStartTimestamp And 147 | endTimestamp > _previousEndTimestamp) Or 148 | endTimestamp <= _previousStartTimestamp Or 149 | startTimestamp >= _previousEndTimestamp Then ' Cases 8, 10a), 10b) 150 | Me.DataStore.ClearData ' Clear all 151 | _previousStartTimestamp = startTimestamp 152 | _previousEndTimestamp = endTimestamp 153 | Else If startTimestamp >= _previousStartTimestamp And 154 | endTimestamp <= _previousEndTimestamp Then ' Cases 1, 3, 4, 6 155 | Exit Sub ' Do nothing 156 | Else If startTimestamp < _previousStartTimestamp Then ' Cases 2, 5 157 | If endTimestamp < _previousEndTimestamp Then ' Case 5 158 | Do While endTimestamp < _previousEndTimestamp ' Remove forward 159 | _previousEndTimestamp = _previousEndTimestamp. 160 | AddSeconds(-CalculationInterval) 161 | Me.DataStore.RemoveData(_previousEndTimestamp) 162 | Loop 163 | End If 164 | endTimestamp = _previousStartTimestamp ' Add backward 165 | _previousStartTimestamp = startTimestamp 166 | Else If endTimestamp > _previousEndTimestamp Then ' Cases 7, 9 167 | If startTimestamp > _previousStartTimestamp Then ' Case 9 168 | Do While _previousStartTimestamp < startTimestamp ' Remove backward 169 | Me.DataStore.RemoveData(_previousStartTimestamp) 170 | _previousStartTimestamp = _previousStartTimestamp. 171 | AddSeconds(CalculationInterval) 172 | Loop 173 | End If 174 | startTimestamp = _previousEndTimestamp ' Add forward 175 | _previousEndTimestamp = endTimestamp 176 | End If 177 | 178 | Try 179 | ' Retrieve all data from the data source. Will pass start and end 180 | ' timestamps. The driver can then prepare the dataset for which 181 | ' calculations are required in the next step. The (aligned) end time 182 | ' itself is excluded. 183 | PrepareData(startTimestamp, endTimestamp) 184 | Catch ex As Exception 185 | DBM.Logger.LogWarning(ex.ToString, Me.ToString) 186 | End Try 187 | 188 | Finally 189 | Monitor.Exit(_lock) ' Unblock 190 | End Try 191 | 192 | End Sub 193 | 194 | 195 | End Class 196 | 197 | 198 | End Namespace 199 | -------------------------------------------------------------------------------- /src/dbm/DBMStatisticsItem.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Math 23 | Imports Vitens.DynamicBandwidthMonitor.DBMStrings 24 | 25 | 26 | Namespace Vitens.DynamicBandwidthMonitor 27 | 28 | 29 | Public Class DBMStatisticsItem 30 | 31 | 32 | Private _count As Integer 33 | Private _mean, _nmbe, _rmsd, _cvrmsd, _slope, _originSlope, _angle, 34 | _originAngle, _intercept, _standardError, _correlation, 35 | _modifiedCorrelation, _determination As Double 36 | 37 | 38 | Public Property Count As Integer 39 | Get 40 | Return _count 41 | End Get 42 | Set(value As Integer) 43 | _count = value 44 | End Set 45 | End Property 46 | 47 | 48 | Public Property Mean As Double 49 | Get 50 | Return _mean 51 | End Get 52 | Set(value As Double) 53 | _mean = value 54 | End Set 55 | End Property 56 | 57 | 58 | Public Property NMBE As Double 59 | Get 60 | Return _nmbe 61 | End Get 62 | Set(value As Double) 63 | _nmbe = value 64 | End Set 65 | End Property 66 | 67 | 68 | Public Property RMSD As Double 69 | Get 70 | Return _rmsd 71 | End Get 72 | Set(value As Double) 73 | _rmsd = value 74 | End Set 75 | End Property 76 | 77 | 78 | Public Property CVRMSD As Double 79 | Get 80 | Return _cvrmsd 81 | End Get 82 | Set(value As Double) 83 | _cvrmsd = value 84 | End Set 85 | End Property 86 | 87 | 88 | Public Property Slope As Double 89 | Get 90 | Return _slope 91 | End Get 92 | Set(value As Double) 93 | _slope = value 94 | End Set 95 | End Property 96 | 97 | 98 | Public Property OriginSlope As Double 99 | Get 100 | Return _originSlope 101 | End Get 102 | Set(value As Double) 103 | _originSlope = value 104 | End Set 105 | End Property 106 | 107 | 108 | Public Property Angle As Double 109 | Get 110 | Return _angle 111 | End Get 112 | Set(value As Double) 113 | _angle = value 114 | End Set 115 | End Property 116 | 117 | 118 | Public Property OriginAngle As Double 119 | Get 120 | Return _originAngle 121 | End Get 122 | Set(value As Double) 123 | _originAngle = value 124 | End Set 125 | End Property 126 | 127 | 128 | Public Property Intercept As Double 129 | Get 130 | Return _intercept 131 | End Get 132 | Set(value As Double) 133 | _intercept = value 134 | End Set 135 | End Property 136 | 137 | 138 | Public Property StandardError As Double 139 | Get 140 | Return _standardError 141 | End Get 142 | Set(value As Double) 143 | _standardError = value 144 | End Set 145 | End Property 146 | 147 | 148 | Public Property Correlation As Double 149 | Get 150 | Return _correlation 151 | End Get 152 | Set(value As Double) 153 | _correlation = value 154 | End Set 155 | End Property 156 | 157 | 158 | Public Property ModifiedCorrelation As Double 159 | Get 160 | Return _modifiedCorrelation 161 | End Get 162 | Set(value As Double) 163 | _modifiedCorrelation = value 164 | End Set 165 | End Property 166 | 167 | 168 | Public Property Determination As Double 169 | Get 170 | Return _determination 171 | End Get 172 | Set(value As Double) 173 | _determination = value 174 | End Set 175 | End Property 176 | 177 | 178 | Public Function HasInsufficientData As Boolean 179 | 180 | Return Me.Count < 3 ' Need at least 3 data points. 181 | 182 | End Function 183 | 184 | 185 | Public Function Calibrated As Boolean 186 | 187 | ' ASHRAE Guideline 14-2014, Measurement of Energy, Demand, and Water 188 | ' Savings 189 | ' American Society of Heating, Refrigerating and Air Conditioning 190 | ' Engineers (ASHRAE). Handbook Fundamentals; American Society of Heating, 191 | ' Refrigerating and Air Conditioning Engineers: Atlanta, GA, USA, 2013; 192 | ' Volume 111. 193 | ' "The computer model shall have an NMBE of 5% and a CV(RMSE) of 15% 194 | ' relative to monthly calibration data. If hourly calibration data are 195 | ' used, these requirements shall be 10% and 30%, respectively." 196 | 197 | ' IPMVP, International Performance Measurement and Verification Protocol 198 | ' Efficiency Valuation Organization. International Performance Measurement 199 | ' and Verification Protocol: Concepts and Options for Determining Energy 200 | ' and Water Savings, Volume I; Technical Report; Efficiency Valuation 201 | ' Organization: Washington, DC, USA, 2012. 202 | ' "Though there is no universal standard for a minimum acceptable R² 203 | ' value, 0.75 is often considered a reasonable indicator of a good 204 | ' causal relationship amongst the energy and independent variables." 205 | 206 | Return Abs(Me.NMBE) <= 0.1 And 207 | Abs(Me.CVRMSD) <= 0.3 And 208 | Me.Determination >= 0.75 209 | 210 | End Function 211 | 212 | 213 | Public Function SystematicError As Double 214 | 215 | ' The normalized mean bias error is used as a measure of the systematic 216 | ' error. 217 | 218 | Return Me.NMBE 219 | 220 | End Function 221 | 222 | 223 | Public Function RandomError As Double 224 | 225 | ' For the random error, the difference between the absolute normalized 226 | ' mean bias error and the absolute coefficient of variation of the 227 | ' root-mean-square deviation is used. 228 | 229 | Return Abs(Me.CVRMSD)-Abs(SystematicError) 230 | 231 | End Function 232 | 233 | 234 | Public Function Fit As Double 235 | 236 | ' The determination, R², as a measure of fit. 237 | 238 | Return Me.Determination 239 | 240 | End Function 241 | 242 | 243 | Public Function Brief As String 244 | 245 | ' Model calibration metrics: systematic error, random error, and fit 246 | ' DBM can calculate model calibration metrics. This information is exposed 247 | ' in the DBMTester utility and the DBMDataRef data reference. The model is 248 | ' considered to be calibrated if all of the following conditions are met: 249 | ' * the absolute normalized mean bias error (NMBE, as a measure of bias) 250 | ' is 10% or lower, 251 | ' * the absolute coefficient of variation of the root-mean-square 252 | ' deviation (CV(RMSD), as a measure of error) is 30% or lower, 253 | ' * the determination (R², as a measure of fit) is 0.75 or higher. 254 | ' The normalized mean bias error is used as a measure of the systematic 255 | ' error. For the random error, the difference between the absolute 256 | ' normalized mean bias error and the absolute coefficient of variation of 257 | ' the root-mean-square deviation is used. 258 | ' There are several agencies that have developed guidelines and 259 | ' methodologies to establish a measure of the accuracy of models. We 260 | ' decided to follow the guidelines as documented in ASHRAE Guideline 261 | ' 14-2014, Measurement of Energy, Demand, and Water Savings, by the 262 | ' American Society of Heating, Refrigerating and Air Conditioning 263 | ' Engineers, and International Performance Measurement and Verification 264 | ' Protocol: Concepts and Options for Determining Energy and Water Savings, 265 | ' Volume I, by the Efficiency Valuation Organization. 266 | 267 | If HasInsufficientData Then Return StatisticsInsufficientData 268 | 269 | Return String.Format(StatisticsBrief, 270 | Calibrated, Me.Count, SystematicError, RandomError, Fit) 271 | 272 | End Function 273 | 274 | 275 | End Class 276 | 277 | 278 | End Namespace 279 | -------------------------------------------------------------------------------- /src/dbm/DBMStatistics.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Collections.Generic 23 | Imports System.Double 24 | Imports System.Math 25 | Imports Vitens.DynamicBandwidthMonitor.DBMMath 26 | 27 | 28 | Namespace Vitens.DynamicBandwidthMonitor 29 | 30 | 31 | Public Class DBMStatistics 32 | 33 | 34 | ' Contains statistical functions which are returned all at once on 35 | ' calling the Statistics method. 36 | 37 | 38 | Public Overloads Shared Function Statistics(dependent() As Double, 39 | Optional independent() As Double = Nothing) As DBMStatisticsItem 40 | 41 | ' Performs calculation of several statistics functions on the input 42 | ' data. If no values for the independent variable are passed, a linear 43 | ' scale starting at 0 is assumed and exponential weighting is used. 44 | ' The result of the calculation is returned as a new object. 45 | 46 | Dim i As Integer 47 | Dim weights(), totalWeight, sumX, sumY, sumXX, sumYY, sumXY As Double 48 | 49 | Statistics = New DBMStatisticsItem 50 | 51 | With Statistics 52 | 53 | If independent Is Nothing Then ' No independent var, assume linear scale 54 | ReDim independent(dependent.Length-1) 55 | For i = 0 To dependent.Length-1 56 | independent(i) = i 57 | Next i 58 | weights = ExponentialWeights(dependent.Length) ' Get weights. 59 | Else 60 | ReDim weights(dependent.Length-1) 61 | For i = 0 To dependent.Length-1 62 | weights(i) = 1 ' Linear weight. 63 | Next i 64 | End If 65 | 66 | ' Calculate sums 67 | If dependent.Length > 0 And dependent.Length = independent.Length Then 68 | 69 | ' Iteration 1: Count number of values and calculate total weight. 70 | For i = 0 To dependent.Length-1 71 | If Not IsNaN(dependent(i)) And Not IsNaN(independent(i)) Then 72 | .Count += 1 73 | totalWeight += weights(i) 74 | End If 75 | Next i 76 | 77 | ' Iteration 2: Calculate weighted statistics. 78 | For i = 0 To dependent.Length-1 79 | If Not IsNaN(dependent(i)) And Not IsNaN(independent(i)) Then 80 | weights(i) = weights(i)/totalWeight*.Count 81 | .NMBE += weights(i)*(dependent(i)-independent(i)) 82 | .RMSD += weights(i)*(dependent(i)-independent(i))^2 83 | sumX += weights(i)*independent(i) 84 | sumY += weights(i)*dependent(i) 85 | sumXX += weights(i)*independent(i)^2 86 | sumYY += weights(i)*dependent(i)^2 87 | sumXY += weights(i)*independent(i)*dependent(i) 88 | End If 89 | Next i 90 | 91 | End If 92 | 93 | If .Count = 0 Then Return Statistics ' Empty, non-eq, or no non-NaN pair 94 | 95 | .Mean = sumX/.Count ' Average 96 | 97 | ' MBE (Mean Bias Error), as its name indicates, is the average of the 98 | ' errors of a sample space. Generally, it is a good indicator of the 99 | ' overall behavior of the simulated data with regards to the regression 100 | ' line of the sample. NMBE (Normalized Mean Bias Error) is a 101 | ' normalization of the MBE index that is used to scale the results of 102 | ' MBE, making them comparable. It quantifies the MBE index by dividing 103 | ' it by the mean of measured values, giving the global difference 104 | ' between the real values and the predicted ones. 105 | .NMBE = .NMBE/.Count/.Mean 106 | 107 | ' The root-mean-square deviation (RMSD) or root-mean-square error (RMSE) 108 | ' is a frequently used measure of the differences between values (sample 109 | ' or population values) predicted by a model or an estimator and the 110 | ' values observed. The RMSD represents the square root of the second 111 | ' sample moment of the differences between predicted values and observed 112 | ' values or the quadratic mean of these differences. These deviations 113 | ' are called residuals when the calculations are performed over the data 114 | ' sample that was used for estimation and are called errors (or 115 | ' prediction errors) when computed out-of-sample. The RMSD serves to 116 | ' aggregate the magnitudes of the errors in predictions for various data 117 | ' points into a single measure of predictive power. 118 | .RMSD = Sqrt(.RMSD/.Count) 119 | 120 | ' Normalizing the RMSD facilitates the comparison between datasets or 121 | ' models with different scales. Though there is no consistent means of 122 | ' normalization in the literature, common choices are the mean or the 123 | ' range (defined as the maximum value minus the minimum value) of the 124 | ' measured data. This value is commonly referred to as the normalized 125 | ' root-mean-square deviation or error (NRMSD or NRMSE), and often 126 | ' expressed as a percentage, where lower values indicate less residual 127 | ' variance. In many cases, especially for smaller samples, the sample 128 | ' range is likely to be affected by the size of sample which would 129 | ' hamper comparisons. When normalizing by the mean value of the 130 | ' measurements, the term coefficient of variation of the RMSD, CV(RMSD) 131 | ' may be used to avoid ambiguity. This is analogous to the coefficient 132 | ' of variation with the RMSD taking the place of the standard deviation. 133 | .CVRMSD = .RMSD/.Mean 134 | 135 | .Slope = (.Count*sumXY-sumX*sumY)/(.Count*sumXX-sumX^2) ' Lin.regression 136 | .OriginSlope = sumXY/sumXX ' Lin.regression through the origin (alpha=0) 137 | .Angle = SlopeToAngle(.Slope) ' Angle in degrees 138 | .OriginAngle = SlopeToAngle(.OriginSlope) ' Angle in degrees 139 | .Intercept = (sumX*sumXY-sumY*sumXX)/(sumX^2-.Count*sumXX) 140 | 141 | ' Standard error of the predicted y-value for each x in the regression. 142 | ' The standard error is a measure of the amount of error in the 143 | ' prediction of y for an individual x. 144 | For i = 0 to dependent.Length-1 145 | If Not IsNaN(dependent(i)) And Not IsNaN(independent(i)) Then 146 | .StandardError += 147 | weights(i)*(dependent(i)-independent(i)*.Slope-.Intercept)^2 148 | End If 149 | Next i 150 | ' n-2 is used because two parameters (slope and intercept) were 151 | ' estimated in order to estimate the sum of squares. 152 | .StandardError = Sqrt(.StandardError/Max(0, .Count-2)) 153 | 154 | ' A number that quantifies some type of correlation and dependence, 155 | ' meaning statistical relationships between two or more random 156 | ' variables or observed data values. 157 | .Correlation = (.Count*sumXY-sumX*sumY)/ 158 | Sqrt((.Count*sumXX-sumX^2)*(.Count*sumYY-sumY^2)) 159 | 160 | ' Average is not removed in modified correlation as the expected average 161 | ' is zero, assuming the calculated forecasts are correct. 162 | .ModifiedCorrelation = sumXY/Sqrt(sumXX*sumYY) 163 | 164 | ' A number that indicates the proportion of the variance in the 165 | ' dependent variable that is predictable from the independent variable. 166 | .Determination = .Correlation^2 167 | 168 | End With 169 | 170 | Return Statistics 171 | 172 | End Function 173 | 174 | 175 | Public Overloads Shared Function Statistics( 176 | results As List(Of DBMResult)) As DBMStatisticsItem 177 | 178 | Dim i As Integer 179 | Dim forecasts(results.Count-1), measurements(results.Count-1) As Double 180 | 181 | For i = 0 To results.Count-1 182 | With results.Item(i).ForecastItem 183 | forecasts(i) = .Forecast 184 | measurements(i) = .Measurement 185 | End With 186 | Next i 187 | 188 | Return Statistics(forecasts, measurements) 189 | 190 | End Function 191 | 192 | 193 | End Class 194 | 195 | 196 | End Namespace 197 | -------------------------------------------------------------------------------- /src/dbm/DBM.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2023 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Collections.Generic 23 | Imports System.Globalization 24 | Imports System.Math 25 | Imports System.Threading 26 | Imports System.Threading.Thread 27 | Imports Vitens.DynamicBandwidthMonitor.DBMDate 28 | Imports Vitens.DynamicBandwidthMonitor.DBMInfo 29 | Imports Vitens.DynamicBandwidthMonitor.DBMMath 30 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 31 | Imports Vitens.DynamicBandwidthMonitor.DBMStatistics 32 | 33 | 34 | ' Assembly title 35 | 36 | 37 | 38 | Namespace Vitens.DynamicBandwidthMonitor 39 | 40 | 41 | Public Class DBM 42 | 43 | 44 | ' Water company Vitens has created a demonstration site called the Vitens 45 | ' Innovation Playground (VIP), in which new technologies and methodologies 46 | ' are developed, tested, and demonstrated. The projects conducted in the 47 | ' demonstration site can be categorized into one of four themes: energy 48 | ' optimization, real-time leak detection, online water quality monitoring, 49 | ' and customer interaction. In the real-time leak detection theme, a method 50 | ' for leak detection based on statistical demand forecasting was developed. 51 | 52 | ' Using historical demand patterns and statistical methods - such as median 53 | ' absolute deviation, linear regression, sample variance, and exponential 54 | ' moving averages - real-time values can be compared to a forecast demand 55 | ' pattern and checked to be within calculated bandwidths. The method was 56 | ' implemented in Vitens' realtime data historian, continuously comparing 57 | ' measured demand values to be within operational bounds. 58 | 59 | ' One of the advantages of this method is that it doesn't require manual 60 | ' configuration or training sets. Next to leak detection, unmeasured supply 61 | ' between areas and unscheduled plant shutdowns were also detected. The 62 | ' method was found to be such a success within the company, that it was 63 | ' implemented in an operational dashboard and is now used in day-to-day 64 | ' operations. 65 | 66 | ' Vitens is the largest drinking water company in The Netherlands. We 67 | ' deliver top quality drinking water to 5.6 million people and companies in 68 | ' the provinces Flevoland, Fryslan, Gelderland, Utrecht and Overijssel and 69 | ' some municipalities in Drenthe and Noord-Holland. Annually we deliver 350 70 | ' million m3 water with 1,400 employees, 100 water treatment works and 71 | ' 49,000 kilometres of water mains. 72 | 73 | ' One of our main focus points is using advanced water quality, quantity and 74 | ' hydraulics models to further improve and optimize our treatment and 75 | ' distribution processes. 76 | 77 | 78 | Private Shared _logger As DBMLoggerAbstract = New DBMLoggerConsole 79 | Private Shared _productShown As Boolean 80 | Private _lock As New Object ' Object for exclusive lock on critical section. 81 | Private _points As New Dictionary(Of Object, DBMPoint) 82 | 83 | 84 | Public Shared Property Logger As DBMLoggerAbstract 85 | Get 86 | Return _logger 87 | End Get 88 | Set(value As DBMLoggerAbstract) 89 | _logger = value 90 | End Set 91 | End Property 92 | 93 | 94 | Public Sub New(Optional logger As DBMLoggerAbstract = Nothing) 95 | 96 | If logger IsNot Nothing Then DBM.Logger = logger 97 | If Not _productShown Then 98 | DBM.Logger.LogInformation(Product) 99 | _productShown = True 100 | End If 101 | 102 | End Sub 103 | 104 | 105 | Private Function Point(pointDriver As DBMPointDriverAbstract) As DBMPoint 106 | 107 | ' Returns DBMPoint object from the dictionary. If dictionary does not yet 108 | ' contain object, it is added. 109 | 110 | Monitor.Enter(_lock) ' Block 111 | Try 112 | 113 | If Not _points.ContainsKey(pointDriver.Point) Then 114 | _points.Add(pointDriver.Point, New DBMPoint(pointDriver)) 115 | End If 116 | 117 | Return _points.Item(pointDriver.Point) 118 | 119 | Finally 120 | Monitor.Exit(_lock) ' Unblock 121 | End Try 122 | 123 | End Function 124 | 125 | 126 | Public Shared Function HasCorrelation(relErrCorr As Double, 127 | relErrAngle As Double) As Boolean 128 | 129 | ' If correlation with measurement and (relative) forecast errors are 130 | ' about the same size. 131 | 132 | Return relErrCorr > CorrelationThreshold And 133 | Abs(relErrAngle-SlopeToAngle(1)) <= RegressionAngleRange 134 | 135 | End Function 136 | 137 | 138 | Public Shared Function HasAnticorrelation(absErrCorr As Double, 139 | absErrAngle As Double, subtractSelf As Boolean) As Boolean 140 | 141 | ' If anticorrelation with adjacent measurement and (absolute) forecast 142 | ' errors are about the same size. 143 | 144 | Return absErrCorr < -CorrelationThreshold And 145 | Abs(absErrAngle+SlopeToAngle(1)) <= RegressionAngleRange And 146 | Not subtractSelf 147 | 148 | End Function 149 | 150 | 151 | Public Shared Function Suppress(factor As Double, 152 | absErrCorr As Double, absErrAngle As Double, 153 | relErrCorr As Double, relErrAngle As Double, 154 | subtractSelf As Boolean) As Double 155 | 156 | ' Events can be suppressed when a strong correlation is found in the 157 | ' relative forecast errors of a containing area, or if a strong 158 | ' anti-correlation is found in the absolute forecast errors of an 159 | ' adjacent area. In both cases, the direction (regression through origin) 160 | ' of the error point cloud has to be around -45 or +45 degrees to indicate 161 | ' that both errors are about the same (absolute) size. 162 | 163 | If HasCorrelation(relErrCorr, relErrAngle) Or 164 | HasAnticorrelation(absErrCorr, absErrAngle, subtractSelf) Then 165 | Return 0 166 | Else 167 | Return factor 168 | End If 169 | 170 | End Function 171 | 172 | 173 | Public Function GetResult(inputPointDriver As DBMPointDriverAbstract, 174 | correlationPoints As List(Of DBMCorrelationPoint), timestamp As DateTime, 175 | Optional culture As CultureInfo = Nothing) As DBMResult 176 | 177 | ' This is the main function to call to calculate a result for a specific 178 | ' timestamp. If a list of DBMCorrelationPoints is passed, events can be 179 | ' suppressed if a strong correlation is found. 180 | 181 | Return GetResults(inputPointDriver, correlationPoints, 182 | timestamp, NextInterval(timestamp), 1, culture)(0) 183 | 184 | End Function 185 | 186 | 187 | Public Function GetResults(inputPointDriver As DBMPointDriverAbstract, 188 | correlationPoints As List(Of DBMCorrelationPoint), 189 | startTimestamp As DateTime, endTimestamp As DateTime, 190 | Optional numberOfValues As Integer = 0, 191 | Optional culture As CultureInfo = Nothing) As List(Of DBMResult) 192 | 193 | ' This is the main function to call to calculate results for a time range. 194 | ' The end timestamp is exclusive. If a list of DBMCorrelationPoints is 195 | ' passed, events can be suppressed if a strong correlation is found. 196 | 197 | Dim offset As Integer = EMATimeOffset(EMAPreviousPeriods+1) 198 | Dim result As DBMResult 199 | Dim correlationPoint As DBMCorrelationPoint 200 | Dim correlationResult As DBMResult 201 | Dim absoluteErrorStatsItem, 202 | relativeErrorStatsItem As New DBMStatisticsItem 203 | 204 | If correlationPoints Is Nothing Then ' Empty list if Nothing was passed. 205 | correlationPoints = New List(Of DBMCorrelationPoint) 206 | End If 207 | 208 | ' Shift the start and end timestamps into the future using the negative 209 | ' EMA time offset. Then later on, shift the resulting timestamps back to 210 | ' the original value. 211 | startTimestamp = startTimestamp.AddSeconds(-offset) 212 | endTimestamp = endTimestamp.AddSeconds(-offset) 213 | 214 | ' Use culture used by the current thread if no culture was passed. 215 | If culture Is Nothing Then culture = CurrentThread.CurrentCulture 216 | 217 | ' Calculate results for input point. 218 | GetResults = Point(inputPointDriver).GetResults(startTimestamp, 219 | endTimestamp, numberOfValues, True, correlationPoints.Count > 0, 220 | Nothing, culture) 221 | 222 | If correlationPoints.Count > 0 Then ' If correlation points are available. 223 | 224 | For Each result In GetResults ' Iterate over results for time range. 225 | 226 | With result 227 | 228 | If Abs(.Factor) > 0 Then ' If there is an event for this result. 229 | 230 | For Each correlationPoint In correlationPoints ' Iterate over pts. 231 | 232 | If Abs(.Factor) > 0 Then ' Keep going while event not suppressed 233 | 234 | ' Calculate result for correlation point. We call the 235 | ' GetResults method for the entire remaining time range (but 236 | ' only request a single result), so that we already have all 237 | ' required data for any next intervals we might need this for 238 | ' (Case 3 instead of Case 9). 239 | If correlationPoint.SubtractSelf Then 240 | correlationResult = Point(correlationPoint.PointDriver). 241 | GetResults(.Timestamp, endTimestamp, 1, False, True, 242 | Point(inputPointDriver), culture)(0) ' Subtract input. 243 | Else 244 | correlationResult = Point(correlationPoint.PointDriver). 245 | GetResults(.Timestamp, endTimestamp, 1, False, True, 246 | Nothing, culture)(0) 247 | End If 248 | 249 | ' Calculate statistics of errors compared to forecast. 250 | absoluteErrorStatsItem = Statistics( 251 | correlationResult.GetAbsoluteErrors, .GetAbsoluteErrors) 252 | relativeErrorStatsItem = Statistics( 253 | correlationResult.GetRelativeErrors, .GetRelativeErrors) 254 | 255 | ' Suppress if not local event. 256 | .Factor = Suppress(.Factor, 257 | absoluteErrorStatsItem.ModifiedCorrelation, 258 | absoluteErrorStatsItem.OriginAngle, 259 | relativeErrorStatsItem.ModifiedCorrelation, 260 | relativeErrorStatsItem.OriginAngle, 261 | correlationPoint.SubtractSelf) 262 | 263 | End If 264 | 265 | Next correlationPoint 266 | 267 | End If 268 | 269 | End With 270 | 271 | Next result 272 | 273 | End If 274 | 275 | ' Shift the resulting timestamps back to the original value since they 276 | ' were moved into the future before to compensate for exponential moving 277 | ' average (EMA) time shifting. 278 | For Each result In GetResults 279 | result.Timestamp = result.Timestamp.AddSeconds(offset) 280 | Next result 281 | 282 | Return GetResults 283 | 284 | End Function 285 | 286 | 287 | End Class 288 | 289 | 290 | End Namespace 291 | -------------------------------------------------------------------------------- /src/dbm/DBMMath.vb: -------------------------------------------------------------------------------- 1 | ' Dynamic Bandwidth Monitor 2 | ' Leak detection method implemented in a real-time data historian 3 | ' Copyright (C) 2014-2022 J.H. Fitié, Vitens N.V. 4 | ' 5 | ' This file is part of DBM. 6 | ' 7 | ' DBM is free software: you can redistribute it and/or modify 8 | ' it under the terms of the GNU General Public License as published by 9 | ' the Free Software Foundation, either version 3 of the License, or 10 | ' (at your option) any later version. 11 | ' 12 | ' DBM is distributed in the hope that it will be useful, 13 | ' but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ' GNU General Public License for more details. 16 | ' 17 | ' You should have received a copy of the GNU General Public License 18 | ' along with DBM. If not, see . 19 | 20 | 21 | Imports System 22 | Imports System.Double 23 | Imports System.Math 24 | Imports Vitens.DynamicBandwidthMonitor.DBMParameters 25 | 26 | 27 | Namespace Vitens.DynamicBandwidthMonitor 28 | 29 | 30 | Public Class DBMMath 31 | 32 | 33 | ' Contains mathematical and statistical functions. 34 | 35 | 36 | Public Shared Function NormSInv(p As Double) As Double 37 | 38 | ' Returns the inverse of the standard normal cumulative distribution. 39 | ' The distribution has a mean of zero and a standard deviation of one. 40 | ' Approximation of inverse standard normal CDF developed by 41 | ' Peter J. Acklam 42 | 43 | Dim q, r As Double 44 | Dim f As Integer 45 | 46 | If p < 0.02425 Then ' Left tail 47 | q = Sqrt(-2*Log(p)) 48 | f = 1 49 | ElseIf p <= 0.97575 Then 50 | q = p-0.5 51 | r = q*q 52 | Return (((((-3.96968302866538E+01*r+2.20946098424521E+02)*r- 53 | 2.75928510446969E+02)*r+1.38357751867269E+02)*r-3.06647980661472E+01)* 54 | r+2.50662827745924)*q/(((((-5.44760987982241E+01*r+ 55 | 1.61585836858041E+02)*r-1.55698979859887E+02)*r+6.68013118877197E+01)* 56 | r-1.32806815528857E+01)*r+1) 57 | Else ' Right tail 58 | q = Sqrt(-2*Log(1-p)) 59 | f = -1 60 | End If 61 | 62 | Return f*(((((-7.78489400243029E-03*q-3.22396458041136E-01)*q- 63 | 2.40075827716184)*q-2.54973253934373)*q+4.37466414146497)*q+ 64 | 2.93816398269878)/((((7.78469570904146E-03*q+3.2246712907004E-01)*q+ 65 | 2.445134137143)*q+3.75440866190742)*q+1) 66 | 67 | End Function 68 | 69 | 70 | Public Shared Function TInv2T(p As Double, dof As Integer) As Double 71 | 72 | ' Returns the two-tailed inverse of the Student's t-distribution. 73 | ' Hill's approx. inverse t-dist.: Comm. of A.C.M Vol.13 No.10 1970 pg 620 74 | 75 | Dim a, b, c, d, x, y As Double 76 | 77 | If dof = 1 Then 78 | p *= PI/2 79 | Return Cos(p)/Sin(p) 80 | ElseIf dof = 2 Then 81 | Return Sqrt(2/(p*(2-p))-2) 82 | Else 83 | a = 1/(dof-0.5) 84 | b = 48/(a^2) 85 | c = ((20700*a/b-98)*a-16)*a+96.36 86 | d = ((94.5/(b+c)-3)/b+1)*Sqrt(a*PI/2)*dof 87 | x = d*p 88 | y = x^(2/dof) 89 | If y > a+0.05 Then 90 | x = NormSInv(p/2) 91 | y = x^2 92 | If dof < 5 Then 93 | c += 0.3*(dof-4.5)*(x+0.6) 94 | End If 95 | c = (((d/2*x-0.5)*x-7)*x-2)*x+b+c 96 | y = (((((0.4*y+6.3)*y+36)*y+94.5)/c-y-3)/b+1)*x 97 | y = Exp(a*y^2)-1 98 | Else 99 | y = ((1/(((dof+6)/(dof*y)-0.089*d-0.822)*(dof+2)*3)+0.5/(dof+4))*y-1)* 100 | (dof+1)/(dof+2)+1/y 101 | End If 102 | Return Sqrt(dof*y) 103 | End If 104 | 105 | End Function 106 | 107 | 108 | Public Shared Function TInv(p As Double, dof As Integer) As Double 109 | 110 | ' Returns the left-tailed inverse of the Student's t-distribution. 111 | 112 | Return Sign(p-0.5)*TInv2T(1-Abs(p-0.5)*2, dof) 113 | 114 | End Function 115 | 116 | 117 | Public Shared Function MeanAbsoluteDeviationScaleFactor As Double 118 | 119 | ' Estimator; scale factor k 120 | ' For normally distributed data, multiply MAD by scale factor k to 121 | ' obtain an estimate of the normal scale parameter sigma. 122 | ' R.C. Geary. The Ratio of the Mean Deviation to the Standard Deviation 123 | ' as a Test of Normality. Biometrika, 1935. Cited on page 8. 124 | 125 | Return Sqrt(PI/2) 126 | 127 | End Function 128 | 129 | 130 | Public Shared Function MedianAbsoluteDeviationScaleFactor( 131 | n As Integer) As Double ' Estimator; scale factor k 132 | 133 | ' k is a constant scale factor, which depends on the distribution. 134 | ' For a symmetric distribution with zero mean, the population MAD is the 135 | ' 75th percentile of the distribution. 136 | ' Huber, P. J. (1981). Robust statistics. New York: John Wiley. 137 | 138 | If n < 30 Then 139 | Return 1/TInv(0.75, n) ' n < 30 Student's t-distribution 140 | Else 141 | Return 1/NormSInv(0.75) ' n >= 30 Standard normal distribution 142 | End If 143 | 144 | End Function 145 | 146 | 147 | Public Shared Function ControlLimitRejectionCriterion(p As Double, 148 | n As Integer) As Double 149 | 150 | ' Return two-sided critical z-values for confidence interval p. 151 | ' Student's t-distribution approaches the normal z distribution at 152 | ' 30 samples. 153 | ' Student. 1908. Probable error of a correlation 154 | ' coefficient. Biometrika 6, 2-3, 302–310. 155 | ' Hogg and Tanis' Probability and Statistical Inference (7e). 156 | 157 | If n < 30 Then 158 | Return TInv((p+1)/2, n) ' n < 30 Student's t-distribution 159 | Else 160 | Return NormSInv((p+1)/2) ' n >= 30 Standard normal distribution 161 | End If 162 | 163 | End Function 164 | 165 | 166 | Public Shared Function NonNaNCount(values() As Double) As Integer 167 | 168 | ' Returns number of values in the array excluding NaNs. 169 | 170 | Dim value As Double 171 | Dim count As Integer 172 | 173 | For Each value In values 174 | If Not IsNaN(value) Then 175 | count += 1 176 | End If 177 | Next 178 | 179 | Return count 180 | 181 | End Function 182 | 183 | 184 | Public Shared Function Mean(values() As Double) As Double 185 | 186 | ' Returns the arithmetic mean; the sum of the sampled values divided 187 | ' by the number of items in the sample. NaNs are excluded. 188 | 189 | Dim value, sum As Double 190 | Dim count As Integer 191 | 192 | For Each value In values 193 | If Not IsNaN(value) Then 194 | sum += value 195 | count += 1 196 | End If 197 | Next 198 | 199 | Return sum/count 200 | 201 | End Function 202 | 203 | 204 | Public Shared Function Median(values() As Double) As Double 205 | 206 | ' The median is the value separating the higher half of a data sample, 207 | ' a population, or a probability distribution, from the lower half. In 208 | ' simple terms, it may be thought of as the "middle" value of a data set. 209 | ' NaNs are excluded. 210 | 211 | Dim medianValues(NonNaNCount(values)-1), Value As Double 212 | Dim count As Integer 213 | 214 | If medianValues.Length = 0 Then Return NaN ' No non-NaN values. 215 | 216 | For Each Value In values 217 | If Not IsNaN(Value) Then 218 | medianValues(count) = Value 219 | count += 1 220 | End If 221 | Next 222 | 223 | Array.Sort(medianValues) 224 | 225 | If medianValues.Length Mod 2 = 0 Then 226 | Return (medianValues(medianValues.Length\2)+ 227 | medianValues(medianValues.Length\2-1))/2 228 | Else 229 | Return medianValues(medianValues.Length\2) 230 | End If 231 | 232 | End Function 233 | 234 | 235 | Public Shared Function StDevP(values() As Double) As Double 236 | 237 | ' In statistics, the standard deviation is a measure of the amount of 238 | ' variation or dispersion of a set of values. A low standard deviation 239 | ' indicates that the values tend to be close to the mean (also called the 240 | ' expected value) of the set, while a high standard deviation indicates 241 | ' that the values are spread out over a wider range. 242 | 243 | Dim meanValues, value As Double 244 | Dim count As Integer 245 | 246 | meanValues = Mean(values) 247 | 248 | For Each value In values 249 | If Not IsNaN(value) Then 250 | StDevP += (value-meanValues)^2 251 | count += 1 252 | End If 253 | Next 254 | StDevP /= count 255 | StDevP = Sqrt(StDevP) 256 | 257 | Return StDevP 258 | 259 | End Function 260 | 261 | 262 | Public Shared Function AbsoluteDeviation(values() As Double, 263 | from As Double) As Double() 264 | 265 | ' Returns an array which contains the absolute values of the input 266 | ' array from which the central tendency has been subtracted. 267 | 268 | Dim i As Integer 269 | Dim absDev(values.Length-1) As Double 270 | 271 | For i = 0 to values.Length-1 272 | absDev(i) = Abs(values(i)-from) 273 | Next i 274 | 275 | Return absDev 276 | 277 | End Function 278 | 279 | 280 | Public Shared Function MeanAbsoluteDeviation(values() As Double) As Double 281 | 282 | ' The mean absolute deviation (MAD) of a set of data 283 | ' is the average distance between each data value and the mean. 284 | 285 | Return Mean(AbsoluteDeviation(values, Mean(values))) 286 | 287 | End Function 288 | 289 | 290 | Public Shared Function MedianAbsoluteDeviation(values() As Double) As Double 291 | 292 | ' The median absolute deviation (MAD) is a robust measure of the 293 | ' variability of a univariate sample of quantitative data. 294 | 295 | Return Median(AbsoluteDeviation(values, Median(values))) 296 | 297 | End Function 298 | 299 | 300 | Public Shared Function UseMeanAbsoluteDeviation( 301 | values() As Double) As Boolean 302 | 303 | ' Returns true if the Mean Absolute Deviation has to be used instead of 304 | ' the Median Absolute Deviation to detect outliers. Median absolute 305 | ' deviation has a 50% breakdown point. 306 | 307 | Return MedianAbsoluteDeviation(values) = 0 308 | 309 | End Function 310 | 311 | 312 | Public Shared Function CentralTendency(values() As Double) As Double 313 | 314 | ' Returns the central tendency for the data series, based on either the 315 | ' mean or median absolute deviation. In statistics, a central tendency 316 | ' (or measure of central tendency) is a central or typical value for a 317 | ' probability distribution. 318 | 319 | If UseMeanAbsoluteDeviation(values) Then 320 | Return Mean(values) 321 | Else 322 | Return Median(values) 323 | End If 324 | 325 | End Function 326 | 327 | 328 | Public Shared Function ControlLimit(values() As Double, 329 | p As Double) As Double 330 | 331 | ' Returns the control limits for the data series, based on either the 332 | ' mean or median absolute deviation, scale factor and rejection criterion. 333 | ' Control limits are used to detect signals in process data that indicate 334 | ' that a process is not in control and, therefore, not operating 335 | ' predictably. 336 | 337 | Dim Count As Integer = NonNaNCount(values) 338 | 339 | If UseMeanAbsoluteDeviation(values) Then 340 | Return MeanAbsoluteDeviation(values)* 341 | MeanAbsoluteDeviationScaleFactor* 342 | ControlLimitRejectionCriterion(p, Count-1) 343 | Else 344 | Return MedianAbsoluteDeviation(values)* 345 | MedianAbsoluteDeviationScaleFactor(Count-1)* 346 | ControlLimitRejectionCriterion(p, Count-1) 347 | End If 348 | 349 | End Function 350 | 351 | 352 | Public Shared Function RemoveOutliers(values() As Double) As Double() 353 | 354 | ' Returns an array which contains the input data from which outliers 355 | ' are filtered (replaced with NaNs) using either the mean or median 356 | ' absolute deviation function. 357 | 358 | Dim valuesCentralTendency, valuesControlLimit, 359 | filteredValues(values.Length-1) As Double 360 | Dim i As Integer 361 | 362 | valuesCentralTendency = CentralTendency(values) 363 | valuesControlLimit = ControlLimit(values, OutlierCI) 364 | 365 | For i = 0 to values.Length-1 366 | If Abs(values(i)-valuesCentralTendency) > valuesControlLimit Then 367 | filteredValues(i) = NaN ' Filter outlier 368 | Else 369 | filteredValues(i) = values(i) ' Keep inlier 370 | End If 371 | Next i 372 | 373 | Return filteredValues 374 | 375 | End Function 376 | 377 | 378 | Public Shared Function ExponentialWeights(count As Integer) As Double() 379 | 380 | Dim alpha, weight, weights(count-1), totalWeight As Double 381 | Dim i As Integer 382 | 383 | alpha = 2/(count+1) ' Smoothing factor 384 | weight = 1 ' Initial weight 385 | 386 | For i = 0 To count-1 387 | weights(i) = weight 388 | totalWeight += weight 389 | weight /= 1-alpha ' Increase weight 390 | Next i 391 | 392 | For i = 0 To count-1 393 | weights(i) /= totalWeight ' Normalise weights 394 | Next i 395 | 396 | Return weights 397 | 398 | End Function 399 | 400 | 401 | Public Shared Function ExponentialMovingAverage( 402 | values() As Double) As Double 403 | 404 | ' Filter high frequency variation 405 | ' An exponential moving average (EMA), is a type of infinite impulse 406 | ' response filter that applies weighting factors which increase 407 | ' exponentially. 408 | 409 | Dim i As Integer 410 | Dim weights() As Double = ExponentialWeights(values.Length) 411 | Dim totalWeight As Double 412 | 413 | For i = 0 To values.Length-1 414 | If Not IsNaN(values(i)) Then ' Exclude NaN values. 415 | ExponentialMovingAverage += values(i)*weights(i) 416 | totalWeight += weights(i) ' Used to correct for NaN values. 417 | End If 418 | Next i 419 | 420 | ' Return NaN if there are no non-NaN values, or if the most recent value 421 | ' is NaN. 422 | If totalWeight = 0 Or IsNaN(values(values.Length-1)) Then Return NaN 423 | 424 | ExponentialMovingAverage /= totalWeight 425 | 426 | Return ExponentialMovingAverage 427 | 428 | End Function 429 | 430 | 431 | Public Shared Function SlopeToAngle(slope As Double) As Double 432 | 433 | ' Returns angle in degrees for Slope. 434 | 435 | Return Atan(slope)/(2*PI)*360 436 | 437 | End Function 438 | 439 | 440 | Public Shared Function Lerp(v0 As Double, v1 As Double, 441 | t As Double) As Double 442 | 443 | ' In mathematics, linear interpolation is a method of curve fitting using 444 | ' linear polynomials to construct new data points within the range of a 445 | ' discrete set of known data points. 446 | 447 | ' Imprecise method, which does not guarantee v = v1 when t = 1, due to 448 | ' floating-point arithmetic error. This method is monotonic. This form may 449 | ' be used when the hardware has a native fused multiply-add instruction. 450 | 'Return v0+t*(v1-v0) 451 | 452 | ' Precise method, which guarantees v = v1 when t = 1. This method is 453 | ' monotonic only when v0 * v1 < 0. Lerping between same values might not 454 | ' produce the same value 455 | Return (1-t)*v0+t*v1 456 | 457 | End Function 458 | 459 | 460 | End Class 461 | 462 | 463 | End Namespace 464 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Logo](img/dbmlogo.png) 2 | 3 | # DBM 4 | Dynamic Bandwidth Monitor\ 5 | Leak detection method implemented in a real-time data historian\ 6 | Copyright (C) 2014-2024 J.H. Fitié, Vitens N.V. 7 | 8 | ## Description 9 | Water company Vitens has created a demonstration site called the Vitens Innovation Playground (VIP), in which new technologies and methodologies are developed, tested, and demonstrated. The projects conducted in the demonstration site can be categorized into one of four themes: energy optimization, real-time leak detection, online water quality monitoring, and customer interaction. In the real-time leak detection theme, a method for leak detection based on statistical demand forecasting was developed. 10 | 11 | Using historical demand patterns and statistical methods - such as median absolute deviation, linear regression, sample variance, and exponential moving averages - real-time values can be compared to a forecast demand pattern and checked to be within calculated bandwidths. The method was implemented in Vitens' realtime data historian, continuously comparing measured demand values to be within operational bounds. 12 | 13 | One of the advantages of this method is that it doesn't require manual configuration or training sets. Next to leak detection, unmeasured supply between areas and unscheduled plant shutdowns were also detected. The method was found to be such a success within the company, that it was implemented in an operational dashboard and is now used in day-to-day operations. 14 | 15 | ### Keywords 16 | Real-time, leak detection, demand forecasting, demand patterns, operational dashboard 17 | 18 | ## Samples 19 | 20 | ### Sample 1 - Forecast 21 | ![Sample 1](img/sample1.png) 22 | 23 | In this example, two days before and after the current day are shown. For historic values, the measured data (black) is shown along with the forecast value (red). The upper and lower control limits (gray) were not crossed, so the DBM factor value (blue) equals zero. For future values, the forecast is shown along with the upper and lower control limits. Reliable forecasts can be made for at least seven days in advance. 24 | 25 | ### Sample 2 - Event 26 | ![Sample 2](img/sample2.png) 27 | 28 | In this example, an event causes the measured value (black) to cross the upper control limit (gray). The DBM factor value (blue) is greater than one during this time (calculated as _(measured value - forecast value)/(upper control limit - forecast value)_). 29 | 30 | ### Sample 3 - Suppressed event (correlation) 31 | ![Sample 3a](img/sample3a.png) 32 | ![Sample 3b](img/sample3b.png) 33 | 34 | In this example, an event causes the measured value (black) to cross the upper and lower control limits (gray). Because the pattern is checked against a similar pattern which has a comparable relative forecast error (calculated as _(forecast value / measured value) - 1_), the event is suppressed. The DBM factor value is reset to zero during this time. 35 | 36 | ### Sample 4 - Suppressed event (anticorrelation) 37 | ![Sample 4a](img/sample4a.png) 38 | ![Sample 4b](img/sample4b.png) 39 | 40 | In this example, an event causes the measured value (black) to cross the lower control limit (gray). Because the pattern is checked against a similar, adjacent, pattern which has a comparable, but inverted, absolute forecast error (calculated as _forecast value - measured value_), the event is suppressed. The DBM factor value is reset to zero during this time. 41 | 42 | ## Program information 43 | 44 | ### Requirements 45 | | Priority | Requirement | Version | 46 | | --------- | ------------------------------------------------------------- | ---------- | 47 | | Mandatory | Microsoft .NET Framework | 4.0.30319 | 48 | | Optional | AVEVA PI Asset Framework Software Development Kit (PI AF SDK) | 2.10.7.283 | 49 | 50 | ### Drivers 51 | DBM uses drivers to read information from a source of data. The following drivers are included: 52 | 53 | | Driver | Description | Identifier (`Point`) | Remarks | 54 | | ---------------------------- | --------------------------------------- | ------------------------------------------------ | ---------------------------------------------------------------------- | 55 | | `DBMPointDriverCSV.vb` | Driver for CSV files (timestamp,value). | `String` (CSV filename) | Data interval must be the same as the `CalculationInterval` parameter. | 56 | | `DBMPointDriverAVEVAPIAF.vb` | Driver for AVEVA PI Asset Framework. | `OSIsoft.AF.Asset.AFAttribute` (PI AF attribute) | Used by PI AF Data Reference `DBMDataRef`. | 57 | 58 | ### Parameters 59 | DBM can be configured using several parameters. The values for these parameters can be changed at runtime in the `Vitens.DynamicBandwidthMonitor.DBMParameters` class. 60 | 61 | | Parameter | Default value | Units | Description | 62 | | ---------------------------- | ------------- | ------------- | ----------------------------------------------------------------------------------------------------- | 63 | | `CalculationInterval` | 300 | seconds | Time interval at which the calculation is run. | 64 | | `UseSundayForHolidays` | True | | Use forecast of the previous Sunday for holidays. | 65 | | `ComparePatterns` | 12 | weeks | Number of weeks to look back to forecast the current value and control limits. | 66 | | `EMAPreviousPeriods` | 5 | intervals | Number of previous intervals used to smooth the data. | 67 | | `OutlierCI` | 0.99 | ratio | Confidence interval used for removing outliers. | 68 | | `BandwidthCI` | 0.99 | ratio | Confidence interval used for determining control limits. | 69 | | `CorrelationPreviousPeriods` | 23 | intervals | Number of previous intervals used to calculate forecast error correlation when an event is found. | 70 | | `CorrelationThreshold` | 0.83666 | dimensionless | Absolute correlation lower limit for detecting (anti)correlation. | 71 | | `RegressionAngleRange` | 18.435 | degrees | Regression angle range (around -45/+45 degrees) required when suppressing based on (anti)correlation. | 72 | 73 | ### DBMTester 74 | DBMTester is a command line utility that can be used to quickly calculate DBM results using the CSV driver. The following arguments are available: 75 | 76 | | Argument | Count | Description | 77 | | -------- | ------ | --------------------------------------------------------------------------------- | 78 | | `-i=` | 1 | Specifies the input point (CSV file). | 79 | | `-c=` | 0..n | Adds a correlation point (CSV file). | 80 | | `-cs=` | 0..n | Adds a correlation point (CSV file) from which the input point is subtracted. | 81 | | `-iv=` | 0..1 | Changes the `CalculationInterval` parameter. | 82 | | `-us=` | 0..1 | Changes the `UseSundayForHolidays` parameter. | 83 | | `-p=` | 0..1 | Changes the `ComparePatterns` parameter. | 84 | | `-ep=` | 0..1 | Changes the `EMAPreviousPeriods` parameter. | 85 | | `-oi=` | 0..1 | Changes the `OutlierCI` parameter. | 86 | | `-bi=` | 0..1 | Changes the `BandwidthCI` parameter. | 87 | | `-cp=` | 0..1 | Changes the `CorrelationPreviousPeriods` parameter. | 88 | | `-ct=` | 0..1 | Changes the `CorrelationThreshold` parameter. | 89 | | `-ra=` | 0..1 | Changes the `RegressionAngleRange` parameter. | 90 | | `-st=` | 1 | Start timestamp for calculations. | 91 | | `-et=` | 0..1 | End timestamp for calculations, all intervals in between are calculated. | 92 | | `-f=` | 0..1 | Output format. Default for local formatting, `intl` for international formatting. | 93 | 94 | ### DBMDataRef 95 | DBMDataRef is a custom AVEVA PI Asset Framework data reference which integrates DBM with PI AF. The `register.bat` script automatically registers the data reference and support assemblies when run on the PI AF server. The data reference uses the parent attribute as input and automatically uses attributes from sibling and parent elements based on the same template containing good data for correlation calculations, unless the `NoCorrelation` category is applied to the output attribute. The value returned from the DBM calculation is determined by the applied property/trait: 96 | 97 | | Property/trait | Return value | Description | 98 | | -------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------- | 99 | | None | Factor | | 100 | | `Target` | Measured value, forecast if not available | Indicates the aimed-for measurement value or process output. | 101 | | `Forecast` | Forecast value | | 102 | | `Minimum` | Lower control limit (p = 0.9999) | Indicates the very lowest possible measurement value or process output. | 103 | | `LoLo` | Lower control limit (default) | Indicates a very low measurement value or process output, typically an abnormal one that initiates an alarm. | 104 | | `Lo` | Lower control limit (p = 0.95) | Indicates a low measurement value or process output, typically one that initiates a warning. | 105 | | `Hi` | Upper control limit (p = 0.95) | Indicates a high measurement value or process output, typically one that initiates a warning. | 106 | | `HiHi` | Upper control limit (default) | Indicates a very high measurement value or process output, typically an abnormal one that initiates an alarm. | 107 | | `Maximum` | Upper control limit (p = 0.9999) | Indicates the very highest possible measurement value or process output. | 108 | 109 | The `Target` trait returns the original, valid raw measurements, augmented with forecast data for invalid and future data. Data quality is marked as `Substituted` for invalid data replaced by forecast values and for future forecast values, or as `Questionable` for data exceeding `Minimum` and `Maximum` control limits. 110 | ![Augmented](img/augmented.png) 111 | 112 | For the `Target` trait, DBM also detects and removes incorrect flatlines in the data and, if a reliable forecast can be made, replaces them with forecast values, which are then weight adjusted to the original time range total. Data quality is marked as `Substituted` for this data. 113 | 114 | Beginning with PI AF 2018 SP3 Patch 2, all AF plugins must be signed with a valid certificate. Users must ensure any 3rd party or custom plugins are signed with a valid certificate. Digitally signing plugins increases the users' confidence that it is from a trusted entity. AF data references that are not signed could have been tampered with and are potentially dangerous. Therefore, in order to protect its users, AVEVA software enforces that all AF 2.x data reference plugins be signed. Use `sign.bat` to sign the data reference and support assemblies with your pfx certificate file before registering the data reference with PI AF. 115 | 116 | ### Model calibration metrics: systematic error, random error, and fit 117 | DBM can calculate model calibration metrics. This information is exposed in the DBMTester utility and the DBMDataRef data reference. The model is considered to be calibrated if all of the following conditions are met: 118 | 119 | * the absolute normalized mean bias error (NMBE, as a measure of bias) is 10% or lower, 120 | * the absolute coefficient of variation of the root-mean-square deviation (CV(RMSD), as a measure of error) is 30% or lower, 121 | * the determination (R², as a measure of fit) is 0.75 or higher. 122 | 123 | The normalized mean bias error is used as a measure of the systematic error. For the random error, the difference between the absolute normalized mean bias error and the absolute coefficient of variation of the root-mean-square deviation is used. 124 | 125 | There are several agencies that have developed guidelines and methodologies to establish a measure of the accuracy of models. We decided to follow the guidelines as documented in _ASHRAE Guideline 14-2014, Measurement of Energy, Demand, and Water Savings_, by the American Society of Heating, Refrigerating and Air Conditioning Engineers, and _International Performance Measurement and Verification Protocol: Concepts and Options for Determining Energy and Water Savings, Volume I_, by the Efficiency Valuation Organization. 126 | 127 | An example of the model calibration metrics:\ 128 | `Calibrated: True (n 2016; Systematic error 2.2%; Random error 4.2%; Fit 97.9%)` 129 | 130 | ### License 131 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 132 | 133 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 134 | 135 | You should have received a copy of the GNU General Public License along with this program. If not, see . 136 | 137 | ## About Vitens 138 | Vitens is the largest drinking water company in The Netherlands. We deliver top quality drinking water to 5.7 million people and companies in the provinces Flevoland, Fryslan, Gelderland, Utrecht and Overijssel and some municipalities in Drenthe and Noord-Holland. Annually we deliver 350 million m3 water with 1,400 employees, 100 water treatment works and 50,000 kilometres of water mains. 139 | 140 | One of our main focus points is using advanced water quality, quantity and hydraulics models to further improve and optimize our treatment and distribution processes. 141 | 142 | ![Vitens](img/vitens.png) 143 | 144 | https://www.vitens.nl/ 145 | 146 | ## About AVEVA 147 | AVEVA, the AVEVA logo and logotype, OSIsoft, the OSIsoft logo and logotype, Managed PI, OSIsoft Advanced Services, OSIsoft Cloud Services, OSIsoft Connected Services, OSIsoft EDS, PI ACE, PI Advanced Computing Engine, PI AF SDK, PI API, PI Asset Framework, PI Audit Viewer, PI Builder, PI Cloud Connect, PI Connectors, PI Data Archive, PI DataLink, PI DataLink Server, PI Developers Club, PI Integrator for Business Analytics, PI Interfaces, PI JDBC Driver, PI Manual Logger, PI Notifications, PI ODBC Driver, PI OLEDB Enterprise, PI OLEDB Provider, PI OPC DA Server, PI OPC HDA Server, PI ProcessBook, PI SDK, PI Server, PI Square, PI System, PI System Access, PI Vision, PI Visualization Suite, PI Web API, PI WebParts, PI Web Services, RLINK, and RtReports are all trademarks of AVEVA Group plc or its subsidiaries. 148 | 149 | ![AVEVA](img/aveva.png) 150 | 151 | https://www.aveva.com/ 152 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------