public AnnotatedRecord copy() { AnnotatedRecord ann = new AnnotatedRecord(); foreach (Label lab in labels) { ann.Labels.Add(lab); } ann.StartHour = start_hour; ann.StartMinute = start_minute; ann.StartSecond = start_second; ann.StartMillisecond = start_millisecond; ann.StartUnix = start_unix; ann.StartDate = start_date; ann.EndDate = end_date; ann.EndHour = end_hour; ann.EndMinute = end_minute; ann.EndSecond = end_second; ann.EndMillisecond = end_millisecond; ann.EndUnix = end_unix; ann.Quality = quality; return(ann); }
public Annotation parse() { Annotation annotation = new Annotation(); XmlDocument dom = new XmlDocument(); dom.Load(this.xmlFile); XmlNode xNode=dom.DocumentElement; if ( (xNode.Name == Constants.ANNOTATION_ELEMENT) && (xNode.HasChildNodes)) { foreach (XmlNode iNode in xNode.ChildNodes) { //Console.WriteLine(iNode.Name); //parsing file information if (iNode.Name == Constants.FILE_INFO_ELEMENT) { foreach (XmlNode jNode in iNode.ChildNodes) { //Console.WriteLine(jNode.Name); foreach (XmlAttribute jAttribute in jNode.Attributes) { if (jAttribute.Name == Constants.NAME_ATTRIBUTE) { if (jNode.Name == Constants.SUBJECT_ELEMENT) { annotation.FileInfo.Subject = jAttribute.Value; } else if (jNode.Name == Constants.OBSERVER_ELEMENT) { annotation.FileInfo.Observer = jAttribute.Value; } else if (jNode.Name == Constants.LOCATION_ELEMENT) { annotation.FileInfo.Location = jAttribute.Value; } else if (jNode.Name == Constants.NOTES_ELEMENT) { annotation.FileInfo.Notes = jAttribute.Value; } } } } } //parsing labels else if (iNode.Name == Constants.LABELS_ELEMENT) { //parsing the categories foreach (XmlNode jNode in iNode.ChildNodes) { //double frequency = 1500; if (jNode.Name == Constants.CATEGORY_ELEMENT) { Category category = new Category(); //parsing category attributes foreach (XmlAttribute jAttribute in jNode.Attributes) { if (jAttribute.Name == Constants.NAME_ATTRIBUTE) { category.Name=jAttribute.Value.Replace(' ','-').Replace(',','_').ToLower(); }else if (jAttribute.Name == Constants.PROPERTY_ATTRIBUTE) { category.Property=jAttribute.Value; } } //parsing category labels foreach (XmlNode kNode in jNode.ChildNodes) { foreach (XmlAttribute kAttribute in kNode.Attributes) { if (kAttribute.Name == Constants.NAME_ATTRIBUTE) { Label newlabel = new Label(kAttribute.Value.Replace(' ', '-').Replace(',', '_').ToLower(), category.Name); //newlabel.InitializeTone(this.caller.Handle.ToInt32(),frequency); category.Labels.Add(newlabel); //frequency += 200; } } } annotation.Categories.Add(category); } } } else if (iNode.Name == Constants.DATA_ELEMENT) { int startYear = 0, startMonth = 0, startDay = 0, startHour = 0,startMinute = 0,startSecond = 0, startMillisecond=0; int endYear = 0, endMonth = 0, endDay = 0, endHour = 0, endMinute = 0, endSecond = 0, endMillisecond = 0; //parsing Annotated Records foreach (XmlNode jNode in iNode.ChildNodes) { //double frequency = 1500; if (jNode.Name == Constants.LABEL_ELEMENT) { //parsing category attributes foreach (XmlAttribute jAttribute in jNode.Attributes) { if (jAttribute.Name == Constants.DATE_ATTRIBUTE) { //parse date string p =@"(\d+)/(\d+)/(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if (m.Groups.Count == 4) { startMonth = endMonth = Convert.ToInt32(m.Groups[1].Value); startDay = endDay = Convert.ToInt32(m.Groups[2].Value); startYear = endYear = Convert.ToInt32(m.Groups[3].Value); } else throw new Exception("Error parsing " + Constants.DATE_ATTRIBUTE + ". " + jAttribute.Value); } else if (jAttribute.Name == Constants.STARTDATE_ATTRIBUTE) { //parse date string p = @"(\d+)-(\d+)-(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if (m.Groups.Count == 4) { startMonth = Convert.ToInt32(m.Groups[1].Value); startDay = Convert.ToInt32(m.Groups[2].Value); startYear = Convert.ToInt32(m.Groups[3].Value); } else throw new Exception("Error parsing " + Constants.STARTDATE_ATTRIBUTE + ". " + jAttribute.Value); } else if (jAttribute.Name == Constants.ENDDATE_ATTRIBUTE) { //parse date string p = @"(\d+)-(\d+)-(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if (m.Groups.Count == 4) { endMonth = Convert.ToInt32(m.Groups[1].Value); endDay = Convert.ToInt32(m.Groups[2].Value); endYear = Convert.ToInt32(m.Groups[3].Value); } else throw new Exception("Error parsing " + Constants.ENDDATE_ATTRIBUTE + ". " + jAttribute.Value); } else if (jAttribute.Name == Constants.STARTTIME_ATTRIBUTE) { string p = @"(\d+):(\d+):(\d+)\.(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if (m.Groups.Count == 5) { startHour= Convert.ToInt32(m.Groups[1].Value); startMinute = Convert.ToInt32(m.Groups[2].Value); startSecond = Convert.ToInt32(m.Groups[3].Value); startMillisecond = Convert.ToInt32(m.Groups[4].Value); } else throw new Exception("Error parsing " + Constants.STARTTIME_ATTRIBUTE + ". " + jAttribute.Value); } else if (jAttribute.Name == Constants.ENDTIME_ATTRIBUTE) { string p = @"(\d+):(\d+):(\d+)\.(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if (m.Groups.Count == 5) { endHour = Convert.ToInt32(m.Groups[1].Value); endMinute = Convert.ToInt32(m.Groups[2].Value); endSecond = Convert.ToInt32(m.Groups[3].Value); endMillisecond = Convert.ToInt32(m.Groups[4].Value); } else throw new Exception("Error parsing " + Constants.ENDTIME_ATTRIBUTE+ ". " + jAttribute.Value); } } DateTime startDT = new DateTime(startYear, startMonth, startDay, startHour, startMinute, startSecond, startMillisecond); DateTime endDT = new DateTime(endYear, endMonth, endDay, endHour, endMinute, endSecond, endMillisecond); AnnotatedRecord annotatedRecord = new AnnotatedRecord(); annotatedRecord.StartDate = startDT.ToString("MM-dd-yyyy"); annotatedRecord.StartHour = startDT.Hour; annotatedRecord.StartMinute = startDT.Minute; annotatedRecord.StartSecond = startDT.Second; TimeSpan ts = startDT.Subtract(new DateTime(1970, 1, 1, 0, 0, 0,0)); //TimeSpan ts = startDT - new DateTime(1970, 1, 1, 0, 0, 0, 0); annotatedRecord.StartUnix = ts.TotalMilliseconds; //for some data might require day light savings adjustment annotatedRecord.StartUnix -= 1 * 60 * 60 * 1000; annotatedRecord.EndDate = endDT.ToString("MM-dd-yyyy"); annotatedRecord.EndHour = endDT.Hour; annotatedRecord.EndMinute = endDT.Minute; annotatedRecord.EndSecond = endDT.Second; ts = endDT.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0,0)); //ts = endDT - new DateTime(1970, 1, 1, 0, 0, 0, 0, 0); annotatedRecord.EndUnix = ts.TotalMilliseconds; annotatedRecord.EndUnix -= 1 * 60 * 60 * 1000; //parsing values foreach (XmlNode kNode in jNode.ChildNodes) { string label = "", category = ""; foreach (XmlAttribute kAttribute in kNode.Attributes) { if (kAttribute.Name == Constants.LABEL_ATTRIBUTE) { label = kAttribute.Value; } else if (kAttribute.Name == Constants.CATEGORY_ATTRIBUTE) { category= kAttribute.Value; } } Label newlabel = new Label(label, category); annotatedRecord.Labels.Add(newlabel); } annotation.Data.Add(annotatedRecord); } } } } } return annotation; }
public AnnotatedRecord copy() { AnnotatedRecord ann = new AnnotatedRecord(); foreach (Label lab in labels) { ann.Labels.Add(lab); } ann.StartHour = start_hour; ann.StartMinute = start_minute; ann.StartSecond = start_second; ann.StartMillisecond = start_millisecond; ann.StartUnix = start_unix; ann.StartDate = start_date; ann.EndDate = end_date; ann.EndHour = end_hour; ann.EndMinute = end_minute; ann.EndSecond = end_second; ann.EndMillisecond = end_millisecond; ann.EndUnix = end_unix; ann.Quality = quality; return ann; }
public Annotation parse() { Annotation annotation = new Annotation(); XmlDocument dom = new XmlDocument(); dom.Load(this.xmlFile); XmlNode xNode = dom.DocumentElement; if ((xNode.Name == Constants.ANNOTATION_ELEMENT) && (xNode.HasChildNodes)) { foreach (XmlNode iNode in xNode.ChildNodes) { //Console.WriteLine(iNode.Name); //parsing file information if (iNode.Name == Constants.FILE_INFO_ELEMENT) { foreach (XmlNode jNode in iNode.ChildNodes) { //Console.WriteLine(jNode.Name); foreach (XmlAttribute jAttribute in jNode.Attributes) { if (jAttribute.Name == Constants.NAME_ATTRIBUTE) { if (jNode.Name == Constants.SUBJECT_ELEMENT) { annotation.FileInfo.Subject = jAttribute.Value; } else if (jNode.Name == Constants.OBSERVER_ELEMENT) { annotation.FileInfo.Observer = jAttribute.Value; } else if (jNode.Name == Constants.LOCATION_ELEMENT) { annotation.FileInfo.Location = jAttribute.Value; } else if (jNode.Name == Constants.NOTES_ELEMENT) { annotation.FileInfo.Notes = jAttribute.Value; } } } } } //parsing labels else if (iNode.Name == Constants.LABELS_ELEMENT) { //parsing the categories foreach (XmlNode jNode in iNode.ChildNodes) { //double frequency = 1500; if (jNode.Name == Constants.CATEGORY_ELEMENT) { Category category = new Category(); //parsing category attributes foreach (XmlAttribute jAttribute in jNode.Attributes) { if (jAttribute.Name == Constants.NAME_ATTRIBUTE) { category.Name = jAttribute.Value.Replace("A - ", "").Replace("A- ", "").Replace(' ', '-').Replace(',', '_').ToLower(); } else if (jAttribute.Name == Constants.PROPERTY_ATTRIBUTE) { category.Property = jAttribute.Value; } } //parsing category labels foreach (XmlNode kNode in jNode.ChildNodes) { foreach (XmlAttribute kAttribute in kNode.Attributes) { if (kAttribute.Name == Constants.NAME_ATTRIBUTE) { Label newlabel = new Label(kAttribute.Value.Replace("A - ", "").Replace("A- ", "").Replace(' ', '-').Replace(',', '_').ToLower(), category.Name); //newlabel.InitializeTone(this.caller.Handle.ToInt32(),frequency); category.Labels.Add(newlabel); //frequency += 200; } } } annotation.Categories.Add(category); } } } else if (iNode.Name == Constants.DATA_ELEMENT) { int startYear = 0, startMonth = 0, startDay = 0, startHour = 0, startMinute = 0, startSecond = 0, startMillisecond = 0; int endYear = 0, endMonth = 0, endDay = 0, endHour = 0, endMinute = 0, endSecond = 0, endMillisecond = 0; //parsing Annotated Records foreach (XmlNode jNode in iNode.ChildNodes) { //double frequency = 1500; if (jNode.Name == Constants.LABEL_ELEMENT) { //parsing category attributes foreach (XmlAttribute jAttribute in jNode.Attributes) { if (jAttribute.Name == Constants.DATE_ATTRIBUTE) { //parse date string p = @"(\d+)/(\d+)/(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if (m.Groups.Count == 4) { startMonth = endMonth = Convert.ToInt32(m.Groups[1].Value); startDay = endDay = Convert.ToInt32(m.Groups[2].Value); startYear = endYear = Convert.ToInt32(m.Groups[3].Value); } else { throw new Exception("Error parsing " + Constants.DATE_ATTRIBUTE + ". " + jAttribute.Value); } } else if (jAttribute.Name == Constants.STARTTIME_ATTRIBUTE) { //parse date string p = @"(\d+):(\d+):(\d+)([.](\d+))?"; Match m = Regex.Match(jAttribute.Value, p); startHour = Convert.ToInt32(m.Groups[1].Value); startMinute = Convert.ToInt32(m.Groups[2].Value); startSecond = Convert.ToInt32(m.Groups[3].Value); startMillisecond = 0; if (m.Groups[5].Value.Length > 0) { startMillisecond = Convert.ToInt32(m.Groups[5].Value); } } else if (jAttribute.Name == Constants.ENDTIME_ATTRIBUTE) { //parse date string p = @"(\d+):(\d+):(\d+)([.](\d+))?"; Match m = Regex.Match(jAttribute.Value, p); endHour = Convert.ToInt32(m.Groups[1].Value); endMinute = Convert.ToInt32(m.Groups[2].Value); endSecond = Convert.ToInt32(m.Groups[3].Value); endMillisecond = 0; if (m.Groups[5].Value.Length > 0) { endMillisecond = Convert.ToInt32(m.Groups[5].Value); } } else if (jAttribute.Name == Constants.STARTDATE_ATTRIBUTE) { //parse date //2008-06-17 14:03:42-07:00 string p = @"^(\d+)-(\d+)-(\d+)\s+(\d+):(\d+):(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if ((m.Groups.Count == 7) || (m.Groups.Count == 6)) { startMonth = Convert.ToInt32(m.Groups[2].Value); startDay = Convert.ToInt32(m.Groups[3].Value); startYear = Convert.ToInt32(m.Groups[1].Value); startHour = Convert.ToInt32(m.Groups[4].Value); startMinute = Convert.ToInt32(m.Groups[5].Value); startSecond = Convert.ToInt32(m.Groups[6].Value); startMillisecond = 0; } else { throw new Exception("Error parsing " + Constants.STARTDATE_ATTRIBUTE + ". " + jAttribute.Value); } } else if (jAttribute.Name == Constants.ENDDATE_ATTRIBUTE) { //parse date string p = @"^(\d+)-(\d+)-(\d+)\s+(\d+):(\d+):(\d+)"; Match m = Regex.Match(jAttribute.Value, p); if ((m.Groups.Count == 7) || (m.Groups.Count == 6)) { endMonth = Convert.ToInt32(m.Groups[2].Value); endDay = Convert.ToInt32(m.Groups[3].Value); endYear = Convert.ToInt32(m.Groups[1].Value); endHour = Convert.ToInt32(m.Groups[4].Value); endMinute = Convert.ToInt32(m.Groups[5].Value); endSecond = Convert.ToInt32(m.Groups[6].Value); endMillisecond = 0; } else { throw new Exception("Error parsing " + Constants.ENDDATE_ATTRIBUTE + ". " + jAttribute.Value); } } } DateTime startDT = new DateTime(startYear, startMonth, startDay, startHour, startMinute, startSecond, startMillisecond); DateTime endDT = new DateTime(endYear, endMonth, endDay, endHour, endMinute, endSecond, endMillisecond); AnnotatedRecord annotatedRecord = new AnnotatedRecord(); annotatedRecord.StartDate = startDT.ToString("MM-dd-yyyy"); annotatedRecord.StartHour = startDT.Hour; annotatedRecord.StartMinute = startDT.Minute; annotatedRecord.StartSecond = startDT.Second; annotatedRecord.StartMillisecond = startDT.Millisecond; TimeSpan ts = startDT.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0)); //TimeSpan ts = startDT - new DateTime(1970, 1, 1, 0, 0, 0, 0); annotatedRecord.StartUnix = ts.TotalMilliseconds; //for some data might require day light savings adjustment //annotatedRecord.StartUnix -= 1 * 60 * 60 * 1000; annotatedRecord.EndDate = endDT.ToString("MM-dd-yyyy"); annotatedRecord.EndHour = endDT.Hour; annotatedRecord.EndMinute = endDT.Minute; annotatedRecord.EndSecond = endDT.Second; annotatedRecord.EndMillisecond = endDT.Millisecond; ts = endDT.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, 0)); //ts = endDT - new DateTime(1970, 1, 1, 0, 0, 0, 0, 0); annotatedRecord.EndUnix = ts.TotalMilliseconds; //annotatedRecord.EndUnix -= 1 * 60 * 60 * 1000; //parsing values foreach (XmlNode kNode in jNode.ChildNodes) { string label = "", category = ""; foreach (XmlAttribute kAttribute in kNode.Attributes) { if (kAttribute.Name == Constants.LABEL_ATTRIBUTE) { label = kAttribute.Value.Replace("A - ", "").Replace("A- ", "").Replace(' ', '-').Replace(',', '_').ToLower(); } else if (kAttribute.Name == Constants.CATEGORY_ATTRIBUTE) { category = kAttribute.Value; } } Label newlabel = new Label(label, category); annotatedRecord.Labels.Add(newlabel); } annotation.Data.Add(annotatedRecord); } } } } } return(annotation); }
private void startStopButton_Click(object sender, EventArgs e) { Button button = (Button)sender; //button state is now start if (button.BackColor == System.Drawing.Color.Green) { // this.startSound.Play(); //Generator generator = new Generator(); //generator.InitializeSound(this.Handle.ToInt32()); //generator.CreateBuffer(); this.startStopButton.Text = "Stop"; this.startStopButton.BackColor = System.Drawing.Color.Red; this.overallTimer.reset(); this.overallTimer.start(); this.goodTimer.reset(); this.goodTimer.start(); //store the current state of the categories this.currentRecord = new AnnotatedRecord(); this.currentRecord.StartDate = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK"); this.currentRecord.StartHour = DateTime.Now.Hour; this.currentRecord.StartMinute = DateTime.Now.Minute; this.currentRecord.StartSecond = DateTime.Now.Second; TimeSpan ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)); this.currentRecord.StartUnix = ts.TotalSeconds; //check all buttons values, store them and disable them foreach (Button category_button in categoryButtons) { int button_id = Convert.ToInt32(category_button.Name); Category category = (Category)this.annotation.Categories[button_id]; string current_label = ((AXML.Label)category.Labels[(int)this.buttonIndex[button_id]]).Name; this.currentRecord.Labels.Add(new AXML.Label(current_label, category.Name)); category_button.Enabled = false; } } else if (button.BackColor == System.Drawing.Color.Red) { // this.stopSound.Play(); this.startStopButton.Text = "Start"; this.startStopButton.BackColor = System.Drawing.Color.Green; this.overallTimer.reset(); this.goodTimer.reset(); //store the current state of the categories this.currentRecord.EndDate = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK"); this.currentRecord.EndHour = DateTime.Now.Hour; this.currentRecord.EndMinute = DateTime.Now.Minute; this.currentRecord.EndSecond = DateTime.Now.Second; TimeSpan ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)); this.currentRecord.EndUnix = ts.TotalSeconds; this.annotation.Data.Add(this.currentRecord); //each time an activity is stopped, rewrite the file on disk, need to backup file to avoid corruption this.annotation.ToXMLFile(); this.annotation.ToCSVFile(); foreach (Button category_button in categoryButtons) category_button.Enabled = true; } }
private void readDataTimer_Tick(object sender, EventArgs e) { #region Bluetooth Reconnection Code #if (PocketPC) //Start a reconnection thread foreach (Receiver receiver in this.sensors.Receivers) { if (!receiver.Running) //&& (!receiver.Restarting)) { aMITesActivityLogger.WriteLogComment("Connection broke with " + receiver.ID + ". Restarting"); //reconnectionThreadQuit[receiver.ID] = false; BluetoothConnector btc=new BluetoothConnector(receiver, this.bluetoothControllers, this.mitesDecoders); aMITesActivityLogger.WriteLogComment("Initializing reconnection thread"); //ts[receiver.ID] = new Thread(new ThreadStart(btc.Reconnect)); //ts[receiver.ID].Start(); btc.Reconnect(); aMITesActivityLogger.WriteLogComment("Reconnection thread started"); receiver.Restarting = true; } else if (receiver.Restarted) { aMITesActivityLogger.WriteLogComment("Reconnection completed"); receiver.Restarted = false; receiver.Restarting = false; receiver.Running = true; } } #endif #endregion Bluetooth Reconnection Code #region Poll All Wockets and MITes and Decode Data Receiver currentReceiver = null; try { //Poll each CONNECTED receiver channel with the right decoder foreach (Receiver receiver in this.sensors.Receivers) { currentReceiver = receiver; #if (PocketPC) if ((receiver.Type == SXML.Constants.RECEIVER_BLUETOOTH) && (receiver.Running == true)) { if (receiver.Decoder == SXML.Constants.DECODER_MITES) this.mitesDecoders[receiver.ID].GetSensorData(this.bluetoothControllers[receiver.ID], MITesDecoder.MITES_SENSOR); else if (receiver.Decoder == SXML.Constants.DECODER_WOCKETS) this.mitesDecoders[receiver.ID].GetSensorData(this.bluetoothControllers[receiver.ID], MITesDecoder.WOCKETS_SENSOR); else if (receiver.Decoder == SXML.Constants.DECODER_SPARKFUN) this.mitesDecoders[receiver.ID].GetSensorData(this.bluetoothControllers[receiver.ID], MITesDecoder.SPARKFUN_SENSOR); } else #endif if (receiver.Type == SXML.Constants.RECEIVER_USB) this.mitesDecoders[receiver.ID].GetSensorData(this.mitesControllers[receiver.ID]); } if (++ttwcounter == 6000) { TextWriter ttw = new StreamWriter("\\Internal Storage\\ts.txt"); ttw.WriteLine(DateTime.Now.ToLongTimeString()); ttw.Close(); ttwcounter = 0; } } //Thrown when there is a Bluetooth failure //TODO: Make sure no USB failure happening catch (Exception ex) { currentReceiver.Running = false; //connectionLost = true; return; } //Reset the index of the master decoder and copy all data in order into the master decoder this.masterDecoder.someMITesDataIndex = 0; //Only decode running receivers (i.e. with no connection failure) foreach (Receiver receiver in this.sensors.Receivers) if (receiver.Running) this.masterDecoder.MergeDataOrderProperly(this.mitesDecoders[receiver.ID]); #endregion Poll All Wockets and MITes and Decode Data #region Poll Builtin Data #if (PocketPC) GenericAccelerometerData polledData = null; if (unprocessedBuiltin == true) { this.builtinData.Timestamp = Environment.TickCount; this.builtinData.Unixtimestamp = UnixTime.GetUnixTime(); polledData = this.builtinData; } #endif #endregion Poll Builtin Data #region Train in realtime and generate ARFF File if (IsTraining == true) { //We are autotraining each activity after the other if (AutoTraining == true) { //Get current activity to train string current_activity = ((AXML.Label)((AXML.Category)this.annotation.Categories[0]).Labels[autoTrainingIndex]).Name; //Check if trained if (Extractor.IsTrained(current_activity)) { //store the completed annotation and reset the variables this.currentRecord.EndDate = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK"); this.currentRecord.EndHour = DateTime.Now.Hour; this.currentRecord.EndMinute = DateTime.Now.Minute; this.currentRecord.EndSecond = DateTime.Now.Second; TimeSpan ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)); this.currentRecord.EndUnix = ts.TotalSeconds; this.annotation.Data.Add(this.currentRecord); //each time an activity is stopped, rewrite the file on disk, need to backup file to avoid corruption this.annotation.ToXMLFile(); this.annotation.ToCSVFile(); isExtracting = false; //Point to the next activity and Calculate the delay to start training this.startActivityTime = Environment.TickCount + Extractor.Configuration.TrainingWaitTime * 1000;//Constants.TRAINING_GAP; autoTrainingIndex++; //If we exceeded the last activity then training is completed if (autoTrainingIndex == ((AXML.Category)this.annotation.Categories[0]).Labels.Count) { this.trainingLabel.Text = "Training Completed"; this.goodTimer.reset(); this.overallTimer.reset(); Thread.Sleep(3000); EndTraining(); } else // if there are still activities to train beep twice and reset good timer { this.goodTimer.reset(); #if (PocketPC) PlaySound(@"\Windows\Voicbeep", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_SYNC)); PlaySound(@"\Windows\Voicbeep", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_SYNC)); #endif } } //if the current activity is not trained and the start time is more that the current time //then calculate the feature vector else if (this.startActivityTime < Environment.TickCount) // TRAINING_GAP passed { //initialize for extraction if (isExtracting == false) { this.trainingLabel.Text = "Training " + current_activity; this.goodTimer.start(); //store the current state of the categories this.currentRecord = new AnnotatedRecord(); this.currentRecord.StartDate = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK"); this.currentRecord.StartHour = DateTime.Now.Hour; this.currentRecord.StartMinute = DateTime.Now.Minute; this.currentRecord.StartSecond = DateTime.Now.Second; TimeSpan ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)); this.currentRecord.StartUnix = ts.TotalSeconds; this.currentRecord.Labels.Add(new AXML.Label(current_activity, "none")); isExtracting = true; } //Extract feature vector from accelerometer data and write an arff line double lastTimeStamp = Extractor.StoreMITesWindow(); #if (PocketPC) if ((this.sensors.HasBuiltinSensors) && (polledData != null)) { //store it in Extractor Buffers as well lastTimeStamp = Extractor.StoreBuiltinData(polledData); } #endif if (Extractor.GenerateFeatureVector(lastTimeStamp)) { Extractor.TrainingTime[current_activity] = (int)Extractor.TrainingTime[current_activity] + Extractor.Configuration.OverlapTime;// get it from configuration string arffSample = Extractor.toString() + "," + current_activity.Replace(' ', '_'); this.tw.WriteLine(arffSample); this.label8.Text = Extractor.DiscardedLossRateWindows.ToString(); } } //if we are waiting for the activity to be trained else this.trainingLabel.Text = "Training " + current_activity + " in " + ((int)(this.startActivityTime - Environment.TickCount) / 1000) + " secs"; } else // Manual Training { } } #endregion Train in realtime and generate ARFF File #region Classifying activities #if (PocketPC) if (isClassifying == true) { double lastTimeStamp = Extractor.StoreMITesWindow(); if ((this.sensors.HasBuiltinSensors) && (polledData != null)) { //aMITesLoggerPLFormat.SaveRawMITesBuiltinData(polledData); //store it in Extractor Buffers as well lastTimeStamp = Extractor.StoreBuiltinData(polledData); } if (Extractor.GenerateFeatureVector(lastTimeStamp)) { Instance newinstance = new Instance(instances.numAttributes()); newinstance.Dataset = instances; for (int i = 0; (i < Extractor.Features.Length); i++) newinstance.setValue(instances.attribute(i), Extractor.Features[i]); double predicted = classifier.classifyInstance(newinstance); string predicted_activity = newinstance.dataset().classAttribute().value_Renamed((int)predicted); int currentIndex = (int)labelIndex[predicted_activity]; labelCounters[currentIndex] = (int)labelCounters[currentIndex] + 1; classificationCounter++; if (classificationCounter == Extractor.Configuration.SmoothWindows) { classificationCounter = 0; int mostCount = 0; string mostActivity = ""; for (int j = 0; (j < labelCounters.Length); j++) { if (labelCounters[j] > mostCount) { mostActivity = activityLabels[j]; mostCount = labelCounters[j]; } labelCounters[j] = 0; } pieChart.SetActivity(mostActivity); if (this.aList.getEmptyPercent() == 1) this.aList.reset(); else this.aList.increment(mostActivity); if (previousActivity != mostActivity) { this.activityTimer.stop(); this.activityTimer.reset(); currentCalories = 0; } else { if (this.activityTimer.isRunning() == false) this.activityTimer.start(); } if (mostActivity == "standing") { currentCalories += 1; totalCalories += 1; } else if (mostActivity == "walking") { currentCalories += 2; totalCalories += 2; } else if (mostActivity == "brisk-walking") { currentCalories += 4; totalCalories += 4; } else { currentCalories += 1; totalCalories += 1; } pieChart.SetCalories(totalCalories, currentCalories); pieChart.Data = this.aList.toPercentHashtable(); pieChart.Invalidate(); previousActivity = mostActivity; } } } #endif #endregion Classifying activities #region Storing CSV data for the grapher (PC Only) #if (!PocketPC) if (isCollectingDetailedData == true) { if (activityCountWindowSize > Extractor.Configuration.QualityWindowSize) //write a line to CSV and initialize { DateTime now = DateTime.Now; DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); TimeSpan diff = now.Subtract(origin); string timestamp = diff.TotalMilliseconds + "," + now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ssK"); string master_csv_line = timestamp; string hr_csv_line = timestamp; //to restore the date //DateTime restored = origin.AddMilliseconds(diff.TotalMilliseconds); if (this.overallTimer.isRunning()) { foreach (Button button in this.categoryButtons) master_csv_line += "," + button.Text; } else { foreach (Button button in this.categoryButtons) master_csv_line += ","; } foreach (Sensor sensor in this.sensors.Sensors) { string csv_line1 = timestamp; string csv_line2 = timestamp; string csv_line3 = timestamp; int sensor_id = Convert.ToInt32(sensor.ID); if (sensor_id > 0) //No HR { if (acCounters[sensor_id] > 0) { csv_line2 += "," + MITesDataFilterer.MITesPerformanceTracker[sensor_id].LastSamplingRate; csv_line1 += "," + ((double)(averageX[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ","; csv_line1 += ((double)(averageY[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ","; csv_line1 += ((double)(averageZ[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00"); csv_line3 += "," + ((int)(averageRawX[sensor_id] / acCounters[sensor_id])) + ","; csv_line3 += ((int)(averageRawY[sensor_id] / acCounters[sensor_id])) + ","; csv_line3 += ((int)(averageRawZ[sensor_id] / acCounters[sensor_id])); master_csv_line += "," + MITesDataFilterer.MITesPerformanceTracker[sensor_id].LastSamplingRate; master_csv_line += "," + ((int)(averageRawX[sensor_id] / acCounters[sensor_id])) + ","; master_csv_line += ((int)(averageRawY[sensor_id] / acCounters[sensor_id])) + ","; master_csv_line += ((int)(averageRawZ[sensor_id] / acCounters[sensor_id])); master_csv_line += "," + ((double)(averageX[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ","; master_csv_line += ((double)(averageY[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00") + ","; master_csv_line += ((double)(averageZ[sensor_id] / (double)acCounters[sensor_id])).ToString("00.00"); } else { csv_line1 += ",,,,"; csv_line3 += ",,,,"; csv_line2 += ",0"; master_csv_line += ",0,,,,,,"; } this.activityCountCSVs[sensor_id].WriteLine(csv_line1); this.samplingCSVs[sensor_id].WriteLine(csv_line2); this.averagedRaw[sensor_id].WriteLine(csv_line3); } averageX[sensor_id] = 0; averageY[sensor_id] = 0; averageZ[sensor_id] = 0; averageRawX[sensor_id] = 0; averageRawY[sensor_id] = 0; averageRawZ[sensor_id] = 0; prevX[sensor_id] = 0; prevY[sensor_id] = 0; prevY[sensor_id] = 0; acCounters[sensor_id] = 0; } if (hrCount > 0) { this.hrCSV.WriteLine(hr_csv_line + "," + (int)(sumHR / hrCount)); this.masterCSV.WriteLine(master_csv_line + "," + (int)(sumHR / hrCount)); } else { this.hrCSV.WriteLine(hr_csv_line + ","); this.masterCSV.WriteLine(master_csv_line + ","); } hrCount = 0; sumHR = 0; activityCountWindowSize = 0; } activityCountWindowSize += 10; //add 10 milliseconds } #endif #endregion Storing CSV data for the grapher (PC Only) #region Calibration and CSV Calculateion Code if ((isCalibrating) || (isCollectingDetailedData == true)) { //store sum of abs values of consecutive accelerometer readings for (int i = 0; (i < this.masterDecoder.someMITesDataIndex); i++) { if ((this.masterDecoder.someMITesData[i].type != (int)MITesTypes.NOISE) && (this.masterDecoder.someMITesData[i].type == (int)MITesTypes.ACCEL)) { int channel = 0, x = 0, y = 0, z = 0; channel = (int)this.masterDecoder.someMITesData[i].channel; x = (int)this.masterDecoder.someMITesData[i].x; y = (int)this.masterDecoder.someMITesData[i].y; z = (int)this.masterDecoder.someMITesData[i].z; #region Calibration Calculation if (isCalibrating) { if (this.calSensor == -1) { if (this.currentCalibrationSensorIndex < this.sensors.Sensors.Count) { this.calX = new int[Constants.CALIBRATION_SAMPLES]; this.calY = new int[Constants.CALIBRATION_SAMPLES]; this.calZ = new int[Constants.CALIBRATION_SAMPLES]; this.calSensor = Convert.ToInt32(((Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ID); this.calSensorPosition = Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION; int receiver_id = Convert.ToInt32(((Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).Receiver); int[] channels = new int[6]; #if (PockectPC) if (this.calSensor != PhoneAccelerometers.Constants.BUILT_IN_ACCELEROMETER_CHANNEL_ID) { #endif channels[0] = this.calSensor; this.mitesControllers[receiver_id].SetChannels(1, channels); #if (PockectPC) } #endif } else //all sensors are calibrated { TextWriter tw = new StreamWriter("SensorData.xml"); tw.WriteLine(this.sensors.toXML()); tw.Close(); MessageBox.Show("Calibration... Completed"); #if (PocketPC) Application.Exit(); System.Diagnostics.Process.GetCurrentProcess().Kill(); #else Environment.Exit(0); #endif } } if (channel == this.calSensor) { if (this.calSensorPosition == Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION) { this.calX[this.calCounter] = x; this.calY[this.calCounter] = y; this.calCounter++; } else //vertical { this.calZ[this.calCounter] = z; this.calCounter++; } // if all required samples are collected if (this.calCounter == Constants.CALIBRATION_SAMPLES) { if (this.calSensorPosition == Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION) { this.calSensorPosition = Constants.CALIBRATION_SIDE_VERTICAL_POSITION; double meanX = 0.0, meanY = 0.0; double stdX = 0.0, stdY = 0.0; this.label17.Text = "Calibration Completed! Please place the sensor " + ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ID + " vertical on a flat surface then click start."; this.pictureBox2.Image = this.verticalMITes; this.button2.Enabled = true; for (int j = 0; (j < this.calCounter); j++) { meanX += (double)this.calX[j]; meanY += (double)this.calY[j]; } meanX = meanX / this.calCounter; meanY = meanY / this.calCounter; ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).XMean = meanX; ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).YMean = meanY; for (int j = 0; (j < this.calCounter); j++) { stdX += Math.Pow(this.calX[j] - meanX, 2); stdY += Math.Pow(this.calY[j] - meanY, 2); } stdX = Math.Sqrt(stdX / (this.calCounter - 1)); stdY = Math.Sqrt(stdY / (this.calCounter - 1)); ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).XStd = stdX; ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).YStd = stdY; } else { if (this.currentCalibrationSensorIndex < this.sensors.Sensors.Count) { this.label17.Text = "Calibration Completed! Please place the sensor " + ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ID + " horizontal on a flat surface then click start."; this.pictureBox2.Image = this.horizontalMITes; this.button2.Enabled = true; } this.calSensorPosition = Constants.CALIBRATION_FLAT_HORIZONTAL_POSITION; double meanZ = 0.0; double stdZ = 0.0; for (int j = 0; (j < this.calCounter); j++) meanZ += (double)this.calZ[j]; meanZ = meanZ / this.calCounter; ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ZMean = meanZ; for (int j = 0; (j < this.calCounter); j++) stdZ += Math.Pow(this.calZ[j] - meanZ, 2); stdZ = Math.Sqrt(stdZ / (this.calCounter - 1)); ((SXML.Sensor)this.sensors.Sensors[this.currentCalibrationSensorIndex]).ZStd = stdZ; this.currentCalibrationSensorIndex++; this.calSensor = -1; } this.isCalibrating = false; this.calCounter = 0; } } } #endregion Calibration Calculation #region CSV values calculation (PC Only) #if (!PocketPC) else if (isCollectingDetailedData) { if (channel <= this.sensors.MaximumSensorID) //if junk comes ignore it { if ((prevX[channel] > 0) && (prevY[channel] > 0) && (prevZ[channel] > 0) && (x > 0) && (y > 0) && (z > 0)) { averageX[channel] = averageX[channel] + Math.Abs(prevX[channel] - x); averageRawX[channel] = averageRawX[channel] + x; averageY[channel] = averageY[channel] + Math.Abs(prevY[channel] - y); averageRawY[channel] = averageRawY[channel] + y; averageZ[channel] = averageZ[channel] + Math.Abs(prevZ[channel] - z); averageRawZ[channel] = averageRawZ[channel] + z; acCounters[channel] = acCounters[channel] + 1; } prevX[channel] = x; prevY[channel] = y; prevZ[channel] = z; } } #endif #endregion CSV values calculation (PC Only) } } } #endregion Calibration and CSV Calculateion Code //Remove data with any values =0 or 1022 aMITesDataFilterer.RemoveZeroNoise(); this.masterDecoder.UpdateSamplingRate(aMITesDataFilterer.CountNonNoise()); if (printSamplingCount > 500) { //((System.Windows.Forms.Label)this.sensorLabels["SampRate"]).Text = "Samp: " + this.mitesDecoders[0].GetSamplingRate(); ((System.Windows.Forms.Label)this.sensorLabels["SampRate"]).Text = "Samp: ttt";//+this.masterDecoder.GetSamplingRate(); //textBoxRate.Text = "Samp: " + aMITesDecoder.GetSamplingRate(); //aMITesLogger.WriteLogComment(textBoxUV.Text); printSamplingCount = 0; } else printSamplingCount++; // Check HR values int hr = aMITesHRAnalyzer.Update(); #if (PocketPC) #else if (hr > 0) { sumHR += hr; hrCount++; } #endif //Compute/get Activity Counts for (int i = 0; (i < this.sensors.Sensors.Count); i++) { int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID); if (sensor_id > 0) ((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]).UpdateActivityCounts(); //else if (sensor_id == 0) // aMITesHRAnalyzer.Update(); } for (int i = 0; (i < this.sensors.Sensors.Count); i++) { int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID); if (sensor_id > 0) ((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]).PrintMaxMin(); } if (((MITesActivityCounter)this.aMITesActivityCounters[this.sensors.FirstAccelerometer]).IsNewEpoch(1000)) { aMITesHRAnalyzer.ComputeEpoch(30000); //if (this.tabControl1.TabIndex == 0) // ReportHR(); for (int i = 0; (i < this.sensors.Sensors.Count); i++) { int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID); if (sensor_id > 0) ((MITesActivityCounter)this.aMITesActivityCounters[sensor_id]).ComputeEpoch(); } if (!isWrittenKey) // Write the key once at the top of the file { isWrittenKey = true; aMITesActivityLogger.StartReportKeyLine(); for (int i = 0; (i < this.sensors.Sensors.Count); i++) { int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID); if (sensor_id > 0) aMITesActivityLogger.AddKeyLine(((MITesActivityCounter)this.aMITesActivityCounters[sensor_id])); } aMITesActivityLogger.AddKeyLine(aMITesHRAnalyzer); aMITesActivityLogger.SaveReportKeyLine(); } aMITesActivityLogger.StartReportLine(); for (int i = 0; (i < this.sensors.Sensors.Count); i++) { int sensor_id = Convert.ToInt32(((SXML.Sensor)this.sensors.Sensors[i]).ID); if (sensor_id > 0) aMITesActivityLogger.AddReportLine(((MITesActivityCounter)this.aMITesActivityCounters[sensor_id])); } aMITesActivityLogger.AddReportLine(aMITesHRAnalyzer); aMITesActivityLogger.SaveReportLine(); } #region Store the sensor data if (flushTimer == 0) aMITesLoggerPLFormat.FlushBytes(); if (flushTimer > FLUSH_TIMER_MAX) flushTimer = -1; flushTimer++; #endregion Store the sensor data // Graph accelerometer data for multiple recievers #if (PocketPC) if (isPlotting) GraphAccelerometerValues(polledData); #endif #if (PocketPC) if (polledData != null) { this.builtinData = null; this.unprocessedBuiltin = false; } #endif }