public string Classify(double lastTimestamp) { string predicted_class = null; //attempt to generate a feature vector if (Extractor.GenerateFeatureVector(lastTimestamp)) { Instance newinstance = new Instance(instances.numAttributes()); newinstance.Dataset = instances; for (int i = 0; (i < this.features.Count); i++) newinstance.setValue(instances.attribute(i), Extractor.Features[this.featureIndex[i]]); double predicted = classifier.classifyInstance(newinstance); predicted_class = newinstance.dataset().classAttribute().value_Renamed((int)predicted); } return predicted_class; }
/// <summary> Convert a single instance over. The converted instance is /// added to the end of the output queue. /// /// </summary> /// <param name="instance">the instance to convert /// </param> private void convertInstance(Instance instance) { Instance inst = null; if (instance is SparseInstance) { double[] vals = new double[instance.numValues()]; int[] indices = new int[instance.numValues()]; int num = 0; for (int j = 0; j < instance.numValues(); j++) { if (instance.isMissingSparse(j) && (getInputFormat().classIndex() != instance.index(j)) && (instance.attributeSparse(j).Nominal || instance.attributeSparse(j).Numeric)) { if (m_ModesAndMeans[instance.index(j)] != 0.0) { vals[num] = m_ModesAndMeans[instance.index(j)]; indices[num] = instance.index(j); num++; } } else { vals[num] = instance.valueSparse(j); indices[num] = instance.index(j); num++; } } if (num == instance.numValues()) { inst = new SparseInstance(instance.weight(), vals, indices, instance.numAttributes()); } else { double[] tempVals = new double[num]; int[] tempInd = new int[num]; Array.Copy(vals, 0, tempVals, 0, num); Array.Copy(indices, 0, tempInd, 0, num); inst = new SparseInstance(instance.weight(), tempVals, tempInd, instance.numAttributes()); } } else { double[] vals = new double[getInputFormat().numAttributes()]; for (int j = 0; j < instance.numAttributes(); j++) { if (instance.isMissing(j) && (getInputFormat().classIndex() != j) && (getInputFormat().attribute(j).Nominal || getInputFormat().attribute(j).Numeric)) { vals[j] = m_ModesAndMeans[j]; } else { vals[j] = instance.value_Renamed(j); } } inst = new Instance(instance.weight(), vals); } inst.Dataset = instance.dataset(); push(inst); }
/// <summary> Convert a single instance over if the class is nominal. The converted /// instance is added to the end of the output queue. /// /// </summary> /// <param name="instance">the instance to convert /// </param> private void convertInstance(Instance instance) { double[] vals = new double[outputFormatPeek().numAttributes()]; int attSoFar = 0; for (int j = 0; j < getInputFormat().numAttributes(); j++) { weka.core.Attribute att = getInputFormat().attribute(j); if (!att.Nominal || (j == getInputFormat().classIndex()) || !m_Columns.isInRange(j)) { vals[attSoFar] = instance.value_Renamed(j); attSoFar++; } else { if (att.numValues() <= 2) { vals[attSoFar] = instance.value_Renamed(j); attSoFar++; } else { if (instance.isMissing(j)) { for (int k = 0; k < att.numValues(); k++) { vals[attSoFar + k] = instance.value_Renamed(j); } } else { for (int k = 0; k < att.numValues(); k++) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" if (k == (int) instance.value_Renamed(j)) { vals[attSoFar + k] = 1; } else { vals[attSoFar + k] = 0; } } } attSoFar += att.numValues(); } } } Instance inst = null; if (instance is SparseInstance) { inst = new SparseInstance(instance.weight(), vals); } else { inst = new Instance(instance.weight(), vals); } copyStringValues(inst, false, instance.dataset(), InputStringIndex, getOutputFormat(), OutputStringIndex); inst.Dataset = getOutputFormat(); push(inst); }
/// <summary> Evaluates the classifier on a single instance. /// /// </summary> /// <param name="classifier">machine learning classifier /// </param> /// <param name="instance">the test instance to be classified /// </param> /// <returns> the prediction made by the clasifier /// </returns> /// <throws> Exception if model could not be evaluated </throws> /// <summary> successfully or the data contains string attributes /// </summary> public virtual double evaluateModelOnce(Classifier classifier, Instance instance) { Instance classMissing = (Instance) instance.copy(); double pred = 0; classMissing.Dataset = instance.dataset(); classMissing.setClassMissing(); if (m_ClassIsNominal) { double[] dist = classifier.distributionForInstance(classMissing); pred = Utils.maxIndex(dist); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" if (dist[(int) pred] <= 0) { pred = Instance.missingValue(); } updateStatsForClassifier(dist, instance); } else { pred = classifier.classifyInstance(classMissing); updateStatsForPredictor(pred, instance); } return pred; }
private void readDataTimer_Tick(object sender, EventArgs e) { if (okTimer > 3000) okTimer = -1; okTimer++; #if (PocketPC) #else if (this.Visible) this.Visible = false; #endif if (isStartedReceiver) { count++; if ((Environment.TickCount - time) >= 1000) { ave = sum / (double)count; //textBoxDist.Text = "R: " + count + " T: " + sum; aMITesLogger.WriteLogComment("R: " + count + " T: " + sum); sum = 0; count = 0; time = Environment.TickCount; } //aMITesDecoder.GetSensorData(this.mitesControllers[0]); for (int i = 0; (i < this.sensors.TotalReceivers); i++) // FIX SSI this.mitesDecoders[i].GetSensorData(this.mitesControllers[i]); for (int i = 1; (i < this.sensors.TotalReceivers); i++) this.mitesDecoders[0].MergeDataOrderProperly(this.mitesDecoders[i]); //A training session has started if (IsTraining==true) { if (AutoTraining == true) { string current_activity = ((AXML.Label)((AXML.Category)this.annotation.Categories[0]).Labels[autoTrainingIndex]).Name; if (Extractor.IsTrained(current_activity)) { this.startActivityTime = Environment.TickCount + Extractor.Configuration.TrainingWaitTime*1000;//Constants.TRAINING_GAP; autoTrainingIndex++; //check if auto training completed if (autoTrainingIndex == ((AXML.Category)this.annotation.Categories[0]).Labels.Count) { //this.label5.Text = "TR completed"; //this.label11.Text = "Training Completed"; EndTraining(); this.goodTimer.reset(); this.overallTimer.reset(); } else { ((Button)this.categoryButtons[0]).Text = ((AXML.Label)((AXML.Category)this.annotation.Categories[0]).Labels[autoTrainingIndex]).Name; this.goodTimer.reset(); PlaySound(@"\Windows\Voicbeep", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_SYNC)); PlaySound(@"\Windows\Voicbeep", IntPtr.Zero, (int)(PlaySoundFlags.SND_FILENAME | PlaySoundFlags.SND_SYNC)); } } else if (this.startActivityTime < Environment.TickCount) // TRAINING_GAP passed { // this.label5.Text = "TR in progress"; //this.label11.Text = "Training " + current_activity; this.goodTimer.start(); double lastTimeStamp = Extractor.StoreMITesWindow(); if (Extractor.GenerateFeatureVector(lastTimeStamp)) { Extractor.TrainingTime[current_activity] = (int)Extractor.TrainingTime[current_activity] + 200;//Extractor.Configuration.OverlapTime;// get it from configuration string arffSample = Extractor.toString() + "," + current_activity.Replace(' ', '_'); this.tw.WriteLine(arffSample); this.label8.Text = Extractor.DiscardedLossRateWindows.ToString(); //this.label10.Text = Extractor.DiscardedConsecutiveLossWindows.ToString(); } } else { // this.label5.Text = "TR in " + ((int)(this.startActivityTime - Environment.TickCount) / 1000) + " secs"; // this.label11.Text = "Training " + current_activity + " in " + ((int)(this.startActivityTime - Environment.TickCount) / 1000) + " secs"; } } else // Manual Training { } } //Classifying if (isClassifying==true) { double lastTimeStamp = Extractor.StoreMITesWindow(); 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]; labelCounters[j] = 0; } this.label6.Text = mostActivity; //this.label11.Text = "Fahd is "+mostActivity; } } } 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 //store sum of abs values of consecutive accelerometer readings for (int i = 0; (i < this.mitesDecoders[0].someMITesDataIndex); i++) { if ((this.mitesDecoders[0].someMITesData[i].type != (int)MITesTypes.NOISE) && (this.mitesDecoders[0].someMITesData[i].type == (int)MITesTypes.ACCEL)) { int channel = 0, x = 0, y = 0, z = 0; channel = (int)this.mitesDecoders[0].someMITesData[i].channel; x = (int)this.mitesDecoders[0].someMITesData[i].x; y = (int)this.mitesDecoders[0].someMITesData[i].y; z = (int)this.mitesDecoders[0].someMITesData[i].z; // if ((channel != 14) && (channel != 7) && (channel != 8) && (channel != 11) && (channel != 4) // && (channel != 17) && (channel != 1) && (channel != 0)) // { // Console.Out.Write("error"); // } 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; } } } // if (this.isCollectingDetailedData == true) // aMITesLogger.SaveRawData(); //Collecting Simple plotting data for demos // for each channel create a file and write to it //if (this.isCollectingSimpleData == true) //{ // for (int i = 0; i < aMITesDecoder.someMITesDataIndex; i++) // { // if ((aMITesDecoder.someMITesData[i].type != (int)MITesTypes.NOISE) && // (aMITesDecoder.someMITesData[i].type == (int)MITesTypes.ACCEL)) // { // int channel = 0, x = 0, y = 0, z = 0; // channel = (int)aMITesDecoder.someMITesData[i].channel; // double unixtimestamp = aMITesDecoder.someMITesData[i].unixTimeStamp; // if (this.tws[channel] == null) // { // xs[channel] = 0; // ys[channel] = 0; // zs[channel] = 0; // this.mitesLastTimeStamps[channel] = unixtimestamp; // this.mitesSampleCounters[channel] = 0; // this.tws[channel] = new StreamWriter(this.dataDirectory + "\\MITes_Channel" + channel + ".dat"); // } // xs[channel] = xs[channel]+ (int)aMITesDecoder.someMITesData[i].x; // ys[channel] = ys[channel] +(int)aMITesDecoder.someMITesData[i].y; // zs[channel] = zs[channel] + (int)aMITesDecoder.someMITesData[i].z; // this.mitesSampleCounters[channel]=this.mitesSampleCounters[channel]+1; // // if ((unixtimestamp-this.mitesLastTimeStamps[channel])>=1000) // //{ // this.tws[channel].WriteLine(unixtimestamp + "," + // (int)(xs[channel] / this.mitesSampleCounters[channel]) + "," + // (int)(ys[channel] / this.mitesSampleCounters[channel]) + "," + // (int)(zs[channel] / this.mitesSampleCounters[channel])); // xs[channel] = 0; // ys[channel] = 0; // zs[channel] = 0; // this.mitesLastTimeStamps[channel]=unixtimestamp; // System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // dateTime = dateTime.AddMilliseconds(unixtimestamp); // this.mitesSampleCounters[channel]=0; // //} // } // } //} //aMITesLoggerReader.GetSensorData(10, true); // true indicates PLFormat sum += this.mitesDecoders[0].GetLastByteNum(); aMITesLogger.SaveRawData(); if (flushTimer == 0) aMITesLogger.FlushBytes(); if (flushTimer > 6000) flushTimer = -1; flushTimer++; aMITesDataFilterer.RemoveZeroNoise(); this.mitesDecoders[0].UpdateSamplingRate(aMITesDataFilterer.CountNonNoise()); if (printSamplingCount > 500) { ((System.Windows.Forms.Label)this.sensorLabels["SampRate"]).Text = "Samp: " + this.mitesDecoders[0].GetSamplingRate(); //textBoxRate.Text = "Samp: " + aMITesDecoder.GetSamplingRate(); //aMITesLogger.WriteLogComment(textBoxUV.Text); printSamplingCount = 0; } else printSamplingCount++; // Check HR values int hr = aMITesHRAnalyzer.Update(); if (hr > 0) { sumHR += hr; hrCount++; } //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 (PocketPC) if (this.tabControl1.TabIndex == 0) { #endif ReportActivityCounts(); ReportHR(); #if (PocketPC) } #endif 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(); } // Graph accelerometer data if (isPlotting) GraphAccelerometerValues(); stepsToWarning++; } }
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 }