Ejemplo n.º 1
0
void UI_ExportAnnotationswindow::ExportButtonClicked()
{
  int i, j, n,
      len,
      csv_format=0,
      hdl,
      annot_cnt,
      temp,
      include_duration;

  char path[MAX_PATH_LENGTH],
       str[1024],
       separator;

  FILE *annotationfile=NULL;

  struct annotationblock *annot, *annot_list;

  struct edfhdrblock *hdr;

  struct date_time_struct tm;


  if(CSVRadioButton->isChecked() == true)
  {
    if(asciiSecondsRadioButton->isChecked() == true)
    {
      csv_format = 1;
    }

    if(asciiISOtimeRadioButton->isChecked() == true)
    {
      csv_format = 2;
    }

    if(asciiISOtimedateRadioButton->isChecked() == true)
    {
      csv_format = 3;
    }

    if(asciiISOtimeFractionRadioButton->isChecked() == true)
    {
      csv_format = 4;
    }

    if(asciiISOtimedateFractionRadioButton->isChecked() == true)
    {
      csv_format = 5;
    }
  }

  if(EDFplusRadioButton->isChecked() == true)
  {
    csv_format = 0;
  }

  if(XMLRadioButton->isChecked() == true)
  {
    csv_format = 8;
  }

   mainwindow->export_annotations_var->format = csv_format;

  if(separatorBox->currentIndex() == 0)
  {
    separator = ',';
    mainwindow->export_annotations_var->separator = 0;
  }
  else
  {
    separator = '\t';
    mainwindow->export_annotations_var->separator = 1;
  }

  if(durationCheckBox->checkState() == Qt::Checked)
  {
    include_duration = 1;
    mainwindow->export_annotations_var->duration = 1;
  }
  else
  {
    include_duration = 0;
    mainwindow->export_annotations_var->duration = 0;
  }

  if(!mainwindow->files_open)
  {
    ExportAnnotsDialog->close();
    return;
  }

  if(filelist->count() < 1)
  {
    ExportAnnotsDialog->close();
    return;
  }

  ExportButton->setEnabled(false);
  CloseButton->setEnabled(false);

  for(i=0; i<mainwindow->files_open; i++)
  {
    if(!strcmp(mainwindow->edfheaderlist[i]->filename, filelist->item(filelist->currentRow())->text().toLocal8Bit().data()))
    {
      break;
    }
  }

  if(i==mainwindow->files_open)
  {
    ExportAnnotsDialog->close();
    return;
  }

  n = i;

  if(mergeRadioButton->isChecked() == true)
  {
    n = mainwindow->sel_viewtime;
  }

  hdr = mainwindow->edfheaderlist[n];

  path[0] = 0;
  if(mainwindow->recent_savedir[0]!=0)
  {
    strcpy(path, mainwindow->recent_savedir);
    strcat(path, "/");
  }
  len = strlen(path);
  get_filename_from_path(path + len, mainwindow->edfheaderlist[n]->filename, MAX_PATH_LENGTH - len);
  remove_extension_from_filename(path);
  if((csv_format > 0) && (csv_format < 6))
  {
    strcat(path, "_annotations.txt");

    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "Text files (*.txt *.TXT *.csv *.CSV)").toLocal8Bit().data());
  }

  if(csv_format == 8)
  {
    strcat(path, "_annotations.xml");

    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "XML files (*.xml *.XML)").toLocal8Bit().data());
  }

  if(csv_format == 0)
  {
    strcat(path, "_annotations.edf");

    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());
  }

  if(!strcmp(path, ""))
  {
    ExportAnnotsDialog->close();
    return;
  }

  get_directory_from_path(mainwindow->recent_savedir, path, MAX_PATH_LENGTH);

  if(mainwindow->file_is_opened(path))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Export annotations", "Error, selected file is in use.");
    messagewindow.exec();
    return;
  }

  annot_list = edfplus_annotation_copy_list(&mainwindow->annotationlist[n]);

  if(mergeRadioButton->isChecked() == true)
  {
    for(i=0; i < mainwindow->files_open; i++)
    {
      if(i != mainwindow->sel_viewtime)
      {
        annot_cnt = edfplus_annotation_count(&mainwindow->annotationlist[i]);

        for(j=0; j < annot_cnt; j++)
        {
          edfplus_annotation_add_copy(&annot_list, edfplus_annotation_item(&mainwindow->annotationlist[i], j));

          annot = edfplus_annotation_item(&annot_list, edfplus_annotation_count(&annot_list) - 1);

          annot->onset -= (mainwindow->edfheaderlist[i]->viewtime - mainwindow->edfheaderlist[mainwindow->sel_viewtime]->viewtime);
        }
      }
    }

    edfplus_annotation_sort(&annot_list);
  }

  annot_cnt = edfplus_annotation_count(&annot_list);

///////////////////////////// CSV (text) export //////////////////////////////////////

  if((csv_format > 0) && (csv_format < 6))
  {
    annotationfile = fopeno(path, "wb");
    if(annotationfile==NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open annotationfile for writing.");
      messagewindow.exec();
      ExportAnnotsDialog->close();
      edfplus_annotation_delete_list(&annot_list);
      return;
    }

    if(include_duration)
    {
      fprintf(annotationfile, "Onset%cDuration%cAnnotation\n", separator, separator);
    }
    else
    {
      fprintf(annotationfile, "Onset%cAnnotation\n", separator);
    }

    for(j=0; j < annot_cnt; j++)
    {
      annot = edfplus_annotation_item(&annot_list, j);
      if(annot == NULL)
      {
        break;
      }
      strncpy(str, annot->annotation, 1024);
      str[1023] = 0;
      utf8_to_latin1(str);

      len = strlen(str);
      for(i=0; i<len; i++)
      {
        if((((unsigned char *)str)[i] < 32) || (((unsigned char *)str)[i] == ','))
        {
          str[i] = '.';
        }
      }

      if(csv_format == 1)
      {
        if(include_duration)
        {
          fprintf(annotationfile, "%+.7f%c%s%c%s\n", (double)(annot->onset - hdr->starttime_offset) / TIME_DIMENSION, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%+.7f%c%s\n", (double)(annot->onset - hdr->starttime_offset) / TIME_DIMENSION, separator, str);
        }
      }

      if(csv_format == 2)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%02i:%02i:%02i%c%s%c%s\n", tm.hour, tm.minute, tm.second, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%02i:%02i:%02i%c%s\n", tm.hour, tm.minute, tm.second, separator, str);
        }
      }

      if(csv_format == 3)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i%c%s%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, separator, str);
        }
      }

      if(csv_format == 4)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);

          temp = TIME_DIMENSION + temp;
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%02i:%02i:%02i.%07i%c%s%c%s\n", tm.hour, tm.minute, tm.second, temp, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%02i:%02i:%02i.%07i%c%s\n", tm.hour, tm.minute, tm.second, temp, separator, str);
        }
      }

      if(csv_format == 5)
      {
        temp = annot->onset % TIME_DIMENSION;

        if(temp < 0)
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);

          temp = TIME_DIMENSION + temp;
        }
        else
        {
          utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
        }

        if(include_duration)
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i.%07i%c%s%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, temp, separator, annot->duration, separator, str);
        }
        else
        {
          fprintf(annotationfile, "%04i-%02i-%02iT%02i:%02i:%02i.%07i%c%s\n", tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, temp, separator, str);
        }
      }
    }

    fclose(annotationfile);

    edfplus_annotation_delete_list(&annot_list);

    QMessageBox messagewindow(QMessageBox::Information, "Ready", "Done.");
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();

    ExportAnnotsDialog->close();

    return;
  }

