protected override List <Action> GetActions() { List <Action> actions = Constants.ClassificationIds.Select(classificationId => (Action)(() => { var actionStopwatch = new AFStopwatch(); actionStopwatch.Start(); string query = $"Template:EFOutageClassification |Id:={classificationId} SortField:ID"; // Sometimes we use AFSearchMode.StartInclusive other times AFSearchMode.Overlapped. StartInclusive we use when a start and end time is provided // Is there a performance difference? var afEventFrameSearch = new AFEventFrameSearch(AfDatabase, "ASearch", query); var maxCount = 1000; var eventFrames = afEventFrameSearch.FindEventFrames(0, true, maxCount).Take(maxCount).ToList(); var count = eventFrames.Count; TestOutput.AddActionResult( new ActionPerformanceResult { ActionMillis = actionStopwatch.ElapsedMilliseconds, ResultCount = count }); })).ToList(); return(actions); }
protected override List <Action> GetActions() { if (ElementNames == null) { ElementNames = new[] { string.Empty }; } var templateFilter = string.IsNullOrEmpty(TemplateName) ? string.Empty : $"Template:{TemplateName}"; List <Action> actions = ElementNames.Select(elementName => (Action)(() => { var actionStopwatch = new AFStopwatch(); actionStopwatch.Start(); var elementNameFilter = elementName != String.Empty ? $"ElementName:{elementName}" : String.Empty; string query = $"{elementNameFilter} {templateFilter} {ValueQuery} SortField:ID"; // Sometimes we use AFSearchMode.StartInclusive other times AFSearchMode.Overlapped. StartInclusive we use when a start and end time is provided // Is there a performance difference? var afEventFrameSearch = new AFEventFrameSearch(AfDatabase, "ASearch", query); var maxCount = 1000; var eventFrames = afEventFrameSearch.FindEventFrames(0, true, maxCount).Take(maxCount).ToList(); var count = eventFrames.Count; TestOutput.AddActionResult( new ActionPerformanceResult { ActionMillis = actionStopwatch.ElapsedMilliseconds, ResultCount = count }); })).ToList(); return(actions); }
private int ReviewStatus_AFEventFrameSearch_CalculateCountOnAllTurbines(int reviewStatus, string windFarmName) { var templateName = "EFTCMVibrationEvent"; var attributeName = "ReviewStatus"; AFStopwatch stopwatch = new AFStopwatch(); var afEventFrameSearch = new AFEventFrameSearch(_afDatabase, "MyQuery", "ElementName:" + windFarmName + " Template:" + templateName + " |" + attributeName + ":=" + reviewStatus + " SortField:ID"); var countDictionary = new Dictionary <string, int>(); IEnumerable <AFEventFrame> efs = afEventFrameSearch.FindEventFrames(pageSize: pagesize); //Console.WriteLine("Done : " + efs.Count() + ", " + stopwatch.ElapsedMilliseconds + "ms"); var eventFramesGroupedByPrimaryReferencedElementNames = efs.GroupBy(ef => ef.PrimaryReferencedElement.Name); foreach (var eventFrameGroup in eventFramesGroupedByPrimaryReferencedElementNames) { countDictionary[eventFrameGroup.Key] = eventFrameGroup.Count(); } //Console.WriteLine("Done2 : " + efs.Count() + ", " + stopwatch.ElapsedMilliseconds + "ms"); return(stopwatch.ElapsedMilliseconds); //_log.Info($"Time:{stopwatch.Elapsed.TotalSeconds}, Template:{templateName}, {attributeName}:{reviewStatus}, Element:{windFarmName}, Element Count: {countDictionary.Keys.Count}, EventFrame Count:{countDictionary.Sum(e => e.Value)}"); //foreach (var counts in countDictionary) //{ // _log.Info($"{counts.Key}:{counts.Value}"); //} }
private int AFEventFrameSearch(string templateName, string elementName = null, string attributeName = null, object value = null) { AFStopwatch stopwatch = new AFStopwatch(); string elementNameFilter = elementName != null ? "ElementName:" + elementName + " " : string.Empty; string query = $"Template:{templateName} SortField:ID"; if (elementName != null) { query += $" ElementName:{elementName}"; } if (attributeName != null) { query += $" |{attributeName}:={value}"; } var afEventFrameSearch = new AFEventFrameSearch(_afDatabase, "MyQuery" + value, query); if (pageCount != 0) { afEventFrameSearch.CacheTimeout = TimeSpan.FromSeconds(30); for (int page = 0; page < pageCount; page++) { var afEventFrames = afEventFrameSearch.FindEventFrames(startIndex: page * pagesize, fullLoad: false, pageSize: pagesize) .ToList(); //var uniqueIds = afEventFrames.Select(ef => ef.Attributes["SourceSystemUniqueId"]); //Console.WriteLine($"Page:{page + 1}, PageSize:{pagesize}, EFCount:{afEventFrames.Count}"); } } else { var afEventFrames = afEventFrameSearch.FindEventFrames(fullLoad: false, pageSize: pagesize).ToList(); //var uniqueIds = afEventFrames.Select(ef => ef.Attributes["SourceSystemUniqueId"]); //Console.WriteLine($"EFCount:{afEventFrames.Count}"); } //Console.WriteLine("Done : " + afEventFrames.Count + ", " + stopwatch.ElapsedMilliseconds + "ms"); return(stopwatch.ElapsedMilliseconds); //_log.Info($"time:{stopwatch.Elapsed.TotalSeconds}, Template:{templateName}, {attributeName}:{value}, Element:{elementName}, count:{afEventFrames.Count}"); }
private void Button_Click(object sender, RoutedEventArgs re) { //parse the start and end times AFTime startTime, endTime; if (AFTime.TryParse(StartDate.Text, out startTime) && AFTime.TryParse(EndDate.Text, out endTime)) { //find event frames with the event frame template in the time slot var search = new AFEventFrameSearch(db, "Find", AFSearchMode.Overlapped, startTime, endTime, $"Template:={eventFrameTemplate.Name}"); List <AFEventFrame> efs = search.FindEventFrames().OrderBy(ef => ef.Attributes[matchingAttribute].GetValue().ValueAsInt32()).ToList(); //read in csv file List <CSVLine> lines = new List <CSVLine>(); using (var reader = new StreamReader(CSV.Text)) { while (!reader.EndOfStream) { var line = reader.ReadLine(); var split = line.Split(','); int id; if (int.TryParse(split[0], out id)) { lines.Add(new CSVLine(id, split[1])); } } } lines = lines.OrderBy(line => line.ID).ToList(); //iterate through lines of csv //match identifier column with "matchingAttribute" int e = 0, l = 0; while (e < efs.Count && l < lines.Count) { int ef_id = efs[e].Attributes[matchingAttribute].GetValue().ValueAsInt32(); int line_id = lines[l].ID; if (ef_id == line_id) { //match -- update efs[e].Attributes["Attribute1"].SetValue(new AFValue(lines[l].Value)); l++; e++; } else if (ef_id > line_id) { l++; } else { e++; } } } }
public static IEnumerable <AFEventFrame> FindDowntimeEvents(AFDatabase afdb, string relayName, bool InProgress) { var eventSearch = new AFEventFrameSearch(afdb, "Template Search", $"Template:'Downtime' Name:{relayName}* InProgress:{InProgress}"); var events = eventSearch.FindEventFrames(); foreach (var item in events) { Console.WriteLine($"Event Found {item.Name}, time: {item.StartTime} - {item.EndTime} Duration: {item.Duration}"); } return(events); }
internal void InitialRun() { ComputeStatistics(); AFEventFrameSearch currentEventFrameQuery = new AFEventFrameSearch(afdatabse, "currentEvent", eventFrameQuery.Tokens.ToList()); currentEventFrameQuery.Tokens.Add(new AFSearchToken(AFSearchFilter.InProgress, AFSearchOperator.Equal, "True")); IEnumerable <AFEventFrame> currentEventFrames = currentEventFrameQuery.FindEventFrames(0, true, int.MaxValue); foreach (AFEventFrame currentEventFrame in currentEventFrames) { WriteValues(currentEventFrame.StartTime); } }
static void PrintReport(AFDatabase database, AFElementTemplate eventFrameTemplate) { DateTime timereference = DateTime.Now.AddDays(-7); AFTime startTime = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local)); AFTime endTime = startTime.LocalTime.AddDays(+8); string query = string.Format("template:\"{0}\" ElementName:\"{1}\"", eventFrameTemplate.Name, "Meter003"); AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFSearchMode.StartInclusive, startTime, endTime, query); foreach (AFEventFrame ef in eventFrameSearch.FindEventFrames()) { Console.WriteLine("{0}, {1}, {2}", ef.Name, ef.PrimaryReferencedElement.Name, ef.Attributes["Average Energy Usage"].GetValue().Value); } }
static void PrintReport(AFDatabase database, AFElementTemplate eventFrameTemplate) { AFTime startTime = DateTime.Today.AddDays(-7); AFTime endTime = startTime.LocalTime.AddDays(+8); // Or DateTime.Today.AddDays(1); string queryString = $"template:'{eventFrameTemplate.Name}' ElementName:Meter003"; using (AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFSearchMode.StartInclusive, startTime, endTime, queryString)) { eventFrameSearch.CacheTimeout = TimeSpan.FromMinutes(5); foreach (AFEventFrame ef in eventFrameSearch.FindEventFrames()) { Console.WriteLine("{0}, {1}, {2}", ef.Name, ef.PrimaryReferencedElement.Name, ef.Attributes["Average Energy Usage"].GetValue().Value); } } }
internal void InitialRun() { currentFrameQuery = currentEventFrame(eventFrameQuery); ComputeStatistics(); //AFEventFrameSearch currentEventFrameQuery = currentEventFrame(eventFrameQuery); IEnumerable <AFEventFrame> currentEventFrames = currentFrameQuery.FindEventFrames(0, true, int.MaxValue); try { foreach (AFEventFrame currentEventFrame in currentEventFrames) { WriteValues(currentEventFrame.StartTime); } } catch (System.Exception e) { logger.Error($"{calculationName} : Was not able to write initial data due {e.Message}"); } }
private List <AFEventFrame> GetEventFramesFromAfEventFrameSearch(string templateName, string elementName, string attributeName, object value) { string query = $"Template:{templateName} SortField:ID"; if (elementName != null) { query += $" ElementName:{elementName}"; } if (attributeName != null) { query += $" |{attributeName}:={value}"; } var afEventFrameSearch = new AFEventFrameSearch(AfDatabase, "MyQuery" + value, AFSearchMode.StartInclusive, Start, End, query); return(afEventFrameSearch.FindEventFrames().ToList()); }
static public void CaptureValues(AFDatabase database, AFElementTemplate eventFrameTemplate) { // Formulate search constraints on time and template DateTime timereference = DateTime.Now.AddDays(-7); AFTime startTime = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local)); string query = string.Format("template:\"{0}\"", eventFrameTemplate.Name); AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFEventFrameSearchMode.ForwardFromStartTime, startTime, query); int startIndex = 0; foreach (AFEventFrame item in eventFrameSearch.FindEventFrames()) { item.CaptureValues(); if ((startIndex++ % 512) == 0) { database.CheckIn(); } } database.CheckIn(); }
private void lbNotificationRules_SelectedIndexChanged(object sender, EventArgs e) { // Selected notification rule AFNotificationRule SelectedNotificationRule = lbNotificationRules.SelectedItem as AFNotificationRule; // Clear the notificaiton list lbNotificationInstances.Items.Clear(); // Check empty Selected if (SelectedNotificationRule == null) { return; } // Get information from Notification Rule Selected; AFTime startTime = new AFTime(tbStart.Text); AFTime endTime = new AFTime(tbEnd.Text); AFElement targetElement = SelectedNotificationRule.Target; AFDatabase database = SelectedNotificationRule.Database; // Consulting the dataBase string query = string.Format("Element: '{0}' {1}", targetElement.GetPath(database), SelectedNotificationRule.Criteria); AFEventFrameSearch search = new AFEventFrameSearch(database, "", AFSearchMode.Overlapped, startTime, endTime, query); search.CacheTimeout = TimeSpan.FromMinutes(5); IEnumerable <AFEventFrame> instances = search.FindEventFrames(fullLoad: false); // Populate the eventframe listbox foreach (AFEventFrame instance in instances) { string s = string.Format("Element: {0}, \t{1}, \t{2}" , targetElement.Name , instance.StartTime.LocalTime , instance.EndTime == AFTime.MaxValue ? "Event is ongoing": instance.EndTime.LocalTime.ToString()); lbNotificationInstances.Items.Add(s); } }
static void Main(string[] args) { NetworkCredential credential = new NetworkCredential(connectionInfo.user, connectionInfo.password); var piSystem = (new PISystems())[connectionInfo.AFServerName]; piSystem.Connect(credential); var afdb = piSystem.Databases[connectionInfo.AFDatabaseName]; //using tokens List <AFSearchToken> tokenList = new List <AFSearchToken>(); tokenList.Add(new AFSearchToken(AFSearchFilter.Template, AFSearchOperator.Equal, "Low Contaiment Strength")); tokenList.Add(new AFSearchToken(AFSearchFilter.Name, AFSearchOperator.Equal, "T001*")); var tokenSearch = new AFEventFrameSearch(afdb, "Template Search", tokenList); //using search string //var query = "Template:'Low Contaiment Strength' Name:T001*"; //var stringSearch = new AFEventFrameSearch(afdb, "Template Search", query); var results = tokenSearch.FindEventFrames(0, false, 10); var counter = 0; foreach (var item in results) { Console.WriteLine($"Event {item.Name}, time: {item.StartTime} - {item.EndTime} Duration: {item.Duration}"); counter++; if (counter > 9) { break; } } Console.ReadKey(); }
static public void CaptureValues(AFDatabase database, AFElementTemplate eventFrameTemplate) { // Formulate search constraints on time and template AFTime startTime = DateTime.Today.AddDays(-7); string queryString = $"template:\"{eventFrameTemplate.Name}\""; using (AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFEventFrameSearchMode.ForwardFromStartTime, startTime, queryString)) { eventFrameSearch.CacheTimeout = TimeSpan.FromMinutes(5); int count = 0; foreach (AFEventFrame item in eventFrameSearch.FindEventFrames()) { item.CaptureValues(); if ((count++ % 500) == 0) { database.CheckIn(); } } if (database.IsDirty) { database.CheckIn(); } } }
internal void ComputeStatistics() { logger.Info($"{calculationName} Starting some recalcuations"); IEnumerable <AFEventFrame> eventFrames = eventFrameQuery.FindEventFrames(0, true, int.MaxValue); //if (eventFrames) List <AFValues> trends = new List <AFValues>(); try { foreach (AFEventFrame EF in eventFrames) { trends.Add(sensor.Data.InterpolatedValues(EF.TimeRange, interval, null, "", true)); } logger.Debug($"{calculationName} : Succefully captured data and eventframes"); } catch (System.Exception e) { logger.Error($"{calculationName} : Was not succesfull in querying data or event frames, {e.Message}"); return; } List <AFValues> slices = GetSlices(trends); foreach (KeyValuePair <AFAttributeTrait, AFValues> bound in bounds) { bound.Value.Clear(); } foreach (AFValues slice in slices) { foreach (KeyValuePair <AFAttributeTrait, AFValues> bound in bounds) { bound.Value.Add(performCalculation(calculationsToPerform[bound.Key], slice)); } } logger.Info($"{calculationName} : Finishing some recalculation"); }
//Get instances, which are Event Frames beginning with PI Notifications 2016 private void FindNotificationInstances() { gridNotificationInstances.Rows.Clear(); if (!btnView.Enabled) { return; } var rule = lboxNotificationRules.SelectedItem as AFNotificationRule; var startTime = tbStartTime.Tag as AFTime?; var endTime = tbEndTime.Tag as AFTime?; var database = Element.Database; //We echo the current notification rule search criteria, which includes literal "Criteria:" //but include the Target element in the filter. string query = string.Format("Element:'{0}' {1}", Element.GetPath(database), rule.Criteria); AFEventFrameSearch search = new AFEventFrameSearch(database, "", AFSearchMode.Overlapped, startTime.Value, endTime.Value, query); search.CacheTimeout = TimeSpan.FromMinutes(5); IEnumerable <AFEventFrame> instances = search.FindEventFrames(fullLoad: true); //Populate listbox with notification instances, which are just event frames in PI Notifications 2016 or later. foreach (AFEventFrame instance in instances) { // For multi-trigger analyses, the "Start Trigger Name" would be null on the parent event frame if there were multiple triggers. // We should suppress those. Note the "Start Trigger Name" is our default attribute. object defaultObject = instance.DefaultAttribute?.GetValue() ?? (object)string.Empty; if (!string.IsNullOrWhiteSpace(defaultObject.ToString())) { object endObject = (instance.EndTime == AFTime.MaxValue) ? (object)"ongoing/active" : instance.EndTime.LocalTime; gridNotificationInstances.Rows.Add(instance.StartTime.LocalTime, endObject, defaultObject); } } }
internal void ComputeStatistics() { IEnumerable <AFEventFrame> eventFrames = eventFrameQuery.FindEventFrames(0, true, int.MaxValue); List <AFValues> trends = new List <AFValues>(); foreach (AFEventFrame EF in eventFrames) { // To Do add cases in case the value is very bad trends.Add(sensor.Data.InterpolatedValues(EF.TimeRange, interval, null, "", true)); } List <AFValues> slices = GetSlices(trends); foreach (KeyValuePair <AFAttributeTrait, AFValues> bound in bounds) { bound.Value.Clear(); } foreach (AFValues slice in slices) { foreach (KeyValuePair <AFAttributeTrait, AFValues> bound in bounds) { bound.Value.Add(performCalculation(calculationsToPerform[bound.Key], slice)); } } }
static public void CaptureValues(AFDatabase database, AFElementTemplate eventFrameTemplate) { // Formulate search constraints on time and template DateTime timereference = DateTime.Now.AddDays(-7); AFTime startTime = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local)); string query = string.Format("template:\"{0}\"", eventFrameTemplate.Name); AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFEventFrameSearchMode.ForwardFromStartTime, startTime, query); int startIndex = 0; foreach (AFEventFrame item in eventFrameSearch.FindEventFrames()) { item.CaptureValues(); if ((startIndex++ % 512) == 0) database.CheckIn(); } database.CheckIn(); }