Example #1
0
    def test_SampleWriting(self):
        channel_info1 = {
            'label': 'test_label1',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        channel_info2 = {
            'label': 'test_label2',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre2',
            'transducer': 'trans2'
        }
        f = pyedflib.EdfWriter(self.bdf_data_file,
                               2,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info1)
        f.setSignalHeader(1, channel_info2)

        data1 = np.ones(500) * 0.1
        data2 = np.ones(500) * 0.2
        data_list = []
        data_list.append(data1)
        data_list.append(data2)
        f.writeSamples(data_list)

        f.close()
        del f

        f = pyedflib.EdfReader(self.bdf_data_file)
        data1_read = f.readSignal(0)
        data2_read = f.readSignal(1)
        f._close()
        del f
        np.testing.assert_equal(len(data1), len(data1_read))
        np.testing.assert_equal(len(data2), len(data2_read))
        np.testing.assert_almost_equal(data1, data1_read)
        np.testing.assert_almost_equal(data2, data2_read)
Example #2
0
 def _export_edf(self, fname):
     """Export raw to EDF/BDF file (requires pyEDFlib)."""
     import pyedflib
     name, ext = splitext(split(fname)[-1])
     if ext == ".edf":
         filetype = pyedflib.FILETYPE_EDFPLUS
         dmin, dmax = -32768, 32767
     elif ext == ".bdf":
         filetype = pyedflib.FILETYPE_BDFPLUS
         dmin, dmax = -8388608, 8388607
     data = self.current["data"].get_data() * 1e6  # convert to microvolts
     fs = self.current["data"].info["sfreq"]
     nchan = self.current["data"].info["nchan"]
     ch_names = self.current["data"].info["ch_names"]
     if self.current["data"].info["meas_date"] is not None:
         meas_date = self.current['data'].info["meas_date"][0]
     else:
         meas_date = None
     prefilter = (f"{self.current['data'].info['highpass']}Hz - "
                  f"{self.current['data'].info['lowpass']}")
     pmin, pmax = data.min(axis=1), data.max(axis=1)
     f = pyedflib.EdfWriter(fname, nchan, filetype)
     channel_info = []
     data_list = []
     for i in range(nchan):
         channel_info.append(
             dict(label=ch_names[i],
                  dimension="uV",
                  sample_rate=fs,
                  physical_min=pmin[i],
                  physical_max=pmax[i],
                  digital_min=dmin,
                  digital_max=dmax,
                  transducer="",
                  prefilter=prefilter))
         data_list.append(data[i])
     f.setTechnician("Exported by MNELAB")
     f.setSignalHeaders(channel_info)
     if meas_date is not None:
         f.setStartdatetime(datetime.utcfromtimestamp(meas_date))
     # note that currently, only blocks of whole seconds can be written
     f.writeSamples(data_list)
     if self.current["data"].annotations is not None:
         for ann in self.current["data"].annotations:
             f.writeAnnotation(ann["onset"], ann["duration"],
                               ann["description"])
Example #3
0
    def test_EdfWriter_BDF(self):
        channel_info1 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        channel_info2 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.bdf_data_file,
                               2,
                               file_type=pyedflib.FILETYPE_BDF)
        f.setSignalHeader(0, channel_info1)
        f.setSignalHeader(1, channel_info2)

        data = np.ones(100) * 0.1
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.close()
        del f

        f = pyedflib.EdfReader(self.bdf_data_file)

        np.testing.assert_equal(f.getLabel(0), 'test_label')
        np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
        np.testing.assert_equal(f.getPrefilter(0), 'pre1')
        np.testing.assert_equal(f.getTransducer(0), 'trans1')
        np.testing.assert_equal(f.getSampleFrequency(0), 100)
        f._close()
        del f
Example #4
0
    def test_EdfWriter_EDF(self):
        channel_info1 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 32767,
            'digital_min': -32768,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        channel_info2 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 32767,
            'digital_min': -32768,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.edf_data_file,
                               2,
                               file_type=pyedflib.FILETYPE_EDF)
        f.setSignalHeader(0, channel_info1)
        f.setSignalHeader(1, channel_info2)
        data = np.ones(100) * 0.1
        assert f.writePhysicalSamples(
            data) == 0, 'error while writing physical sample'
        assert f.writePhysicalSamples(
            data) == 0, 'error while writing physical sample'
        del f

        f = pyedflib.EdfReader(self.edf_data_file)

        np.testing.assert_equal(f.getLabel(0), 'test_label')
        np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
        np.testing.assert_equal(f.getPrefilter(0), 'pre1')
        np.testing.assert_equal(f.getTransducer(0), 'trans1')
        np.testing.assert_equal(f.getSampleFrequency(0), 100)
        self.assertEqual(f.filetype, pyedflib.FILETYPE_EDF)

        del f
Example #5
0
    def test_subsecond_starttime(self):

        f = pyedflib.EdfWriter(self.edfplus_data_file,
                               1,
                               file_type=pyedflib.FILETYPE_EDFPLUS)

        channel_info = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 32767,
            'digital_min': -32768,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        startdate = datetime(2017, 1, 2, 13, 14, 15, 250)
        header = {
            'technician': 'tec1',
            'recording_additional': 'recAdd1',
            'patientname': 'pat1',
            'patient_additional': 'patAdd1',
            'patientcode': 'code1',
            'equipment': 'eq1',
            'admincode': 'admin1',
            'gender': 1,
            'startdate': startdate,
            'birthdate': date(1951, 8, 2)
        }
        f.setHeader(header)
        f.setStartdatetime(startdate)
        f.setSignalHeader(0, channel_info)
        data = np.ones(100) * 0.1
        assert f.writePhysicalSamples(
            data) == 0, 'error while writing physical sample'
        assert f.writePhysicalSamples(
            data) == 0, 'error while writing physical sample'
        del f

        f = pyedflib.EdfReader(self.edfplus_data_file)
        startdate2 = f.getStartdatetime()
        assert startdate2 == startdate, 'write {} != read {}'.format(
            startdate, startdate2)
        del f
