def create_time_series(self, storage_path, connectivity=None, surface=None,
                        region_map=None, region_volume_map=None):
     return TimeSeriesEEG(storage_path=storage_path,
                          sensors=self.sensors,
                          sample_period=self.period,
                          title=' ' + self.__class__.__name__,
                          **self._transform_user_tags())
Exemple #2
0
 def create_time_series(self,
                        connectivity=None,
                        surface=None,
                        region_map=None,
                        region_volume_map=None):
     return TimeSeriesEEG(sensors=self.sensors,
                          sample_period=self.period,
                          title=' ' + self.__class__.__name__)
    def create_timeseries(self, connectivity, ts_type=None, sensors=None):
        """
        Create a stored TimeSeries entity.
        """
        operation, _, storage_path = self.__create_operation()

        if ts_type == "EEG":
            time_series = TimeSeriesEEG(storage_path=storage_path,
                                        sensors=sensors)
        else:
            rm = dao.get_generic_entity(RegionMapping, connectivity.gid,
                                        '_connectivity')
            if len(rm) < 1:
                rm = None
            else:
                rm = rm[0]
            time_series = TimeSeriesRegion(storage_path=storage_path,
                                           connectivity=connectivity,
                                           region_mapping=rm)

        data = numpy.random.random((10, 10, 10, 10))
        time_series.write_data_slice(data)
        time_series.write_time_slice(numpy.arange(10))
        adapter_instance = StoreAdapter([time_series])
        OperationService().initiate_prelaunch(operation, adapter_instance, {})
        time_series = dao.get_datatype_by_gid(time_series.gid)
        return time_series
Exemple #4
0
    def create_eeg_ts(self, data_shape, sensors):
        if sensors.number_of_sensors != data_shape[1]:
            raise LaunchException("Data has %d channels but the sensors have %d"
                                  % (data_shape[1], sensors.number_of_sensors))

        ts_idx = TimeSeriesEEGIndex()
        ts_idx.fk_sensors_gid = sensors.gid

        ts_h5_path = h5.path_for(self.storage_path, TimeSeriesEEGH5, ts_idx.gid)
        ts_h5 = TimeSeriesEEGH5(ts_h5_path)
        ts_h5.sensors.store(uuid.UUID(sensors.gid))

        return TimeSeriesEEG(), ts_idx, ts_h5
 def create_timeseries(self, connectivity, ts_type=None, sensors=None):
     """
     Create a stored TimeSeries entity.
     """
     operation, _, storage_path = self.__create_operation()
     if ts_type == "EEG":
         time_series = TimeSeriesEEG(storage_path=storage_path, sensors=sensors)
     else:
         time_series = TimeSeriesRegion(storage_path=storage_path, connectivity=connectivity)
     data = numpy.random.random((10, 10, 10, 10))
     time = numpy.arange(10)
     time_series.write_data_slice(data)
     time_series.write_time_slice(time)
     adapter_instance = StoreAdapter([time_series])
     OperationService().initiate_prelaunch(operation, adapter_instance, {})
     time_series = dao.get_datatype_by_gid(time_series.gid)
     return time_series