///////////////////////////// XML export //////////////////////////////////////

  if(csv_format == 8)
  {
    annotationfile = fopeno(path, "wb");
    if(annotationfile==NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open annotationfile for writing.");
      messagewindow.exec();
      ExportAnnotsDialog->close();
      edfplus_annotation_delete_list(&annot_list);
      return;
    }

    fprintf(annotationfile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

    fprintf(annotationfile, "<!-- Generated by " PROGRAM_NAME " " PROGRAM_VERSION " -->\n");

    fprintf(annotationfile, "<annotationlist>\n");

    utc_to_date_time(hdr->utc_starttime, &tm);

    fprintf(annotationfile, " <recording_start_time>%04i-%02i-%02iT%02i:%02i:%02i.%07i</recording_start_time>\n",
                            tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, (int)hdr->starttime_offset);

    for(j=0; j < annot_cnt; j++)
    {
      annot = edfplus_annotation_item(&annot_list, j);
      if(annot == NULL)
      {
        break;
      }

      temp = annot->onset % TIME_DIMENSION;

      if(temp < 0)
      {
        utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION) - 1, &tm);

        temp = TIME_DIMENSION + temp;
      }
      else
      {
        utc_to_date_time(hdr->utc_starttime + (annot->onset / TIME_DIMENSION), &tm);
      }

      fprintf(annotationfile, " <annotation>\n"
                              "  <onset>%04i-%02i-%02iT%02i:%02i:%02i.%07i</onset>\n"
                              "  <duration>%s</duration>\n"
                              "  <description>",
                              tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second, temp, annot->duration);

      xml_fwrite_encode_entity(annotationfile, annot->annotation);

      fprintf(annotationfile,                     "</description>\n"
                              " </annotation>\n");
    }

    fprintf(annotationfile, "</annotationlist>\n");

    fclose(annotationfile);

    edfplus_annotation_delete_list(&annot_list);

    QMessageBox messagewindow(QMessageBox::Information, "Ready", "Done.");
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();

    ExportAnnotsDialog->close();

    return;
  }

///////////////////////////// EDFplus export //////////////////////////////////////

  if(csv_format == 0)
  {
    hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_EDFPLUS, 0);
    if(hdl < 0)
    {
      switch(hdl)
      {
        case EDFLIB_MALLOC_ERROR : strcpy(str, "EDFlib: malloc error");
                                  break;
        case EDFLIB_NO_SUCH_FILE_OR_DIRECTORY : strcpy(str, "EDFlib: no such file or directory");
                                  break;
        case EDFLIB_MAXFILES_REACHED : strcpy(str, "EDFlib: maximum files reached");
                                  break;
        case EDFLIB_FILE_ALREADY_OPENED : strcpy(str, "EDFlib: file already opened");
                                  break;
        case EDFLIB_NUMBER_OF_SIGNALS_INVALID : strcpy(str, "EDFlib: number of signals is invalid");
                                  break;
        default : strcpy(str, "EDFlib: unknown error");
                                  break;
      }

      QMessageBox messagewindow(QMessageBox::Critical, "Error", str);
      messagewindow.exec();
      edfplus_annotation_delete_list(&annot_list);
      ExportAnnotsDialog->close();
      return;
    }

    utc_to_date_time(hdr->utc_starttime, &tm);
    edf_set_startdatetime(hdl, tm.year, tm.month, tm.day, tm.hour, tm.minute, tm.second);

    if((hdr->edfplus) || (hdr->bdfplus))
    {
      edf_set_patientname(hdl, hdr->plus_patient_name);
      edf_set_patientcode(hdl, hdr->plus_patientcode);
      if(!(strcmp(hdr->plus_gender, "Male")))
      {
        edf_set_gender(hdl, 1);
      }
      if(!(strcmp(hdr->plus_gender, "Female")))
      {
        edf_set_gender(hdl, 0);
      }
      if(hdr->plus_birthdate[0] != 0)
      {
        if(!(strncmp(hdr->plus_birthdate + 3, "jan", 3)))  n = 1;
        if(!(strncmp(hdr->plus_birthdate + 3, "feb", 3)))  n = 2;
        if(!(strncmp(hdr->plus_birthdate + 3, "mar", 3)))  n = 3;
        if(!(strncmp(hdr->plus_birthdate + 3, "apr", 3)))  n = 4;
        if(!(strncmp(hdr->plus_birthdate + 3, "may", 3)))  n = 5;
        if(!(strncmp(hdr->plus_birthdate + 3, "jun", 3)))  n = 6;
        if(!(strncmp(hdr->plus_birthdate + 3, "jul", 3)))  n = 7;
        if(!(strncmp(hdr->plus_birthdate + 3, "aug", 3)))  n = 8;
        if(!(strncmp(hdr->plus_birthdate + 3, "sep", 3)))  n = 9;
        if(!(strncmp(hdr->plus_birthdate + 3, "oct", 3)))  n = 10;
        if(!(strncmp(hdr->plus_birthdate + 3, "nov", 3)))  n = 11;
        if(!(strncmp(hdr->plus_birthdate + 3, "dec", 3)))  n = 12;
        edf_set_birthdate(hdl, atoi(hdr->plus_birthdate + 7), n, atoi(hdr->plus_birthdate));
      }
      edf_set_patient_additional(hdl, hdr->plus_patient_additional);
      edf_set_admincode(hdl, hdr->plus_admincode);
      edf_set_technician(hdl, hdr->plus_technician);
      edf_set_equipment(hdl, hdr->plus_equipment);
      edf_set_recording_additional(hdl, hdr->plus_recording_additional);
    }
    else
    {
      edf_set_patientname(hdl, hdr->patient);
      edf_set_recording_additional(hdl, hdr->recording);
    }

    int hasdot,
        decimals;

    for(j=0; j < annot_cnt; j++)
    {
      annot = edfplus_annotation_item(&annot_list, j);
      if(annot == NULL)
      {
        break;
      }

      if(annot->duration[0] == 0)
      {
        edfwrite_annotation_utf8(hdl, annot->onset / 1000LL, -1LL, annot->annotation);
      }
      else
      {
        strcpy(str, annot->duration);

        len = strlen(str);

        hasdot = 0;

        for(i=0; i<len; i++)
        {
          if(str[i] == '.')
          {
            hasdot = 1;

            for(decimals=0; decimals<4; decimals++)
            {
              str[i] = str[i+1];

              if(str[i] == 0)
              {
                for( ; decimals<4; decimals++)
                {
                  str[i] = '0';

                  i++;
                }

                i--;
              }

              i++;
            }

            str[i] = 0;

            break;
          }
        }

        if(!hasdot)
        {
          strcat(str, "0000");
        }

        edfwrite_annotation_utf8(hdl, annot->onset / 1000LL, atoi(str), annot->annotation);
      }
    }

    if(edfclose_file(hdl) != 0)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred: edfclose_file()");
      messagewindow.exec();
    }

    edfplus_annotation_delete_list(&annot_list);

    QMessageBox messagewindow(QMessageBox::Information, "Ready", "Done.");
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();

    ExportAnnotsDialog->close();
  }
}
Ejemplo n.º 2
0
void UI_BI98002EDFwindow::SelectFileButton()
{
  int i, j, n,
      tmp,
      end_of_file,
      samplefreq=0,
      chns = 3,
      hdl,
      samplesize=1,
      bufsize,
      *buf2,
      datablocks,
      blocks_written,
      checked_modelnumber=0,
      checked_samplerate=0,
      checked_recordhours=0,
      checked_recorddate=0,
      checked_recordtime=0,
      startdate_year=0,
      startdate_month=0,
      startdate_day=0,
      starttime_hour=0,
      starttime_minute=0,
      starttime_second=0,
      progress_steps;

  char path[MAX_PATH_LENGTH],
       outputfilename[MAX_PATH_LENGTH],
       str[2048],
       str2[128],
       *buf1,
       tmp2,
       modelnumber_str[32];

  FILE *dcmfile,
       *evtfile;



  strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "DCM files (*.dcm *.DCM)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    return;
  }

  get_directory_from_path(recent_opendir, path, MAX_PATH_LENGTH);

  get_filename_from_path(outputfilename, path, MAX_PATH_LENGTH);

  dcmfile = fopeno(path, "rb");
  if(dcmfile==NULL)
  {
    snprintf(str, 2048, "Can not open file %s for reading.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", QString::fromLocal8Bit(str));
    messagewindow.exec();
    return;
  }

  remove_extension_from_filename(path);
  strcat(path, ".EVT");
  evtfile = fopeno(path, "rb");
  if(evtfile==NULL)
  {
    remove_extension_from_filename(path);
    strcat(path, ".evt");
    evtfile = fopeno(path, "rb");
    if(evtfile==NULL)
    {
      snprintf(str, 2048, "Can not open file %s for reading.", path);
      QMessageBox messagewindow(QMessageBox::Critical, "Error", str);
      messagewindow.exec();
      fclose(dcmfile);
      return;
    }
  }