Example #6
0
    def test_read_incorrect_file(self):

        # this should simply not be found and not trigger the UTF8 warning
        with self.assertRaises(FileNotFoundError):
            f = pyedflib.EdfReader('does_not_exist')

        # this file is corrupted and should be found, but not be read
        # so the Exception should be OSError and not FileNotFoundError
        with self.assertRaises(OSError):
            with open(self.tmp_edf_file, 'wb') as f:
                f.write(b'0123456789')
            f = pyedflib.EdfReader(self.tmp_edf_file)

        # now we create a file that is not EDF/BDF compliant
        # this should raise an OSError and not a FileNotFoundError
        with self.assertRaises(OSError) as cm:
            channel_info = {
                'label': 'test_label',
                'dimension': 'mV',
                'sample_rate': 256,
                'sample_frequency': 100,
                'physical_max': 1.0,
                'physical_min': -1.0,
                'digital_max': 8388607,
                'digital_min': -8388608,
                'prefilter': 'pre1',
                'transducer': 'trans1'
            }
            with pyedflib.EdfWriter(self.bdf_accented_file,
                                    1,
                                    file_type=pyedflib.FILETYPE_BDFPLUS) as f:
                f.setSignalHeader(0, channel_info)
                f.setTechnician('tec1')
                data = np.ones(100) * 0.1
                f.writePhysicalSamples(data)

            with open(self.bdf_accented_file, 'rb') as f:
                content = bytearray(f.read())
                content[181] = 58
            with open(self.bdf_accented_file, 'wb') as f:
                f.write(content)

            f = pyedflib.EdfReader(self.bdf_accented_file)
        # However, the error before should not be a FileNotFoundError
        assert not isinstance(cm.exception, FileNotFoundError)
Example #7
0
 def writeFile(self, eeg, project, path):
     try:
         name = path + "\\" + eeg.name + "_" + project + ".edf"
         if os.path.isfile(name):
             # it already exists
             f = eeg.name + "_" + project + ".edf"
             msg = wx.MessageDialog(None,
                                    "El archivo '" + f + "' ya existe. "
                                    "\n¿Desea reemplazar el archivo?",
                                    caption="¡Alerta!",
                                    style=wx.YES_NO | wx.CENTRE)
             if msg.ShowModal() == wx.ID_NO:
                 return  # we don't to anything
             else:
                 # deleting the prev file
                 os.remove(name)
         file = pyedflib.EdfWriter(name, len(eeg.selectedCh))
         labels = eeg.getLabels()
         samples = []
         j = 0
         for i in eeg.selectedCh:
             chanInfo = {
                 u'label': labels[i],
                 u'dimension': 'mV',
                 u'sample_rate': int(eeg.frequency),
                 u'physical_max': float(eeg.amUnits[0]),
                 u'physical_min': float(eeg.amUnits[1]),
                 u'digital_max': int(eeg.amUnits[0]),
                 u'digital_min': int(eeg.amUnits[1]),
                 u'prefilter': 'pre1',
                 u'transducer': 'trans1'
             }
             file.setSignalHeader(j, chanInfo)
             ch = eeg.getChannel(i)
             ch.readings = np.array(ch.readings)
             samples.append(ch.readings)
             j += 1
         samples = np.array(samples)
         # needs to be in microseconds
         duration = int(eeg.duration * 100000)
         file.setDatarecordDuration(duration)
         file.writeSamples(samples)
         file.close()
     except:
         self.setError(2)
Example #8
0
    def test_BdfReader_Read_accented_file(self):
        channel_info = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        try:
            f = pyedflib.EdfWriter(self.bdf_accented_file,
                                   1,
                                   file_type=pyedflib.FILETYPE_BDFPLUS)
        except IOError:
            print('cannot write', self.bdf_accented_file)
            np.testing.assert_raises(IOError, 'cannot write file')
            return
        f.setSignalHeader(0, channel_info)
        f.setTechnician('tec1')
        data = np.ones(100) * 0.1
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        del f

        try:
            f = pyedflib.EdfReader(self.bdf_accented_file,
                                   pyedflib.READ_ALL_ANNOTATIONS,
                                   pyedflib.DO_NOT_CHECK_FILE_SIZE)
        except IOError:
            print('cannot open', self.bdf_accented_file)
            np.testing.assert_raises(IOError, 'cannot open file')
            return
        np.testing.assert_equal(f.getTechnician(), 'tec1')

        np.testing.assert_equal(f.getLabel(0), 'test_label')
        np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
        np.testing.assert_equal(f.getPrefilter(0), 'pre1')
        np.testing.assert_equal(f.getTransducer(0), 'trans1')
        np.testing.assert_equal(f.getSampleFrequency(0), 100)
        np.testing.assert_equal(f.getSignalHeader(0), channel_info)
        np.testing.assert_equal(f.getSignalHeaders(), [channel_info])
        del f
Example #9
0
 def write_edf(self,in_signal,headers,nameEdf):
     '''
     Descripción: Se encarga de escribir los datos del nuevo EEG
     Entradas: - headers: etiquetas del .edf 
               - in_signal: Matriz de Canales X Tiempo
               - nameEdf : Nombre con el que se desea guardar el nuevo .edf
     ''' 
     edf = pyedflib.EdfWriter(nameEdf,len(in_signal),file_type=pyedflib.FILETYPE_EDFPLUS)
     edf_info = []
     edf_signal = []
     for i in range (len(in_signal)):
         channel_info={'label':headers[i]['label'],'dimension':headers[i]['dimension'],'sample_rate':headers[i]['sample_rate'],'physical_max':headers[i]['physical_max'] , 'physical_min': headers[i]['physical_min'], 'digital_max': headers[i]['digital_max'], 'digital_min': headers[i]['digital_min'], 'transducer':headers[i]['transducer'] , 'prefilter':headers[i]['prefilter']+',notch '+str(self.f0)+'Hz'}
         edf_info.append(channel_info)
         edf_signal.append(in_signal[i])
     edf.setSignalHeaders(edf_info)
     edf.writeSamples(edf_signal)
     edf.close()
     del edf
