Exemplo n.º 1
0
    ///////////////////////////////////////////////////////////////////////////////
    // Methods for doing main class job                                          //
    ///////////////////////////////////////////////////////////////////////////////
    #region METHODS

    /// <summary>
    /// This method exports the fixations of the given <see cref="SampleType"/>
    /// to the given File including AOI information.
    /// </summary>
    /// <param name="options">An <see cref="ExportOptions"/> with options for the file export.</param>
    /// <param name="type">The <see cref="SampleType"/> to be exported.</param>
    private void Export(ExportOptions options, SampleType type)
    {
      string tableName = string.Empty;
      string fileName = string.Empty;

      DataTable dataTable = new DataTable();
      switch (type)
      {
        case SampleType.Gaze:
          tableName = "GazeFixations";
          dataTable = Document.ActiveDocument.DocDataSet.GazeFixations;
          fileName = options.GazeFileName;
          break;
        case SampleType.Mouse:
          tableName = "MouseFixations";
          dataTable = Document.ActiveDocument.DocDataSet.MouseFixations;
          fileName = options.MouseFileName;
          break;
      }

      bool unknownSubjectFound = false;
      string missingSubjectName = string.Empty;

      using (StreamWriter exportFileWriter = new StreamWriter(fileName))
      {
        // Write Documentation
        exportFileWriter.WriteLine("# File: " + Path.GetFileName(fileName));
        exportFileWriter.WriteLine("# Created: " + DateTime.Today.Date.ToLongDateString() + "," + DateTime.Now.ToLongTimeString());
        exportFileWriter.WriteLine("# with: " + Application.ProductName + " Version: " + Document.ActiveDocument.ExperimentSettings.OgamaVersion.ToString(3));

        exportFileWriter.WriteLine("# Contents: " + tableName + " table.");
        exportFileWriter.WriteLine("# Applies to Projekt:" + Document.ActiveDocument.ExperimentSettings.Name);
        exportFileWriter.WriteLine("#");

        if (options.ExportFixations)
        {
          // Write Column Names
          foreach (DataColumn dataColumn in dataTable.Columns)
          {
            exportFileWriter.Write(dataColumn.Caption);
            exportFileWriter.Write("\t");
          }
        }
        else
        {
          // We should export saccades which need some other column descriptions
          exportFileWriter.Write("SubjectName");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("TrialID");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("TrialSequence");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("CountInTrial");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("StartTime");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Duration");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Distance");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Velocity");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Validity");
          exportFileWriter.Write("\t");
        }

        if (options.ExportSubjectDetails)
        {
          exportFileWriter.Write("SubjectCategory");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Age");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Sex");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Handedness");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Comments");
          exportFileWriter.Write("\t");

          DataTable customParams =
            Document.ActiveDocument.DocDataSet.ParamsAdapter.GetData();
          foreach (DataRow paramRow in customParams.Rows)
          {
            exportFileWriter.Write(paramRow["Param"]);
            exportFileWriter.Write("\t");
          }
        }

        if (options.ExportTrialDetails)
        {
          exportFileWriter.Write("Trial Name");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("Trial Category");
          exportFileWriter.Write("\t");
          exportFileWriter.Write("SlideNr");
          exportFileWriter.Write("\t");
        }

        if (options.ExportAOIDetails)
        {
          if (options.ExportFixations)
          {
            exportFileWriter.Write("AOI");
            exportFileWriter.Write("\t");
            exportFileWriter.Write("AOI group");
            exportFileWriter.Write("\t");
          }
          else
          {
            exportFileWriter.Write("Saccade Target AOI");
            exportFileWriter.Write("\t");
            exportFileWriter.Write("Saccade Target AOI group");
            exportFileWriter.Write("\t");
          }
        }

        exportFileWriter.WriteLine();

        int trialID = -1;
        int lastTrialID = -1;

        string subjectName = string.Empty;
        string lastsubjectName = "LastSubjectKLSMA";

        DataView trialsAOIsView = new DataView(Document.ActiveDocument.DocDataSet.AOIs);
        SubjectsData subjectData = new SubjectsData();
        Dictionary<string, string> subjectParams = new Dictionary<string, string>();

        // Sort fixation data
        DataView fixationsView = new DataView(dataTable);
        fixationsView.Sort = "SubjectName, TrialSequence, CountInTrial ASC";

        VGElementCollection trialAOIs = new VGElementCollection();
        string category = string.Empty;
        string trialName = string.Empty;
        PointF lastFixationCenter = PointF.Empty;
        long lastFixationEndTime = 0;
        int lastFixationDuration = 0;
        int countInTrial = 0;
        int slideNr = 0;
        List<long> slideStartTimes = new List<long>();
        foreach (DataRowView dataRow in fixationsView)
        {
          trialID = (int)dataRow["TrialID"];

          // Skip trials that are not selected.
          if (!options.CheckedTrialIDs.Contains(trialID))
          {
            continue;
          }

          int trialSequence = (int)dataRow["TrialSequence"];
          long startTime = (long)dataRow["StartTime"];
          int length = (int)dataRow["Length"];
          float posX = Convert.ToSingle(dataRow["PosX"]);
          float posY = Convert.ToSingle(dataRow["PosY"]);
          PointF fixationCenter = new PointF(posX, posY);

          subjectName = dataRow["SubjectName"].ToString();
          if (!options.CheckedSubjects.Contains(subjectName))
          {
            continue;
          }

          if (options.ExportSubjectDetails)
          {
            if (subjectName != lastsubjectName)
            {
              subjectData = new SubjectsData();

              DataTable subjectsTable = Document.ActiveDocument.DocDataSet.SubjectsAdapter.GetDataBySubject(subjectName);
              if (subjectsTable.Rows.Count == 0)
              {
                unknownSubjectFound = true;
                missingSubjectName = subjectName;
                continue;
              }

              // Parse subject information
              if (!subjectsTable.Rows[0].IsNull("Age"))
              {
                subjectData.Age = (int)subjectsTable.Rows[0]["Age"];
              }

              subjectData.Category = subjectsTable.Rows[0]["Category"].ToString();
              subjectData.Comments = subjectsTable.Rows[0]["Comments"].ToString();
              subjectData.Handedness = subjectsTable.Rows[0]["Handedness"].ToString();
              subjectData.Sex = subjectsTable.Rows[0]["Sex"].ToString();

              // Parse custom subject information
              subjectParams.Clear();
              DataTable subjectParamsTable = Document.ActiveDocument.DocDataSet.SubjectParametersAdapter.GetDataBySubject(subjectName);
              foreach (DataRow paramRow in subjectParamsTable.Rows)
              {
                subjectParams.Add(paramRow["Param"].ToString(), paramRow["ParamValue"].ToString());
              }

              lastsubjectName = subjectName;
            }
          }

          if (trialID != lastTrialID)
          {
            slideStartTimes.Clear();
            DataTable trialEvents = Document.ActiveDocument.DocDataSet.TrialEventsAdapter.GetDataBySubjectNameTrialSequenceButOnlySlideChangeResponses(subjectName, trialSequence);
            foreach (DataRow slideEventRow in trialEvents.Rows)
            {
              slideStartTimes.Add((long)slideEventRow["EventTime"]);
            }

            countInTrial = 0;
            slideNr = 0;

            if (options.ExportTrialDetails || options.ExportAOIDetails)
            {
              DataTable trialTable = Document.ActiveDocument.DocDataSet.TrialsAdapter.GetDataBySubjectAndTrialID(subjectName, trialID);
              if (trialTable.Rows.Count > 0)
              {
                category = trialTable.Rows[0]["Category"].ToString();
                trialName = trialTable.Rows[0]["TrialName"].ToString();
              }

              string filter = "TrialID=" + trialID + string.Empty;
              trialsAOIsView.RowFilter = filter;
              lastTrialID = trialID;
              trialAOIs.Clear();

              foreach (DataRowView row in trialsAOIsView)
              {
                string strPtList = row["ShapePts"].ToString();
                string aoiType = row["ShapeType"].ToString();
                string aoiName = row["ShapeName"].ToString();
                string shapeGroup = row["ShapeGroup"].ToString();

                VGElement aoi = Queries.GetVGElementFromDatabase(aoiType, aoiName, shapeGroup, strPtList);
                trialAOIs.Add(aoi);
              }
            }
          }

          if (slideStartTimes.Count > (slideNr + 1) && startTime > slideStartTimes[slideNr])
          {
            slideNr++;
          }

          if (options.ExportFixations)
          {
            // Write fixation table content
            foreach (object cellValue in dataRow.Row.ItemArray)
            {
              exportFileWriter.Write(cellValue.ToString());
              exportFileWriter.Write("\t");
            }
          }
          else
          {
            if (countInTrial != 0)
            {
              // we should export saccades
              exportFileWriter.Write(subjectName);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(trialID);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(trialSequence);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(countInTrial);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(lastFixationEndTime);
              exportFileWriter.Write("\t");
              int duration = (int)(startTime - lastFixationEndTime);
              exportFileWriter.Write(duration);
              exportFileWriter.Write("\t");
              float distance = VGPolyline.Distance(lastFixationCenter, fixationCenter);
              exportFileWriter.Write(distance);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(distance / duration);
              exportFileWriter.Write("\t");

              int validity = 0;
              if (duration > lastFixationDuration)
              {
                validity = -1;
              }

              exportFileWriter.Write(validity);
              exportFileWriter.Write("\t");
            }
          }

          if (options.ExportSubjectDetails)
          {
            if (options.ExportFixations || countInTrial != 0)
            {
              // Write subject information
              exportFileWriter.Write(subjectData.Category);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(subjectData.Age);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(subjectData.Sex);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(subjectData.Handedness);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(subjectData.Comments);
              exportFileWriter.Write("\t");

              foreach (string paramValue in subjectParams.Values)
              {
                exportFileWriter.Write(paramValue);
                exportFileWriter.Write("\t");
              }
            }
          }

          if (options.ExportTrialDetails)
          {
            if (options.ExportFixations || countInTrial != 0)
            {
              // Write trial information
              exportFileWriter.Write(trialName != string.Empty ? trialName : "NamelessTrial");
              exportFileWriter.Write("\t");
              exportFileWriter.Write(category);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(slideNr);
              exportFileWriter.Write("\t");
            }
          }

          if (options.ExportAOIDetails)
          {
            if (options.ExportFixations || countInTrial != 0)
            {
              // Retrieve AOI position
              string hittedAOIName = string.Empty;
              string hittedAOIGroup = string.Empty;
              List<string[]> hittedAOIs = Statistics.Statistic.FixationHitsAOI(trialAOIs, dataRow);

              if (hittedAOIs.Count == 0)
              {
                hittedAOIName = "nowhere";
                hittedAOIGroup = "nowhere";
              }

              foreach (string[] aoi in hittedAOIs)
              {
                // Concatenate hitted AOIs
                hittedAOIName += aoi[0] + "#";
                hittedAOIGroup += aoi[1] + "#";
              }

              if (hittedAOIs.Count > 0)
              {
                hittedAOIName = hittedAOIName.Substring(0, hittedAOIName.Length - 1);
                hittedAOIGroup = hittedAOIGroup.Substring(0, hittedAOIGroup.Length - 1);
              }

              exportFileWriter.Write(hittedAOIName);
              exportFileWriter.Write("\t");
              exportFileWriter.Write(hittedAOIGroup);
              exportFileWriter.Write("\t");
            }
          }

          if (options.ExportFixations || countInTrial != 0)
          {
            // Write new line for next row.
            exportFileWriter.WriteLine();
          }

          countInTrial++;
          lastFixationCenter = fixationCenter;
          lastFixationEndTime = startTime + length;
          lastFixationDuration = length;
        }
      }

      if (unknownSubjectFound)
      {
        string message = "At least one fixation of an subject that is not in the database anymore " +
          "was found. Subject: '" + missingSubjectName + "'" + Environment.NewLine +
          "Please re-run a complete fixation calculation for all subjects.";
        ExceptionMethods.ProcessMessage("Old subject fixations found", message);
      }

      ExceptionMethods.ProcessMessage("Export successful.", "Fixations were successfully exported to file");
    }