/***************** check if the file is valid ******************************/

  for(end_of_file=0; end_of_file == 0; )
  {
    for(i=0; i<256; i++)
    {
      tmp = fgetc(evtfile);

      if(tmp == '\n')
      {
        break;
      }

      if(tmp == EOF)
      {
        end_of_file = 1;

        break;
      }

      str[i] = tmp;
    }

    str[i] = 0;

    if(!(strncmp(str, "Sampling Rate=", 14)))
    {
      samplefreq = atoi(str + 14);
      switch(samplefreq)
      {
        case  128 : break;
        case  256 : break;
        case  512 : break;
        case 1024 : break;

        default : QMessageBox messagewindow(QMessageBox::Critical, "Error", "Unknown samplerate.");
                  messagewindow.exec();
                  fclose(dcmfile);
                  fclose(evtfile);
                  return;
      }

      checked_samplerate = 1;
    }

    if(!(strncmp(str, "Model number=", 13)))
    {
      strncpy(modelnumber_str, str + 13, 8);
      modelnumber_str[8] = 0;

      if(strcmp(modelnumber_str, "TM SD01G") &&
         strcmp(modelnumber_str, "SD SD02G"))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong modelnumber.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_modelnumber = 1;
    }

    if(!(strncmp(str, "Record Date=", 12)))
    {
      strncpy(str2, str + 12, 10);
      str2[10] = 0;

      startdate_year = atoi(str2);
      startdate_month = atoi(str2 + 5);
      startdate_day = atoi(str2 + 8);

      if((startdate_year < 1970) || (startdate_year > 3000) ||
         (startdate_month < 1)   || (startdate_month > 12)  ||
         (startdate_day < 1)     || (startdate_day > 31))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong record date.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_recorddate = 1;
    }

    if(!(strncmp(str, "Record Time=", 12)))
    {
      strncpy(str2, str + 12, 10);
      str2[8] = 0;

      starttime_hour = atoi(str2);
      starttime_minute = atoi(str2 + 3);
      starttime_second = atoi(str2 + 6);

      if((starttime_hour < 0)  || (starttime_hour > 23)   ||
        (starttime_minute < 0) || (starttime_minute > 59) ||
        (starttime_second < 0) || (starttime_second > 59))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong recordtime.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_recordtime = 1;
    }

    if(!(strncmp(str, "Record Hours=", 13)))
    {
      strncpy(str2, str + 13, 10);
      str2[2] = 0;

      if((atoi(str2) != 24) && (atoi(str2) != 48))
      {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Wrong record hours.");
        messagewindow.exec();
        fclose(dcmfile);
        fclose(evtfile);
        return;
      }

      checked_recordhours = 1;
    }
  }

  if(!checked_modelnumber ||
     !checked_samplerate  ||
     !checked_recordhours ||
     !checked_recorddate  ||
     !checked_recordtime)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Missing line.");
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    return;
  }

///////////////////////////////////////////////////////////////////////////////////

  bufsize = chns * samplesize * samplefreq;

  buf1 = (char *)malloc(bufsize);
  if(buf1 == NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Malloc error.");
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    return;
  }

  buf2 = (int *)malloc(bufsize * sizeof(int));
  if(buf2 == NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Malloc error.");
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    free(buf1);
    return;
  }