Example #10
0
    def test_subsecond_annotation(self):
        channel_info = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.bdfplus_data_file,
                               1,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info)
        data = np.ones(100) * 0.1
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writeAnnotation(1.23456, 0.2222, u"annotation1_ä")
        f.writeAnnotation(0.2567, -1, u"annotation2_ü")
        f.writeAnnotation(1.2567, 0, u"annotation3_ö")
        f.writeAnnotation(1.3067, -1, u"annotation4_ß")
        del f

        f = pyedflib.EdfReader(self.bdfplus_data_file)
        self.assertEqual(f.filetype, pyedflib.FILETYPE_BDFPLUS)

        ann_time, ann_duration, ann_text = f.readAnnotations()
        del f
        np.testing.assert_almost_equal(ann_time[0], 1.2345, decimal=4)
        np.testing.assert_almost_equal(ann_duration[0], 0.2222, decimal=4)
        np.testing.assert_equal(ann_text[0][0:12], "annotation1_")
        np.testing.assert_almost_equal(ann_time[1], 0.2567, decimal=4)
        np.testing.assert_almost_equal(ann_duration[1], -1)
        np.testing.assert_equal(ann_text[1][0:12], "annotation2_")
        np.testing.assert_almost_equal(ann_time[2], 1.2567, decimal=4)
        np.testing.assert_almost_equal(ann_duration[2], 0)
        np.testing.assert_equal(ann_text[2][0:12], "annotation3_")
        np.testing.assert_almost_equal(ann_time[3], 1.3067, decimal=4)
        np.testing.assert_almost_equal(ann_duration[3], -1)
        np.testing.assert_equal(ann_text[3][0:12], "annotation4_")
Example #11
0
    def test_EdfReader_Check_Size(self):
        sample_frequency = 100
        channel_info = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 256,
            'sample_frequency': sample_frequency,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.bdf_broken_file,
                               1,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info)
        f.setTechnician('tec1')
        data = np.ones(100) * 0.1
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        del f

        f = pyedflib.EdfReader(self.bdf_broken_file,
                               pyedflib.READ_ALL_ANNOTATIONS,
                               pyedflib.DO_NOT_CHECK_FILE_SIZE)
        np.testing.assert_equal(f.getTechnician(), 'tec1')

        np.testing.assert_equal(f.getLabel(0), 'test_label')
        np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
        np.testing.assert_equal(f.getPrefilter(0), 'pre1')
        np.testing.assert_equal(f.getTransducer(0), 'trans1')
        np.testing.assert_equal(f.getSampleFrequency(0), sample_frequency)

        # When both 'sample_rate' and 'sample_frequency' are present, we write
        # the file using the latter, which means that when we read it back,
        # only the 'sample_frequency' value is present.
        expected_signal_header = {
            **channel_info, 'sample_rate': sample_frequency
        }
        np.testing.assert_equal(f.getSignalHeader(0), expected_signal_header)
        np.testing.assert_equal(f.getSignalHeaders(), [expected_signal_header])
        del f
Example #12
0
    def test_AnnotationWriting(self):
        channel_info = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.bdf_data_file,
                               1,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info)
        data = np.ones(100) * 0.1
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writeAnnotation(1.23, 0.2, u"annotation1_ä")
        f.writeAnnotation(0.25, -1, u"annotation2_ü")
        f.writeAnnotation(1.25, 0, u"annotation3_ö")
        f.writeAnnotation(1.30, -1, u"annotation4_ß")
        f.close()
        del f

        f = pyedflib.EdfReader(self.bdf_data_file)
        ann_time, ann_duration, ann_text = f.readAnnotations()
        f._close()
        del f
        np.testing.assert_almost_equal(ann_time[0], 1.23)
        np.testing.assert_almost_equal(ann_duration[0], 0.2)
        np.testing.assert_equal(ann_text[0], "annotation1_..")
        np.testing.assert_almost_equal(ann_time[1], 0.25)
        np.testing.assert_almost_equal(ann_duration[1], -1)
        np.testing.assert_equal(ann_text[1], "annotation2_..")
        np.testing.assert_almost_equal(ann_time[2], 1.25)
        np.testing.assert_almost_equal(ann_duration[2], 0)
        np.testing.assert_equal(ann_text[2], "annotation3_..")
        np.testing.assert_almost_equal(ann_time[3], 1.30)
        np.testing.assert_almost_equal(ann_duration[3], -1)
        np.testing.assert_equal(ann_text[3], "annotation4_..")
Example #13
0
    def test_physical_range_inequality(self):
        # Prepare data
        channel_data1 = np.sin(np.arange(1,1001))
        channel_info1 = {'label': 'test_label_sin', 'dimension': 'mV', 'sample_rate': 100,
                        'physical_max': max(channel_data1), 'physical_min': min(channel_data1),
                        'digital_max': 8388607, 'digital_min': -8388608,
                        'prefilter': 'pre1', 'transducer': 'trans1'}

        channel_data2 = np.zeros((1000,))
        channel_info2 = {'label': 'test_label_zero', 'dimension': 'mV', 'sample_rate': 100,
                            'physical_max': max(channel_data2), 'physical_min': min(channel_data2),
                            'digital_max': 8388607, 'digital_min': -8388608,
                            'prefilter': 'pre1', 'transducer': 'trans1'}
        f = pyedflib.EdfWriter(self.edf_data_file, 2,
                                file_type=pyedflib.FILETYPE_BDF)
        f.setSignalHeader(0,channel_info1)
        f.setSignalHeader(1,channel_info2)
        
        # Test that assertion fails
        self.assertRaises(AssertionError, f.writeSamples, [channel_data1, channel_data2])
Example #14
0
    def test_BytesChars(self):
        channel_info = {
            'label': b'test_label',
            'dimension': b'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': b'      ',
            'transducer': b'trans1'
        }
        f = pyedflib.EdfWriter(self.bdfplus_data_file,
                               1,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info)
        data = np.ones(100) * 0.1
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.writeAnnotation(1.23, 0.2, b'Zaehne')
        f.writeAnnotation(0.25, -1, b'Fuss')
        f.writeAnnotation(1.25, 0, b'abc')

        del f

        f = pyedflib.EdfReader(self.bdfplus_data_file)
        self.assertEqual(f.filetype, pyedflib.FILETYPE_BDFPLUS)

        ann_time, ann_duration, ann_text = f.readAnnotations()
        del f
        np.testing.assert_almost_equal(ann_time[0], 1.23)
        np.testing.assert_almost_equal(ann_duration[0], 0.2)
        np.testing.assert_equal(ann_text[0], "Zaehne")
        np.testing.assert_almost_equal(ann_time[1], 0.25)
        np.testing.assert_almost_equal(ann_duration[1], -1)
        np.testing.assert_equal(ann_text[1], "Fuss")
        np.testing.assert_almost_equal(ann_time[2], 1.25)
        np.testing.assert_almost_equal(ann_duration[2], 0)
        np.testing.assert_equal(ann_text[2], "abc")