Exemplo n.º 2
0
    /// <summary>
    ///   This method iterates the imported fixation rows to
    ///   catch the trial changes that are detected during the call
    ///   of <see cref="GenerateOgamaFixationDataList(int)" />.
    ///   The trials are then written into the trial list.
    /// </summary>
    private static void GenerateOgamaSubjectAndTrialList()
    {
      // Clear foregoing imports.
      TrialList.Clear();
      SubjectList.Clear();

      if (FixationDataList.Count == 0)
      {
        return;
      }

      // Initializes variables
      var lastSequence = -5;
      var lastSubject = "#";

      // Iterate raw data list
      for (int i = 0; i < FixationDataList.Count; i++)
      {
        var importRow = FixationDataList[i];
        int currentSequence = importRow.TrialSequence;
        string currentSubject = importRow.SubjectName;

        FixationDataList[i] = importRow;

        // If subject has changed write new subject table entry.
        if (currentSubject != lastSubject)
        {
          var newSubjectsData = new SubjectsData { SubjectName = currentSubject };
          SubjectList.Add(newSubjectsData);
          lastSubject = currentSubject;
        }

        // If trial has changed parse the trial information to 
        // create a trial entry in the trialList.
        if (currentSequence != lastSequence)
        {
          string subject = importRow.SubjectName ?? "Subject1";

          // Create trial row
          var newTrialData = new TrialsData
                               {
                                 SubjectName = subject,
                                 TrialSequence = importRow.TrialSequence,
                                 TrialID = importRow.TrialID,
                                 TrialName = importRow.TrialID.ToString(CultureInfo.InvariantCulture)
                               };

          TrialList.Add(newTrialData);

          lastSequence = currentSequence;
        }
      }
    }