///////////////////////////////////////////////////////////////////////////////////

  path[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(path, recent_savedir);
    strcat(path, "/");
  }
  strcat(path, outputfilename);
  remove_extension_from_filename(path);
  strcat(path, ".edf");

  strcpy(path, QFileDialog::getSaveFileName(0, "Select outputfile", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(path, ""))
  {
    fclose(dcmfile);
    fclose(evtfile);
    free(buf1);
    free(buf2);
    return;
  }

  get_directory_from_path(recent_savedir, path, MAX_PATH_LENGTH);

  hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_EDFPLUS, chns);
  if(hdl<0)
  {
    snprintf(str, 2048, "Can not open file %s for writing.", path);
    QMessageBox messagewindow(QMessageBox::Critical, "Error", str);
    messagewindow.exec();
    fclose(dcmfile);
    fclose(evtfile);
    free(buf1);
    free(buf2);
    return;
  }

  for(i=0; i<chns; i++)
  {
    edf_set_samplefrequency(hdl, i, samplefreq);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_digital_maximum(hdl, i, 127);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_digital_minimum(hdl, i, -128);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_physical_maximum(hdl, i, 2442.307692);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_physical_minimum(hdl, i, -2461.538462);
  }

  for(i=0; i<chns; i++)
  {
    edf_set_physical_dimension(hdl, i, "uV");
  }

  edf_set_label(hdl, 0, "channel 1");

  edf_set_label(hdl, 1, "channel 2");

  edf_set_label(hdl, 2, "channel 3");

  edf_set_equipment(hdl, modelnumber_str);

  edf_set_patientname(hdl, "BI9800");

  edf_set_startdatetime(hdl, startdate_year, startdate_month, startdate_day, starttime_hour, starttime_minute, starttime_second);

  fseeko(dcmfile, 0LL, SEEK_END);
  datablocks = ftello(dcmfile) / bufsize;
  fseeko(dcmfile, 0LL, SEEK_SET);

  QProgressDialog progress("Converting...", "Cancel", 0, datablocks, myobjectDialog);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

  progress_steps = datablocks / 100;
  if(progress_steps < 1)
  {
    progress_steps = 1;
  }

  for(blocks_written=0; ; blocks_written++)
  {
    if(!(blocks_written % progress_steps))
    {
      progress.setValue(blocks_written);

      qApp->processEvents();

      if(progress.wasCanceled() == true)
      {
        break;
      }
    }

    n = fread(buf1, bufsize, 1, dcmfile);
    if(n != 1)
    {
      break;
    }

    for(i=0; i<samplefreq; i++)
    {
      for(j=0; j<chns; j++)
      {
        tmp2 = buf1[(i * chns) + j] + 128;
        buf2[(j * samplefreq) + i] = tmp2;
      }
    }

    edf_blockwrite_digital_samples(hdl, buf2);
  }

  progress.reset();

  edfwrite_annotation_latin1(hdl, 0LL, -1LL, "Recording starts");

  fseeko(evtfile, 0LL, SEEK_SET);

  for(end_of_file=0; end_of_file == 0; )
  {
    for(i=0; i<256; i++)
    {
      tmp = fgetc(evtfile);

      if((tmp == '\n') || (tmp == '\r'))
      {
        break;
      }

      if(tmp == EOF)
      {
        end_of_file = 1;

        break;
      }

      str[i] = tmp;
    }

    str[i] = 0;

    if((isdigit(str[0])) && (isdigit(str[1])))
    {
      starttime_hour = atoi(str);
      starttime_minute = atoi(str + 3);
      starttime_second = atoi(str + 6);

      if((starttime_hour < 0)   || (starttime_hour > 23)   ||
         (starttime_minute < 0) || (starttime_minute > 59) ||
         (starttime_second < 0) || (starttime_second > 59))
      {
      }
      else
      {
        if(strlen(str) > 9)
        {
          edfwrite_annotation_latin1(hdl, (starttime_second + (starttime_minute * 60) + (starttime_hour * 3600)) * 10000, -1, str + 9);
        }
      }
    }
  }

  edfwrite_annotation_latin1(hdl, blocks_written * 10000LL, -1LL, "Recording ends");

  edfclose_file(hdl);

  fclose(dcmfile);
  fclose(evtfile);
  free(buf1);
  free(buf2);
}
Ejemplo n.º 3
0
void UI_AverageCurveWindow::export_edf(void)
{
  int i, j, k, p,
      type,
      edf_hdl,
      smp_per_record,
      datarecords,
      smpls_left;

  char path[MAX_PATH_LENGTH],
       str[512];

  double *buf,
         frequency,
         frequency2;


  smp_per_record = signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].smp_per_record;

  datarecords = avg_samples_on_screen / smp_per_record;

  smpls_left = avg_samples_on_screen % smp_per_record;

  path[0] = 0;
  if(mainwindow->recent_savedir[0]!=0)
  {
    strcpy(path, mainwindow->recent_savedir);
    strcat(path, "/");
  }
  get_filename_from_path(path + strlen(path), signalcomp->edfhdr->filename, 512);
  remove_extension_from_filename(path);
  sprintf(path + strlen(path), " averaging %s %i triggers [%s]",
          signalcomp->signallabel,
          avg_cnt,
          avg_annotation);

  if(signalcomp->edfhdr->edf)
  {
    strcat(path, ".edf");

    strcpy(path, QFileDialog::getSaveFileName(0, "Save as EDF", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());
  }
  else
  {
    strcat(path, ".bdf");

    strcpy(path, QFileDialog::getSaveFileName(0, "Save as BDF", QString::fromLocal8Bit(path), "BDF files (*.bdf *.BDF)").toLocal8Bit().data());
  }

  if(!strcmp(path, ""))
  {
    return;
  }

  get_directory_from_path(mainwindow->recent_savedir, path, MAX_PATH_LENGTH);

  if(signalcomp->edfhdr->edf)
  {
    edf_hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_EDFPLUS, 1);
  }
  else
  {
    edf_hdl = edfopen_file_writeonly(path, EDFLIB_FILETYPE_BDFPLUS, 1);
  }

  if(edf_hdl < 0)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not open output file for writing.");
    messagewindow.exec();
    return;
  }

  edf_set_samplefrequency(edf_hdl, 0, smp_per_record);

  if(edf_set_datarecord_duration(edf_hdl, signalcomp->edfhdr->long_data_record_duration / 100LL))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Datarecordduration out of range.");
    messagewindow.exec();
    return;
  }

  if(signalcomp->edfhdr->edf)
  {
    edf_set_digital_maximum(edf_hdl, 0, 32767);
    edf_set_digital_minimum(edf_hdl, 0, -32768);
  }
  else
  {
    edf_set_digital_maximum(edf_hdl, 0, 8388607);
    edf_set_digital_minimum(edf_hdl, 0, -8388608);
  }

  edf_set_physical_maximum(edf_hdl, 0, avg_max_value);
  edf_set_physical_minimum(edf_hdl, 0, avg_min_value);
  edf_set_label(edf_hdl, 0, signalcomp->signallabel);
  edf_set_physical_dimension(edf_hdl, 0, signalcomp->physdimension);

  p = 0;

  for(j=0; j<signalcomp->fidfilter_cnt; j++)
  {
    type = signalcomp->fidfilter_type[j];

    frequency = signalcomp->fidfilter_freq[j];

    frequency2 = signalcomp->fidfilter_freq2[j];

    if(type == 0)
    {
      p += sprintf(str + p, "HP:%f", frequency);
    }

    if(type == 1)
    {
      p += sprintf(str + p, "LP:%f", frequency);
    }

    if(type == 2)
    {
      p += sprintf(str + p, "N:%f", frequency);
    }

    if(type == 3)
    {
      p += sprintf(str + p, "BP:%f", frequency);
    }

    if(type == 4)
    {
      p += sprintf(str + p, "BS:%f", frequency);
    }

    for(k=(p-1); k>0; k--)
    {
      if(str[k]!='0')  break;
    }

    if(str[k]=='.')  str[k] = 0;
    else  str[k+1] = 0;

    p = strlen(str);

    if((type == 3) || (type == 4))
    {
      p += sprintf(str + p, "-%f", frequency2);

      for(k=(p-1); k>0; k--)
      {
        if(str[k]!='0')  break;
      }

      if(str[k]=='.')  str[k] = 0;
      else  str[k+1] = 0;
    }

    strcat(str, "Hz ");

    p = strlen(str);

    if(p>80)  break;
  }

  for(j=0; j<signalcomp->ravg_filter_cnt; j++)
  {
    if(signalcomp->ravg_filter_type[j] == 0)
    {
      p += sprintf(str + p, "HP:%iSmpls ", signalcomp->ravg_filter[j]->size);
    }

    if(signalcomp->ravg_filter_type[j] == 1)
    {
      p += sprintf(str + p, "LP:%iSmpls ", signalcomp->ravg_filter[j]->size);
    }

    p = strlen(str);

    if(p>80)  break;
  }

  strcat(str, signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].prefilter);
  edf_set_prefilter(edf_hdl, 0, str);
  edf_set_transducer(edf_hdl, 0, signalcomp->edfhdr->edfparam[signalcomp->edfsignal[0]].transducer);

  if((signalcomp->edfhdr->edfplus) || (signalcomp->edfhdr->bdfplus))
  {
    edf_set_patientname(edf_hdl, signalcomp->edfhdr->plus_patient_name);
    sprintf(str, "%i triggers \"%s\" averaged. %s", avg_cnt, avg_annotation, signalcomp->edfhdr->plus_recording_additional);
    edf_set_recording_additional(edf_hdl, str);
    edf_set_patientcode(edf_hdl, signalcomp->edfhdr->plus_patientcode);
    if(signalcomp->edfhdr->plus_gender[0] == 'M')
    {
      edf_set_gender(edf_hdl, 1);
    }
    if(signalcomp->edfhdr->plus_gender[0] == 'F')
    {
      edf_set_gender(edf_hdl, 0);
    }
    edf_set_patient_additional(edf_hdl, signalcomp->edfhdr->plus_patient_additional);
    edf_set_admincode(edf_hdl, signalcomp->edfhdr->plus_admincode);
    edf_set_technician(edf_hdl, signalcomp->edfhdr->plus_technician);
    edf_set_equipment(edf_hdl, signalcomp->edfhdr->plus_equipment);
  }
  else
  {
    edf_set_patientname(edf_hdl, signalcomp->edfhdr->patient);
    sprintf(str, "%i triggers \"%s\" averaged. %s", avg_cnt, avg_annotation, signalcomp->edfhdr->recording);
    edf_set_recording_additional(edf_hdl, str);
  }

  for(i=0; i<datarecords; i++)
  {
    edfwrite_physical_samples(edf_hdl, avgbuf + (i * smp_per_record));
  }

  if(smpls_left)
  {
    buf = (double *)calloc(1, smp_per_record * sizeof(double));
    if(buf == NULL)
    {
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "Malloc error (buf).");
      messagewindow.exec();
    }
    else
    {
      for(i=0; i<smpls_left; i++)
      {
        buf[i] = avgbuf[(datarecords * smp_per_record) + i];
      }

      edfwrite_physical_samples(edf_hdl, buf);

      free(buf);
    }
  }

  edfwrite_annotation_latin1(edf_hdl,
                             (avg_period * 10000.0) / (double)avg_trigger_position_ratio,
                             -1,
                             avg_annotation);

  edfclose_file(edf_hdl);
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
  int i, j,
      hdl,
      chns=1,
      smp_freq=8192,
      fileduration=300,
      linear=1;

  double buf[smp_freq],
         q,
         sine_1,
         startfreq=10.0,
         stopfreq=4095.0,
         freqspan,
         freq;

  long long samples,
            sampleswritten;

  char str[256];