Example #15
0
def correct_edf(edfpath, ebmheader, saveas="./out.edf"):
    """Correct edf based on header from ebm

    Parameters
    ----------
    edfpath : str
        path of the old edf
    ebmheader : [type]
        return value from get_ebm_headers
    saveas : str, optional
        path of the new edf, by default "./out.edf"
    """
    with pyedflib.EdfReader(edfpath) as old_edf:
        edf_header = old_edf.getHeader()
        #         events = f_test.readAnnotations()
        signal_headers = old_edf.getSignalHeaders()
        edf_starttime = old_edf.getStartdatetime()

        signals = []
        num_of_signal = len(signal_headers)
        duration = np.zeros(num_of_signal)

        for i in range(num_of_signal):
            signal_tmp = old_edf.readSignal(i)
            label, freq = signal_headers[i]["label"], signal_headers[i][
                "sample_rate"]
            corrected_signal = correct_signal(signal_tmp, freq, label,
                                              edf_starttime, ebmheader)
            signals.append(corrected_signal)
            duration[i] = corrected_signal.size // freq
        max_duration = max(duration)
        for i in range(num_of_signal):
            freq = signal_headers[i]["sample_rate"]
            num_of_zeros = int((max_duration - duration[i]) * freq)
            if num_of_zeros != 0:
                signals[i] = np.concatenate(
                    [signals[i], np.zeros(num_of_zeros)])
    with pyedflib.EdfWriter(saveas, num_of_signal) as new_edf:
        new_edf.setHeader(edf_header)
        new_edf.setSignalHeaders(signal_headers)
        new_edf.writeSamples(signals)
Example #16
0
def curves_to_edf(
    curves: List[CurveItem], filepath: str, index_label: str = 'timens'
) -> None:
    headers = []
    signals = []

    beginns = min(c.series.index[0] for c in curves)
    endns = max(c.series.index[-1] for c in curves)
    begindt = datetime.fromtimestamp(beginns * 1e-9)

    # Use global min / max of values since some viewers need this (edfbrowser)
    physmax = max(c.series.max() for c in curves)
    physmin = min(c.series.min() for c in curves)

    # Ask the user for the physical dimension shared by all curves
    dim = askUserValue(Parameter('Enter physical dimension', str))

    for c in curves:
        s = c.series
        header = {
            'label': c.name(),
            'sample_rate': c.samplerate,
            'physical_max': physmax,
            'physical_min': physmin,
            'digital_max': 32767,
            'digital_min': -32768,
            'transducer': '',
            'prefilter': '',
            'dimension': dim,
        }
        headers.append(header)
        resampled = interp_series(s, c.samplerate, beginns, endns)
        signals.append(resampled)

    edf = pyedflib.EdfWriter(
        str(filepath), len(signals), file_type=pyedflib.FILETYPE_EDFPLUS
    )
    edf.setStartdatetime(begindt)
    edf.setSignalHeaders(headers)
    edf.writeSamples(signals)
    edf.close()
Example #17
0
    def test_EdfWriter_EDF_contextmanager(self):
        channel_info1 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 32767,
            'digital_min': -32768,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        channel_info2 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 32767,
            'digital_min': -32768,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        with pyedflib.EdfWriter(self.edf_data_file,
                                2,
                                file_type=pyedflib.FILETYPE_EDF) as f:
            f.setSignalHeader(0, channel_info1)
            f.setSignalHeader(1, channel_info2)
            data = np.ones(100) * 0.1
            f.writePhysicalSamples(data)
            f.writePhysicalSamples(data)

        with pyedflib.EdfReader(self.edf_data_file) as f:
            np.testing.assert_equal(f.getLabel(0), 'test_label')
            np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
            np.testing.assert_equal(f.getPrefilter(0), 'pre1')
            np.testing.assert_equal(f.getTransducer(0), 'trans1')
            np.testing.assert_equal(f.getSampleFrequency(0), 100)
Example #18
0
    def test_EdfWriter_EDFplus(self):
        channel_info = {'label': 'test_label', 'dimension': 'mV', 'sample_rate': 100,
                        'physical_max': 1.0, 'physical_min': -1.0,
                        'digital_max': 32767, 'digital_min': -32768,
                        'prefilter': 'pre1', 'transducer': 'trans1'}
        f = pyedflib.EdfWriter(self.edfplus_data_file, 1,
                                file_type=pyedflib.FILETYPE_EDFPLUS)

        header = {'technician': 'tec1', 'recording_additional': 'recAdd1', 'patientname': 'pat1',
                  'patient_additional': 'patAdd1', 'patientcode': 'code1', 'equipment': 'eq1',
                  'admincode':'admin1','gender':1,'startdate':datetime(2017, 1, 1, 1, 1, 1),'birthdate':date(1951, 8, 2)}
        f.setHeader(header)
        f.setSignalHeader(0,channel_info)
        data = np.ones(100) * 0.1
        assert f.writePhysicalSamples(data)==0, 'error while writing physical sample'
        assert f.writePhysicalSamples(data)==0, 'error while writing physical sample'
        del f

        f = pyedflib.EdfReader(self.edfplus_data_file)
        np.testing.assert_equal(f.getTechnician(), 'tec1')
        np.testing.assert_equal(f.getRecordingAdditional(), 'recAdd1')
        np.testing.assert_equal(f.getPatientName(), 'pat1')
        np.testing.assert_equal(f.getPatientCode(), 'code1')
        np.testing.assert_equal(f.getEquipment(), 'eq1')
        np.testing.assert_equal(f.getPatientAdditional(), 'patAdd1')
        np.testing.assert_equal(f.getAdmincode(), 'admin1')
        np.testing.assert_equal(f.getGender(), 'Male')
        np.testing.assert_equal(f.getBirthdate(), '02 aug 1951')
        np.testing.assert_equal(f.getStartdatetime(), datetime(2017, 1, 1, 1, 1, 1))

        np.testing.assert_equal(f.getLabel(0), 'test_label')
        np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
        np.testing.assert_equal(f.getPrefilter(0), 'pre1')
        np.testing.assert_equal(f.getTransducer(0), 'trans1')
        np.testing.assert_equal(f.getSampleFrequency(0), 100)
        self.assertEqual(f.filetype, pyedflib.FILETYPE_EDFPLUS)
        del f