Exemplo n.º 3
0
    ///////////////////////////////////////////////////////////////////////////////
    // Eventhandler                                                              //
    ///////////////////////////////////////////////////////////////////////////////
    #region EVENTS

    ///////////////////////////////////////////////////////////////////////////////
    // Eventhandler for UI, Menu, Buttons, Toolbars etc.                         //
    ///////////////////////////////////////////////////////////////////////////////
    #region WINDOWSEVENTHANDLER
    #endregion //WINDOWSEVENTHANDLER

    ///////////////////////////////////////////////////////////////////////////////
    // Eventhandler for Custom Defined Events                                    //
    ///////////////////////////////////////////////////////////////////////////////
    #region CUSTOMEVENTHANDLER
    #endregion //CUSTOMEVENTHANDLER

    #endregion //EVENTS

    ///////////////////////////////////////////////////////////////////////////////
    // Methods and Eventhandling for Background tasks                            //
    ///////////////////////////////////////////////////////////////////////////////
    #region BACKGROUNDWORKER
    #endregion //BACKGROUNDWORKER

    ///////////////////////////////////////////////////////////////////////////////
    // Inherited methods                                                         //
    ///////////////////////////////////////////////////////////////////////////////
    #region OVERRIDES
    #endregion //OVERRIDES

    ///////////////////////////////////////////////////////////////////////////////
    // Methods for doing main class job                                          //
    ///////////////////////////////////////////////////////////////////////////////
    #region METHODS

    /// <summary>
    /// Generate all the lists of subject, trial and raw data.
    /// </summary>
    /// <remarks>This is the heart of the class. If something does not work as expected,
    /// first have a look here.</remarks>
    private static void GenerateSubjectTrialRawdataList()
    {
      rawDataList.Clear();
      trialList.Clear();
      subjectList.Clear();
      trialEventsList.Clear();

      // Use the decimal separator specified.
      NumberFormatInfo nfi = CultureInfo.GetCultureInfo("en-US").NumberFormat;
      if (asciiSettings.DecimalSeparatorCharacter == ',')
      {
        nfi = CultureInfo.GetCultureInfo("de-DE").NumberFormat;
      }

      // Begin reading File
      string lastSubject = string.Empty;
      int lastTrialID = -5;
      string line = string.Empty;
      int counter = 0;
      try
      {
        // Open file
        using (StreamReader importReader = new StreamReader(asciiSettings.Filename))
        {
          string[] columns;
          Dictionary<string, int> columnNames = new Dictionary<string, int>();

          // Read every line of ImportFile
          while ((line = importReader.ReadLine()) != null)
          {
            // ignore empty lines
            if (line.Trim() == string.Empty)
            {
              continue;
            }

            // Ignore Quotes 
            if (line.StartsWith("#"))
            {
              continue;
            }

            // Skip first line filled with column titles
            if (counter == 0)
            {
              columns = line.Split('\t');
              for (int i = 0; i < columns.Length; i++)
              {
                columnNames.Add(columns[i], i);
              }

              counter++;
              continue;
            }

            // Split line in columns
            string[] items = line.Split('\t');

            // read subjects data
            string subjectName = items[columnNames["SubjectName"]];
            if (subjectName != lastSubject)
            {
              SubjectsData newSubjectData = new SubjectsData();
              newSubjectData.SubjectName = subjectName;
              newSubjectData.Category = items[columnNames["SubjectCategory"]];
              int result;
              if (int.TryParse(items[columnNames["Age"]], out result))
              {
                newSubjectData.Age = result;
              }

              newSubjectData.Sex = items[columnNames["Sex"]];
              newSubjectData.Handedness = items[columnNames["Handedness"]];
              newSubjectData.Comments = items[columnNames["Comments"]];

              if (!subjectList.Contains(newSubjectData))
              {
                subjectList.Add(newSubjectData);
              }

              lastSubject = subjectName;
            }

            // read trials data
            int trialID = Convert.ToInt32(items[columnNames["TrialID"]]);
            if (trialID != lastTrialID)
            {
              TrialsData newTrialsData = new TrialsData();
              newTrialsData.SubjectName = subjectName;
              newTrialsData.TrialID = trialID;
              newTrialsData.TrialName = items[columnNames["TrialName"]];
              newTrialsData.TrialSequence = Convert.ToInt32(items[columnNames["TrialSequence"]]);
              newTrialsData.Category = items[columnNames["TrialCategory"]];
              newTrialsData.TrialStartTime = Convert.ToInt64(items[columnNames["TrialStartTime"]]);
              int result;
              if (int.TryParse(items[columnNames["Duration"]], out result))
              {
                newTrialsData.Duration = result;
              }

              if (items[columnNames["EliminateData"]] != string.Empty)
              {
                newTrialsData.EliminateData = true;
              }

              if (!trialList.Contains(newTrialsData))
              {
                trialList.Add(newTrialsData);
              }

              lastTrialID = trialID;
            }

            // read trials data
            string eventeventID = items[columnNames["EventEventID"]];
            if (eventeventID != string.Empty)
            {
              TrialEventsData newTrialEventsData = new TrialEventsData();
              newTrialEventsData.EventID = Convert.ToInt32(items[columnNames["EventEventID"]]);
              newTrialEventsData.EventParam = items[columnNames["EventParam"]];
              newTrialEventsData.EventTask = items[columnNames["EventTask"]];
              newTrialEventsData.EventTime = Convert.ToInt64(items[columnNames["EventTime"]]);
              newTrialEventsData.EventType = items[columnNames["EventType"]];
              newTrialEventsData.SubjectName = subjectName;
              newTrialEventsData.TrialSequence = Convert.ToInt32(items[columnNames["TrialSequence"]]);
              if (!trialEventsList.Contains(newTrialEventsData))
              {
                trialEventsList.Add(newTrialEventsData);
              }
            }

            // Create Ogama columns placeholder
            RawData newRawData = new RawData();

            // Save time value
            newRawData.Time = Convert.ToInt64(items[columnNames["Time"]]);
            newRawData.SubjectName = subjectName;
            newRawData.TrialSequence = Convert.ToInt32(items[columnNames["TrialSequence"]]);
            newRawData.Category = items[columnNames["TrialCategory"]];

            if (items[columnNames["PupilDiaX"]] != string.Empty)
            {
              newRawData.PupilDiaX = Convert.ToSingle(items[columnNames["PupilDiaX"]], nfi);
            }

            if (items[columnNames["PupilDiaY"]] != string.Empty)
            {
              newRawData.PupilDiaY = Convert.ToSingle(items[columnNames["PupilDiaY"]], nfi);
            }

            if (items[columnNames["GazePosX"]] != string.Empty)
            {
              newRawData.GazePosX = Convert.ToSingle(items[columnNames["GazePosX"]], nfi);
            }

            if (items[columnNames["GazePosY"]] != string.Empty)
            {
              newRawData.GazePosY = Convert.ToSingle(items[columnNames["GazePosY"]], nfi);
            }

            if (items[columnNames["MousePosX"]] != string.Empty)
            {
              newRawData.MousePosX = Convert.ToSingle(items[columnNames["MousePosX"]], nfi);
            }

            if (items[columnNames["MousePosY"]] != string.Empty)
            {
              newRawData.MousePosY = Convert.ToSingle(items[columnNames["MousePosY"]], nfi);
            }

            if (items[columnNames["EventID"]] != string.Empty)
            {
              newRawData.EventID = Convert.ToInt32(items[columnNames["EventID"]]);
            }

            // Add the parsed raw data row to the list.
            rawDataList.Add(newRawData);
          }
        }
      }
      catch (Exception ex)
      {
        ExceptionMethods.HandleException(ex);
      }
    }