Exemple #6
0
 def create_eeg_ts(self, data, sensors):
     if sensors.number_of_sensors != data.shape[1]:
         raise LaunchException(
             "Data has %d channels but the sensors have %d" %
             (data.shape[1], sensors.number_of_sensors))
     return TimeSeriesEEG(storage_path=self.storage_path, sensors=sensors)
    def launch(self, matfile):
        mat = loadmat(matfile)
        hdr = mat['hdr']
        fs, ns = [hdr[key][0, 0][0, 0] for key in ['Fs', 'nSamples']]

        # the entities to populate
        #ch = SensorsMEG(storage_path=self.storage_path)
        ts = TimeSeriesEEG(storage_path=self.storage_path)

        # (nchan x ntime) -> (t, sv, ch, mo)
        dat = mat['dat'].T[:, numpy.newaxis, :, numpy.newaxis]

        # write data
        ts.write_data_slice(dat)

        # fill in header info
        ts.length_1d, ts.length_2d, ts.length_3d, ts.length_4d = dat.shape
        ts.labels_ordering = 'Time 1 Channel 1'.split()
        ts.write_time_slice(numpy.r_[:ns] * 1.0 / fs)
        ts.start_time = 0.0
        ts.sample_period_unit = 's'
        ts.sample_period = 1.0 / float(fs)
        ts.close_file()

        return ts
    def launch(self, matfile, fdtfile):

        self.mat = loadmat(matfile)
        self.fs = self.mat['EEG']['srate'][0, 0][0, 0]
        self.nsamp = self.mat['EEG']['pnts'][0, 0][0, 0]
        self.data = numpy.fromfile(fdtfile, dtype=numpy.float32)
        self.data = self.data.reshape((self.nsamp, -1)).T
        self.nchan = self.data.shape[0]
        self.labels = [
            c[0] for c in self.mat['EEG']['chanlocs'][0, 0]['labels'][0]
        ]

        ch = SensorsEEG(storage_path=self.storage_path,
                        labels=self.labels,
                        number_of_sensors=len(self.labels))
        self._capture_operation_results([ch])

        ts = TimeSeriesEEG(sensors=ch, storage_path=self.storage_path)

        # (nchan x ntime) -> (t, sv, ch, mo)
        dat = self.data.T[:, numpy.newaxis, :, numpy.newaxis]

        # write data
        ts.write_data_slice(dat)

        # fill in header info
        ts.length_1d, ts.length_2d, ts.length_3d, ts.length_4d = dat.shape
        ts.labels_ordering = 'Time 1 Channel 1'.split()
        ts.write_time_slice(numpy.r_[:dat.shape[0]] * 1.0 / self.fs)
        ts.start_time = 0.0
        ts.sample_period_unit = 's'
        ts.sample_period = 1.0 / float(self.fs)
        ts.close_file()

        return ts
    def launch(self, vhdr, dat):

        self.filename = vhdr
        self.wd, _ = os.path.split(vhdr)

        # read file
        with open(vhdr, 'r') as fd:
            self.srclines = fd.readlines()

        # config parser expects each section to have header
        # but vhdr has some decorative information at the beginning
        while not self.srclines[0].startswith('['):
            self.srclines.pop(0)

        self.sio = StringIO()
        self.sio.write('\n'.join(self.srclines))
        self.sio.seek(0)

        self.cp = ConfigParser.ConfigParser()
        self.cp.readfp(self.sio)

        for opt in self.cp.options('Common Infos'):
            setattr(self, opt, self.cp.get('Common Infos', opt))

        self.binaryformat = self.cp.get('Binary Infos', 'BinaryFormat')

        self.labels = [
            self.cp.get('Channel Infos', o).split(',')[0]
            for o in self.cp.options('Channel Infos')
        ]

        self.fs = self.srate = 1e6 / float(self.samplinginterval)
        self.nchan = int(self.numberofchannels)

        # important if not in same directory
        self.datafile = os.path.join(self.wd, self.datafile)

        self.read_data()

        # create TVB datatypes
        ch = SensorsEEG(storage_path=self.storage_path,
                        labels=self.labels,
                        number_of_sensors=len(self.labels))
        uid = vhdr + '-sensors'
        self._capture_operation_results([ch], uid=uid)

        ts = TimeSeriesEEG(sensors=ch, storage_path=self.storage_path)
        dat = self.data.T[:, numpy.newaxis, :, numpy.newaxis]
        ts.write_data_slice(dat)
        ts.length_1d, ts.length_2d, ts.length_3d, ts.length_4d = dat.shape
        ts.labels_ordering = 'Time 1 Channel 1'.split()
        ts.write_time_slice(numpy.r_[:dat.shape[0]] * 1.0 / self.fs)
        ts.start_time = 0.0
        ts.sample_period_unit = 's'
        ts.sample_period = 1.0 / float(self.fs)
        ts.close_file()

        return ts
    def launch(self, matfile):
        mat = loadmat(matfile)
        hdr = mat['hdr']
        fs, ns = [hdr[key][0, 0][0, 0] for key in ['Fs', 'nSamples']]

        # the entities to populate
        #ch = SensorsMEG(storage_path=self.storage_path)
        ts = TimeSeriesEEG(storage_path=self.storage_path)

        # (nchan x ntime) -> (t, sv, ch, mo)
        dat = mat['dat'].T[:, numpy.newaxis, :, numpy.newaxis]

        # write data
        ts.write_data_slice(dat)

        # fill in header info
        ts.length_1d, ts.length_2d, ts.length_3d, ts.length_4d = dat.shape
        ts.labels_ordering = 'Time 1 Channel 1'.split()
        ts.write_time_slice(numpy.r_[:ns] * 1.0 / fs)
        ts.start_time = 0.0
        ts.sample_period_unit = 's'
        ts.sample_period = 1.0 / float(fs)
        ts.close_file()

        return ts
    def launch(self, matfile, fdtfile):

        self.mat = loadmat(matfile)
        self.fs = self.mat['EEG']['srate'][0, 0][0, 0]
        self.nsamp = self.mat['EEG']['pnts'][0, 0][0, 0]
        self.data = numpy.fromfile(fdtfile, dtype=numpy.float32)
        self.data = self.data.reshape((self.nsamp, -1)).T
        self.nchan = self.data.shape[0]
        self.labels = [c[0] for c in self.mat['EEG']['chanlocs'][0, 0]['labels'][0]]

        ch = SensorsEEG(
            storage_path=self.storage_path,
            labels=self.labels,
            number_of_sensors=len(self.labels)
        )
        self._capture_operation_results([ch])

        ts = TimeSeriesEEG(
            sensors=ch,
            storage_path=self.storage_path
        )

        # (nchan x ntime) -> (t, sv, ch, mo)
        dat = self.data.T[:, numpy.newaxis, :, numpy.newaxis]

        # write data
        ts.write_data_slice(dat)

        # fill in header info
        ts.length_1d, ts.length_2d, ts.length_3d, ts.length_4d = dat.shape
        ts.labels_ordering = 'Time 1 Channel 1'.split()
        ts.write_time_slice(numpy.r_[:dat.shape[0]] * 1.0 / self.fs)
        ts.start_time = 0.0
        ts.sample_period_unit = 's'
        ts.sample_period = 1.0 / float(self.fs)
        ts.close_file()

        return ts
    def launch(self, vhdr, dat):

        self.filename = vhdr
        self.wd, _ = os.path.split(vhdr)

        # read file
        with open(vhdr, 'r') as fd:
            self.srclines = fd.readlines()

        # config parser expects each section to have header
        # but vhdr has some decorative information at the beginning
        while not self.srclines[0].startswith('['):
            self.srclines.pop(0)

        self.sio = StringIO()
        self.sio.write('\n'.join(self.srclines))
        self.sio.seek(0)

        self.cp = ConfigParser.ConfigParser()
        self.cp.readfp(self.sio)

        for opt in self.cp.options('Common Infos'):
            setattr(self, opt, self.cp.get('Common Infos', opt))

        self.binaryformat = self.cp.get('Binary Infos', 'BinaryFormat')

        self.labels = [self.cp.get('Channel Infos', o).split(',')[0]
                       for o in self.cp.options('Channel Infos')]

        self.fs = self.srate = 1e6 / float(self.samplinginterval)
        self.nchan = int(self.numberofchannels)

        # important if not in same directory
        self.datafile = os.path.join(self.wd, self.datafile)

        self.read_data()

        # create TVB datatypes
        ch = SensorsEEG(
            storage_path=self.storage_path,
            labels=self.labels,
            number_of_sensors=len(self.labels)
        )
        uid = vhdr + '-sensors'
        self._capture_operation_results([ch], uid=uid)

        ts = TimeSeriesEEG(
            sensors=ch,
            storage_path=self.storage_path
        )
        dat = self.data.T[:, numpy.newaxis, :, numpy.newaxis]
        ts.write_data_slice(dat)
        ts.length_1d, ts.length_2d, ts.length_3d, ts.length_4d = dat.shape
        ts.labels_ordering = 'Time 1 Channel 1'.split()
        ts.write_time_slice(numpy.r_[:dat.shape[0]] * 1.0 / self.fs)
        ts.start_time = 0.0
        ts.sample_period_unit = 's'
        ts.sample_period = 1.0 / float(self.fs)
        ts.close_file()

        return ts