Example #19
0
    def test_EdfReader_Check_Size(self):
        channel_info = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.bdf_broken_file,
                               1,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info)
        f.setTechnician('tec1')
        data = np.ones(100) * 0.1
        f.writePhysicalSamples(data)
        f.writePhysicalSamples(data)
        f.close()
        del f

        f = pyedflib.EdfReader(self.bdf_broken_file,
                               pyedflib.READ_ALL_ANNOTATIONS,
                               pyedflib.DO_NOT_CHECK_FILE_SIZE)
        np.testing.assert_equal(f.getTechnician(), 'tec1')

        np.testing.assert_equal(f.getLabel(0), 'test_label')
        np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
        np.testing.assert_equal(f.getPrefilter(0), 'pre1')
        np.testing.assert_equal(f.getTransducer(0), 'trans1')
        np.testing.assert_equal(f.getSampleFrequency(0), 100)
        np.testing.assert_equal(f.getSignalHeader(0), channel_info)
        np.testing.assert_equal(f.getSignalHeaders(), [channel_info])
        f._close()
        del f
Example #20
0
abrout = next(s for s in args if 'abr_outfile' in s)
abr_outstring = abrout.split('=')
abr_outfile = abr_outstring[1]
logger.debug('ABR output file name found. File name = %s\n', abr_outfile)

logger.info('Saving output file data...\n')


# Gets input bdf file header from raw data file to use in the created MMN and ABR files
logger.debug('Reading input file header information to save into MMN and ABR files...\n')
infile_info = pyedflib.EdfReader(fname)


# Creates MMN .bdf data file from cropped MMN data using pyedflib module
logger.debug('Begin writing MMN data to .bdf file.\n')
m = pyedflib.EdfWriter(mmn_outfile, len(cropped_mmn.info['ch_names']), file_type=pyedflib.FILETYPE_BDF)

logger.info('Creating file: %s with %i channels.\n', mmn_outfile, len(cropped_mmn.info['ch_names']))

logger.debug('Writing input file header info into MMN header\n')
header = infile_info.getHeader()
m.setHeader(header)

logger.info('Creating individual channel headers...\n')
x = 0
mmn_chan_data = []

logger.debug('Writing individual channel headers in accordance to respective channels on input file...\n')
for x in xrange(0,len(cropped_mmn.info['ch_names'])):
    dict = infile_info.getSignalHeader(x)
    mmn_chan_info = {'label': dict['label'], 'dimension': 'mV', 'sample_rate': freq, 'physical_max': 1.0, 'physical_min': -2.0, 'digital_max': 8388607, 'digital_min': -8388608, 'prefilter': dict['prefilter'], 'transducer': dict['transducer']}
Example #21
0
#    4    pulse 2           100 uV    1 Hz    256 Hz
#    5    pulse 3           100 uV    1 Hz    217 Hz
#    6    noise             100 uV    - Hz    200 Hz
#    7    sine 1 Hz         100 uV    1 Hz    200 Hz
#    8    sine 8 Hz         100 uV    8 Hz    200 Hz
#    9    sine 8.1777 Hz    100 uV    8.25 Hz 200 Hz
#    10    sine 8.5 Hz       100 uV    8.5Hz   200 Hz
#    11    sine 15 Hz        100 uV   15 Hz    200 Hz
#    12    sine 17 Hz        100 uV   17 Hz    200 Hz
#    13    sine 50 Hz        100 uV   50 Hz    200 Hz

if __name__ == '__main__':
    test_data_file = os.path.join('.', 'test_generator2.edf')
    file_duration = 600
    f = pyedflib.EdfWriter(test_data_file,
                           13,
                           file_type=pyedflib.FILETYPE_EDFPLUS)
    channel_info = []
    data_list = []

    ch_dict = {
        'label': 'squarewave',
        'dimension': 'uV',
        'sample_frequency': 200,
        'physical_max': 100,
        'physical_min': -100,
        'digital_max': 32767,
        'digital_min': -32768,
        'transducer': '',
        'prefilter': ''
    }
def lfp_to_edf(paths, day_path, idx, fs, letter_id, config):
    """ lfp_to_edf(paths,day_path,idx,fs,letter_id,config)
    Converts lfp to EDF across channels
    """

    # set channel order
    ch_id = config['ch_id']

    # get channel list
    ch_list = list(
        filter(
            lambda k: config['file_ext'] in k,
            os.listdir(
                os.path.join(paths['bin_path'], paths['subject_id'],
                             day_path))))

    # pre allocate empty vectors
    channel_info = []
    data_list = []

    for i in range(len(ch_list)):

        # get files in order
        file = list(filter(lambda k: ch_id[i] in k, ch_list))[0]

        # load memory mapped file
        load_name = os.path.join(paths['bin_path'], paths['subject_id'],
                                 day_path, file)
        fp = np.memmap(load_name, dtype=config['file_type'], mode='r')

        # pass file into a variable and delete memory mapped object
        data = fp[idx[0] * fs * 3600:idx[1] * fs * 3600]
        del fp

        # append to list for storage - remove mean and scale data
        data_list.append((data - np.mean(data)) / config['file_norm'])

        # get channel properties
        ch_dict = {
            'label': ch_id[i],
            'dimension': config['dimension'][i],
            'sample_rate': fs,
            'physical_max': config['physical_max'][i],
            'physical_min': config['physical_min'][i],
            'digital_max': config['digital_max'][i],
            'digital_min': config['digital_min'][i],
            'transducer': '',
            'prefilter': ''
        }

        # appent to channel info
        channel_info.append(ch_dict)

    # create data file name + path
    data_file = os.path.join(paths['edf_path'], paths['subject_id'],
                             day_path + '_' + letter_id + '.edf')

    # intialize EDF object
    f = pyedflib.EdfWriter(data_file,
                           len(ch_id),
                           file_type=pyedflib.FILETYPE_EDF)

    # write file to EDF object
    f.setSignalHeaders(channel_info)
    f.writeSamples(data_list)

    # close and delete EDF object
    f.close()
    del f
Example #23
0
infilename = sys.argv[1] or 'in.txt'
outfilename = sys.argv[2] or 'out.edf'

CHANNELS = [
    'AF3', 'AF4', 'F7', 'F8', 'F3', 'F4', 'FC5', 'FC6', 'T7', 'T8', 'P7', 'P8',
    'O1', 'O2'
]