Exemplo n.º 4
0
    /// <summary>
    /// This method writes a new <see cref="SubjectsData"/> information
    /// to the subjects data table of the dataset.
    /// </summary>
    /// <remarks>This change has to be afterwards written to the database file
    /// with a call to 
    /// <code>int affectedRows = Document.ActiveDocument.DocDataSet.TadSubjects.Update(
    /// Document.ActiveDocument.DocDataSet.Subjects);</code></remarks>
    /// <param name="subjectData">A <see cref="SubjectsData"/> with the 
    /// new subject information.</param>
    /// <returns><strong>True</strong>, if successful otherwise, <strong>false</strong>.</returns>
    public static bool WriteSubjectToDataSet(SubjectsData subjectData)
    {
      SQLiteOgamaDataSet.SubjectsRow workSubjectData;
      workSubjectData = Document.ActiveDocument.DocDataSet.Subjects.NewSubjectsRow();
      workSubjectData.SubjectName = subjectData.SubjectName;

      if (subjectData.Category == null)
      {
        workSubjectData.SetCategoryNull();
      }
      else
      {
        workSubjectData.Category = subjectData.Category;
      }

      if (subjectData.Age == null)
      {
        workSubjectData.SetAgeNull();
      }
      else
      {
        workSubjectData.Age = (int)subjectData.Age;
      }

      if (subjectData.Sex == null)
      {
        workSubjectData.SetSexNull();
      }
      else
      {
        workSubjectData.Sex = subjectData.Sex;
      }

      if (subjectData.Handedness == null)
      {
        workSubjectData.SetHandednessNull();
      }
      else
      {
        workSubjectData.Handedness = subjectData.Handedness;
      }

      if (subjectData.Comments == null)
      {
        workSubjectData.SetCommentsNull();
      }
      else
      {
        workSubjectData.Comments = subjectData.Comments;
      }

      try
      {
        Document.ActiveDocument.DocDataSet.Subjects.BeginLoadData();
        Document.ActiveDocument.DocDataSet.Subjects.AddSubjectsRow(workSubjectData);
        Document.ActiveDocument.DocDataSet.Subjects.EndLoadData();
      }
      catch (Exception ex)
      {
        ExceptionMethods.HandleException(ex);

        return false;
      }

      return true;
    }
