private double CalculateSignalToNoise(List <double> values, Guid key) { int sampleCount = values.Count; int keyIndex = InputMeasurementKeys.IndexOf(item => item.SignalID == key); SignalType keySignalType = InputMeasurementKeyTypes[keyIndex]; // If its a Phase if ((keySignalType == SignalType.IPHA || keySignalType == SignalType.VPHA) && sampleCount == m_refWindow.Count && Reference != null) { values = Angle.Unwrap(values.Select((item, index) => item - (Angle)m_refWindow[index]).ToArray()).Select(item => (double)item).ToList(); } values = values.Where(item => !double.IsNaN(item)).ToList(); sampleCount = values.Count; if (sampleCount < 1) { return(double.NaN); } double sampleAverage = values.Average(); double totalVariance = values.Select(item => item - sampleAverage).Select(deviation => deviation * deviation).Sum(); double result = 10 * Math.Log10(Math.Abs(sampleAverage / Math.Sqrt(totalVariance / sampleCount))); return(double.IsInfinity(result) ? double.NaN : result); }
/// <summary> /// Gets measurement record, creating it if needed. /// </summary> /// <param name="instance">Target <see cref="IIndependentAdapterManager"/> instance.</param> /// <param name="currentDeviceID">Device ID associated with current adapter, or zero if none.</param> /// <param name="pointTag">Point tag of measurement.</param> /// <param name="alternateTag">Alternate tag of measurement.</param> /// <param name="signalReference">Signal reference of measurement.</param> /// <param name="description">Description of measurement.</param> /// <param name="signalType">Signal type of measurement.</param> /// <param name="targetHistorianAcronym">Acronym of target historian for measurement.</param> /// <returns>Measurement record.</returns> public static MeasurementRecord GetMeasurementRecord(this IIndependentAdapterManager instance, int currentDeviceID, string pointTag, string alternateTag, string signalReference, string description, SignalType signalType = SignalType.CALC, string targetHistorianAcronym = "PPA") { // Open database connection as defined in configuration file "systemSettings" category using (AdoDataConnection connection = instance.GetConfiguredConnection()) { TableOperations <DeviceRecord> deviceTable = new TableOperations <DeviceRecord>(connection); TableOperations <MeasurementRecord> measurementTable = new TableOperations <MeasurementRecord>(connection); TableOperations <HistorianRecord> historianTable = new TableOperations <HistorianRecord>(connection); TableOperations <SignalTypeRecord> signalTypeTable = new TableOperations <SignalTypeRecord>(connection); // Lookup target device ID int?deviceID = currentDeviceID > 0 ? currentDeviceID : deviceTable.QueryRecordWhere("Acronym = {0}", instance.Name)?.ID; // Lookup target historian ID int?historianID = historianTable.QueryRecordWhere("Acronym = {0}", targetHistorianAcronym)?.ID; // Lookup signal type ID int signalTypeID = signalTypeTable.QueryRecordWhere("Acronym = {0}", signalType.ToString())?.ID ?? 1; // Lookup measurement record by point tag, creating a new record if one does not exist MeasurementRecord measurement = measurementTable.QueryRecordWhere("SignalReference = {0}", signalReference) ?? measurementTable.NewRecord(); // Update record fields measurement.DeviceID = deviceID; measurement.HistorianID = historianID; measurement.PointTag = pointTag; measurement.AlternateTag = alternateTag; measurement.SignalReference = signalReference; measurement.SignalTypeID = signalTypeID; measurement.Description = description; // Save record updates measurementTable.AddNewOrUpdateRecord(measurement); // Re-query new records to get any database assigned information, e.g., unique Guid-based signal ID if (measurement.PointID == 0) { measurement = measurementTable.QueryRecordWhere("SignalReference = {0}", signalReference); } // Notify host system of configuration changes instance.OnConfigurationChanged(); return(measurement); } }
private StatisticsCollection CreateStatistics(TableOperations <MeasurementRecord> table, MeasurementKey key, Device device, int HistorianID, SignalType type) { MeasurementRecord inMeasurement = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()); int signaltype; using (AdoDataConnection connection = new AdoDataConnection("systemSettings")) { TableOperations <SignalTypeRecord> signalTypeTable = new TableOperations <SignalTypeRecord>(connection); signaltype = signalTypeTable.QueryRecordWhere("Acronym = {0}", "CALC").ID; } string outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SUM"; // Sum if (table.QueryRecordCountWhere("SignalReference = {0}", outputReference) < 1) { table.AddNewRecord(new MeasurementRecord { HistorianID = HistorianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SUM", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SUM", SignalTypeID = signaltype, SignalReference = outputReference, Description = inMeasurement.Description + " Summ of UBAL", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }); } // sqrdSum outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SQR"; if (table.QueryRecordCountWhere("SignalReference = {0}", outputReference) < 1) { table.AddNewRecord(new MeasurementRecord { HistorianID = HistorianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SQR", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SQR", SignalTypeID = signaltype, SignalReference = outputReference, Description = inMeasurement.Description + " Summ of Sqared UBAL", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }); } // Min outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MIN"; if (table.QueryRecordCountWhere("SignalReference = {0}", outputReference) < 1) { table.AddNewRecord(new MeasurementRecord { HistorianID = HistorianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MIN", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MIN", SignalTypeID = signaltype, SignalReference = outputReference, Description = inMeasurement.Description + " Minimum UBAL", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }); } // Max outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MAX"; if (table.QueryRecordCountWhere("SignalReference = {0}", outputReference) < 1) { table.AddNewRecord(new MeasurementRecord { HistorianID = HistorianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MAX", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MAX", SignalTypeID = signaltype, SignalReference = outputReference, Description = inMeasurement.Description + " Maximum UBAL", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }); } // Number of Points outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:NUM"; if (table.QueryRecordCountWhere("SignalReference = {0}", outputReference) < 1) { table.AddNewRecord(new MeasurementRecord { HistorianID = HistorianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:NUM", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:NUM", SignalTypeID = signaltype, SignalReference = outputReference, Description = inMeasurement.Description + " Number of Points", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }); } // Number of Points above Alert outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:ALT"; if (table.QueryRecordCountWhere("SignalReference = {0}", outputReference) < 1) { table.AddNewRecord(new MeasurementRecord { HistorianID = HistorianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:ALT", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:ALT", SignalTypeID = signaltype, SignalReference = outputReference, Description = inMeasurement.Description + " number of Alerts", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }); } StatisticsCollection result = new StatisticsCollection(); outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SUM"; result.Sum = MeasurementKey.LookUpBySignalID(table.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:SQR"; result.SqrD = MeasurementKey.LookUpBySignalID(table.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MIN"; result.Min = MeasurementKey.LookUpBySignalID(table.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:MAX"; result.Max = MeasurementKey.LookUpBySignalID(table.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:NUM"; result.Total = MeasurementKey.LookUpBySignalID(table.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); outputReference = table.QueryRecordWhere("SignalID = {0}", key.SignalID.ToString()).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL:ALT"; result.Alert = MeasurementKey.LookUpBySignalID(table.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); result.Reset(); return(result); }
/// <summary> /// Initializes <see cref="UnBalancedCalculation"/>. /// </summary> public override void Initialize() { new ConnectionStringParser <CalculatedMesaurementAttribute>().ParseConnectionString(ConnectionString, this); base.Initialize(); m_threePhaseComponent = new List <ThreePhaseSet>(); m_statisticsMapping = new Dictionary <Guid, StatisticsCollection>(); m_saveStats = SaveAggregates; CategorizedSettingsElementCollection reportSettings = ConfigurationFile.Current.Settings["reportSettings"]; reportSettings.Add("IUnbalanceThreshold", "4.0", "Current Unbalance Alert threshold."); reportSettings.Add("VUnbalanceThreshold", "4.0", "Voltage Unbalance Alert threshold."); double i_threshold = reportSettings["IUnbalanceThreshold"].ValueAs(1.0D); double v_threshold = reportSettings["VUnbalanceThreshold"].ValueAs(1.0D); List <Guid> processed = new List <Guid>(); using (AdoDataConnection connection = new AdoDataConnection("systemSettings")) { TableOperations <MeasurementRecord> measurementTable = new TableOperations <MeasurementRecord>(connection); TableOperations <ActiveMeasurement> activeMeasurmentTable = new TableOperations <ActiveMeasurement>(connection); TableOperations <Device> deviceTable = new TableOperations <Device>(connection); TableOperations <SignalTypeRecord> signalTable = new TableOperations <SignalTypeRecord>(connection); Device device = deviceTable.QueryRecordWhere("Acronym = {0}", ResultDeviceName); int historianID = Convert.ToInt32(connection.ExecuteScalar("SELECT ID FROM Historian WHERE Acronym = {0}", new object[] { HistorianInstance })); // Take Care of the Device if (InputMeasurementKeys.Length < 1) { return; } m_nodeID = deviceTable.QueryRecordWhere("Id={0}", measurementTable.QueryRecordWhere("SignalID = {0}", InputMeasurementKeys[0].SignalID).DeviceID).NodeID; if (device == null) { device = CreateDefaultDevice(deviceTable); OnStatusMessage(MessageLevel.Warning, $"Default Device for Output Measurments not found. Created Device {device.Acronym}"); } if (MappingFilePath != "") { // Read Mapping File using (StreamReader reader = new StreamReader(FilePath.GetAbsolutePath(MappingFilePath))) { string line; int index = -1; while ((line = reader.ReadLine()) != null) { index++; List <string> pointTags = line.Split(',').Select(item => item.Trim()).ToList(); List <MeasurementKey> availableInputs = new List <MeasurementKey>(3); if (pointTags.Count != 3) { OnStatusMessage(MessageLevel.Warning, $"Skipping Line {index} in mapping file."); continue; } OnStatusMessage(MessageLevel.Info, $"PointTag of Measurment 1 is: {pointTags[0]}"); OnStatusMessage(MessageLevel.Info, $"PointTag of Measurment 1 is: {pointTags[0]}"); OnStatusMessage(MessageLevel.Info, $"PointTag of Measurment 1 is: {pointTags[0]}"); // check if measurments are in inputmeasurments availableInputs.Add(InputMeasurementKeys.FirstOrDefault(item => item.SignalID == GetSignalID(pointTags[0], activeMeasurmentTable))); availableInputs.Add(InputMeasurementKeys.FirstOrDefault(item => item.SignalID == GetSignalID(pointTags[1], activeMeasurmentTable))); availableInputs.Add(InputMeasurementKeys.FirstOrDefault(item => item.SignalID == GetSignalID(pointTags[2], activeMeasurmentTable))); if (availableInputs[0] == null || availableInputs[1] == null || availableInputs[2] == null) { OnStatusMessage(MessageLevel.Warning, $"Skipping Line {index} in mapping file. PointTag not found"); continue; } SignalType type = GetSignalType(availableInputs[0], new TableOperations <ActiveMeasurement>(connection)); MeasurementKey neg = availableInputs.FirstOrDefault(item => SearchNegative(item, new TableOperations <ActiveMeasurement>(connection)) && GetSignalType(item, new TableOperations <ActiveMeasurement>(connection)) == type); MeasurementKey pos = availableInputs.FirstOrDefault(item => SearchPositive(item, new TableOperations <ActiveMeasurement>(connection)) && GetSignalType(item, new TableOperations <ActiveMeasurement>(connection)) == type); MeasurementKey zero = availableInputs.FirstOrDefault(item => SearchZero(item, new TableOperations <ActiveMeasurement>(connection)) && GetSignalType(item, new TableOperations <ActiveMeasurement>(connection)) == type ); if (neg != null && zero != null && pos != null) { MeasurementKey unBalance; string outputReference = measurementTable.QueryRecordWhere("SignalID = {0}", pos.SignalID).SignalReference + "-" + (type == SignalType.IPHM? "I" : "V") + "UBAL"; if (measurementTable.QueryRecordCountWhere("SignalReference = {0}", outputReference) > 0) { // Measurement Exists unBalance = MeasurementKey.LookUpBySignalID(measurementTable.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); } else { // Add Measurment to Database and make a statement MeasurementRecord inMeasurement = measurementTable.QueryRecordWhere("SignalID = {0}", pos.SignalID); MeasurementRecord outMeasurement = new MeasurementRecord { HistorianID = historianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL", SignalTypeID = signalTable.QueryRecordWhere("Acronym = {0}", "CALC").ID, SignalReference = outputReference, Description = GetDescription(pos, new TableOperations <ActiveMeasurement>(connection)) + " UnBalanced", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }; measurementTable.AddNewRecord(outMeasurement); unBalance = MeasurementKey.LookUpBySignalID(measurementTable.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); OnStatusMessage(MessageLevel.Warning, $"Output measurment {outputReference} not found. Creating measurement"); } double threshold = InputMeasurementKeyTypes[InputMeasurementKeys.IndexOf(item => item == availableInputs[0])] == SignalType.IPHM ? i_threshold : v_threshold; m_threePhaseComponent.Add(new ThreePhaseSet(pos, zero, neg, unBalance, threshold)); if (m_saveStats) { m_statisticsMapping.Add(pos.SignalID, CreateStatistics(measurementTable, pos, device, historianID, type)); } } else { OnStatusMessage(MessageLevel.Warning, $"Skipping Line {index} in mapping file. Did not find pos. neg. and zero seq."); } } } } else { foreach (MeasurementKey key in InputMeasurementKeys) { if (processed.Contains(key.SignalID)) { continue; } // ensure only magnitudes are being used if (!(GetSignalType(key, new TableOperations <ActiveMeasurement>(connection)) == SignalType.IPHM || GetSignalType(key, new TableOperations <ActiveMeasurement>(connection)) == SignalType.VPHM)) { continue; } bool isNeg = SearchNegative(key, new TableOperations <ActiveMeasurement>(connection)); bool isPos = SearchPositive(key, new TableOperations <ActiveMeasurement>(connection)); bool isZero = SearchZero(key, new TableOperations <ActiveMeasurement>(connection)); if (!(isNeg || isPos || isZero)) { continue; } string description = GetDescription(key, new TableOperations <ActiveMeasurement>(connection)); // Check to make sure can actually deal with this if (description == string.Empty) { OnStatusMessage(MessageLevel.Warning, "Failed to apply automatic Line bundling to " + key.SignalID); continue; } //Make sure only correct Type (V vs I) makes it here.... SignalType type = GetSignalType(key, new TableOperations <ActiveMeasurement>(connection)); MeasurementKey neg = InputMeasurementKeys.FirstOrDefault(item => GetDescription(item, new TableOperations <ActiveMeasurement>(connection)) == description && SearchNegative(item, new TableOperations <ActiveMeasurement>(connection)) && GetSignalType(item, new TableOperations <ActiveMeasurement>(connection)) == type); MeasurementKey pos = InputMeasurementKeys.FirstOrDefault(item => GetDescription(item, new TableOperations <ActiveMeasurement>(connection)) == description && SearchPositive(item, new TableOperations <ActiveMeasurement>(connection)) && GetSignalType(item, new TableOperations <ActiveMeasurement>(connection)) == type); MeasurementKey zero = InputMeasurementKeys.FirstOrDefault(item => GetDescription(item, new TableOperations <ActiveMeasurement>(connection)) == description && SearchZero(item, new TableOperations <ActiveMeasurement>(connection)) && GetSignalType(item, new TableOperations <ActiveMeasurement>(connection)) == type ); if (neg != null && zero != null && pos != null) { MeasurementKey unBalance; string outputReference = measurementTable.QueryRecordWhere("SignalID = {0}", pos.SignalID).SignalReference + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL"; if (measurementTable.QueryRecordCountWhere("SignalReference = {0}", outputReference) > 0) { // Measurement Exists unBalance = MeasurementKey.LookUpBySignalID(measurementTable.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); } else { // Add Measurment to Database and make a statement MeasurementRecord inMeasurement = measurementTable.QueryRecordWhere("SignalID = {0}", pos.SignalID); MeasurementRecord outMeasurement = new MeasurementRecord { HistorianID = historianID, DeviceID = device.ID, PointTag = inMeasurement.PointTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL", AlternateTag = inMeasurement.AlternateTag + "-" + (type == SignalType.IPHM ? "I" : "V") + "UBAL", SignalTypeID = signalTable.QueryRecordWhere("Acronym = {0}", "CALC").ID, SignalReference = outputReference, Description = GetDescription(pos, new TableOperations <ActiveMeasurement>(connection)) + " UnBalanced", Enabled = true, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, CreatedBy = UserInfo.CurrentUserID, UpdatedBy = UserInfo.CurrentUserID, SignalID = Guid.NewGuid(), Adder = 0.0D, Multiplier = 1.0D }; measurementTable.AddNewRecord(outMeasurement); unBalance = MeasurementKey.LookUpBySignalID(measurementTable.QueryRecordWhere("SignalReference = {0}", outputReference).SignalID); OnStatusMessage(MessageLevel.Warning, $"Output measurment {outputReference} not found. Creating measurement"); } double threshold = InputMeasurementKeyTypes[InputMeasurementKeys.IndexOf(item => item == key)] == SignalType.IPHM ? i_threshold : v_threshold; m_threePhaseComponent.Add(new ThreePhaseSet(pos, zero, neg, unBalance, threshold)); processed.Add(pos.SignalID); processed.Add(neg.SignalID); processed.Add(zero.SignalID); if (m_saveStats) { m_statisticsMapping.Add(pos.SignalID, CreateStatistics(measurementTable, pos, device, historianID, type)); } } else { if (pos != null) { processed.Add(pos.SignalID); } if (neg != null) { processed.Add(neg.SignalID); } if (zero != null) { processed.Add(zero.SignalID); } } } } if (m_threePhaseComponent.Count == 0) { OnStatusMessage(MessageLevel.Error, "No case with all 3 sequences was found"); } } }