/usr/share/pyshared/biom/sparsedict.py is in python-biom-format 1.1.2-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 | #!/usr/bin/env python
from numpy import array, ndarray
from operator import itemgetter
from biom.util import flatten
__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2012, BIOM-Format Project"
__credits__ = ["Daniel McDonald", "Jai Ram Rideout", "Greg Caporaso",
"Jose Clemente", "Justin Kuczynski"]
__license__ = "GPL"
__url__ = "http://biom-format.org"
__version__ = "1.1.2"
__maintainer__ = "Daniel McDonald"
__email__ = "daniel.mcdonald@colorado.edu"
class SparseDict(dict):
"""Support for sparse dicts
Must specify rows and columns in advance
Object cannot "grow" in shape
There is additional overhead on inserts in order to support rapid lookups
across rows or columns
"""
def __init__(self, rows, cols, dtype=float, enable_indices=True):
self.shape = (rows, cols)
self.dtype = dtype # casting is minimal, trust the programmer...
if enable_indices:
self._index_rows = [set() for i in range(rows)]
self._index_cols = [set() for i in range(cols)]
else:
self._index_rows = None
self._index_rows = None
self._indices_enabled = enable_indices
def copy(self):
"""Return a copy of self"""
new_self = self.__class__(self.shape[0], self.shape[1], self.dtype, \
self._indices_enabled)
new_self.update(self)
return new_self
def __setitem__(self,args,value):
"""Wrap setitem, complain if out of bounds"""
try:
row,col = args
except:
# fast support foo[5] = 10, like numpy 1d vectors
col = args
row = 0
args = (row,col) # passed onto update_internal_indices
in_self_rows, in_self_cols = self.shape
if row >= in_self_rows or row < 0:
raise KeyError, "The specified row is out of bounds"
if col >= in_self_cols or col < 0:
raise KeyError, "The specified col is out of bounds"
if value == 0:
if args in self:
self._update_internal_indices(args, value)
del self[args]
else:
return
else:
self._update_internal_indices(args, value)
super(SparseDict, self).__setitem__(args, value)
def __getitem__(self,args):
"""Wrap getitem to handle slices"""
try:
row,col = args
except TypeError:
raise IndexError, "Must specify (row, col)"
if isinstance(row, slice):
if row.start is None and row.stop is None:
return self.getCol(col)
else:
raise AttributeError, "Can only handle full : slices per axis"
elif isinstance(col, slice):
if col.start is None and col.stop is None:
return self.getRow(row)
else:
raise AttributeError, "Can only handle full : slices per axis"
else:
# boundary check
self_rows, self_cols = self.shape
if row >= self_rows or row < 0:
raise IndexError, "Row index out of range"
if col >= self_cols or col < 0:
raise IndexError, "Col index out of range"
# return dtype(0) if args don't exist
if args not in self:
return self.dtype(0)
return super(SparseDict, self).__getitem__(args)
def _update_internal_indices(self, args, value):
"""Update internal row,col indices"""
if not self._indices_enabled:
return
row,col = args
if value == 0:
if args in self:
self._index_rows[row].remove(args)
self._index_cols[col].remove(args)
else:
return # short circuit, no point in setting 0
else:
self._index_rows[row].add(args)
self._index_cols[col].add(args)
def getRow(self, row):
"""Returns a row: {((row,col):value}"""
in_self_rows, in_self_cols = self.shape
if row >= in_self_rows or row < 0:
raise IndexError, "The specified row is out of bounds"
new_row = SparseDict(1, in_self_cols, enable_indices=False)
d = {}
for r,c in self._index_rows[row]:
d[(0,c)] = super(SparseDict, self).__getitem__((r,c))
new_row.update(d)
return new_row
def getCol(self, col):
"""Return a col: {((row,col):value}"""
in_self_rows, in_self_cols = self.shape
if col >= in_self_cols or col < 0:
raise IndexError, "The specified col is out of bounds"
new_col = SparseDict(in_self_rows, 1, enable_indices=False)
d = {}
for r,c in self._index_cols[col]:
d[(r,0)] = super(SparseDict, self).__getitem__((r,c))
new_col.update(d)
return new_col
def transpose(self):
"""Transpose self"""
new_self = self.__class__(*self.shape[::-1], \
enable_indices=self._indices_enabled)
new_self.update(dict([((c,r),v) for (r,c),v in self.iteritems()]))
return new_self
T = property(transpose)
def _get_size(self):
"""Returns the number of nonzero elements stored"""
return len(self)
size = property(_get_size)
def update(self, update_dict):
"""Update self"""
in_self_rows, in_self_cols = self.shape
# handle zero values different and dont pass them to update
scrubbed = {}
for (row,col),value in update_dict.items():
if row >= in_self_rows or row < 0:
raise KeyError, "The specified row is out of bounds"
if col >= in_self_cols or col < 0:
raise KeyError, "The specified col is out of bounds"
if value == 0:
self.__setitem__((row,col), 0)
else:
scrubbed[(row,col)] = value
if self._indices_enabled:
self._update_internal_indices((row,col), value)
super(SparseDict, self).update(scrubbed)
def to_sparsedict(values, transpose=False, dtype=float):
"""Tries to returns a populated SparseDict object
NOTE: assumes the max value observed in row and col defines the size of the
matrix
"""
# if it is a vector
if isinstance(values, ndarray) and len(values.shape) == 1:
if transpose:
mat = nparray_to_sparsedict(values[:,newaxis], dtype)
else:
mat = nparray_to_sparsedict(values, dtype)
return mat
if isinstance(values, ndarray):
if transpose:
mat = nparray_to_sparsedict(values.T, dtype)
else:
mat = nparray_to_sparsedict(values, dtype)
return mat
# the empty list
elif isinstance(values, list) and len(values) == 0:
mat = SparseDict(0,0)
return mat
# list of np vectors
elif isinstance(values, list) and isinstance(values[0], ndarray):
mat = list_nparray_to_sparsedict(values, dtype)
if transpose:
mat = mat.T
return mat
# list of dicts, each representing a row in row order
elif isinstance(values, list) and isinstance(values[0], dict):
mat = list_dict_to_sparsedict(values, dtype)
if transpose:
mat = mat.T
return mat
elif isinstance(values, dict):
mat = dict_to_sparsedict(values, dtype)
if transpose:
mat = mat.T
return mat
else:
raise TableException, "Unknown input type"
def list_list_to_sparsedict(data, dtype=float, shape=None):
"""Convert a list of lists into a sparsedict
[[row, col, value], ...]
"""
d = dict([((r,c),dtype(v)) for r,c,v in data if v != 0])
if shape is None:
n_rows = 0
n_cols = 0
for (r,c) in d:
if r >= n_rows:
n_rows = r + 1 # deal with 0-based indexes
if c >= n_cols:
n_cols = c + 1
mat = SparseDict(n_rows, n_cols)
else:
mat = SparseDict(*shape)
mat.update(d)
return mat
def nparray_to_sparsedict(data, dtype=float):
"""Convert a numpy array to a dict"""
if len(data.shape) == 1:
mat = SparseDict(1, data.shape[0], dtype=dtype,enable_indices=False)
for idx,v in enumerate(data):
if v != 0:
mat[(0,idx)] = dtype(v)
else:
mat = SparseDict(*data.shape)
for row_idx, row in enumerate(data):
for col_idx, value in enumerate(row):
if value != 0:
mat[(row_idx, col_idx)] = dtype(value)
return mat
def list_nparray_to_sparsedict(data, dtype=float):
"""Takes a list of numpy arrays and creates a dict"""
mat = SparseDict(len(data), len(data[0]))
for row_idx, row in enumerate(data):
if len(row.shape) != 1:
raise TableException, "Cannot convert non-1d vectors!"
if len(row) != mat.shape[1]:
raise TableException, "Row vector isn't the correct length!"
for col_idx, val in enumerate(row):
mat[row_idx, col_idx] = dtype(val)
return mat
def list_dict_to_sparsedict(data, dtype=float):
"""Takes a list of dict {(0,col):val} and creates a full dict"""
if isinstance(data[0], SparseDict):
if data[0].shape[0] > data[0].shape[1]:
is_col = True
n_cols = len(data)
n_rows = data[0].shape[0]
else:
is_col = False
n_rows = len(data)
n_cols = data[0].shape[1]
else:
all_keys = flatten([d.keys() for d in data])
n_rows = max(all_keys, key=itemgetter(0))[0] + 1
n_cols = max(all_keys, key=itemgetter(1))[1] + 1
if n_rows > n_cols:
is_col = True
n_cols = len(data)
else:
is_col = False
n_rows = len(data)
mat = SparseDict(n_rows, n_cols)
for row_idx,row in enumerate(data):
for (foo,col_idx),val in row.items():
if is_col:
mat[foo,row_idx] = dtype(val)
else:
mat[row_idx,col_idx] = dtype(val)
return mat
def dict_to_sparsedict(data, dtype=float):
"""takes a dict {(row,col):val} and creates a SparseDict"""
n_rows = max(data.keys(), key=itemgetter(0))[0] + 1
n_cols = max(data.keys(), key=itemgetter(1))[1] + 1
mat = SparseDict(n_rows, n_cols)
mat.update(data)
return mat
|