Exemplo n.º 5
0
    /// <summary>
    ///   This method iterates the imported raw data rows to
    ///   catch the trial changes that are detected during the call
    ///   of <see cref="GenerateOgamaRawDataList(int)" />.
    ///   The trials are then written into the trial list.
    /// </summary>
    private static void GenerateOgamaSubjectAndTrialList()
    {
      // Clear foregoing imports.
      TrialList.Clear();
      SubjectList.Clear();

      if (RawDataList.Count == 0)
      {
        // string message = "The parsing of the log file into OGAMAs " +
        // "Raw data columns failed. No lines have been successfully read. " +
        // Environment.NewLine +
        // "So the trial generation could not be started." +
        // Environment.NewLine + "Please change the import settings and try again";
        // ExceptionMethods.ProcessErrorMessage(message);
        return;
      }

      // Initializes variables
      int currentSequence = 0;
      int lastSequence = -5;
      string currentSubject = "#";
      string lastSubject = "#";
      int overallTrialCounter = 0;
      int trialCounter = 0;
      int subjectCounter = 0;

      // Iterate raw data list
      for (int i = 0; i < RawDataList.Count; i++)
      {
        RawData importRow = RawDataList[i];
        currentSequence = importRow.TrialSequence;
        currentSubject = importRow.SubjectName;

        // If subject has changed write new subject table entry.
        if (currentSubject != lastSubject)
        {
          var newSubjectsData = new SubjectsData();
          newSubjectsData.SubjectName = currentSubject;
          SubjectList.Add(newSubjectsData);

          if (subjectCounter > 0)
          {
            TrialsData tempSubjetData = TrialList[overallTrialCounter - 1];
            tempSubjetData.Duration = (int)(RawDataList[i - 1].Time - tempSubjetData.TrialStartTime);
            TrialList[overallTrialCounter - 1] = tempSubjetData;
          }

          lastSubject = currentSubject;
          lastSequence = -5;
          trialCounter = 0;
          subjectCounter++;
        }

        // If trial has changed parse the trial information to 
        // create a trial entry in the trialList.
        if (currentSequence != lastSequence)
        {
          string subject = importRow.SubjectName != null ? importRow.SubjectName : "Subject1";
          string categorie = importRow.Category != null ? importRow.Category : string.Empty;
          int trialID = currentSequence;
          if (detectionSetting.TrialSequenceToTrialIDAssignments.ContainsKey(currentSequence))
          {
            trialID = detectionSetting.TrialSequenceToTrialIDAssignments[currentSequence];
          }

          string image = "No image file specified";

          switch (detectionSetting.StimuliImportMode)
          {
            case StimuliImportModes.UseiViewXMSG:
              if (detectionSetting.ImageDictionary.ContainsKey(currentSequence))
              {
                image = detectionSetting.ImageDictionary[currentSequence];
              }

              break;
            case StimuliImportModes.UseImportColumn:
            case StimuliImportModes.UseAssignmentTable:
              if (detectionSetting.TrialSequenceToTrialIDAssignments.ContainsKey(currentSequence))
              {
                trialID = detectionSetting.TrialSequenceToTrialIDAssignments[currentSequence];
                if (detectionSetting.TrialIDToImageAssignments.ContainsKey(trialID))
                {
                  image = detectionSetting.TrialIDToImageAssignments[trialID];
                }
              }

              break;
            case StimuliImportModes.SearchForImageEnding:
              if (detectionSetting.ImageDictionary.ContainsKey(currentSequence))
              {
                image = detectionSetting.ImageDictionary[currentSequence];
              }

              break;
          }

          // Add empty trial to sequence numbering.
          if (detectionSetting.StimuliImportMode != StimuliImportModes.UseImportColumn
              && image == "No image file specified")
          {
            if (!detectionSetting.TrialSequenceToTrialIDAssignments.ContainsKey(currentSequence))
            {
              detectionSetting.TrialSequenceToTrialIDAssignments.Add(currentSequence, 0);
            }
          }

          long time = 0;
          switch (detectionSetting.TrialImportMode)
          {
            ////// Use the table timing
            ////if (detectionSetting.TrialSequenceToStarttimeAssignments.ContainsKey(currentSequence))
            ////{
            ////  time = detectionSetting.TrialSequenceToStarttimeAssignments[currentSequence];
            ////}
            //// break;
            case TrialSequenceImportModes.UseAssignmentTable:
            case TrialSequenceImportModes.UseMSGLines:
            case TrialSequenceImportModes.UseImportColumn:

              // Use the raw data timing
              time = importRow.Time;
              break;
          }

          // Create trial row
          var newTrialData = new TrialsData();
          newTrialData.SubjectName = subject;
          newTrialData.TrialSequence = currentSequence;
          newTrialData.TrialID = trialID;
          newTrialData.TrialName = image;
          newTrialData.Category = categorie;
          newTrialData.TrialStartTime = time;
          newTrialData.Duration = -1;
          TrialList.Add(newTrialData);

          lastSequence = currentSequence;
          trialCounter++;
          overallTrialCounter++;

          // Calculate trial duration for foregoing trial.
          if (trialCounter > 1)
          {
            TrialsData tempSubjetData = TrialList[overallTrialCounter - 2];
            int duration = 0;
            switch (detectionSetting.TrialImportMode)
            {
              case TrialSequenceImportModes.UseAssignmentTable:

                // Use the table timing
                duration = (int)(time - tempSubjetData.TrialStartTime);
                break;
              case TrialSequenceImportModes.UseMSGLines:
              case TrialSequenceImportModes.UseImportColumn:

                // Use the raw data timing
                duration = (int)(RawDataList[i].Time - tempSubjetData.TrialStartTime);
                break;
            }

            //// If there is lot of time (>200ms) left between last and current trial
            //// don´t use the space in between for the duration value.
            ////if (rawDataList[i].Time - rawDataList[i - 1].Time > 200)
            ////{
            ////  duration = (int)(rawDataList[i - 1].Time - tempSubjetData.TrialStartTime);
            ////}
            tempSubjetData.Duration = duration;
            TrialList[overallTrialCounter - 2] = tempSubjetData;
          }
        }
      }

      // Reached end of rawdatalist, so add last trial duration value from last entry
      if (trialCounter >= 1)
      {
        TrialsData tempSubjetData = TrialList[overallTrialCounter - 1];
        tempSubjetData.Duration = (int)(RawDataList[RawDataList.Count - 1].Time - tempSubjetData.TrialStartTime);
        TrialList[overallTrialCounter - 1] = tempSubjetData;
      }
    }