with open(infilename, 'r') as f:
    lines = f.readlines()
    data = [[json.loads(line)[chan] for chan in CHANNELS] for line in lines]
    npdata = np.array(data).transpose()

    file_duration = len(lines) / 128
    f = pyedflib.EdfWriter(outfilename,
                           len(CHANNELS),
                           file_type=pyedflib.FILETYPE_BDFPLUS)

    channel_info = [{
        'label': name,
        'dimension': 'uV',
        'sample_rate': 128,
        'physical_max': 106496,
        'physical_min': -106496,
        'digital_max': 8192,
        'digital_min': -8192,
        'transducer': '',
        'prefilter': ''
    } for name in CHANNELS]
    data_list = []
Example #24
0
outstring = argout.split('=')
deci_outfile = outstring[1]
logger.debug('Output file name found. File name = %s\n', deci_outfile)

logger.info('Saving output file data...\n')

# Gets input bdf file header from raw data file to use in the created decimated file
logger.debug(
    'Reading input file header information to save into MMN and ABR files...\n'
)
infile_info = pyedflib.EdfReader(fname)

# Creates .bdf data file from decimated data using pyedflib module
logger.debug('Begin writing data to .bdf file.\n')
d = pyedflib.EdfWriter(deci_outfile,
                       len(deci_data.info['ch_names']),
                       file_type=pyedflib.FILETYPE_BDF)

logger.info('Creating file: %s with %i channels.\n', deci_outfile,
            len(deci_data.info['ch_names']))

logger.debug('Writing input file header info into decimated data header\n')
header = infile_info.getHeader()
d.setHeader(header)

logger.info('Creating individual channel headers...\n')
x = 0
chan_data = []