#ifdef BDF_FORMAT
  hdl = edfopen_file_writeonly("freq_sweep.bdf", EDFLIB_FILETYPE_BDFPLUS, chns);
#else
  hdl = edfopen_file_writeonly("freq_sweep.edf", EDFLIB_FILETYPE_EDFPLUS, chns);
#endif

  if(hdl<0)
  {
    printf("error: edfopen_file_writeonly()\n");

    return(1);
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_samplefrequency(hdl, i, smp_freq))
    {
      printf("error: edf_set_samplefrequency()\n");

      return(1);
    }
  }

#ifdef BDF_FORMAT
  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_maximum(hdl, i, 8388607))
    {
      printf("error: edf_set_digital_maximum()\n");

      return(1);
    }
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_minimum(hdl, i, -8388608))
    {
      printf("error: edf_set_digital_minimum()\n");

      return(1);
    }
  }
#else
  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_maximum(hdl, i, 32767))
    {
      printf("error: edf_set_digital_maximum()\n");

      return(1);
    }
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_minimum(hdl, i, -32768))
    {
      printf("error: edf_set_digital_minimum()\n");

      return(1);
    }
  }
#endif

  for(i=0; i<chns; i++)
  {
    if(edf_set_physical_maximum(hdl, i, 400.0))
    {
      printf("error: edf_set_physical_maximum()\n");

      return(1);
    }
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_physical_minimum(hdl, i, -400.0))
    {
      printf("error: edf_set_physical_minimum()\n");

      return(1);
    }
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_physical_dimension(hdl, i, "uV"))
    {
      printf("error: edf_set_physical_dimension()\n");

      return(1);
    }
  }

  if(edf_set_label(hdl, 0, "sweep"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_equipment(hdl, "Software generated file"))
  {
    printf("edf_set_equipment()\n");

    return(1);
  }

  if(linear)
  {
    sprintf(str, "Linear frequency sweep from %fHz to %fHz", startfreq, stopfreq);
  }
  else
  {
    sprintf(str, "Logarithmic frequency sweep from %fHz to %fHz", startfreq, stopfreq);
  }
  remove_trailing_zeros(str);
  edf_set_patientname(hdl, str);

  edfwrite_annotation_latin1(hdl, 0LL, -1LL, "Recording starts");

  sine_1 = 0.0;

  sampleswritten = 0;

  samples = fileduration * (long long)smp_freq;

  freqspan = stopfreq - startfreq;

  for(j=0; j<fileduration; j++)
  {
    for(i=0; i<smp_freq; i++)
    {
      q = M_PI * 2.0;
      q /= (smp_freq / freq);
      sine_1 += q;
      q = sin(sine_1);
      q *= 200.0;
      buf[i] = q;
      if(linear)
      {
        freq = startfreq + (freqspan * ((double)sampleswritten / (double)samples));
      }
      else
      {
//        freq = exp10((((double)sampleswritten / (double)samples)) * log10(stopfreq));
        freq = exp10(((((startfreq / stopfreq) * ((stopfreq / freqspan) * samples)) + sampleswritten) / ((stopfreq / freqspan) * samples)) * log10(stopfreq));
      }
      sampleswritten++;
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    if(!(j%10))
    {
      sprintf(str, "%fHz", freq);
      remove_trailing_zeros(str);
      edfwrite_annotation_latin1(hdl, j * 10000LL, -1LL, str);
    }
  }

  sprintf(str, "%fHz", freq);
  remove_trailing_zeros(str);
  edfwrite_annotation_latin1(hdl, j * 10000LL, -1LL, str);

  edfwrite_annotation_latin1(hdl, fileduration * 10000LL, -1LL, "Recording ends");

  edfclose_file(hdl);

  return(0);
}
Ejemplo n.º 5
0
int main(int argc, char *argv[])
{
  int i, j,
      hdl,
      chns;

  double buf[1000],
         q,
         sine_1,
         sine_8,
         sine_81777,
         sine_85,
         sine_15,
         sine_17,
         sine_50;

  struct{
          long long samples;
          long long triggers[512];
          int index;
          int code;
          int bitposition;
          int smp_in_bit;
        } dc_event_stat;



  memset(&dc_event_stat, 0, sizeof(dc_event_stat));

  dc_event_stat.code = 0;

  dc_event_stat.triggers[0] = 1951;

  for(i=1; i<512; i++)
  {
    dc_event_stat.triggers[i] = (i * 1667) + 1951;
  }

  chns = 14;

#ifdef BDF_FORMAT
  hdl = edfopen_file_writeonly("test_generator.bdf", EDFLIB_FILETYPE_BDFPLUS, chns);
#else
  hdl = edfopen_file_writeonly("test_generator.edf", EDFLIB_FILETYPE_EDFPLUS, chns);
#endif

  if(hdl<0)
  {
    printf("error: edfopen_file_writeonly()\n");

    return(1);
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_samplefrequency(hdl, i, SMP_FREQ))
    {
      printf("error: edf_set_samplefrequency()\n");

      return(1);
    }
  }

  if(edf_set_samplefrequency(hdl, 3, SMP_FREQ_2))
  {
    printf("error: edf_set_samplefrequency()\n");

    return(1);
  }

  if(edf_set_samplefrequency(hdl, 4, SMP_FREQ_3))
  {
    printf("error: edf_set_samplefrequency()\n");

    return(1);
  }

  if(edf_set_samplefrequency(hdl, 13, 1000))
  {
    printf("error: edf_set_samplefrequency()\n");

    return(1);
  }

#ifdef BDF_FORMAT
  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_maximum(hdl, i, 8388607))
    {
      printf("error: edf_set_digital_maximum()\n");

      return(1);
    }
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_minimum(hdl, i, -8388608))
    {
      printf("error: edf_set_digital_minimum()\n");

      return(1);
    }
  }

  if(edf_set_digital_minimum(hdl, 13, 8300000))
  {
    printf("error: edf_set_digital_minimum()\n");

    return(1);
  }

#else
  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_maximum(hdl, i, 32767))
    {
      printf("error: edf_set_digital_maximum()\n");

      return(1);
    }
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_digital_minimum(hdl, i, -32768))
    {
      printf("error: edf_set_digital_minimum()\n");

      return(1);
    }
  }