Exemplo n.º 6
0
    /// <summary>
    /// Initializes a new instance of the Tracker class.
    /// </summary>
    /// <param name="owningRecordModule">
    /// The <see cref="RecordModule"/>
    ///   form wich host the recorder.
    /// </param>
    /// <param name="trackerConnectButton">
    /// The <see cref="Button"/>
    ///   named "Connect" at the tab page of the tracking device.
    /// </param>
    /// <param name="trackerSubjectButton">
    /// The <see cref="Button"/>
    ///   named "Subject" at the tab page of the tracking device.
    /// </param>
    /// <param name="trackerCalibrateButton">
    /// The <see cref="Button"/>
    ///   named "Calibrate" at the tab page of the tracking device.
    /// </param>
    /// <param name="trackerRecordButton">
    /// The <see cref="Button"/>
    ///   named "Record" at the tab page of the tracking device.
    /// </param>
    /// <param name="trackerSubjectNameTextBox">
    /// The <see cref="TextBox"/>
    ///   which should contain the subject name at the tab page of the tracking device.
    /// </param>
    /// <param name="trackerSettingsFile">
    /// The file with full path to the settings
    ///   xml file of the tracking device.
    /// </param>
    protected Tracker(
      RecordModule owningRecordModule,
      Button trackerConnectButton,
      Button trackerSubjectButton,
      Button trackerCalibrateButton,
      Button trackerRecordButton,
      TextBox trackerSubjectNameTextBox,
      string trackerSettingsFile)
    {
      if (trackerSubjectButton == null)
      {
        throw new ArgumentNullException(
          "trackerSubjectButton",
          "All custom devices should have a subject button on their tab pages.");
      }

      if (trackerRecordButton == null)
      {
        throw new ArgumentNullException(
          "trackerRecordButton",
          "All custom devices should have a record button on their tab pages.");
      }

      this.recordModule = owningRecordModule;
      this.connectButton = trackerConnectButton;
      this.subjectButton = trackerSubjectButton;
      this.calibrateButton = trackerCalibrateButton;
      this.recordButton = trackerRecordButton;
      this.subjectNameTextBox = trackerSubjectNameTextBox;
      this.settingsFile = trackerSettingsFile;

      // Wires the recording finished event from the record module
      // to wait for resetting the button states after recording
      // stopped
      this.recordModule.RecordingFinished += this.RecordModuleNewRecordingFinished;

      // Wires the GazeDataChanged event of this tracking device
      // to the record modules
      // event handler.
      this.GazeDataChanged += this.recordModule.TrackerGazeDataChanged;

      // Create new empty subject
      this.subject = new SubjectsData();

      // Wire button events.
      this.recordButton.Click += this.BtnRecordClick;

      if (this.calibrateButton != null)
      {
        this.calibrateButton.Click += this.BtnCalibrateClick;
      }

      this.subjectButton.Click += this.BtnSubjectNameClick;

      if (this.connectButton != null)
      {
        this.connectButton.Click += this.BtnConnectClick;
      }
    }