logger.debug(
    'Writing individual channel headers in accordance to respective channels on input file...\n'
Example #25
0
def mne_write_edf(mne_raw,
                  fname,
                  picks=None,
                  tmin=0,
                  tmax=None,
                  overwrite=False):
    """
    Saves the raw content of an MNE.io.Raw and its subclasses to
    a file using the EDF+/BDF filetype
    pyEDFlib is used to save the raw contents of the RawArray to disk
    Parameters
    ----------
    mne_raw : mne.io.Raw
        An object with super class mne.io.Raw that contains the data
        to save
    fname : string
        File name of the new dataset. This has to be a new filename
        unless data have been preloaded. Filenames should end with .edf
    picks : array-like of int | None
        Indices of channels to include. If None all channels are kept.
    tmin : float | None
        Time in seconds of first sample to save. If None first sample
        is used.
    tmax : float | None
        Time in seconds of last sample to save. If None last sample
        is used.
    overwrite : bool
        If True, the destination file (if it exists) will be overwritten.
        If False (default), an error will be raised if the file exists.
    """
    if not issubclass(type(mne_raw), mne.io.BaseRaw):
        raise TypeError('Must be mne.io.Raw type')
    if not overwrite and os.path.exists(fname):
        raise OSError('File already exists. No overwrite.')
    # static settings
    if os.path.splitext(fname)[-1] == '.edf':
        file_type = pyedflib.FILETYPE_EDFPLUS
        dmin, dmax = -32768, 32767
    else:
        file_type = pyedflib.FILETYPE_BDFPLUS
        dmin, dmax = -8388608, 8388607
    sfreq = mne_raw.info['sfreq']
    date = _stamp_to_dt(mne_raw.info['meas_date'])
    date = date.strftime('%d %b %Y %H:%M:%S')
    first_sample = int(sfreq * tmin)
    last_sample = int(sfreq * tmax) if tmax is not None else None

    # convert data
    channels = mne_raw.get_data(picks, start=first_sample, stop=last_sample)

    # convert to microvolts to scale up precision
    channels *= 1e6

    # set conversion parameters
    pmin, pmax = [channels.min(), channels.max()]
    n_channels = len(channels)

    # create channel from this
    try:
        f = pyedflib.EdfWriter(fname,
                               n_channels=n_channels,
                               file_type=file_type)

        channel_info = []
        data_list = []

        for i in range(n_channels):
            ch_dict = {
                'label': mne_raw.ch_names[i],
                'dimension': 'uV',
                'sample_rate': sfreq,
                'physical_min': pmin,
                'physical_max': pmax,
                'digital_min': dmin,
                'digital_max': dmax,
                'transducer': '',
                'prefilter': ''
            }

            channel_info.append(ch_dict)
            data_list.append(channels[i])

        f.setTechnician('mne-gist-save-edf-skjerns')
        f.setSignalHeaders(channel_info)
        f.setStartdatetime(date)
        f.writeSamples(data_list)
    except Exception as e:
        print(e)
        return False
    finally:
        f.close()
    return True
Example #26
0
def write_edf(edf_file,
              signals,
              signal_headers,
              header=None,
              digital=False,
              file_type=-1):
    """
    Write signals to an edf_file. Header can be generated on the fly with
    generic values. EDF+/BDF+ is selected based on the filename extension,
    but can be overwritten by setting filetype to pyedflib.FILETYPE_XXX

    Parameters
    ----------
    edf_file : np.ndarray or list
        where to save the EDF file
    signals : list
        The signals as a list of arrays or a ndarray.

    signal_headers : list of dict
        a list with one signal header(dict) for each signal.
        See pyedflib.EdfWriter.setSignalHeader..
    header : dict
        a main header (dict) for the EDF file, see 
        pyedflib.EdfWriter.setHeader for details.
        If no header present, will create an empty header
    digital : bool, optional
        whether the signals are in digital format (ADC). The default is False.
    filetype: int, optional
        choose filetype for saving. 
        EDF = 0, EDF+ = 1, BDF = 2, BDF+ = 3, automatic from extension = -1

    Returns
    -------
    bool
         True if successful, False if failed.
    """
    assert header is None or isinstance(header, dict), \
        'header must be dictioniary or None'
    assert isinstance(signal_headers, list), \
        'signal headers must be list'
    assert len(signal_headers)==len(signals), \
        'signals and signal_headers must be same length'
    assert file_type in [-1, 0, 1, 2, 3], 'filetype must be in range -1, 3'

    if file_type == -1:
        ext = os.path.splitext(edf_file)[-1]
        if ext == '.edf':
            file_type = pyedflib.FILETYPE_EDFPLUS
        elif ext == '.bdf':
            file_type = pyedflib.FILETYPE_BDFPLUS
        else:
            raise ValueError('Unknown extension {}'.format(ext))

    n_channels = len(signals)

    if header is None: header = {}
    default_header = make_header()
    default_header.update(header)
    header = default_header

    annotations = header.get('annotations', '')

    # check dmin, dmax and pmin, pmax dont exceed signal min/max
    for s, sh in zip(signals, signal_headers):
        dmin, dmax = sh['digital_min'], sh['digital_max']
        pmin, pmax = sh['physical_min'], sh['physical_max']
        label = sh['label']
        if digital:  # exception as it will lead to clipping
            assert dmin<=s.min(), \
            'digital_min is {}, but signal_min is {}' \
            'for channel {}'.format(dmin, s.min(), label)
            assert dmax>=s.max(), \
            'digital_min is {}, but signal_min is {}' \
            'for channel {}'.format(dmax, s.max(), label)
        else:  # only warning, as this will not lead to clipping
            assert pmin<=s.min(), \
            'phys_min is {}, but signal_min is {} ' \
            'for channel {}'.format(pmin, s.min(), label)
            assert pmax>=s.max(), \
            'phys_max is {}, but signal_max is {} ' \
            'for channel {}'.format(pmax, s.max(), label)

    with pyedflib.EdfWriter(edf_file,
                            n_channels=n_channels,
                            file_type=file_type) as f:
        f.setSignalHeaders(signal_headers)
        f.setHeader(header)
        f.writeSamples(signals, digital=digital)
        for annotation in annotations:
            f.writeAnnotation(*annotation)
    del f

    return os.path.isfile(edf_file)
Example #27
0
def write_edf(edf_file,
              signals,
              signal_headers,
              header,
              digital=False,
              correct=False):
    """
    Write signals to an edf_file. Header can be generated on the fly.
    
    :param signals: The signals as a list of arrays or a ndarray
    :param signal_headers: a list with one signal header(dict) for each signal.
                           See pyedflib.EdfWriter.setSignalHeader
    :param header: a main header (dict) for the EDF file, see 
                   pyedflib.EdfWriter.setHeader for details
    :param digital: whether signals are presented digitally 
                    or in physical values
    
    :returns: True if successful, False if failed
    """
    assert header is None or isinstance(header, dict), \
        'header must be dictioniary'
    assert isinstance(signal_headers, list), \
        'signal headers must be list'
    assert len(signal_headers)==len(signals), \
        'signals and signal_headers must be same length'

    n_channels = len(signals)

    # check min and max values
    if digital == True and correct:
        for sig, sigh in zip(signals, signal_headers):
            dmin, dmax = sigh['digital_min'], sigh['digital_max']
            pmin, pmax = sigh['physical_min'], sigh['physical_max']
            ch_name = sigh['label']
            if dmin > dmax:
                logging.warning('{}: dmin>dmax, {}>{}, will correct'.format(\
                                ch_name, dmin, dmax))
                dmin, dmax = dmax, dmin
                sig *= -1
            if pmin > pmax:
                logging.warning('{}: pmin>pmax, {}>{}, will correct'.format(\
                                 ch_name, pmin, pmax))
                pmin, pmax = pmax, pmin
                sig *= -1
            dsmin, dsmax = round(sig.min()), round(sig.max())
            psmin = dig2phys(dsmin, dmin, dmax, pmin, pmax)
            psmax = dig2phys(dsmax, dmin, dmax, pmin, pmax)
            min_dist = np.abs(dig2phys(1, dmin, dmax, pmin, pmax))
            if dsmin < dmin:
                logging.warning('{}:Digital signal minimum is {}'\
                                ', but value range is {}, will correct'.format\
                                (ch_name, dmin, dsmin))
                dsmin = min(dsmin, 32767)
                sigh['digital_min'] = dsmin

            if dsmax > dmax:
                logging.warning('{}:Digital signal maximum is {}'\
                                ', but value range is {}, will correct'.format\
                                (ch_name, dmax, dsmax))
                dsmax = min(dsmax, 32767)
                sigh['digital_max'] = dsmax
            if psmax - min_dist > pmax:
                logging.warning('{}:Phyiscal signal maximum is {}'\
                                ', but value range is {}, will correct'.format\
                                (ch_name, pmax, psmax))
                sigh['physical_max'] = psmax
            if psmin + min_dist < pmin:
                logging.warning('{}:Physical signal minimum is {}'\
                                ', but value range is {}, will correct'.format\
                                (ch_name, pmin, psmin))
                sigh['physical_min'] = psmin

    # also add annotations
    annotations = header.get('annotations', '')

    with pyedflib.EdfWriter(edf_file, n_channels=n_channels) as f:
        f.setSignalHeaders(signal_headers)
        f.setHeader(header)
        f.writeSamples(signals, digital=digital)
        for annotation in annotations:
            f.writeAnnotation(*annotation)
    del f
    return os.path.isfile(edf_file)
Example #28
0
    def test_SampleWriting_digital(self):

        dmin, dmax = [0, 1024]
        pmin, pmax = [0, 1.0]
        channel_info1 = {
            'label': 'test_label1',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': pmax,
            'physical_min': pmin,
            'digital_max': dmax,
            'digital_min': dmin,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        channel_info2 = {
            'label': 'test_label2',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': pmax,
            'physical_min': pmin,
            'digital_max': dmax,
            'digital_min': dmin,
            'prefilter': 'pre2',
            'transducer': 'trans2'
        }

        f = pyedflib.EdfWriter(self.bdfplus_data_file,
                               2,
                               file_type=pyedflib.FILETYPE_EDFPLUS)
        f.setSignalHeader(0, channel_info1)
        f.setSignalHeader(1, channel_info2)

        data1 = np.arange(500, dtype=np.float)
        data2 = np.arange(500, dtype=np.float)
        data_list = []
        data_list.append(data1)
        data_list.append(data2)
        with np.testing.assert_raises(TypeError):
            f.writeSamples(data_list, digital=True)
        f.close()
        del f

        f = pyedflib.EdfWriter(self.bdfplus_data_file,
                               2,
                               file_type=pyedflib.FILETYPE_EDFPLUS)
        f.setSignalHeader(0, channel_info1)
        f.setSignalHeader(1, channel_info2)

        data1 = np.arange(500, dtype=np.int32)
        data2 = np.arange(500, dtype=np.int32)
        data_list = []
        data_list.append(data1)
        data_list.append(data2)
        f.writeSamples(data_list, digital=True)
        del f

        f = pyedflib.EdfReader(self.bdfplus_data_file)
        data1_read = (f.readSignal(0) - pmin) / (
            (pmax - pmin) / (dmax - dmin))  # converting back to digital
        data2_read = (f.readSignal(1) - pmin) / (
            (pmax - pmin) / (dmax - dmin))  # converting back to digital
        del f

        np.testing.assert_equal(len(data1), len(data1_read))
        np.testing.assert_equal(len(data2), len(data2_read))
        np.testing.assert_almost_equal(data1, data1_read)
        np.testing.assert_almost_equal(data2, data2_read)
Example #29
0
    def test_EdfWriter_BDFplus(self):
        channel_info1 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        channel_info2 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.bdfplus_data_file,
                               2,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info1)
        f.setSignalHeader(1, channel_info2)
        f.setTechnician('tec1')
        f.setRecordingAdditional('recAdd1')
        f.setPatientName('pat1')
        f.setPatientCode('code1')
        f.setPatientAdditional('patAdd1')
        f.setAdmincode('admin1')
        f.setEquipment('eq1')
        f.setGender(1)
        f.setBirthdate(date(1951, 8, 2))
        f.setStartdatetime(datetime(2017, 1, 1, 1, 1, 1))
        f.setSamplefrequency(1, 200)
        f.setPhysicalMaximum(1, 2)
        f.setPhysicalMinimum(1, -2)
        f.setLabel(1, 'test 2')
        f.setPhysicalDimension(1, 'l2')
        f.setTransducer(1, 'trans2')
        f.setPrefilter(1, 'pre2')
        data1 = np.ones(100) * 0.1
        data2 = np.ones(200) * 0.2
        f.writePhysicalSamples(data1)
        f.writePhysicalSamples(data2)
        f.writePhysicalSamples(data1)
        f.writePhysicalSamples(data2)
        del f

        f = pyedflib.EdfReader(self.bdfplus_data_file)
        np.testing.assert_equal(f.getTechnician(), 'tec1')
        np.testing.assert_equal(f.getRecordingAdditional(), 'recAdd1')
        np.testing.assert_equal(f.getPatientName(), 'pat1')
        np.testing.assert_equal(f.getPatientCode(), 'code1')
        np.testing.assert_equal(f.getPatientAdditional(), 'patAdd1')
        np.testing.assert_equal(f.getAdmincode(), 'admin1')
        np.testing.assert_equal(f.getEquipment(), 'eq1')
        np.testing.assert_equal(f.getGender(), 'Male')
        np.testing.assert_equal(f.getBirthdate(), '02 aug 1951')
        np.testing.assert_equal(f.getStartdatetime(),
                                datetime(2017, 1, 1, 1, 1, 1))

        np.testing.assert_equal(f.getLabel(0), 'test_label')
        np.testing.assert_equal(f.getPhysicalDimension(0), 'mV')
        np.testing.assert_equal(f.getPrefilter(0), 'pre1')
        np.testing.assert_equal(f.getTransducer(0), 'trans1')
        np.testing.assert_equal(f.getSampleFrequency(0), 100)

        np.testing.assert_equal(f.getLabel(1), 'test 2')
        np.testing.assert_equal(f.getPhysicalDimension(1), 'l2')
        np.testing.assert_equal(f.getPrefilter(1), 'pre2')
        np.testing.assert_equal(f.getTransducer(1), 'trans2')
        np.testing.assert_equal(f.getSampleFrequency(1), 200)
        np.testing.assert_equal(f.getPhysicalMaximum(1), 2)
        np.testing.assert_equal(f.getPhysicalMinimum(1), -2)
        del f
Example #30
0
    def test_EdfWriter_BDFplus2(self):
        channel_info1 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        channel_info2 = {
            'label': 'test_label',
            'dimension': 'mV',
            'sample_rate': 100,
            'physical_max': 1.0,
            'physical_min': -1.0,
            'digital_max': 8388607,
            'digital_min': -8388608,
            'prefilter': 'pre1',
            'transducer': 'trans1'
        }
        f = pyedflib.EdfWriter(self.bdfplus_data_file,
                               2,
                               file_type=pyedflib.FILETYPE_BDFPLUS)
        f.setSignalHeader(0, channel_info1)
        f.setSignalHeader(1, channel_info2)
        f.setTechnician('tec1')
        f.setRecordingAdditional('recAdd1')
        f.setPatientName('empty')

        f.setPatientCode('code1')
        f.setPatientAdditional('patAdd1')
        f.setAdmincode('admin1')
        f.setEquipment('eq1')
        f.setGender("Male")
        f.setBirthdate(date(1951, 8, 2))
        f.setStartdatetime(datetime(2017, 1, 1, 1, 1, 1))
        f.setSamplefrequency(1, 100)
        f.setPhysicalMaximum(1, 2)
        f.setPhysicalMinimum(1, -2)

        data1 = np.ones(100) * 0.1
        data2 = np.ones(100) * 0.2
        f.writePhysicalSamples(data1)
        f.writePhysicalSamples(data2)
        f.writePhysicalSamples(data2)
        f.writePhysicalSamples(data1)
        del f

        f = pyedflib.EdfReader(self.bdfplus_data_file)
        np.testing.assert_equal(f.getTechnician(), 'tec1')
        np.testing.assert_equal(f.getRecordingAdditional(), 'recAdd1')
        np.testing.assert_equal(f.getPatientName(), 'empty')
        np.testing.assert_equal(f.getPatientCode(), 'code1')
        np.testing.assert_equal(f.getPatientAdditional(), 'patAdd1')
        np.testing.assert_equal(f.getAdmincode(), 'admin1')
        np.testing.assert_equal(f.getEquipment(), 'eq1')
        np.testing.assert_equal(f.getGender(), 'Male')
        np.testing.assert_equal(f.getBirthdate(), '02 aug 1951')
        np.testing.assert_equal(f.getStartdatetime(),
                                datetime(2017, 1, 1, 1, 1, 1))

        x01 = f.readSignal(0, 000, 100)
        x02 = f.readSignal(0, 100, 100)
        x11 = f.readSignal(1, 000, 100)
        x12 = f.readSignal(1, 100, 100)
        np.testing.assert_almost_equal(np.sum(np.abs(x01 - data1)),
                                       0,
                                       decimal=4)
        np.testing.assert_almost_equal(np.sum(np.abs(x02 - data2)),
                                       0,
                                       decimal=4)
        np.testing.assert_almost_equal(np.sum(np.abs(x11 - data2)),
                                       0,
                                       decimal=4)
        np.testing.assert_almost_equal(np.sum(np.abs(x12 - data1)),
                                       0,
                                       decimal=4)
        del f