#endif

  for(i=0; i<chns; i++)
  {
    if(edf_set_physical_maximum(hdl, i, 1000.0))
    {
      printf("error: edf_set_physical_maximum()\n");

      return(1);
    }
  }

  if(edf_set_physical_maximum(hdl, 8, 262143.0))
  {
    printf("error: edf_set_physical_maximum()\n");

    return(1);
  }

  if(edf_set_physical_maximum(hdl, 13, 10.0))
  {
    printf("error: edf_set_physical_maximum()\n");

    return(1);
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_physical_minimum(hdl, i, -1000.0))
    {
      printf("error: edf_set_physical_minimum()\n");

      return(1);
    }
  }

  if(edf_set_physical_minimum(hdl, 8, -262144.0))
  {
    printf("error: edf_set_physical_minimum()\n");

    return(1);
  }

  if(edf_set_physical_minimum(hdl, 13, -10.0))
  {
    printf("error: edf_set_physical_minimum()\n");

    return(1);
  }

  for(i=0; i<chns; i++)
  {
    if(edf_set_physical_dimension(hdl, i, "uV"))
    {
      printf("error: edf_set_physical_dimension()\n");

      return(1);
    }
  }

  if(edf_set_physical_dimension(hdl, 13, "V"))
  {
    printf("error: edf_set_physical_dimension()\n");

    return(1);
  }

  i = 0;

  if(edf_set_label(hdl, i++, "squarewave"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "ramp"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "pulse 1"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "pulse 2"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "pulse 3"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "noise"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "sine 1 Hz"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "sine 8 Hz"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "sine 8.1777 Hz"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "sine 8.5 Hz"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "sine 15 Hz"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "sine 17 Hz"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "sine 50 Hz"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_label(hdl, i++, "DC 01"))
  {
    printf("error: edf_set_label()\n");

    return(1);
  }

  if(edf_set_equipment(hdl, "test generator"))
  {
    printf("edf_set_equipment()\n");

    return(1);
  }

  edf_set_birthdate(hdl, 1969, 6, 30);


  sine_1 = 0.0;
  sine_8 = 0.0;
  sine_81777 = 0.0;
  sine_85 = 0.0;
  sine_15 = 0.0;
  sine_17 = 0.0;
  sine_50 = 0.0;

  for(j=0; j<FILE_DURATION; j++)
  {
    if((j%10)<5)                    /* square */
    {
      for(i=0; i<SMP_FREQ; i++)
      {
        buf[i] = 100.0;
      }
    }
    else
    {
      for(i=0; i<SMP_FREQ; i++)
      {
        buf[i] = -100.0;
      }
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                       /* ramp */
    {
      buf[i] = -100.0 + (i * (200.0 / SMP_FREQ));
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                 /* pulse 1 */
    {
      buf[i] = 0.0;
    }

    buf[0] = 100.0;

    buf[SMP_FREQ - 2] = 100.0;

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ_2; i++)               /* pulse 2 */
    {
      buf[i] = 0.0;
    }

    buf[0] = 100.0;

    buf[SMP_FREQ_2 - 2] = 100.0;

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ_3; i++)              /* pulse 3 */
    {
      buf[i] = 0.0;
    }

    buf[0] = 100.0;

    buf[SMP_FREQ_3 - 2] = 100.0;

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* noise */
    {
      buf[i] = (int)(100.0 * (rand() / (RAND_MAX + 1.0)));
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* sine 1 Hz */
    {
      q = M_PI * 2.0;
      q /= SMP_FREQ;
      sine_1 += q;
      q = sin(sine_1);
      q *= 100.0;
      buf[i] = q;
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* sine 8 Hz */
    {
      q = M_PI * 2.0;
      q /= (SMP_FREQ / 8.0);
      sine_8 += q;
      q = sin(sine_8);
      q *= 100.0;
      buf[i] = q + 800.0;         /* add dc-offset */
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* sine 8.1777 Hz */
    {
      q = M_PI * 2.0;
      q /= (SMP_FREQ / 8.1777);
      sine_81777 += q;
      q = sin(sine_81777);
      q *= 100.0;
      buf[i] = q + 6000.0;       /* add dc-offset */
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* sine 8.5 Hz */
    {
      q = M_PI * 2.0;
      q /= (SMP_FREQ / 8.5);
      sine_85 += q;
      q = sin(sine_85);
      q *= 100.0;
      buf[i] = q;
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* sine 15 Hz */
    {
      q = M_PI * 2.0;
      q /= (SMP_FREQ / 15.0);
      sine_15 += q;
      q = sin(sine_15);
      q *= 100.0;
      buf[i] = q;
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* sine 17 Hz */
    {
      q = M_PI * 2.0;
      q /= (SMP_FREQ / 17.0);
      sine_17 += q;
      q = sin(sine_17);
      q *= 100.0;
      buf[i] = q;
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<SMP_FREQ; i++)                /* sine 50 Hz */
    {
      q = M_PI * 2.0;
      q /= (SMP_FREQ / 50.0);
      sine_50 += q;
      q = sin(sine_50);
      q *= 100.0;
      buf[i] = q;
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }

    for(i=0; i<1000; i++)                /* DC 01 */
    {
      if(dc_event_stat.bitposition)
      {
        if(dc_event_stat.bitposition == 1)
        {
          buf[i] = 1.0;
        }
        else
        {
          if(dc_event_stat.code & (1 << (dc_event_stat.bitposition - 2)))
          {
            buf[i] = 1.0;
          }
          else
          {
            buf[i] = 0.0;
          }
        }

        if(++dc_event_stat.smp_in_bit >= 10)
        {
          dc_event_stat.smp_in_bit = 0;

          dc_event_stat.bitposition++;
        }

        if(dc_event_stat.bitposition > 10)
        {
          dc_event_stat.bitposition = 0;

          dc_event_stat.smp_in_bit = 0;

          dc_event_stat.code++;

          dc_event_stat.code &= 255;

          if(++dc_event_stat.index >= 512)
          {
            dc_event_stat.index = 0;

            dc_event_stat.code = 0;
          }
        }
      }
      else
      {
        if(dc_event_stat.samples == dc_event_stat.triggers[dc_event_stat.index])
        {
/*          edfwrite_annotation_latin1(hdl, dc_event_stat.samples * 10LL, -1LL, "Trigger");  */

          dc_event_stat.bitposition = 1;
          dc_event_stat.smp_in_bit = 1;
          buf[i] = 1.0;
        }
        else
        {
          buf[i] = 0.0;
        }
      }

      dc_event_stat.samples++;
    }

    if(edfwrite_physical_samples(hdl, buf))
    {
      printf("error: edfwrite_physical_samples()\n");

      return(1);
    }
  }

  edfwrite_annotation_latin1(hdl, 0LL, -1LL, "Recording starts");

  edfwrite_annotation_latin1(hdl, 2980000LL, -1LL, "Test 1");

  edfwrite_annotation_latin1(hdl, 2940000LL + (long long)((10000.0 / SMP_FREQ) * (SMP_FREQ - 2)), -1LL, "pulse 1");

  edfwrite_annotation_latin1(hdl, 2950000LL + (long long)((10000.0 / SMP_FREQ_2) * (SMP_FREQ_2 - 2)), -1LL, "pulse 2");

  edfwrite_annotation_latin1(hdl, 2960000LL + (long long)((10000.0 / SMP_FREQ_3) * (SMP_FREQ_3 - 2)), -1LL, "pulse 3");

  edfwrite_annotation_latin1(hdl, FILE_DURATION * 10000LL, -1LL, "Recording ends");

  edfclose_file(hdl);

  return(0);
}
Ejemplo n.º 6
0
void UI_Mainwindow::save_screen_waveform()
{
  int i, j,
      n=0,
      chn,
      chns=0,
      hdl=-1,
      yref[MAX_CHNS],
      yor[MAX_CHNS];

  char str[128],
       opath[MAX_PATHLEN];

  short *wavbuf[4];

  long long rec_len=0LL;

  double yinc[MAX_CHNS];

  if(device == NULL)
  {
    return;
  }

  wavbuf[0] = NULL;
  wavbuf[1] = NULL;
  wavbuf[2] = NULL;
  wavbuf[3] = NULL;

  scrn_timer->stop();

  scrn_thread->wait();

  if(devparms.timebasedelayenable)
  {
    rec_len = EDFLIB_TIME_DIMENSION * devparms.timebasedelayscale * devparms.hordivisions;
  }
  else
  {
    rec_len = EDFLIB_TIME_DIMENSION * devparms.timebasescale * devparms.hordivisions;
  }

  if(rec_len < 10LL)
  {
    strcpy(str, "Can not save waveforms when timebase < 1uSec.");
    goto OUT_ERROR;
  }

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])  // Download data only when channel is switched on
    {
      continue;
    }

    wavbuf[chn] = (short *)malloc(WAVFRM_MAX_BUFSZ * sizeof(short));
    if(wavbuf[chn] == NULL)
    {
      strcpy(str, "Malloc error.");
      goto OUT_ERROR;
    }

    chns++;
  }

  if(!chns)
  {
    strcpy(str, "No active channels.");
    goto OUT_ERROR;
  }

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])  // Download data only when channel is switched on
    {
      continue;
    }

    usleep(20000);

    sprintf(str, ":WAV:SOUR CHAN%i", chn + 1);

    tmc_write(str);

    usleep(20000);

    tmc_write(":WAV:FORM BYTE");

    usleep(20000);

    tmc_write(":WAV:MODE NORM");

    usleep(20000);

    tmc_write(":WAV:YINC?");

    usleep(20000);

    tmc_read();

    yinc[chn] = atof(device->buf);

    if(yinc[chn] < 1e-6)
    {
      sprintf(str, "Error, parameter \"YINC\" out of range.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }

    usleep(20000);

    tmc_write(":WAV:YREF?");

    usleep(20000);

    tmc_read();

    yref[chn] = atoi(device->buf);

    if((yref[chn] < 1) || (yref[chn] > 255))
    {
      sprintf(str, "Error, parameter \"YREF\" out of range.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }

    usleep(20000);

    tmc_write(":WAV:YOR?");

    usleep(20000);

    tmc_read();

    yor[chn] = atoi(device->buf);

    if((yor[chn] < -255) || (yor[chn] > 255))
    {
      sprintf(str, "Error, parameter \"YOR\" out of range.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }

    usleep(20000);

    tmc_write(":WAV:DATA?");

    QApplication::setOverrideCursor(Qt::WaitCursor);

    qApp->processEvents();

    n = tmc_read();

    QApplication::restoreOverrideCursor();

    if(n < 0)
    {
      strcpy(str, "Can not read from device.");
      goto OUT_ERROR;
    }

    if(n > WAVFRM_MAX_BUFSZ)
    {
      strcpy(str, "Datablock too big for buffer.");
      goto OUT_ERROR;
    }

    if(n < 16)
    {
      strcpy(str, "Not enough data in buffer.");
      goto OUT_ERROR;
    }

    for(i=0; i<n; i++)
    {
      wavbuf[chn][i] = ((int)(((unsigned char *)device->buf)[i]) - yref[chn] - yor[chn]) << 5;
    }
  }

  opath[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(opath, recent_savedir);
    strcat(opath, "/");
  }
  strcat(opath, "waveform.edf");

  strcpy(opath, QFileDialog::getSaveFileName(this, "Save file", opath, "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(opath, ""))
  {
    goto OUT_NORMAL;
  }

  get_directory_from_path(recent_savedir, opath, MAX_PATHLEN);

  hdl = edfopen_file_writeonly(opath, EDFLIB_FILETYPE_EDFPLUS, chns);
  if(hdl < 0)
  {
    strcpy(str, "Can not create EDF file.");
    goto OUT_ERROR;
  }

  if(edf_set_datarecord_duration(hdl, rec_len / 100LL))
  {
    strcpy(str, "Can not set datarecord duration of EDF file.");
    goto OUT_ERROR;
  }

  j = 0;

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])
    {
      continue;
    }

    edf_set_samplefrequency(hdl, j, n);
    edf_set_digital_maximum(hdl, j, 32767);
    edf_set_digital_minimum(hdl, j, -32768);
    if(devparms.chanscale[chn] > 2)
    {
      edf_set_physical_maximum(hdl, j, yinc[chn] * 32767.0 / 32.0);
      edf_set_physical_minimum(hdl, j, yinc[chn] * -32768.0 / 32.0);
      edf_set_physical_dimension(hdl, j, "V");
    }
    else
    {
      edf_set_physical_maximum(hdl, j, 1000.0 * yinc[chn] * 32767.0 / 32.0);
      edf_set_physical_minimum(hdl, j, 1000.0 * yinc[chn] * -32768.0 / 32.0);
      edf_set_physical_dimension(hdl, j, "mV");
    }
    sprintf(str, "CHAN%i", chn + 1);
    edf_set_label(hdl, j, str);

    j++;
  }

  edf_set_equipment(hdl, devparms.modelname);

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])
    {
      continue;
    }

    if(edfwrite_digital_short_samples(hdl, wavbuf[chn]))
    {
      strcpy(str, "A write error occurred.");
      goto OUT_ERROR;
    }
  }

OUT_NORMAL:

  if(hdl >= 0)
  {
    edfclose_file(hdl);
  }

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    free(wavbuf[chn]);
  }

  scrn_timer->start(devparms.screentimerival);

  return;

OUT_ERROR:

  QMessageBox msgBox;
  msgBox.setIcon(QMessageBox::Critical);
  msgBox.setText(str);
  msgBox.exec();

  if(hdl >= 0)
  {
    edfclose_file(hdl);
  }

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    free(wavbuf[chn]);
  }

  scrn_timer->start(devparms.screentimerival);
}
Ejemplo n.º 7
0
void UI_Mainwindow::save_memory_waveform()
{
  int i, j, k,
      n=0,
      chn,
      chns=0,
      hdl=-1,
      bytes_rcvd=0,
      mempnts,
      yref[MAX_CHNS],
      yor[MAX_CHNS],
      smps_per_record,
      datrecs=1,
      empty_buf;

  char str[128],
       opath[MAX_PATHLEN];

  short *wavbuf[4];

  long long rec_len=0LL;

  double yinc[MAX_CHNS];

  if(device == NULL)
  {
    return;
  }

  scrn_timer->stop();

  scrn_thread->wait();

  wavbuf[0] = NULL;
  wavbuf[1] = NULL;
  wavbuf[2] = NULL;
  wavbuf[3] = NULL;

  mempnts = devparms.acquirememdepth;

  smps_per_record = mempnts;

  QProgressDialog progress("Downloading data...", "Abort", 0, mempnts, this);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(100);

  statusLabel->setText("Downloading data...");

  for(i=0; i<MAX_CHNS; i++)
  {
    if(!devparms.chandisplay[i])
    {
      continue;
    }

    chns++;
  }

  if(!chns)
  {
    strcpy(str, "No active channels.");
    goto OUT_ERROR;
  }

  while(smps_per_record >= (5000000 / chns))
  {
    smps_per_record /= 2;

    datrecs *= 2;
  }

  if(mempnts < 1)
  {
    strcpy(str, "Can not save waveform when memory depth is set to \"Auto\".");
    goto OUT_ERROR;
  }

  rec_len = (EDFLIB_TIME_DIMENSION * (long long)mempnts) / devparms.samplerate;

  if(rec_len < 100)
  {
    strcpy(str, "Can not save waveforms shorter than 10 uSec.\n"
                "Set the horizontal timebase to 1 uSec or higher.");
    goto OUT_ERROR;
  }

  for(i=0; i<MAX_CHNS; i++)
  {
    if(!devparms.chandisplay[i])  // Download data only when channel is switched on
    {
      continue;
    }

    wavbuf[i] = (short *)malloc(mempnts * sizeof(short));
    if(wavbuf[i] == NULL)
    {
      sprintf(str, "Malloc error.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }
  }

  tmc_write(":STOP");

  usleep(20000);

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])  // Download data only when channel is switched on
    {
      continue;
    }

    sprintf(str, ":WAV:SOUR CHAN%i", chn + 1);

    tmc_write(str);

    tmc_write(":WAV:FORM BYTE");

    usleep(20000);

    tmc_write(":WAV:MODE RAW");

    usleep(20000);

    tmc_write(":WAV:YINC?");

    usleep(20000);

    tmc_read();

    yinc[chn] = atof(device->buf);

    if(yinc[chn] < 1e-6)
    {
      sprintf(str, "Error, parameter \"YINC\" out of range.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }

    usleep(20000);

    tmc_write(":WAV:YREF?");

    usleep(20000);

    tmc_read();

    yref[chn] = atoi(device->buf);

    if((yref[chn] < 1) || (yref[chn] > 255))
    {
      sprintf(str, "Error, parameter \"YREF\" out of range.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }

    usleep(20000);

    tmc_write(":WAV:YOR?");

    usleep(20000);

    tmc_read();

    yor[chn] = atoi(device->buf);

    if((yor[chn] < -255) || (yor[chn] > 255))
    {
      sprintf(str, "Error, parameter \"YOR\" out of range.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }

    empty_buf = 0;

    for(bytes_rcvd=0; bytes_rcvd<mempnts ;)
    {
      progress.setValue(bytes_rcvd);

      qApp->processEvents();

      if(progress.wasCanceled())
      {
        strcpy(str, "Canceled");
        goto OUT_ERROR;
      }

      sprintf(str, ":WAV:STAR %i",  bytes_rcvd + 1);

      usleep(20000);

      tmc_write(str);

      if((bytes_rcvd + SAV_MEM_BSZ) > mempnts)
      {
        sprintf(str, ":WAV:STOP %i", mempnts);
      }
      else
      {
        sprintf(str, ":WAV:STOP %i", bytes_rcvd + SAV_MEM_BSZ);
      }

      usleep(20000);

      tmc_write(str);

      usleep(20000);

      tmc_write(":WAV:DATA?");

      n = tmc_read();

      if(n < 0)
      {
        sprintf(str, "Can not read from device.  line %i file %s", __LINE__, __FILE__);
        goto OUT_ERROR;
      }

      printf("received %i bytes, total %i bytes\n", n, n + bytes_rcvd);

      if(n > SAV_MEM_BSZ)
      {
        sprintf(str, "Datablock too big for buffer.  line %i file %s", __LINE__, __FILE__);
        goto OUT_ERROR;
      }

      if(n < 1)
      {
        if(empty_buf++ > 100)
        {
          break;
        }
      }
      else
      {
        empty_buf = 0;
      }

      for(k=0; k<n; k++)
      {
        if((bytes_rcvd + k) >= mempnts)
        {
          break;
        }

        wavbuf[chn][bytes_rcvd + k] = ((int)(((unsigned char *)device->buf)[k]) - yref[chn] - yor[chn]) << 5;
      }

      bytes_rcvd += n;

      if(bytes_rcvd >= mempnts)
      {
        break;
      }
    }

    if(bytes_rcvd < mempnts)
    {
      sprintf(str, "Download error.  line %i file %s", __LINE__, __FILE__);
      goto OUT_ERROR;
    }
  }

  progress.reset();

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])
    {
      continue;
    }

    sprintf(str, ":WAV:SOUR CHAN%i", chn + 1);

    usleep(20000);

    tmc_write(str);

    usleep(20000);

    tmc_write(":WAV:MODE NORM");

    usleep(20000);

    tmc_write(":WAV:STAR 1");

    if(devparms.modelserie == 1)
    {
      usleep(20000);

      tmc_write(":WAV:STOP 1200");
    }
    else
    {
      usleep(20000);

      tmc_write(":WAV:STOP 1400");

      usleep(20000);

      tmc_write(":WAV:POIN 1400");
    }
  }

  if(bytes_rcvd < mempnts)
  {
    sprintf(str, "Download error.  line %i file %s", __LINE__, __FILE__);
    goto OUT_ERROR;
  }
  else
  {
    statusLabel->setText("Downloading finished");
  }

  opath[0] = 0;
  if(recent_savedir[0]!=0)
  {
    strcpy(opath, recent_savedir);
    strcat(opath, "/");
  }
  strcat(opath, "waveform.edf");

  strcpy(opath, QFileDialog::getSaveFileName(this, "Save file", opath, "EDF files (*.edf *.EDF)").toLocal8Bit().data());

  if(!strcmp(opath, ""))
  {
    goto OUT_NORMAL;
  }

  get_directory_from_path(recent_savedir, opath, MAX_PATHLEN);

  hdl = edfopen_file_writeonly(opath, EDFLIB_FILETYPE_EDFPLUS, chns);
  if(hdl < 0)
  {
    strcpy(str, "Can not create EDF file.");
    goto OUT_ERROR;
  }

  if(edf_set_datarecord_duration(hdl, (rec_len / 100LL) / datrecs))
  {
    strcpy(str, "Can not set datarecord duration of EDF file.");
    goto OUT_ERROR;
  }

  j = 0;

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])
    {
      continue;
    }

    edf_set_samplefrequency(hdl, j, smps_per_record);
    edf_set_digital_maximum(hdl, j, 32767);
    edf_set_digital_minimum(hdl, j, -32768);
    if(devparms.chanscale[chn] > 2)
    {
      edf_set_physical_maximum(hdl, j, yinc[chn] * 32767.0 / 32.0);
      edf_set_physical_minimum(hdl, j, yinc[chn] * -32768.0 / 32.0);
      edf_set_physical_dimension(hdl, j, "V");
    }
    else
    {
      edf_set_physical_maximum(hdl, j, 1000.0 * yinc[chn] * 32767.0 / 32.0);
      edf_set_physical_minimum(hdl, j, 1000.0 * yinc[chn] * -32768.0 / 32.0);
      edf_set_physical_dimension(hdl, j, "mV");
    }
    sprintf(str, "CHAN%i", chn + 1);
    edf_set_label(hdl, j, str);

    j++;
  }

  edf_set_equipment(hdl, devparms.modelname);

  for(i=0; i<datrecs; i++)
  {
    for(chn=0; chn<MAX_CHNS; chn++)
    {
      if(!devparms.chandisplay[chn])
      {
        continue;
      }

      if(edfwrite_digital_short_samples(hdl, wavbuf[chn] + (i * smps_per_record)))
      {
        strcpy(str, "A write error occurred.");
        goto OUT_ERROR;
      }
    }
  }

OUT_NORMAL:

  if(hdl >= 0)
  {
    edfclose_file(hdl);
  }

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    free(wavbuf[chn]);
  }

  scrn_timer->start(devparms.screentimerival);

  return;

OUT_ERROR:

  progress.reset();

  statusLabel->setText("Downloading aborted");

  if(hdl >= 0)
  {
    edfclose_file(hdl);
  }

  if(progress.wasCanceled() == false)
  {
    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Critical);
    msgBox.setText(str);
    msgBox.exec();
  }

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    if(!devparms.chandisplay[chn])
    {
      continue;
    }

    sprintf(str, ":WAV:SOUR CHAN%i", chn + 1);

    tmc_write(str);

    tmc_write(":WAV:MODE NORM");

    tmc_write(":WAV:STAR 1");

    if(devparms.modelserie == 1)
    {
      tmc_write(":WAV:STOP 1200");
    }
    else
    {
      tmc_write(":WAV:STOP 1400");

      tmc_write(":WAV:POIN 1400");
    }
  }

  for(chn=0; chn<MAX_CHNS; chn++)
  {
    free(wavbuf[chn]);
  }

  scrn_timer->start(devparms.screentimerival);
}