/usr/share/pyshared/neo/io/neomatlabio.py is in python-neo 0.3.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | # -*- coding: utf-8 -*-
"""
Module for reading/writing Neo objects in MATLAB format (.mat) versions 5 to 7.2.
This module is a bridge for MATLAB users who want to adopt the Neo object representation.
The nomenclature is the same but using Matlab structs and cell arrays.
With this module MATLAB users can use neo.io to read a format and convert it to .mat.
Supported : Read/Write
Author: sgarcia
"""
from datetime import datetime
from distutils import version
import re
import numpy as np
import quantities as pq
# check scipy
try:
import scipy.io
import scipy.version
except ImportError as err:
HAVE_SCIPY = False
SCIPY_ERR = err
else:
if version.LooseVersion(scipy.version.version) < '0.8':
HAVE_SCIPY = False
SCIPY_ERR = ImportError("your scipy version is too old to support " +
"MatlabIO, you need at least 0.8. " +
"You have %s" % scipy.version.version)
else:
HAVE_SCIPY = True
SCIPY_ERR = None
from neo.io.baseio import BaseIO
from neo.core import Block, Segment, AnalogSignal, EventArray, SpikeTrain
from neo.io.tools import create_many_to_one_relationship
from neo import description
classname_lower_to_upper = { }
for k in description.class_by_name.keys():
classname_lower_to_upper[k.lower()] = k
class NeoMatlabIO(BaseIO):
"""
Class for reading/writing Neo objects in MATLAB format (.mat) versions 5 to 7.2.
This module is a bridge for MATLAB users who want to adopt the Neo object representation.
The nomenclature is the same but using Matlab structs and cell arrays.
With this module MATLAB users can use neo.io to read a format and convert it to .mat.
Rules of conversion:
* Neo classes are converted to MATLAB structs.
e.g., a Block is a struct with attributes "name", "file_datetime", ...
* Neo one_to_many relationships are cellarrays in MATLAB.
e.g., ``seg.analogsignals[2]`` in Python Neo will be ``seg.analogsignals{3}`` in MATLAB.
* Quantity attributes are represented by 2 fields in MATLAB.
e.g., ``anasig.t_start = 1.5 * s`` in Python
will be ``anasig.t_start = 1.5`` and ``anasig.t_start_unit = 's'`` in MATLAB.
* classes that inherit from Quantity (AnalogSignal, SpikeTrain, ...) in Python will
have 2 fields (array and units) in the MATLAB struct.
e.g.: ``AnalogSignal( [1., 2., 3.], 'V')`` in Python will be
``anasig.array = [1. 2. 3]`` and ``anasig.units = 'V'`` in MATLAB.
1 - **Scenario 1: create data in MATLAB and read them in Python**
This MATLAB code generates a block::
block = struct();
block.segments = { };
block.name = 'my block with matlab';
for s = 1:3
seg = struct();
seg.name = strcat('segment ',num2str(s));
seg.analogsignals = { };
for a = 1:5
anasig = struct();
anasig.array = rand(100,1);
anasig.units = 'mV';
anasig.t_start = 0;
anasig.t_start_units = 's';
anasig.sampling_rate = 100;
anasig.sampling_rate_units = 'Hz';
seg.analogsignals{a} = anasig;
end
seg.spiketrains = { };
for t = 1:7
sptr = struct();
sptr.array = rand(30,1)*10;
sptr.units = 'ms';
sptr.t_start = 0;
sptr.t_start_units = 'ms';
sptr.t_stop = 10;
sptr.t_stop_units = 'ms';
seg.spiketrains{t} = sptr;
end
block.segments{s} = seg;
end
save 'myblock.mat' block -V7
This code reads it in Python::
import neo
r = neo.io.NeoMatlabIO(filename='myblock.mat')
bl = r.read_block()
print bl.segments[1].analogsignals[2]
print bl.segments[1].spiketrains[4]
2 - **Scenario 2: create data in Python and read them in MATLAB**
This Python code generates the same block as in the previous scenario::
import neo
import quantities as pq
from scipy import rand
bl = neo.Block(name='my block with neo')
for s in range(3):
seg = neo.Segment(name='segment' + str(s))
bl.segments.append(seg)
for a in range(5):
anasig = neo.AnalogSignal(rand(100), units='mV', t_start=0*pq.s, sampling_rate=100*pq.Hz)
seg.analogsignals.append(anasig)
for t in range(7):
sptr = neo.SpikeTrain(rand(30), units='ms', t_start=0*pq.ms, t_stop=10*pq.ms)
seg.spiketrains.append(sptr)
w = neo.io.NeoMatlabIO(filename='myblock.mat')
w.write_block(bl)
This MATLAB code reads it::
load 'myblock.mat'
block.name
block.segments{2}.analogsignals{3}.array
block.segments{2}.analogsignals{3}.units
block.segments{2}.analogsignals{3}.t_start
block.segments{2}.analogsignals{3}.t_start_units
3 - **Scenario 3: conversion**
This Python code converts a Spike2 file to MATLAB::
from neo import Block
from neo.io import Spike2IO, NeoMatlabIO
r = Spike2IO(filename='myspike2file.smr')
w = NeoMatlabIO(filename='convertedfile.mat')
seg = r.read_segment()
bl = Block(name='a block')
bl.segments.append(seg)
w.write_block(bl)
"""
is_readable = True
is_writable = True
supported_objects = [ Block, Segment , AnalogSignal , EventArray, SpikeTrain ]
readable_objects = [Block, ]
writeable_objects = [Block, ]
has_header = False
is_streameable = False
read_params = { Block : [ ] }
write_params = { Block : [ ] }
name = 'neomatlab'
extensions = [ 'mat' ]
mode = 'file'
def __init__(self , filename = None) :
"""
This class read/write neo objects in matlab 5 to 7.2 format.
Arguments:
filename : the filename to read
"""
if not HAVE_SCIPY:
raise SCIPY_ERR
BaseIO.__init__(self)
self.filename = filename
def read_block(self, cascade = True, lazy = False,):
"""
Arguments:
"""
d = scipy.io.loadmat(self.filename, struct_as_record=False,
squeeze_me=True)
assert'block' in d, 'no block in'+self.filename
bl_struct = d['block']
bl = self.create_ob_from_struct(bl_struct, 'Block', cascade = cascade, lazy = lazy)
create_many_to_one_relationship(bl)
return bl
def write_block(self, bl,):
"""
Arguments::
bl: the block to b saved
"""
bl_struct = self.create_struct_from_obj(bl)
for seg in bl.segments:
seg_struct = self.create_struct_from_obj(seg)
bl_struct['segments'].append(seg_struct)
for anasig in seg.analogsignals:
anasig_struct = self.create_struct_from_obj(anasig)
seg_struct['analogsignals'].append(anasig_struct)
for ea in seg.eventarrays:
ea_struct = self.create_struct_from_obj(ea)
seg_struct['eventarrays'].append(ea_struct)
for sptr in seg.spiketrains:
sptr_struct = self.create_struct_from_obj(sptr)
seg_struct['spiketrains'].append(sptr_struct)
scipy.io.savemat(self.filename, {'block':bl_struct}, oned_as = 'row')
def create_struct_from_obj(self, ob, ):
classname = ob.__class__.__name__
struct = { }
# relationship
rel = description.one_to_many_relationship
if classname in rel:
for childname in rel[classname]:
if description.class_by_name[childname] in self.supported_objects:
struct[childname.lower()+'s'] = [ ]
# attributes
necess = description.classes_necessary_attributes[classname]
recomm = description.classes_recommended_attributes[classname]
attributes = necess + recomm
for i, attr in enumerate(attributes):
attrname, attrtype = attr[0], attr[1]
#~ if attrname =='':
#~ struct['array'] = ob.magnitude
#~ struct['units'] = ob.dimensionality.string
#~ continue
if classname in description.classes_inheriting_quantities and \
description.classes_inheriting_quantities[classname] == attrname:
struct[attrname] = ob.magnitude
struct[attrname+'_units'] = ob.dimensionality.string
continue
if not(attrname in ob.annotations or hasattr(ob, attrname)): continue
if getattr(ob, attrname) is None : continue
if attrtype == pq.Quantity:
#ndim = attr[2]
struct[attrname] = getattr(ob,attrname).magnitude
struct[attrname+'_units'] = getattr(ob,attrname).dimensionality.string
elif attrtype ==datetime:
struct[attrname] = str(getattr(ob,attrname))
else:
struct[attrname] = getattr(ob,attrname)
return struct
def create_ob_from_struct(self, struct, classname, cascade = True, lazy = False,):
cl = description.class_by_name[classname]
# check if hinerits Quantity
#~ is_quantity = False
#~ for attr in description.classes_necessary_attributes[classname]:
#~ if attr[0] == '' and attr[1] == pq.Quantity:
#~ is_quantity = True
#~ break
#~ is_quantiy = classname in description.classes_inheriting_quantities
#~ if is_quantity:
if classname in description.classes_inheriting_quantities:
quantity_attr = description.classes_inheriting_quantities[classname]
arr = getattr(struct,quantity_attr)
#~ data_complement = dict(units=str(struct.units))
data_complement = dict(units=str(getattr(struct,quantity_attr+'_units')))
if "sampling_rate" in (at[0] for at in description.classes_necessary_attributes[classname]):
data_complement["sampling_rate"] = 0*pq.kHz # put fake value for now, put correct value later
if "t_stop" in (at[0] for at in description.classes_necessary_attributes[classname]):
if len(arr) > 0:
data_complement["t_stop"] =arr.max()
else:
data_complement["t_stop"] = 0.0
if "t_start" in (at[0] for at in description.classes_necessary_attributes[classname]):
if len(arr) > 0:
data_complement["t_start"] =arr.min()
else:
data_complement["t_start"] = 0.0
if lazy:
ob = cl([ ], **data_complement)
ob.lazy_shape = arr.shape
else:
ob = cl(arr, **data_complement)
else:
ob = cl()
for attrname in struct._fieldnames:
# check children
rel = description.one_to_many_relationship
if classname in rel and attrname[:-1] in [ r.lower() for r in rel[classname] ]:
try:
for c in range(len(getattr(struct,attrname))):
if cascade:
child = self.create_ob_from_struct(getattr(struct,attrname)[c] , classname_lower_to_upper[attrname[:-1]],
cascade = cascade, lazy = lazy)
getattr(ob, attrname.lower()).append(child)
except TypeError:
# strange behavior in scipy.io: if len is 1 so there is no len()
if cascade:
child = self.create_ob_from_struct(getattr(struct,attrname) , classname_lower_to_upper[attrname[:-1]],
cascade = cascade, lazy = lazy)
getattr(ob, attrname.lower()).append(child)
continue
# attributes
if attrname.endswith('_units') or attrname =='units' :#or attrname == 'array':
# linked with another field
continue
if classname in description.classes_inheriting_quantities and \
description.classes_inheriting_quantities[classname] == attrname:
continue
item = getattr(struct, attrname)
# put the good type
necess = description.classes_necessary_attributes[classname]
recomm = description.classes_recommended_attributes[classname]
attributes = necess + recomm
dict_attributes = dict( [ (a[0], a[1:]) for a in attributes])
if attrname in dict_attributes:
attrtype = dict_attributes[attrname][0]
if attrtype == datetime:
m = '(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+).(\d+)'
r = re.findall(m, str(item))
if len(r)==1:
item = datetime( *[ int(e) for e in r[0] ] )
else:
item = None
elif attrtype == np.ndarray:
dt = dict_attributes[attrname][2]
if lazy:
item = np.array([ ], dtype = dt)
ob.lazy_shape = item.shape
else:
item = item.astype( dt )
elif attrtype == pq.Quantity:
ndim = dict_attributes[attrname][1]
units = str(getattr(struct, attrname+'_units'))
if ndim == 0:
item = pq.Quantity(item, units)
else:
if lazy:
item = pq.Quantity([ ], units)
item.lazy_shape = item.shape
else:
item = pq.Quantity(item, units)
else:
item = attrtype(item)
setattr(ob, attrname, item)
return ob
|