Exemple #13
0
    def __init__(self, input=numpy.array([[], []]), **kwargs):
        if isinstance(input, (Timeseries, TimeSeries)):

            if isinstance(input, Timeseries):
                self._tvb = deepcopy(input._tvb)
                self.ts_type = str(input.ts_type)

            elif isinstance(input, TimeSeries):
                self._tvb = deepcopy(input)
                if isinstance(input, TimeSeriesRegion):
                    self.ts_type = "Region"
                if isinstance(input, TimeSeriesSEEG):
                    self.ts_type = "SEEG"
                elif isinstance(input, TimeSeriesEEG):
                    self.ts_type = "EEG"
                elif isinstance(input, TimeSeriesMEG):
                    self.ts_type = "MEG"
                elif isinstance(input, TimeSeriesEEG):
                    self.ts_type = "EEG"
                elif isinstance(input, TimeSeriesVolume):
                    self.ts_type = "Volume"
                elif isinstance(input, TimeSeriesSurface):
                    self.ts_type = "Surface"
                else:
                    self.ts_type = ""
                    warning(
                        "Input TimeSeries %s is not one of the known TVB TimeSeries classes!"
                        % str(input))
            for attr, value in kwargs.items():
                try:
                    setattr(self, attr, value)
                except:
                    setattr(self._tvb, attr, value)

        elif isinstance(input, numpy.ndarray):
            input = prepare_4D(input, self.logger)
            time = kwargs.pop("time", None)
            if time is not None:
                start_time = float(
                    kwargs.pop("start_time", kwargs.pop("start_time",
                                                        time[0])))
                sample_period = float(
                    kwargs.pop(
                        "sample_period",
                        kwargs.pop("sample_period",
                                   numpy.mean(numpy.diff(time)))))
                kwargs.update({
                    "start_time": start_time,
                    "sample_period": sample_period
                })

            # Initialize
            self.ts_type = kwargs.pop("ts_type", "Region")
            labels_ordering = kwargs.get("labels_ordering", None)

            # Get input sensors if any
            input_sensors = None
            if isinstance(kwargs.get("sensors", None), (TVBSensors, Sensors)):
                if isinstance(kwargs["sensors"], Sensors):
                    input_sensors = kwargs["sensors"]._tvb
                    self.ts_type = "%s sensor" % input_sensors.sensors_type
                    kwargs.update({"sensors": input_sensors})
                else:
                    input_sensors = kwargs["sensors"]

            # Create Timeseries
            if isinstance(input_sensors, TVBSensors) or \
                    self.ts_type in ["SEEG sensor", "Internal sensor", "EEG sensor", "MEG sensor"]:
                # ...for Sensor Timeseries
                if labels_ordering is None:
                    labels_ordering = LABELS_ORDERING
                    labels_ordering[2] = "%s sensor" % self.ts_type
                    kwargs.update({"labels_ordering": labels_ordering})
                if isinstance(input_sensors, TVBSensorsInternal) or isequal_string(self.ts_type, "Internal sensor")\
                        or isequal_string(self.ts_type, "SEEG sensor"):
                    self._tvb = TimeSeriesSEEG(data=input, **kwargs)
                    self.ts_type = "SEEG sensor"
                elif isinstance(input_sensors,
                                TVBSensorsEEG) or isequal_string(
                                    self.ts_type, "EEG sensor"):
                    self._tvb = TimeSeriesEEG(data=input, **kwargs)
                    self.ts_type = "EEG sensor"
                elif isinstance(input_sensors,
                                TVBSensorsMEG) or isequal_string(
                                    self.ts_type, "MEG sensor"):
                    self._tvb = TimeSeriesMEG(data=input, **kwargs)
                    self.ts_type = "MEG sensor"
                else:
                    raise_value_error(
                        "Not recognizing sensors of type %s:\n%s" %
                        (self.ts_type, str(input_sensors)))
            else:
                input_surface = kwargs.pop("surface", None)
                if isinstance(
                        input_surface,
                    (Surface, TVBSurface)) or self.ts_type == "Surface":
                    self.ts_type = "Surface"
                    if isinstance(input_surface, Surface):
                        kwargs.update({"surface": input_surface._tvb})
                    else:
                        kwargs.update({"surface": input_surface})
                    if labels_ordering is None:
                        labels_ordering = LABELS_ORDERING
                        labels_ordering[2] = "Vertex"
                        kwargs.update({"labels_ordering": labels_ordering})
                    self._tvb = TimeSeriesSurface(data=input, **kwargs)
                elif isequal_string(self.ts_type, "Region"):
                    if labels_ordering is None:
                        labels_ordering = LABELS_ORDERING
                        labels_ordering[2] = "Region"
                        kwargs.update({"labels_ordering": labels_ordering})
                    self._tvb = TimeSeriesRegion(data=input,
                                                 **kwargs)  # , **kwargs
                elif isequal_string(self.ts_type, "Volume"):
                    if labels_ordering is None:
                        labels_ordering = ["Time", "X", "Y", "Z"]
                        kwargs.update({"labels_ordering": labels_ordering})
                    self._tvb = TimeSeriesVolume(data=input, **kwargs)
                else:
                    self._tvb = TimeSeries(data=input, **kwargs)

            if not numpy.all([
                    dim_label in self._tvb.labels_dimensions.keys()
                    for dim_label in self._tvb.labels_ordering
            ]):
                warning(
                    "Lack of correspondance between timeseries labels_ordering %s\n"
                    "and labels_dimensions!: %s" %
                    (self._tvb.labels_ordering,
                     self._tvb.labels_dimensions.keys()))

        self._tvb.configure()
        self.configure_time()
        self.configure_sample_rate()
        if len(self.title) == 0:
            self._tvb.title = "%s Time Series" % self.ts_type