| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
"""Point and Pointset enhanced array classes. |
| 5 |
|
| 6 |
(Objects of both classes are mutable.) |
| 7 |
|
| 8 |
Robert Clewley, February 2006 |
| 9 |
""" |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
from __future__ import division |
| 14 |
|
| 15 |
from auto import AUTOutil |
| 16 |
from copy import copy, deepcopy |
| 17 |
import sys |
| 18 |
|
| 19 |
numpyimported = False |
| 20 |
ndarray = AUTOutil.ArrayType |
| 21 |
def importnumpy(): |
| 22 |
global N, numpyimported, fromstring, ndarray, array, rank, take, less |
| 23 |
global float64, int32, array2string, shape, zeros, ravel, bool8 |
| 24 |
global _seq_types, _num_equivtype, linalg |
| 25 |
fromstring = None |
| 26 |
usingnumpy = True |
| 27 |
try: |
| 28 |
import matplotlib |
| 29 |
nn = matplotlib.__version__.split('.') |
| 30 |
if int(nn[0]) == 0 and int(nn[1]) < 99: |
| 31 |
|
| 32 |
import matplotlib.numerix |
| 33 |
if matplotlib.numerix.which[0] == 'numeric': |
| 34 |
usingnumpy = False |
| 35 |
except ImportError: |
| 36 |
pass |
| 37 |
|
| 38 |
if usingnumpy: |
| 39 |
try: |
| 40 |
import numpy as N |
| 41 |
from numpy import linalg |
| 42 |
fromstring, ndarray, float64, int32, bool8, floating, integer, rank = ( |
| 43 |
N.fromstring, N.ndarray, N.float64, N.int32, N.bool, |
| 44 |
N.floating, N.integer, N.ndim) |
| 45 |
global _float_types |
| 46 |
global _int_types |
| 47 |
_float_types = (type(1), N.floating) |
| 48 |
_int_types = (type(1), N.integer) |
| 49 |
except ImportError: |
| 50 |
usingnumpy = False |
| 51 |
if not usingnumpy: |
| 52 |
N = AUTOutil |
| 53 |
float64, int32, bool8 = 'd', 'i', 'B' |
| 54 |
ndarray, rank = N.ArrayType, N.rank |
| 55 |
array, take, array2string, shape, zeros, less, ravel = ( |
| 56 |
N.array, N.take, N.array2string, N.shape, N.zeros, N.less, |
| 57 |
N.ravel) |
| 58 |
_seq_types = (list, tuple, ndarray) |
| 59 |
_num_equivtype = {type(1.0): float64, type(1): int32, |
| 60 |
float64: float64, int32: int32, |
| 61 |
float: float64, int: int32} |
| 62 |
numpyimported = True |
| 63 |
|
| 64 |
if fromstring is None: |
| 65 |
class linalg(object): |
| 66 |
def norm(v, normord): |
| 67 |
n = 0.0 |
| 68 |
for x in v: |
| 69 |
n += x ** normord |
| 70 |
return n ** (1.0/normord) |
| 71 |
norm=staticmethod(norm) |
| 72 |
|
| 73 |
_float_types = type(1.0) |
| 74 |
_int_types = type(1) |
| 75 |
|
| 76 |
class symbolMapClass(object): |
| 77 |
"""Abstract class for hassle-free symbol re-mappings.""" |
| 78 |
def __init__(self, symbolMap=None): |
| 79 |
if isinstance(symbolMap, symbolMapClass): |
| 80 |
self.lookupDict = copy(symbolMap.lookupDict) |
| 81 |
elif symbolMap is None: |
| 82 |
self.lookupDict = {} |
| 83 |
else: |
| 84 |
self.lookupDict = copy(symbolMap) |
| 85 |
|
| 86 |
def __call__(self, arg): |
| 87 |
if isinstance(arg, str): |
| 88 |
return self.__getitem__(arg) |
| 89 |
elif hasattr(arg, 'coordnames'): |
| 90 |
|
| 91 |
|
| 92 |
res = copy(arg) |
| 93 |
try: |
| 94 |
res.mapNames(self) |
| 95 |
except AttributeError: |
| 96 |
raise TypeError("symbolMapClass does not know how to " |
| 97 |
"process this type of argument") |
| 98 |
return res |
| 99 |
elif hasattr(arg, 'iteritems'): |
| 100 |
|
| 101 |
res = copy(arg) |
| 102 |
try: |
| 103 |
for k, symbol in arg.iteritems(): |
| 104 |
res[self.__getitem__(k)] = self.__getitem__(symbol) |
| 105 |
|
| 106 |
del res[k] |
| 107 |
except: |
| 108 |
raise TypeError("symbolMapClass does not know how to " |
| 109 |
"process this type of argument") |
| 110 |
return res |
| 111 |
else: |
| 112 |
|
| 113 |
|
| 114 |
try: |
| 115 |
res = copy(arg) |
| 116 |
except TypeError: |
| 117 |
|
| 118 |
res = arg |
| 119 |
try: |
| 120 |
for i, v in enumerate(arg): |
| 121 |
|
| 122 |
res[i] = self.__getitem__(v) |
| 123 |
except: |
| 124 |
try: |
| 125 |
return self.__getitem__(res) |
| 126 |
except: |
| 127 |
raise TypeError("symbolMapClass does not know how to " |
| 128 |
"process this type of argument (%s)"%str(type(arg))) |
| 129 |
else: |
| 130 |
return res |
| 131 |
|
| 132 |
def __eq__(self, other): |
| 133 |
try: |
| 134 |
return self.lookupDict == other.lookupDict |
| 135 |
except AttributeError: |
| 136 |
return False |
| 137 |
|
| 138 |
def __ne__(self, other): |
| 139 |
return not self.__eq__(other) |
| 140 |
|
| 141 |
def __setitem__(self, symbol, mappedsymbol): |
| 142 |
self.lookupDict[symbol] = mappedsymbol |
| 143 |
|
| 144 |
def __getitem__(self, symbol): |
| 145 |
try: |
| 146 |
return self.lookupDict[symbol] |
| 147 |
except (KeyError, TypeError): |
| 148 |
return symbol |
| 149 |
|
| 150 |
def __contains__(self, symbol): |
| 151 |
return self.lookupDict.__contains__(symbol) |
| 152 |
|
| 153 |
def keys(self): |
| 154 |
return self.lookupDict.keys() |
| 155 |
|
| 156 |
def values(self): |
| 157 |
return self.lookupDict.values() |
| 158 |
|
| 159 |
def items(self): |
| 160 |
return self.lookupDict.items() |
| 161 |
|
| 162 |
def iterkeys(self): |
| 163 |
return self.lookupDict.iterkeys() |
| 164 |
|
| 165 |
def itervalues(self): |
| 166 |
return self.lookupDict.itervalues() |
| 167 |
|
| 168 |
def iteritems(self): |
| 169 |
return self.lookupDict.iteritems() |
| 170 |
|
| 171 |
def update(self, amap): |
| 172 |
try: |
| 173 |
|
| 174 |
self.lookupDict.update(amap.lookupDict) |
| 175 |
except AttributeError: |
| 176 |
|
| 177 |
self.lookupDict.update(amap) |
| 178 |
|
| 179 |
def __len__(self): |
| 180 |
return len(self.lookupDict) |
| 181 |
|
| 182 |
def copy(self): |
| 183 |
return symbolMapClass(self) |
| 184 |
|
| 185 |
def __repr__(self): |
| 186 |
return "Symbol mapping" |
| 187 |
|
| 188 |
__str__ = __repr__ |
| 189 |
|
| 190 |
def has_key(self, k): |
| 191 |
return k in self.lookupDict |
| 192 |
|
| 193 |
|
| 194 |
class auxfnDBclass(object): |
| 195 |
"""Auxiliary function database, for use by parsers.""" |
| 196 |
def __init__(self): |
| 197 |
self.auxnames = {} |
| 198 |
|
| 199 |
def addAuxFn(self, auxfnName, parserObj): |
| 200 |
if parserObj not in self.auxnames: |
| 201 |
self.auxnames[parserObj] = auxfnName |
| 202 |
else: |
| 203 |
raise ValueError("Parser object " + parserObj.name + " already " |
| 204 |
"exists in auxiliary function database") |
| 205 |
|
| 206 |
def __repr__(self): |
| 207 |
return "ModelSpec internal helper class: auxfnDBclass object" |
| 208 |
|
| 209 |
__str__ = __repr__ |
| 210 |
|
| 211 |
def __call__(self, parserObj=None): |
| 212 |
if parserObj is None: |
| 213 |
|
| 214 |
return self.auxnames.values() |
| 215 |
else: |
| 216 |
try: |
| 217 |
return [self.auxnames[parserObj]] |
| 218 |
except KeyError: |
| 219 |
return [] |
| 220 |
|
| 221 |
def removeAuxFn(self, auxfnName): |
| 222 |
flagdelete = None |
| 223 |
for k, v in self.auxnames.items(): |
| 224 |
if v == auxfnName: |
| 225 |
flagdelete = k |
| 226 |
break |
| 227 |
if flagdelete is not None: |
| 228 |
del self.auxnames[k] |
| 229 |
|
| 230 |
def clear(self, parserObj): |
| 231 |
if parserObj in self.auxnames: |
| 232 |
del self.auxnames[parserObj] |
| 233 |
|
| 234 |
|
| 235 |
def clearall(self): |
| 236 |
self.auxnames = {} |
| 237 |
|
| 238 |
class DefaultDict(dict): |
| 239 |
"""Dictionary with a default value for unknown keys. |
| 240 |
|
| 241 |
Written by Peter Norvig.""" |
| 242 |
def __init__(self, default): |
| 243 |
self.default = default |
| 244 |
|
| 245 |
def __getitem__(self, key): |
| 246 |
if key in self: return self.get(key) |
| 247 |
return self.setdefault(key, deepcopy(self.default)) |
| 248 |
|
| 249 |
|
| 250 |
def isUniqueSeq(objlist): |
| 251 |
"""Check that list contains items only once""" |
| 252 |
for obj in objlist: |
| 253 |
if objlist.count(obj) != 1: |
| 254 |
return False |
| 255 |
return True |
| 256 |
|
| 257 |
|
| 258 |
def makeArrayIxMap(a): |
| 259 |
return dict(zip(a, range(len(a)))) |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
def invertMap(themap): |
| 264 |
"""invert an index mapping or other form of mapping. |
| 265 |
|
| 266 |
invertMap() returns a dictionary, regardless of whether the |
| 267 |
argument is a dictionary or a list.""" |
| 268 |
if isinstance(themap, dict): |
| 269 |
return dict([(v,k) for (k,v) in themap.items()]) |
| 270 |
elif isinstance(themap, (list, tuple)): |
| 271 |
|
| 272 |
return dict(zip(themap, range(len(themap)))) |
| 273 |
elif isinstance(themap, ndarray): |
| 274 |
|
| 275 |
return dict(zip(themap.tolist(), range(len(themap)))) |
| 276 |
else: |
| 277 |
raise TypeError("Unsupported type for map") |
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
def isincreasing(theseq, withVal=False): |
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
try: |
| 287 |
v_old = theseq[0] |
| 288 |
except IndexError: |
| 289 |
raise ValueError("Problem with sequence passed to " |
| 290 |
"function `isincreasing` -- is it empty?") |
| 291 |
v = array(theseq) |
| 292 |
res = v[1:] > v[:-1] |
| 293 |
if withVal: |
| 294 |
if all(res): |
| 295 |
return True, None, None |
| 296 |
else: |
| 297 |
pos = res.tolist().index(False) |
| 298 |
return False, theseq[pos], theseq[pos+1] |
| 299 |
else: |
| 300 |
return all(res) |
| 301 |
|
| 302 |
|
| 303 |
def sortedDictKeys(d, onlykeys=[], reverse=False): |
| 304 |
"""Return sorted list of keys from a dictionary. |
| 305 |
|
| 306 |
Adapted from original function by Alex Martelli: |
| 307 |
added filtering of keys.""" |
| 308 |
if onlykeys != []: |
| 309 |
keys = intersect(d.keys(), onlykeys) |
| 310 |
else: |
| 311 |
keys = list(d) |
| 312 |
keys.sort() |
| 313 |
if reverse: |
| 314 |
keys.reverse() |
| 315 |
return keys |
| 316 |
|
| 317 |
|
| 318 |
def compareNumTypes(t1, t2): |
| 319 |
_num_type2name = {float64: 'float', int32: 'int', |
| 320 |
type(1.0): 'float', type(1): 'int'} |
| 321 |
try: |
| 322 |
for t in t2: |
| 323 |
if _num_type2name[t1] == _num_type2name[t]: |
| 324 |
return True |
| 325 |
return False |
| 326 |
except TypeError: |
| 327 |
|
| 328 |
try: |
| 329 |
return _num_type2name[t1] == _num_type2name[t2] |
| 330 |
except KeyError: |
| 331 |
return False |
| 332 |
except KeyError: |
| 333 |
return False |
| 334 |
|
| 335 |
|
| 336 |
def intersect(a, b): |
| 337 |
return list(filter(lambda e,b=b : e in b, a)) |
| 338 |
|
| 339 |
def remain(a, b): |
| 340 |
"""Find remainder of two lists, sequences, etc., after intersection. |
| 341 |
Includes repetitions if they occur in the input lists.""" |
| 342 |
return list(filter(lambda e,b=b : e not in b, a)) |
| 343 |
|
| 344 |
__all__ = ['Point', 'Pointset', 'isparameterized', 'pointsToPointset', |
| 345 |
'PointInfo', 'makeNonParameterized', 'arrayToPointset', |
| 346 |
'VarCaller', 'comparePointCoords'] |
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
class VarCaller(object): |
| 352 |
"""Wrapper for Variable type to call Pointset and return array type.""" |
| 353 |
|
| 354 |
def __init__(self, pts): |
| 355 |
if isinstance(pts, (Point, Pointset)): |
| 356 |
self.pts = pts |
| 357 |
else: |
| 358 |
raise TypeError("Invalid type for pts argument") |
| 359 |
|
| 360 |
def __call__(self, x): |
| 361 |
return self.pts(x).toarray() |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
point_keys = ['coorddict', 'coordarray', 'coordtype', 'norm', 'labels'] |
| 369 |
|
| 370 |
|
| 371 |
class Point(object): |
| 372 |
"""N-dimensional point class.""" |
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
def __init__(self, kwd=None, **kw): |
| 378 |
if not numpyimported: |
| 379 |
importnumpy() |
| 380 |
if kwd is not None: |
| 381 |
if kw != {}: |
| 382 |
raise ValueError("Cannot mix keyword dictionary and keywords") |
| 383 |
kw = kwd |
| 384 |
self._parameterized = False |
| 385 |
self.labels = {} |
| 386 |
if intersect(kw.keys(), point_keys) == []: |
| 387 |
|
| 388 |
temp_kw = {} |
| 389 |
temp_kw['coorddict'] = copy(kw) |
| 390 |
kw = copy(temp_kw) |
| 391 |
if 'coorddict' in kw: |
| 392 |
coorddict = {} |
| 393 |
try: |
| 394 |
ct = kw['coordtype'] |
| 395 |
except KeyError: |
| 396 |
self.coordtype = float64 |
| 397 |
else: |
| 398 |
try: |
| 399 |
self.coordtype = _num_equivtype[ct] |
| 400 |
except KeyError: |
| 401 |
raise TypeError('Coordinate type %s not valid for Point'%str(ct)) |
| 402 |
for c, v in kw['coorddict'].items(): |
| 403 |
if not isinstance(c, str): |
| 404 |
c_key = repr(c) |
| 405 |
else: |
| 406 |
c_key = c |
| 407 |
if isinstance(v, list): |
| 408 |
coorddict[c_key] = array(v, self.coordtype) |
| 409 |
elif isinstance(v, ndarray): |
| 410 |
if len(v) == 1: |
| 411 |
coorddict[c_key] = v[0] |
| 412 |
else: |
| 413 |
coorddict[c_key] = array(v) |
| 414 |
assert compareNumTypes(self.coordtype, type(coorddict[c_key][0])), \ |
| 415 |
'type mismatch' |
| 416 |
elif isinstance(v, _float_types): |
| 417 |
assert compareNumTypes(self.coordtype, float64), \ |
| 418 |
'type mismatch' |
| 419 |
coorddict[c_key] = array([v], self.coordtype) |
| 420 |
elif isinstance(v, _int_types): |
| 421 |
assert compareNumTypes(self.coordtype, (int32, float64)), \ |
| 422 |
'type mismatch' |
| 423 |
coorddict[c_key] = array([v], self.coordtype) |
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
else: |
| 428 |
raise TypeError("Must pass numeric type or sequence of " |
| 429 |
"numeric types") |
| 430 |
self.coordnames = list(coorddict) |
| 431 |
|
| 432 |
self.coordnames.sort() |
| 433 |
self.dimension = len(self.coordnames) |
| 434 |
datalist = [] |
| 435 |
for c in self.coordnames: |
| 436 |
assert not isinstance(coorddict[c], (list, tuple)), 'type mismatch' |
| 437 |
datalist.append(coorddict[c][0]) |
| 438 |
self.coordarray = array(datalist, self.coordtype) |
| 439 |
r = rank(self.coordarray) |
| 440 |
if r == 1: |
| 441 |
pass |
| 442 |
elif r == 0: |
| 443 |
self.coordarray = ravel(self.coordarray) |
| 444 |
else: |
| 445 |
raise ValueError("Invalid rank for coordinate array: %i"%r) |
| 446 |
assert self.dimension == self.coordarray.shape[0], "Invalid coord array" |
| 447 |
elif 'coordarray' in kw: |
| 448 |
|
| 449 |
|
| 450 |
if isinstance(kw['coordarray'], ndarray): |
| 451 |
|
| 452 |
|
| 453 |
array_temp = array(kw['coordarray']) |
| 454 |
try: |
| 455 |
if len(array_temp) == 0: |
| 456 |
self.coordtype = _num_equivtype[type(1.0)] |
| 457 |
else: |
| 458 |
self.coordtype = _num_equivtype[type(array_temp[0])] |
| 459 |
except KeyError: |
| 460 |
raise TypeError('Coordinate type %s not valid for Point'%str(ct)) |
| 461 |
elif isinstance(kw['coordarray'], list): |
| 462 |
try: |
| 463 |
self.coordtype = _num_equivtype[kw['coordtype']] |
| 464 |
except KeyError: |
| 465 |
raise TypeError('Coordinate type %s not valid for Point'%str(ct)) |
| 466 |
array_temp = array(kw['coordarray'], self.coordtype) |
| 467 |
else: |
| 468 |
raise TypeError('Coordinate type %s not valid for Point'%str(type(kw['coordarray']))) |
| 469 |
r = rank(array_temp) |
| 470 |
if r == 1: |
| 471 |
self.coordarray = array_temp |
| 472 |
elif r == 0: |
| 473 |
self.coordarray = ravel(array_temp) |
| 474 |
else: |
| 475 |
raise ValueError("Invalid rank for coordinate array: %i"%r) |
| 476 |
self.dimension = self.coordarray.shape[0] |
| 477 |
if 'coordnames' in kw: |
| 478 |
if isinstance(kw['coordnames'], str): |
| 479 |
coordnames = [kw['coordnames']] |
| 480 |
else: |
| 481 |
coordnames = kw['coordnames'] |
| 482 |
else: |
| 483 |
coordnames = [str(cix) for cix in range(self.dimension)] |
| 484 |
if len(coordnames) != self.dimension: |
| 485 |
print("Point initialization error:") |
| 486 |
print("Found coord names: %s (dimension = %s)"% |
| 487 |
(coordnames, len(coordnames))) |
| 488 |
print("vs. data dimension = %s"%self.dimension) |
| 489 |
raise ValueError("Mismatch between number of coordnames and " |
| 490 |
"dimension of data") |
| 491 |
self.coordnames = kw['coordnames'] |
| 492 |
else: |
| 493 |
raise ValueError("Missing coord info in keywords") |
| 494 |
assert isUniqueSeq(self.coordnames), 'Coordinate names must be unique' |
| 495 |
self.makeIxMaps() |
| 496 |
if 'norm' in kw: |
| 497 |
if kw['norm'] == 0: |
| 498 |
raise ValueError("Norm order for point cannot be zero") |
| 499 |
self._normord = kw['norm'] |
| 500 |
else: |
| 501 |
self._normord = 2 |
| 502 |
|
| 503 |
if 'labels' in kw: |
| 504 |
self.addlabel(kw['labels']) |
| 505 |
|
| 506 |
|
| 507 |
def addlabel(self, label): |
| 508 |
if label is None: |
| 509 |
pass |
| 510 |
elif isinstance(label, str): |
| 511 |
self.labels = {label: {}} |
| 512 |
elif isinstance(label, tuple) and len(label)==2: |
| 513 |
if isinstance(label[0], str) and isinstance(label[1], dict): |
| 514 |
self.labels[label[0]] = label[1] |
| 515 |
elif isinstance(label, dict): |
| 516 |
self.labels = label |
| 517 |
else: |
| 518 |
raise TypeError("Point label must be a string, a pair, or a dict") |
| 519 |
|
| 520 |
|
| 521 |
def removelabel(self): |
| 522 |
self.labels = {} |
| 523 |
|
| 524 |
|
| 525 |
def makeIxMaps(self): |
| 526 |
self._name_ix_map = dict(zip(self.coordnames, range(self.dimension))) |
| 527 |
self._ix_name_map = copy(self.coordnames) |
| 528 |
|
| 529 |
|
| 530 |
def todict(self, aslist=False): |
| 531 |
"""Convert Point to a dictionary of array values (or of list with aslist=True).""" |
| 532 |
if aslist: |
| 533 |
return dict(zip(self._ix_name_map, self.coordarray.tolist())) |
| 534 |
else: |
| 535 |
return dict(zip(self._ix_name_map, self.coordarray)) |
| 536 |
|
| 537 |
def __contains__(self, coord): |
| 538 |
return coord in self.coordnames |
| 539 |
|
| 540 |
def __delitem__(self, k): |
| 541 |
raise NotImplementedError |
| 542 |
|
| 543 |
def get(self, coord, d=None): |
| 544 |
if coord in self.coordnames: |
| 545 |
return self.__call__(coord) |
| 546 |
else: |
| 547 |
return d |
| 548 |
|
| 549 |
def update(self, d): |
| 550 |
for k, v in d.items(): |
| 551 |
self.coordarray[self._map_names_to_ixs(k)] = v |
| 552 |
|
| 553 |
def items(self): |
| 554 |
return zip(self._ix_name_map, self.coordarray) |
| 555 |
|
| 556 |
def iteritems(self): |
| 557 |
return iter(zip(self._ix_name_map, self.coordarray)) |
| 558 |
|
| 559 |
def values(self): |
| 560 |
return self.coordarray.tolist() |
| 561 |
|
| 562 |
def itervalues(self): |
| 563 |
return iter(self.coordarray.tolist()) |
| 564 |
|
| 565 |
def keys(self): |
| 566 |
return self._ix_name_map |
| 567 |
|
| 568 |
def iterkeys(self): |
| 569 |
return iter(self._ix_name_map) |
| 570 |
|
| 571 |
def has_key(self, k): |
| 572 |
return k in self.coordnames |
| 573 |
|
| 574 |
|
| 575 |
def _map_names_to_ixs(self, namelist): |
| 576 |
try: |
| 577 |
try: |
| 578 |
|
| 579 |
return self._name_ix_map[namelist] |
| 580 |
except TypeError: |
| 581 |
|
| 582 |
return [self._name_ix_map[n] for n in namelist] |
| 583 |
except KeyError: |
| 584 |
e = sys.exc_info()[1] |
| 585 |
import AUTOExceptions |
| 586 |
raise AUTOExceptions.AUTORuntimeError("Name not found: "+str(e)) |
| 587 |
|
| 588 |
|
| 589 |
def __len__(self): |
| 590 |
return self.dimension |
| 591 |
|
| 592 |
|
| 593 |
def _force_coords_to_ixlist(self, x): |
| 594 |
if x is None: |
| 595 |
return range(self.dimension) |
| 596 |
elif x in range(self.dimension): |
| 597 |
|
| 598 |
return [x] |
| 599 |
elif x in self.coordnames: |
| 600 |
|
| 601 |
return [self._name_ix_map[x]] |
| 602 |
elif isinstance(x, _seq_types): |
| 603 |
if len(x) == 0: |
| 604 |
return range(self.dimension) |
| 605 |
else: |
| 606 |
return [self._force_coords_to_ixlist(el)[0] for el in x] |
| 607 |
elif isinstance(x, slice): |
| 608 |
s1, s2, s3 = x.indices(self.dimension) |
| 609 |
if ((s3 > 0 and s1 >= self.dimension) or |
| 610 |
(s3 < 0 and s2 >= self.dimension)): |
| 611 |
raise ValueError("Slice index out of range") |
| 612 |
return range(s1, s2, s3) |
| 613 |
elif isinstance(x,int): |
| 614 |
raise IndexError("Invalid index: %d"%x + \ |
| 615 |
" -- coord names are: %s"%str(self.coordnames)) |
| 616 |
else: |
| 617 |
raise ValueError("Invalid coordinate / index: %s"%str(x) + \ |
| 618 |
" -- coord names are: %s"%str(self.coordnames)) |
| 619 |
|
| 620 |
|
| 621 |
def __call__(self, coords): |
| 622 |
if coords in range(self.dimension+1): |
| 623 |
if coords == self.dimension: |
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
raise StopIteration |
| 628 |
else: |
| 629 |
return self.coordarray[coords] |
| 630 |
elif coords in self.coordnames: |
| 631 |
ix = self._name_ix_map[coords] |
| 632 |
return self.coordarray[ix] |
| 633 |
else: |
| 634 |
ixlist = self._force_coords_to_ixlist(coords) |
| 635 |
return Point({'coordarray': take(self.coordarray,ixlist), |
| 636 |
'coordnames': [self.coordnames[i] for i in ixlist], |
| 637 |
'coordtype': self.coordtype, |
| 638 |
'norm': self._normord, |
| 639 |
'labels': self.labels}) |
| 640 |
|
| 641 |
__getitem__ = __call__ |
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
|
| 647 |
def __setitem__(self, ixarg, val): |
| 648 |
"""Change coordinate array values.""" |
| 649 |
ixs = self._force_coords_to_ixlist(ixarg) |
| 650 |
if len(ixs) == 1: |
| 651 |
val = [val] |
| 652 |
try: |
| 653 |
for i, v in zip(ixs,val): |
| 654 |
self.coordarray[i] = v |
| 655 |
except TypeError: |
| 656 |
raise TypeError("Bad value type for Point") |
| 657 |
|
| 658 |
|
| 659 |
def toarray(self): |
| 660 |
if self.dimension == 1: |
| 661 |
return self.coordarray[0] |
| 662 |
else: |
| 663 |
return self.coordarray |
| 664 |
|
| 665 |
|
| 666 |
def __add__(self, other): |
| 667 |
res = self.copy() |
| 668 |
try: |
| 669 |
res.coordarray += other.coordarray |
| 670 |
except AttributeError: |
| 671 |
res.coordarray += other |
| 672 |
return res |
| 673 |
|
| 674 |
__radd__ = __add__ |
| 675 |
|
| 676 |
def __sub__(self, other): |
| 677 |
res = self.copy() |
| 678 |
try: |
| 679 |
res.coordarray -= other.coordarray |
| 680 |
except AttributeError: |
| 681 |
res.coordarray -= other |
| 682 |
return res |
| 683 |
|
| 684 |
def __rsub__(self, other): |
| 685 |
res = self.copy() |
| 686 |
try: |
| 687 |
res.coordarray = other.coordarray - res.coordarray |
| 688 |
except AttributeError: |
| 689 |
res.coordarray = other - res.coordarray |
| 690 |
return res |
| 691 |
|
| 692 |
def __mul__(self, other): |
| 693 |
res = self.copy() |
| 694 |
try: |
| 695 |
res.coordarray *= other.coordarray |
| 696 |
except AttributeError: |
| 697 |
res.coordarray *= other |
| 698 |
return res |
| 699 |
|
| 700 |
__rmul__ = __mul__ |
| 701 |
|
| 702 |
def __div__(self, other): |
| 703 |
res = self.copy() |
| 704 |
try: |
| 705 |
res.coordarray /= other.coordarray |
| 706 |
except AttributeError: |
| 707 |
res.coordarray /= other |
| 708 |
return res |
| 709 |
|
| 710 |
__truediv__ = __div__ |
| 711 |
|
| 712 |
def __rdiv__(self, other): |
| 713 |
res = self.copy() |
| 714 |
try: |
| 715 |
res.coordarray = other.coordarray / res.coordarray |
| 716 |
except AttributeError: |
| 717 |
res.coordarray = other / res.coordarray |
| 718 |
return res |
| 719 |
|
| 720 |
__rtruediv__ = __rdiv__ |
| 721 |
|
| 722 |
def __pow__(self, other): |
| 723 |
res = self.copy() |
| 724 |
res.coordarray **= other |
| 725 |
return res |
| 726 |
|
| 727 |
def __neg__(self): |
| 728 |
res = self.copy() |
| 729 |
res.coordarray = - res.coordarray |
| 730 |
return res |
| 731 |
|
| 732 |
def __pos__(self): |
| 733 |
return self.copy() |
| 734 |
|
| 735 |
def __lt__(self, other): |
| 736 |
try: |
| 737 |
assert shape(self) == shape(other) |
| 738 |
if hasattr(other, 'coordnames'): |
| 739 |
if self.coordnames != other.coordnames: |
| 740 |
raise ValueError("Coordinate mismatch") |
| 741 |
return linalg.norm(self.coordarray, self._normord) < \ |
| 742 |
linalg.norm(other.coordarray, self._normord) |
| 743 |
except (AttributeError, TypeError, AssertionError): |
| 744 |
return self.coordarray < other |
| 745 |
except ZeroDivisionError: |
| 746 |
raise ValueError("Norm order for point cannot be zero") |
| 747 |
|
| 748 |
def __gt__(self, other): |
| 749 |
try: |
| 750 |
assert shape(self) == shape(other) |
| 751 |
if hasattr(other, 'coordnames'): |
| 752 |
if self.coordnames != other.coordnames: |
| 753 |
raise ValueError("Coordinate mismatch") |
| 754 |
return linalg.norm(self.coordarray, self._normord) > \ |
| 755 |
linalg.norm(other.coordarray, self._normord) |
| 756 |
except (AttributeError, TypeError, AssertionError): |
| 757 |
return self.coordarray > other |
| 758 |
except ZeroDivisionError: |
| 759 |
raise ValueError("Norm order for point cannot be zero") |
| 760 |
|
| 761 |
def __le__(self, other): |
| 762 |
try: |
| 763 |
assert shape(self) == shape(other) |
| 764 |
if hasattr(other, 'coordnames'): |
| 765 |
if self.coordnames != other.coordnames: |
| 766 |
raise ValueError("Coordinate mismatch") |
| 767 |
return linalg.norm(self.coordarray, self._normord) <= \ |
| 768 |
linalg.norm(other.coordarray, self._normord) |
| 769 |
except (AttributeError, TypeError, AssertionError): |
| 770 |
return self.coordarray <= other |
| 771 |
except ZeroDivisionError: |
| 772 |
raise ValueError("Norm order for point cannot be zero") |
| 773 |
|
| 774 |
def __ge__(self, other): |
| 775 |
try: |
| 776 |
assert shape(self) == shape(other) |
| 777 |
if hasattr(other, 'coordnames'): |
| 778 |
if self.coordnames != other.coordnames: |
| 779 |
raise ValueError("Coordinate mismatch") |
| 780 |
return linalg.norm(self.coordarray, self._normord) >= \ |
| 781 |
linalg.norm(other.coordarray, self._normord) |
| 782 |
except (AttributeError, TypeError, AssertionError): |
| 783 |
return self.coordarray >= other |
| 784 |
except ZeroDivisionError: |
| 785 |
raise ValueError("Norm order for point cannot be zero") |
| 786 |
|
| 787 |
def __eq__(self, other): |
| 788 |
try: |
| 789 |
assert shape(self) == shape(other) |
| 790 |
if hasattr(other, 'coordnames'): |
| 791 |
if self.coordnames != other.coordnames: |
| 792 |
raise ValueError("Coordinate mismatch") |
| 793 |
return linalg.norm(self.coordarray, self._normord) == \ |
| 794 |
linalg.norm(other.coordarray, self._normord) |
| 795 |
except (AttributeError, TypeError, AssertionError): |
| 796 |
return self.coordarray == other |
| 797 |
except ZeroDivisionError: |
| 798 |
raise ValueError("Norm order for point cannot be zero") |
| 799 |
|
| 800 |
def __ne__(self, other): |
| 801 |
try: |
| 802 |
assert shape(self) == shape(other) |
| 803 |
if hasattr(other, 'coordnames'): |
| 804 |
if self.coordnames != other.coordnames: |
| 805 |
raise ValueError("Coordinate mismatch") |
| 806 |
return linalg.norm(self.coordarray, self._normord) != \ |
| 807 |
linalg.norm(other.coordarray, self._normord) |
| 808 |
except (AttributeError, TypeError, AssertionError): |
| 809 |
return self.coordarray != other |
| 810 |
except ZeroDivisionError: |
| 811 |
raise ValueError("Norm order for point cannot be zero") |
| 812 |
|
| 813 |
|
| 814 |
def _infostr(self, verbose=0): |
| 815 |
precision = 8 |
| 816 |
if verbose == 0: |
| 817 |
outputStr = "Point with coords:\n" |
| 818 |
for c in self.coordnames: |
| 819 |
outputStr += c |
| 820 |
if c != self.coordnames[-1]: |
| 821 |
outputStr += "\n" |
| 822 |
elif verbose > 0: |
| 823 |
outputStr = '' |
| 824 |
for c in self.coordnames: |
| 825 |
v = self.coordarray[self._map_names_to_ixs(c)] |
| 826 |
if isinstance(v, ndarray): |
| 827 |
dvstr = str(v[0]) |
| 828 |
else: |
| 829 |
|
| 830 |
dvstr = str(v) |
| 831 |
outputStr += c+': '+dvstr |
| 832 |
if c != self.coordnames[-1]: |
| 833 |
outputStr += "\n" |
| 834 |
for label, infodict in self.labels.items(): |
| 835 |
outputStr += "\nLabels: %s (%s)"%(label, str(infodict)) |
| 836 |
return outputStr |
| 837 |
|
| 838 |
|
| 839 |
def __repr__(self): |
| 840 |
return self._infostr(verbose=1) |
| 841 |
|
| 842 |
|
| 843 |
__str__ = __repr__ |
| 844 |
|
| 845 |
|
| 846 |
def info(self, verboselevel=1): |
| 847 |
print(self._infostr(verboselevel)) |
| 848 |
|
| 849 |
|
| 850 |
def __abs__(self): |
| 851 |
return linalg.norm(self.coordarray, self._normord) |
| 852 |
|
| 853 |
|
| 854 |
def __copy__(self): |
| 855 |
return Point({'coordarray': copy(self.coordarray), |
| 856 |
'coordnames': copy(self.coordnames), |
| 857 |
'coordtype': self.coordtype, |
| 858 |
'norm': self._normord, |
| 859 |
'labels': self.labels}) |
| 860 |
|
| 861 |
copy = __copy__ |
| 862 |
|
| 863 |
|
| 864 |
def __getstate__(self): |
| 865 |
d = copy(self.__dict__) |
| 866 |
|
| 867 |
if not numpyimported: |
| 868 |
importnumpy() |
| 869 |
_num_type2name = {float64: 'float', int32: 'int', |
| 870 |
type(1.0): 'float', type(1): 'int'} |
| 871 |
d['coordtype'] = _num_type2name[self.coordtype] |
| 872 |
return d |
| 873 |
|
| 874 |
|
| 875 |
def __setstate__(self, state): |
| 876 |
if not numpyimported: |
| 877 |
importnumpy() |
| 878 |
_num_name2type = {'float': float64, 'int': int32} |
| 879 |
self.__dict__.update(state) |
| 880 |
|
| 881 |
self.coordtype = _num_name2type[self.coordtype] |
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
|
| 886 |
|
| 887 |
class Pointset(Point): |
| 888 |
"""1D parameterized or non-parameterized set of discrete points. |
| 889 |
(If present, the independent variable must be a float64 or an int32)""" |
| 890 |
|
| 891 |
def __init__(self, kwd=None, **kw): |
| 892 |
if not numpyimported: |
| 893 |
importnumpy() |
| 894 |
if kwd is not None: |
| 895 |
if kw != {}: |
| 896 |
raise ValueError("Cannot mix keyword dictionary and keywords") |
| 897 |
kw = kwd |
| 898 |
if intersect(kw.keys(), point_keys) == []: |
| 899 |
|
| 900 |
temp_kw = {} |
| 901 |
temp_kw['coorddict'] = copy(kw) |
| 902 |
kw = copy(temp_kw) |
| 903 |
|
| 904 |
if 'indepvardict' in kw: |
| 905 |
assert len(kw['indepvardict']) == 1 |
| 906 |
try: |
| 907 |
it = kw['indepvartype'] |
| 908 |
except KeyError: |
| 909 |
self.indepvartype = float64 |
| 910 |
else: |
| 911 |
try: |
| 912 |
self.indepvartype = _num_equivtype[it] |
| 913 |
except KeyError: |
| 914 |
raise TypeError('Independent variable type %s not valid'%str(it)) |
| 915 |
vals = list(kw['indepvardict'].values())[0] |
| 916 |
self.indepvarname = list(kw['indepvardict'])[0] |
| 917 |
if isinstance(vals, _seq_types): |
| 918 |
self.indepvararray = array(vals, self.indepvartype) |
| 919 |
else: |
| 920 |
try: |
| 921 |
assert self.indepvartype == _num_equivtype[type(vals)] |
| 922 |
except (AssertionError, KeyError): |
| 923 |
raise TypeError("Invalid type for independent variable value") |
| 924 |
else: |
| 925 |
self.indepvararray = array([vals], self.indepvartype) |
| 926 |
elif 'indepvararray' in kw: |
| 927 |
if 'indepvarname' in kw: |
| 928 |
self.indepvarname = kw['indepvarname'] |
| 929 |
else: |
| 930 |
self.indepvarname = 't' |
| 931 |
vals = kw['indepvararray'] |
| 932 |
if isinstance(vals, list): |
| 933 |
try: |
| 934 |
it = kw['indepvartype'] |
| 935 |
except: |
| 936 |
self.indepvartype = float64 |
| 937 |
else: |
| 938 |
try: |
| 939 |
self.indepvartype = _num_equivtype[it] |
| 940 |
except KeyError: |
| 941 |
raise TypeError('Independent variable type %s not valid'%str(it)) |
| 942 |
self.indepvararray = array(vals, self.indepvartype) |
| 943 |
elif isinstance(vals, ndarray): |
| 944 |
|
| 945 |
|
| 946 |
if rank(vals) == 0: |
| 947 |
self.indepvararray = array(ravel(vals)) |
| 948 |
else: |
| 949 |
self.indepvararray = array(vals) |
| 950 |
try: |
| 951 |
self.indepvartype = _num_equivtype[type(self.indepvararray[0])] |
| 952 |
except KeyError: |
| 953 |
raise TypeError('Independent variable type ' |
| 954 |
'%s not valid'%type(self.indepvararray[0])) |
| 955 |
else: |
| 956 |
raise TypeError("Invalid type for independent variable " |
| 957 |
"array: "+str(type(vals))) |
| 958 |
|
| 959 |
else: |
| 960 |
|
| 961 |
self.indepvarname = None |
| 962 |
self.indepvartype = None |
| 963 |
self.indepvararray = None |
| 964 |
self._parameterized = False |
| 965 |
if self.indepvarname: |
| 966 |
|
| 967 |
assert isinstance(self.indepvarname, str), \ |
| 968 |
'independent variable name must be a string' |
| 969 |
try: |
| 970 |
self.indepvartype = _num_equivtype[type(self.indepvararray[0])] |
| 971 |
except KeyError: |
| 972 |
raise TypeError('Independent variable type ' |
| 973 |
'%s not valid'%self.indepvararray.dtype) |
| 974 |
r=rank(self.indepvararray) |
| 975 |
if r == 1: |
| 976 |
pass |
| 977 |
elif r == 0: |
| 978 |
self.indepvararray = ravel(self.indepvararray) |
| 979 |
else: |
| 980 |
raise ValueError("Invalid rank for " |
| 981 |
"independent variable array %i"%r) |
| 982 |
|
| 983 |
|
| 984 |
|
| 985 |
do_reverse = not isincreasing(self.indepvararray) |
| 986 |
self._parameterized = True |
| 987 |
|
| 988 |
if 'coorddict' in kw: |
| 989 |
coorddict = {} |
| 990 |
try: |
| 991 |
ct = kw['coordtype'] |
| 992 |
except KeyError: |
| 993 |
self.coordtype = float64 |
| 994 |
else: |
| 995 |
try: |
| 996 |
self.coordtype = _num_equivtype[ct] |
| 997 |
except KeyError: |
| 998 |
raise TypeError('Coordinate type %s not valid for Point'%str(ct)) |
| 999 |
for c, v in kw['coorddict'].items(): |
| 1000 |
if isinstance(c, str): |
| 1001 |
c_key = c |
| 1002 |
else: |
| 1003 |
c_key = repr(c) |
| 1004 |
if isinstance(v, list): |
| 1005 |
coorddict[c_key] = array(v, self.coordtype) |
| 1006 |
elif isinstance(v, ndarray): |
| 1007 |
|
| 1008 |
|
| 1009 |
coorddict[c_key] = array(v, self.coordtype) |
| 1010 |
elif isinstance(v, Pointset): |
| 1011 |
coorddict[c_key] = v.toarray() |
| 1012 |
else: |
| 1013 |
try: |
| 1014 |
assert self.coordtype == _num_equivtype[type(v)] |
| 1015 |
except (AssertionError, KeyError): |
| 1016 |
raise TypeError("Must pass arrays, lists, or numeric types") |
| 1017 |
else: |
| 1018 |
coorddict[c_key] = array([v], self.coordtype) |
| 1019 |
self.coordnames = list(coorddict) |
| 1020 |
|
| 1021 |
self.coordnames.sort() |
| 1022 |
self.dimension = len(self.coordnames) |
| 1023 |
datalist = [] |
| 1024 |
|
| 1025 |
if self._parameterized: |
| 1026 |
my_len = len(self.indepvararray) |
| 1027 |
else: |
| 1028 |
my_len = len(coorddict[self.coordnames[0]]) |
| 1029 |
for c in self.coordnames: |
| 1030 |
xs = coorddict[c] |
| 1031 |
if my_len != len(xs): |
| 1032 |
if self._parameterized: |
| 1033 |
raise ValueError('Independent variable array length must match ' |
| 1034 |
'that of each coordinate array') |
| 1035 |
else: |
| 1036 |
raise ValueError('All coordinate arrays must have same length') |
| 1037 |
datalist.append(xs) |
| 1038 |
self.coordarray = array(datalist, self.coordtype) |
| 1039 |
r = rank(self.coordarray) |
| 1040 |
if r == 2: |
| 1041 |
pass |
| 1042 |
elif r == 1: |
| 1043 |
self.coordarray = array([self.coordarray], self.coordtype) |
| 1044 |
elif r == 0: |
| 1045 |
self.coordarray = array([ravel(self.coordarray)], self.coordtype) |
| 1046 |
else: |
| 1047 |
raise ValueError("Invalid rank for coordinate array: %i"%r) |
| 1048 |
assert self.dimension == self.coordarray.shape[0], "Invalid coord array" |
| 1049 |
elif 'coordarray' in kw: |
| 1050 |
if not isinstance(kw['coordarray'], _seq_types): |
| 1051 |
raise TypeError('Coordinate type %s not valid for Pointset'%str(type(kw['coordarray']))) |
| 1052 |
try: |
| 1053 |
ct = kw['coordtype'] |
| 1054 |
except KeyError: |
| 1055 |
self.coordtype = float64 |
| 1056 |
else: |
| 1057 |
try: |
| 1058 |
self.coordtype = _num_equivtype[ct] |
| 1059 |
except KeyError: |
| 1060 |
raise TypeError('Coordinate type %s not valid'%str(ct)) |
| 1061 |
|
| 1062 |
|
| 1063 |
array_temp = array(kw['coordarray'], self.coordtype) |
| 1064 |
r = rank(array_temp) |
| 1065 |
if r == 2: |
| 1066 |
self.coordarray = array_temp |
| 1067 |
elif r == 1: |
| 1068 |
self.coordarray = array([kw['coordarray']], self.coordtype) |
| 1069 |
elif r == 0: |
| 1070 |
self.coordarray = array([ravel(array_temp)], self.coordtype) |
| 1071 |
else: |
| 1072 |
raise ValueError("Invalid rank for coordinate array %i"%r) |
| 1073 |
self.dimension = self.coordarray.shape[0] |
| 1074 |
if 'coordnames' in kw: |
| 1075 |
if isinstance(kw['coordnames'], str): |
| 1076 |
coordnames = [kw['coordnames']] |
| 1077 |
else: |
| 1078 |
coordnames = kw['coordnames'] |
| 1079 |
else: |
| 1080 |
coordnames = [str(cix) for cix in range(self.dimension)] |
| 1081 |
if len(coordnames) != self.dimension: |
| 1082 |
print("Pointset initialization error:") |
| 1083 |
print("Found Coordnames: %s (dimension = %s)"% |
| 1084 |
(coordnames, len(coordnames))) |
| 1085 |
print("vs. data dimension = %s"%self.dimension) |
| 1086 |
raise ValueError("Mismatch between number of coordnames and " |
| 1087 |
"dimension of data") |
| 1088 |
self.coordnames = coordnames |
| 1089 |
self.coordtype = _num_equivtype[type(self.coordarray[0][0])] |
| 1090 |
else: |
| 1091 |
raise ValueError("Missing coord info in keywords") |
| 1092 |
assert isUniqueSeq(self.coordnames), 'Coordinate names must be unique' |
| 1093 |
self.makeIxMaps() |
| 1094 |
if self._parameterized: |
| 1095 |
assert self.indepvarname not in self.coordnames, \ |
| 1096 |
"Independent variable name appeared in coordinate names" |
| 1097 |
|
| 1098 |
assert self.coordarray.shape[1] == len(self.indepvararray), \ |
| 1099 |
("Coord array length mismatch with independent variable" |
| 1100 |
" array length") |
| 1101 |
|
| 1102 |
|
| 1103 |
|
| 1104 |
if 'checklevel' in kw: |
| 1105 |
checklevel = kw['checklevel'] |
| 1106 |
if checklevel in [0,1]: |
| 1107 |
self.checklevel = checklevel |
| 1108 |
else: |
| 1109 |
raise ValueError("Invalid check level") |
| 1110 |
else: |
| 1111 |
|
| 1112 |
self.checklevel = 1 |
| 1113 |
if 'tolerance' in kw: |
| 1114 |
tol = kw['tolerance'] |
| 1115 |
if tol > 0: |
| 1116 |
self._abseps = tol |
| 1117 |
else: |
| 1118 |
raise ValueError("Tolerance must be a positive real number") |
| 1119 |
else: |
| 1120 |
self._abseps = 1e-10 |
| 1121 |
if 'name' in kw: |
| 1122 |
if isinstance(kw['name'], str): |
| 1123 |
self.name = kw['name'] |
| 1124 |
else: |
| 1125 |
raise TypeError("name argument must be a string") |
| 1126 |
else: |
| 1127 |
self.name = "" |
| 1128 |
if 'norm' in kw: |
| 1129 |
if kw['norm'] == 0: |
| 1130 |
raise ValueError("Norm order for point cannot be zero") |
| 1131 |
self._normord = kw['norm'] |
| 1132 |
else: |
| 1133 |
self._normord = 2 |
| 1134 |
if 'labels' in kw: |
| 1135 |
try: |
| 1136 |
self.labels = PointInfo(kw['labels'].by_index) |
| 1137 |
except AttributeError: |
| 1138 |
self.labels = PointInfo(kw['labels']) |
| 1139 |
else: |
| 1140 |
self.labels = PointInfo() |
| 1141 |
if self._parameterized: |
| 1142 |
if do_reverse: |
| 1143 |
|
| 1144 |
|
| 1145 |
self.indepvararray = self.indepvararray[::-1] |
| 1146 |
self.reverse() |
| 1147 |
if not isincreasing(self.indepvararray): |
| 1148 |
raise ValueError("Independent variable values must be in " |
| 1149 |
"increasing order") |
| 1150 |
|
| 1151 |
|
| 1152 |
def __delitem__(self, k): |
| 1153 |
"""Remove point by index or by coordinate.""" |
| 1154 |
if k in self.coordnames: |
| 1155 |
cs = remain(self.coordnames, k) |
| 1156 |
p_result = copy(self[cs]) |
| 1157 |
self.coordnames = cs |
| 1158 |
self.coordarray = p_result.coordarray |
| 1159 |
self.labels = p_result.labels |
| 1160 |
self.indepvararray = p_result.indepvararray |
| 1161 |
self.makeIxMaps() |
| 1162 |
else: |
| 1163 |
|
| 1164 |
self.remove(k) |
| 1165 |
|
| 1166 |
|
| 1167 |
def remove(self, ix): |
| 1168 |
"""Remove individual Point by its index.""" |
| 1169 |
if ix == 0: |
| 1170 |
try: |
| 1171 |
p_result = copy(self[1:]) |
| 1172 |
except ValueError: |
| 1173 |
|
| 1174 |
raise ValueError("Cannot remove only point in pointset!") |
| 1175 |
else: |
| 1176 |
ix = ix % len(self) |
| 1177 |
p_result = copy(self[:ix]) |
| 1178 |
try: |
| 1179 |
p_result.append(self[ix+1:]) |
| 1180 |
except ValueError: |
| 1181 |
|
| 1182 |
pass |
| 1183 |
self.coordarray = p_result.coordarray |
| 1184 |
self.labels = p_result.labels |
| 1185 |
self.indepvararray = p_result.indepvararray |
| 1186 |
self.makeIxMaps() |
| 1187 |
|
| 1188 |
|
| 1189 |
def reverse(self): |
| 1190 |
"""Reverse order of points *IN PLACE*.""" |
| 1191 |
self.coordarray = self.coordarray[:,::-1] |
| 1192 |
self.labels.mapIndices(dict(zip(range(0,len(self)),range(len(self)-1,-1,-1)))) |
| 1193 |
|
| 1194 |
def rename(self, coord, newcoord): |
| 1195 |
"""Rename a coordinate.""" |
| 1196 |
try: |
| 1197 |
ix = self.coordnames.index(coord) |
| 1198 |
except ValueError: |
| 1199 |
raise ValueError("No such coordinate: %s"%coord) |
| 1200 |
self.coordnames[ix] = newcoord |
| 1201 |
self.makeIxMaps() |
| 1202 |
|
| 1203 |
def makeIxMaps(self): |
| 1204 |
self._name_ix_map = dict(zip(self.coordnames, range(self.dimension))) |
| 1205 |
self._ix_name_map = copy(self.coordnames) |
| 1206 |
if self._parameterized: |
| 1207 |
self._indepvar_ix_map = makeArrayIxMap(self.indepvararray) |
| 1208 |
else: |
| 1209 |
self._indepvar_ix_map = None |
| 1210 |
|
| 1211 |
|
| 1212 |
def addlabel(self, ix, label, info=None): |
| 1213 |
"""Add string label to indexed point. info dictionary is optional""" |
| 1214 |
if ix in range(len(self)): |
| 1215 |
self.labels.update(ix, label, info) |
| 1216 |
else: |
| 1217 |
raise ValueError("Index out of range") |
| 1218 |
|
| 1219 |
|
| 1220 |
def removelabel(self, ix): |
| 1221 |
"""Remove all labels at indexed point.""" |
| 1222 |
del self.labels[ix] |
| 1223 |
|
| 1224 |
|
| 1225 |
def bylabel(self, s): |
| 1226 |
"""Return pointset containing points labelled with the supplied |
| 1227 |
labels. Argument s can be a string or a list of strings.""" |
| 1228 |
if isinstance(s, str): |
| 1229 |
if s == '': |
| 1230 |
raise ValueError("Label must be non-empty") |
| 1231 |
else: |
| 1232 |
ixlist = sortedDictKeys(self.labels[s]) |
| 1233 |
if ixlist != []: |
| 1234 |
return self[ixlist] |
| 1235 |
else: |
| 1236 |
return None |
| 1237 |
elif isinstance(s, list): |
| 1238 |
ixlist = [] |
| 1239 |
for ss in s: |
| 1240 |
if isinstance(ss, str): |
| 1241 |
if ss == '': |
| 1242 |
raise ValueError("Label must be non-empty") |
| 1243 |
ixlist = sortedDictKeys(self.labels[ss]) |
| 1244 |
else: |
| 1245 |
raise TypeError("Invalid label type") |
| 1246 |
if ixlist != []: |
| 1247 |
return self[ixlist] |
| 1248 |
else: |
| 1249 |
return None |
| 1250 |
else: |
| 1251 |
raise TypeError("Invalid label type") |
| 1252 |
|
| 1253 |
|
| 1254 |
|
| 1255 |
def __setitem__(self, ix, p): |
| 1256 |
"""Change individual points, accessed by index (no slicing supported). |
| 1257 |
Individual coordinate values of a point can be changed by adding a |
| 1258 |
cross-reference coordinate name or index. |
| 1259 |
If ix is a variable name then the entire row can be changed (again, |
| 1260 |
no slicing supported).""" |
| 1261 |
if isinstance(ix, _int_types): |
| 1262 |
if isinstance(p, Point): |
| 1263 |
if compareNumTypes(self.coordtype, int32) and \ |
| 1264 |
compareNumTypes(p.coordtype, float64): |
| 1265 |
raise ValueError("Cannot update integer pointset with a float") |
| 1266 |
self.coordarray[:,ix] = p.toarray() |
| 1267 |
if len(p.labels) > 0: |
| 1268 |
self.labels.update({ix: p.labels}) |
| 1269 |
elif isinstance(p, dict): |
| 1270 |
vlist = [] |
| 1271 |
for k in self.coordnames: |
| 1272 |
vlist.append(p[k]) |
| 1273 |
self.coordarray[:,ix] = array(vlist, self.coordtype) |
| 1274 |
elif isinstance(p, _seq_types): |
| 1275 |
self.coordarray[:,ix] = array(p, self.coordtype) |
| 1276 |
else: |
| 1277 |
raise TypeError("Invalid index reference") |
| 1278 |
elif isinstance(ix, tuple) and len(ix) == 2: |
| 1279 |
|
| 1280 |
try: |
| 1281 |
c = self._name_ix_map[ix[1]] |
| 1282 |
except KeyError: |
| 1283 |
c = ix[1] |
| 1284 |
if isinstance(p, _int_types): |
| 1285 |
self.coordarray[c,ix[0]] = p |
| 1286 |
elif isinstance(p, _float_types): |
| 1287 |
if self.coordtype == float64: |
| 1288 |
self.coordarray[c,ix[0]] = p |
| 1289 |
else: |
| 1290 |
raise TypeError("Cannot update an integer pointset with a float") |
| 1291 |
elif isinstance(p, ndarray) and p.shape==(1,): |
| 1292 |
self.coordarray[c,ix[0]] = p[0] |
| 1293 |
elif isinstance(p, list) and len(list) == 1: |
| 1294 |
self.coordarray[c,ix[0]] = p[0] |
| 1295 |
elif isinstance(p, Point) and p.dimension == 1: |
| 1296 |
self.coordarray[c,ix[0]] = p[0] |
| 1297 |
if len(p.labels) > 0: |
| 1298 |
self.labels.update({ix: p.labels}) |
| 1299 |
else: |
| 1300 |
raise TypeError("New value is not a singleton numeric type") |
| 1301 |
elif isinstance(ix, str): |
| 1302 |
if ix == self.indepvarname: |
| 1303 |
if isinstance(p, Pointset): |
| 1304 |
if compareNumTypes(self.indepvartype, int32) and \ |
| 1305 |
compareNumTypes(p.indepvartype, float64): |
| 1306 |
raise ValueError("Cannot update integer independent variable with a float") |
| 1307 |
if len(self) == len(p): |
| 1308 |
self.indepvararray = p.toarray() |
| 1309 |
else: |
| 1310 |
raise ValueError("Size mismatch for new independent variable array") |
| 1311 |
|
| 1312 |
elif isinstance(p, dict): |
| 1313 |
if len(self) == len(p[c]): |
| 1314 |
self.indepvararray = array(p[c], self.indepvartype) |
| 1315 |
else: |
| 1316 |
raise ValueError("Size mismatch for new independent variable array") |
| 1317 |
elif isinstance(p, _seq_types): |
| 1318 |
if len(self) == len(p): |
| 1319 |
self.indepvararray = array(p, self.indepvartype) |
| 1320 |
else: |
| 1321 |
raise ValueError("Size mismatch for new independent variable array") |
| 1322 |
else: |
| 1323 |
raise TypeError("Invalid data") |
| 1324 |
elif ix in self.coordnames: |
| 1325 |
c = self._name_ix_map[ix] |
| 1326 |
if isinstance(p, Pointset): |
| 1327 |
if compareNumTypes(self.coordtype, int32) and \ |
| 1328 |
compareNumTypes(p.coordtype, float64): |
| 1329 |
raise ValueError("Cannot update integer pointset with a float") |
| 1330 |
self.coordarray[c,:] = p.toarray() |
| 1331 |
|
| 1332 |
elif isinstance(p, dict): |
| 1333 |
self.coordarray[c,:] = array(p[c], self.coordtype) |
| 1334 |
elif isinstance(p, _seq_types): |
| 1335 |
self.coordarray[c,:] = array(p, self.coordtype) |
| 1336 |
elif isinstance(p, _real_types): |
| 1337 |
self.coordarray[c,:] = float(p) |
| 1338 |
else: |
| 1339 |
raise TypeError("Invalid data") |
| 1340 |
else: |
| 1341 |
raise TypeError("Invalid variable reference") |
| 1342 |
else: |
| 1343 |
raise TypeError("Invalid Pointset reference") |
| 1344 |
|
| 1345 |
|
| 1346 |
def __getitem__(self, ix): |
| 1347 |
|
| 1348 |
if isinstance(ix, _int_types): |
| 1349 |
|
| 1350 |
|
| 1351 |
if ix < 0: |
| 1352 |
ix = ix + self.coordarray.shape[1] |
| 1353 |
if ix in self.labels: |
| 1354 |
label = self.labels[ix] |
| 1355 |
else: |
| 1356 |
label = {} |
| 1357 |
return Point({'coordarray': self.coordarray[:,ix], |
| 1358 |
'coordnames': self.coordnames, |
| 1359 |
'norm': self._normord, |
| 1360 |
'labels': label}) |
| 1361 |
elif isinstance(ix, tuple): |
| 1362 |
if len(ix) != 2: |
| 1363 |
raise ValueError("Only use 2-tuples in referencing pointset") |
| 1364 |
ref1 = ix[0] |
| 1365 |
ref2 = ix[1] |
| 1366 |
elif isinstance(ix, str): |
| 1367 |
|
| 1368 |
if self._parameterized: |
| 1369 |
if ix == self.indepvarname: |
| 1370 |
return self.indepvararray |
| 1371 |
else: |
| 1372 |
return self.coordarray[self._map_names_to_ixs(ix),:] |
| 1373 |
else: |
| 1374 |
return self.coordarray[self._map_names_to_ixs(ix),:] |
| 1375 |
elif isinstance(ix, list): |
| 1376 |
if all([x in self.coordnames for x in ix]): |
| 1377 |
ref1 = slice(len(self)) |
| 1378 |
ref2 = ix |
| 1379 |
else: |
| 1380 |
ref1 = ix |
| 1381 |
ref2 = None |
| 1382 |
elif isinstance(ix, (ndarray, slice)): |
| 1383 |
ref1 = ix |
| 1384 |
ref2 = None |
| 1385 |
else: |
| 1386 |
raise IndexError("Illegal index %s"%str(ix)) |
| 1387 |
if isinstance(ref1, (list, ndarray, _int_types)): |
| 1388 |
if isinstance(ref1, _int_types): |
| 1389 |
ref1 = [ref1] |
| 1390 |
try: |
| 1391 |
ca = take(self.coordarray, ref1, axis=1) |
| 1392 |
except ValueError: |
| 1393 |
raise ValueError("Invalid variable names given: "%(str(ref1))) |
| 1394 |
try: |
| 1395 |
ci = take(self.indepvararray, ref1, axis=0) |
| 1396 |
except (IndexError, AttributeError, ValueError): |
| 1397 |
|
| 1398 |
pass |
| 1399 |
cl = self.labels[ref1] |
| 1400 |
cl_ixs = cl.getIndices() |
| 1401 |
ixmap = invertMap(ref1) |
| 1402 |
new_cl_ixs = [ixmap[i] for i in cl_ixs] |
| 1403 |
elif isinstance(ref1, slice): |
| 1404 |
s1, s2, s3 = ref1.indices(self.coordarray.shape[1]) |
| 1405 |
if (s3 > 0 and s1 >= len(self)) or (s3 < 0 and s2 >= len(self)): |
| 1406 |
raise ValueError("Slice index out of range") |
| 1407 |
ca = take(self.coordarray, range(s1, s2, s3), axis=1) |
| 1408 |
try: |
| 1409 |
ci = take(self.indepvararray, range(s1, s2, s3),axis=0) |
| 1410 |
except (IndexError, AttributeError, ValueError): |
| 1411 |
|
| 1412 |
pass |
| 1413 |
cl = self.labels[ref1] |
| 1414 |
cl_ixs = cl.getIndices() |
| 1415 |
lowest_ix = s1 |
| 1416 |
if s3 < 0: |
| 1417 |
new_cl_ixs = [lowest_ix-i for i in cl_ixs] |
| 1418 |
else: |
| 1419 |
new_cl_ixs = [i-lowest_ix for i in cl_ixs] |
| 1420 |
else: |
| 1421 |
print("ref1 argument = %s"%ref1) |
| 1422 |
raise TypeError("Type %s is invalid for Pointset indexing"%str(type(ref1))) |
| 1423 |
ixlist = self._force_coords_to_ixlist(ref2) |
| 1424 |
ca = take(ca, ixlist, axis=0) |
| 1425 |
try: |
| 1426 |
cl.mapIndices(dict(zip(cl_ixs, new_cl_ixs))) |
| 1427 |
except AttributeError: |
| 1428 |
pass |
| 1429 |
if self._parameterized: |
| 1430 |
return Pointset({'coordarray': ca, |
| 1431 |
'coordnames': [self.coordnames[i] for i in ixlist], |
| 1432 |
'indepvararray': ci, |
| 1433 |
'indepvarname': self.indepvarname, |
| 1434 |
'norm': self._normord, |
| 1435 |
'labels': cl}) |
| 1436 |
else: |
| 1437 |
return Pointset({'coordarray': ca, |
| 1438 |
'coordnames': [self.coordnames[i] for i in ixlist], |
| 1439 |
'norm': self._normord, |
| 1440 |
'labels': cl}) |
| 1441 |
|
| 1442 |
|
| 1443 |
def _resolve_indepvar(self, p): |
| 1444 |
if self.checklevel == 0: |
| 1445 |
return self._indepvar_ix_map[p] |
| 1446 |
else: |
| 1447 |
try: |
| 1448 |
return self._indepvar_ix_map[p] |
| 1449 |
except: |
| 1450 |
ixs = self.findIndex(p) |
| 1451 |
lval = self.indepvararray[ixs[0]] |
| 1452 |
rval = self.indepvararray[ixs[1]] |
| 1453 |
if p - lval < self._abseps: |
| 1454 |
return ixs[0] |
| 1455 |
elif rval - p <= self._abseps: |
| 1456 |
return ixs[1] |
| 1457 |
else: |
| 1458 |
lerr = p - lval |
| 1459 |
rerr = rval - p |
| 1460 |
raise KeyError( \ |
| 1461 |
"%f not found in (%f, %f) @tol=%.16f: mismatches=(%.16f, %.16f)"%(p,lval,rval,self._abseps,lerr,rerr)) |
| 1462 |
|
| 1463 |
|
| 1464 |
def setTol(self, tol): |
| 1465 |
if tol > 0: |
| 1466 |
self._abseps = tol |
| 1467 |
else: |
| 1468 |
raise ValueError("tolerance must be a positive real number") |
| 1469 |
|
| 1470 |
|
| 1471 |
def __call__(self, p, coords=None): |
| 1472 |
if not self._parameterized: |
| 1473 |
raise TypeError("Cannot call a non-parameterized Pointset") |
| 1474 |
if isinstance(p, _seq_types): |
| 1475 |
|
| 1476 |
|
| 1477 |
try: |
| 1478 |
ix = [self._resolve_indepvar(i) for i in p] |
| 1479 |
except KeyError: |
| 1480 |
raise ValueError("Independent variable value not valid: %s"%str(p)) |
| 1481 |
else: |
| 1482 |
|
| 1483 |
try: |
| 1484 |
ix = self._resolve_indepvar(p) |
| 1485 |
except KeyError: |
| 1486 |
raise ValueError("Independent variable value not valid: " \ |
| 1487 |
+ str(p)) |
| 1488 |
if coords is None: |
| 1489 |
if isinstance(ix, _int_types): |
| 1490 |
label = self.labels[ix] |
| 1491 |
try: |
| 1492 |
label.mapIndices({ix: 0}) |
| 1493 |
except AttributeError: |
| 1494 |
|
| 1495 |
pass |
| 1496 |
return Point({'coordarray': self.coordarray[:,ix], |
| 1497 |
'coordnames': self.coordnames, |
| 1498 |
'norm': self._normord, |
| 1499 |
'labels': label}) |
| 1500 |
else: |
| 1501 |
labels = self.labels[ix] |
| 1502 |
cl_ixs = labels.getIndices() |
| 1503 |
ixmap = invertMap(ix) |
| 1504 |
new_cl_ixs = [ixmap[i] for i in cl_ixs] |
| 1505 |
if isinstance(ix, slice): |
| 1506 |
idx = ix.indices(self.coordarray.shape[1]) |
| 1507 |
lowest_ix = idx[0] |
| 1508 |
if idx[2] < 0: |
| 1509 |
new_cl_ixs = [lowest_ix-i for i in cl_ixs] |
| 1510 |
else: |
| 1511 |
new_cl_ixs = [i-lowest_ix for i in cl_ixs] |
| 1512 |
elif isinstance(ix, (list, ndarray)): |
| 1513 |
new_cl_ixs = [ixmap[i] for i in cl_ixs] |
| 1514 |
try: |
| 1515 |
labels.mapIndices(dict(zip(cl_ixs, new_cl_ixs))) |
| 1516 |
except AttributeError: |
| 1517 |
|
| 1518 |
pass |
| 1519 |
return Pointset({'coordarray': take(self.coordarray, ix, axis=1), |
| 1520 |
'coordnames': self.coordnames, |
| 1521 |
'indepvarname': self.indepvarname, |
| 1522 |
'indepvararray': take(self.indepvararray, ix, axis=0), |
| 1523 |
'norm': self._normord, |
| 1524 |
'labels': labels}) |
| 1525 |
else: |
| 1526 |
clist = self._force_coords_to_ixlist(coords) |
| 1527 |
if isinstance(ix, _int_types): |
| 1528 |
label = self.labels[ix] |
| 1529 |
try: |
| 1530 |
label.mapIndices({ix: 0}) |
| 1531 |
except AttributeError: |
| 1532 |
|
| 1533 |
pass |
| 1534 |
return Point({'coordarray': take(self.coordarray[:, ix],clist), |
| 1535 |
'coordnames': [self.coordnames[i] for i in clist], |
| 1536 |
'norm': self._normord, |
| 1537 |
'labels': label}) |
| 1538 |
else: |
| 1539 |
labels = self.labels[ix] |
| 1540 |
try: |
| 1541 |
labels.mapIndices(dict(zip(labels, [i-ix[0] for i in labels.getIndices()]))) |
| 1542 |
except AttributeError: |
| 1543 |
|
| 1544 |
pass |
| 1545 |
return Pointset({'coordarray': take(take(self.coordarray,clist, |
| 1546 |
axis=0), ix, axis=1), |
| 1547 |
'coordnames': [self.coordnames[i] for i in clist], |
| 1548 |
'indepvarname': self.indepvarname, |
| 1549 |
'indepvararray': take(self.indepvararray, ix, axis=0), |
| 1550 |
'norm': self._normord, |
| 1551 |
'labels': labels}) |
| 1552 |
|
| 1553 |
|
| 1554 |
def __len__(self): |
| 1555 |
return self.coordarray.shape[1] |
| 1556 |
|
| 1557 |
|
| 1558 |
def __contains__(self, other): |
| 1559 |
for i in range(len(self)): |
| 1560 |
if comparePointCoords(self.__getitem__(i), other): |
| 1561 |
return True |
| 1562 |
return False |
| 1563 |
|
| 1564 |
|
| 1565 |
def __lt__(self, other): |
| 1566 |
if isinstance(other, Pointset): |
| 1567 |
if not all(self.indepvararray == other.indepvararray): |
| 1568 |
raise ValueError("Independent variable arrays are not the same") |
| 1569 |
return array([self[i] < other[i] for i in range(len(self))], bool8) |
| 1570 |
elif isinstance(other, Point): |
| 1571 |
return array([p < other for p in self], bool8) |
| 1572 |
else: |
| 1573 |
try: |
| 1574 |
return self.coordarray < other |
| 1575 |
except: |
| 1576 |
raise TypeError("Invalid type for comparison with Pointset") |
| 1577 |
|
| 1578 |
def __gt__(self, other): |
| 1579 |
if isinstance(other, Pointset): |
| 1580 |
if not all(self.indepvararray == other.indepvararray): |
| 1581 |
raise ValueError("Independent variable arrays are not the same") |
| 1582 |
return array([self[i] > other[i] for i in range(len(self))], bool8) |
| 1583 |
elif isinstance(other, Point): |
| 1584 |
return array([p > other for p in self], bool8) |
| 1585 |
else: |
| 1586 |
try: |
| 1587 |
return self.coordarray > other |
| 1588 |
except: |
| 1589 |
raise TypeError("Invalid type for comparison with Pointset") |
| 1590 |
|
| 1591 |
def __le__(self, other): |
| 1592 |
if isinstance(other, Pointset): |
| 1593 |
if not all(self.indepvararray == other.indepvararray): |
| 1594 |
raise ValueError("Independent variable arrays are not the same") |
| 1595 |
return array([self[i] <= other[i] for i in range(len(self))], bool8) |
| 1596 |
elif isinstance(other, Point): |
| 1597 |
return array([p <= other for p in self], bool8) |
| 1598 |
else: |
| 1599 |
try: |
| 1600 |
return self.coordarray <= other |
| 1601 |
except: |
| 1602 |
raise TypeError("Invalid type for comparison with Pointset") |
| 1603 |
|
| 1604 |
def __ge__(self, other): |
| 1605 |
if isinstance(other, Pointset): |
| 1606 |
if not all(self.indepvararray == other.indepvararray): |
| 1607 |
raise ValueError("Independent variable arrays are not the same") |
| 1608 |
return array([self[i] >= other[i] for i in range(len(self))], bool8) |
| 1609 |
elif isinstance(other, Point): |
| 1610 |
return array([p >= other for p in self], bool8) |
| 1611 |
else: |
| 1612 |
try: |
| 1613 |
return self.coordarray >= other |
| 1614 |
except: |
| 1615 |
raise TypeError("Invalid type for comparison with Pointset") |
| 1616 |
|
| 1617 |
def __eq__(self, other): |
| 1618 |
if isinstance(other, Pointset): |
| 1619 |
if not all(self.indepvararray == other.indepvararray): |
| 1620 |
raise ValueError("Independent variable arrays are not the same") |
| 1621 |
return array([self[i] == other[i] for i in range(len(self))], bool8) |
| 1622 |
elif isinstance(other, Point): |
| 1623 |
return array([p == other for p in self], bool8) |
| 1624 |
else: |
| 1625 |
try: |
| 1626 |
return self.coordarray == other |
| 1627 |
except: |
| 1628 |
raise TypeError("Invalid type for comparison with Pointset") |
| 1629 |
|
| 1630 |
def __ne__(self, other): |
| 1631 |
if isinstance(other, Pointset): |
| 1632 |
if len(self) == 0 or len(other) == 0: |
| 1633 |
return True |
| 1634 |
if not all(self.indepvararray == other.indepvararray): |
| 1635 |
raise ValueError("Independent variable arrays are not the same") |
| 1636 |
return array([self[i] != other[i] for i in range(len(self))], bool8) |
| 1637 |
elif isinstance(other, Point): |
| 1638 |
return array([p != other for p in self], bool8) |
| 1639 |
else: |
| 1640 |
try: |
| 1641 |
return self.coordarray != other |
| 1642 |
except: |
| 1643 |
raise TypeError("Invalid type for comparison with Pointset") |
| 1644 |
|
| 1645 |
|
| 1646 |
def insert(self, parg, ix=None): |
| 1647 |
"""Insert individual Point or Pointset before the given index. |
| 1648 |
|
| 1649 |
If ix is not given then the source and target Pointsets must |
| 1650 |
be parameterized. In this case the Point or Pointset will be |
| 1651 |
inserted according to the ordering of independent variable |
| 1652 |
values.""" |
| 1653 |
p=copy(parg) |
| 1654 |
if ix is None: |
| 1655 |
if self._parameterized: |
| 1656 |
if isinstance(p, Point) and self.indepvarname in p.coordnames: |
| 1657 |
t = p[self.indepvarname] |
| 1658 |
tix = self.findIndex(t) |
| 1659 |
if isinstance(tix, tuple): |
| 1660 |
self.insert(p, tix[1]) |
| 1661 |
else: |
| 1662 |
|
| 1663 |
|
| 1664 |
raise ValueError("Point at independent variable " |
| 1665 |
"value %f already present"%t) |
| 1666 |
elif isinstance(p, Pointset) and p._parameterized and \ |
| 1667 |
p.indepvarname == self.indepvarname: |
| 1668 |
|
| 1669 |
|
| 1670 |
|
| 1671 |
|
| 1672 |
|
| 1673 |
iva = self.indepvararray.tolist() |
| 1674 |
vd = self.todict(aslist=True) |
| 1675 |
|
| 1676 |
|
| 1677 |
|
| 1678 |
if len(intersect(self._ix_name_map, p._ix_name_map)) != self.dimension: |
| 1679 |
raise ValueError("Dimension mismatch with inserted Pointset") |
| 1680 |
iva_p = p.indepvararray |
| 1681 |
lenp = len(p) |
| 1682 |
vd_p = p.todict() |
| 1683 |
try: |
| 1684 |
s_ixs = [self.findIndex(iva_p[i])[1]+i for i in range(lenp)] |
| 1685 |
except TypeError: |
| 1686 |
raise ValueError("Independent variable " |
| 1687 |
"values in Pointset already present") |
| 1688 |
p_label_ixs = p.labels.getIndices() |
| 1689 |
s_label_ixs = self.labels.getIndices() |
| 1690 |
sLabelMap = {} |
| 1691 |
pLabelMap = {} |
| 1692 |
for i in range(lenp): |
| 1693 |
s_ix = s_ixs[i] |
| 1694 |
if i in p_label_ixs: |
| 1695 |
pLabelMap[i] = s_ix |
| 1696 |
for s_label_ix in s_label_ixs: |
| 1697 |
if s_label_ix >= s_ix-i: |
| 1698 |
sLabelMap[s_label_ix] = s_label_ix+i+1 |
| 1699 |
|
| 1700 |
for p_ix in range(lenp): |
| 1701 |
s_ix = s_ixs[p_ix] |
| 1702 |
iva.insert(s_ix, iva_p[p_ix]) |
| 1703 |
for k in self._ix_name_map: |
| 1704 |
vd[k].insert(s_ix, vd_p[k][p_ix]) |
| 1705 |
|
| 1706 |
self.indepvararray = array(iva) |
| 1707 |
datalist = [] |
| 1708 |
for c in p._ix_name_map: |
| 1709 |
datalist.append(vd[c]) |
| 1710 |
self.coordarray = array(datalist, self.coordtype) |
| 1711 |
|
| 1712 |
self.labels.mapIndices(sLabelMap) |
| 1713 |
p_labels = copy(p.labels) |
| 1714 |
p_labels.mapIndices(pLabelMap) |
| 1715 |
self.labels.update(p_labels) |
| 1716 |
else: |
| 1717 |
raise TypeError("Inserted Point/Pointset must be " |
| 1718 |
"parameterized and share same independent" |
| 1719 |
"parameter name") |
| 1720 |
else: |
| 1721 |
raise TypeError("Source Pointset must be parameterized") |
| 1722 |
else: |
| 1723 |
if ix > 0: |
| 1724 |
p_result = copy(self[:ix]) |
| 1725 |
p_result.append(p) |
| 1726 |
else: |
| 1727 |
p_result = pointsToPointset(p, self.indepvarname) |
| 1728 |
try: |
| 1729 |
p_result.append(self[ix:]) |
| 1730 |
except ValueError: |
| 1731 |
|
| 1732 |
|
| 1733 |
pass |
| 1734 |
self.coordarray = p_result.coordarray |
| 1735 |
self.labels = p_result.labels |
| 1736 |
self.indepvararray = p_result.indepvararray |
| 1737 |
self.makeIxMaps() |
| 1738 |
|
| 1739 |
|
| 1740 |
def append(self, parg, t=None, skipMatchingIndepvar=False): |
| 1741 |
"""Append individual Point, Pointset or coordinates in place. |
| 1742 |
|
| 1743 |
skipMatchingIndepvar option causes a matching independent |
| 1744 |
variable value at the beginning of p to be skipped (only |
| 1745 |
meaningful for appending parameterized Pointsets). This |
| 1746 |
option is mainly for internal use.""" |
| 1747 |
|
| 1748 |
|
| 1749 |
|
| 1750 |
p = copy(parg) |
| 1751 |
if isinstance(p, Pointset): |
| 1752 |
assert p._parameterized == self._parameterized, "Parameterization mismatch" |
| 1753 |
|
| 1754 |
if compareNumTypes(self.coordtype, int32) and \ |
| 1755 |
compareNumTypes(p.coordtype, float64): |
| 1756 |
raise TypeError("Cannot add float64 pointset to an int32 Pointset") |
| 1757 |
pdim = p.dimension |
| 1758 |
if self._parameterized: |
| 1759 |
if t is None: |
| 1760 |
if self.indepvarname in p.coordnames: |
| 1761 |
t = p[self.indepvarname] |
| 1762 |
pdim = pdim - 1 |
| 1763 |
elif self.indepvarname == p.indepvarname: |
| 1764 |
t = p.indepvararray |
| 1765 |
else: |
| 1766 |
raise ValueError("Independent variable missing from Pointset") |
| 1767 |
if t[0] == self.indepvararray[-1] and skipMatchingIndepvar: |
| 1768 |
tval = t[1:] |
| 1769 |
start_ix = 1 |
| 1770 |
else: |
| 1771 |
tval = t |
| 1772 |
start_ix = 0 |
| 1773 |
if len(tval) > 0 and tval[0] <= self.indepvararray[-1]: |
| 1774 |
print("%s <= %s"%(tval[0],self.indepvararray[-1])) |
| 1775 |
raise ValueError("Independent variable value too small to add pointset") |
| 1776 |
added_len = len(tval) |
| 1777 |
else: |
| 1778 |
if t[0] == self.indepvararray[-1] and skipMatchingIndepvar: |
| 1779 |
tval = t[1:] |
| 1780 |
start_ix = 1 |
| 1781 |
else: |
| 1782 |
tval = t[:] |
| 1783 |
start_ix = 0 |
| 1784 |
if len(tval) > 0 and tval[0] <= self.indepvararray[-1]: |
| 1785 |
raise ValueError("Independent variable value too small to add pointset") |
| 1786 |
added_len = len(tval) |
| 1787 |
else: |
| 1788 |
if t is not None: |
| 1789 |
raise TypeError("t argument cannot be used for non-parameterized pointsets") |
| 1790 |
added_len = p.coordarray.shape[1] |
| 1791 |
start_ix = 0 |
| 1792 |
assert pdim == self.dimension, "Dimension mismatch with Pointset" |
| 1793 |
if pdim < p.dimension: |
| 1794 |
pcoords = copy(p.coordnames) |
| 1795 |
pcoords.remove(p.indepvarname) |
| 1796 |
else: |
| 1797 |
pcoords = p.coordnames |
| 1798 |
if remain(pcoords, self.coordnames) != []: |
| 1799 |
raise ValueError("Coordinate name mismatch with Pointset") |
| 1800 |
old_len = self.coordarray.shape[1] |
| 1801 |
new_len = old_len + added_len |
| 1802 |
old_coords = self.coordarray |
| 1803 |
self.coordarray = zeros((self.dimension, new_len), |
| 1804 |
_num_equivtype[type(self.coordarray[0][0])]) |
| 1805 |
if self._parameterized: |
| 1806 |
old_indepvars = self.indepvararray |
| 1807 |
self.indepvararray = zeros((new_len,), |
| 1808 |
_num_equivtype[type(old_indepvars[0])]) |
| 1809 |
self.indepvararray[:old_len] = old_indepvars |
| 1810 |
tvals = tval[:added_len] |
| 1811 |
self.indepvararray[old_len:] = tvals |
| 1812 |
for tix in range(old_len): |
| 1813 |
self.coordarray[:, tix] = old_coords[:, tix] |
| 1814 |
pdict = p.todict() |
| 1815 |
for ix in range(self.dimension): |
| 1816 |
self.coordarray[ix][old_len:] = pdict[ |
| 1817 |
self._ix_name_map[ix]][start_ix:] |
| 1818 |
p_labels = copy(p.labels) |
| 1819 |
pixs = p.labels.getIndices() |
| 1820 |
p_labels.mapIndices(dict(zip(pixs, [i+old_len for i in pixs]))) |
| 1821 |
self.labels.update(p_labels) |
| 1822 |
elif isinstance(p, Point): |
| 1823 |
|
| 1824 |
if compareNumTypes(self.coordtype, int32) and \ |
| 1825 |
compareNumTypes(p.coordtype, float64): |
| 1826 |
raise TypeError("Cannot add float64 Point to an int32 Pointset") |
| 1827 |
pdim = p.dimension |
| 1828 |
if self._parameterized: |
| 1829 |
if t is None: |
| 1830 |
if self.indepvarname not in p.coordnames: |
| 1831 |
raise ValueError("Independent variable missing from Point") |
| 1832 |
else: |
| 1833 |
tval = p[self.indepvarname] |
| 1834 |
if tval <= self.indepvararray[-1]: |
| 1835 |
raise ValueError("Independent variable value too small to add Point") |
| 1836 |
pdim = pdim - 1 |
| 1837 |
else: |
| 1838 |
if t <= self.indepvararray[-1]: |
| 1839 |
raise ValueError("Independent variable value too small to add Point") |
| 1840 |
tval = t |
| 1841 |
elif t is not None: |
| 1842 |
raise TypeError("t argument cannot be used for non-parameterized Pointsets") |
| 1843 |
assert pdim == self.dimension, "Dimension mismatch with Point" |
| 1844 |
if pdim < p.dimension: |
| 1845 |
pcoords = copy(p.coordnames) |
| 1846 |
if self._parameterized: |
| 1847 |
pcoords.remove(self.indepvarname) |
| 1848 |
else: |
| 1849 |
pcoords = p.coordnames |
| 1850 |
if remain(pcoords, self.coordnames) != []: |
| 1851 |
raise ValueError("Coordinate name mismatch with Point") |
| 1852 |
new_len = self.coordarray.shape[1]+1 |
| 1853 |
old_coords = self.coordarray |
| 1854 |
self.coordarray = zeros((self.dimension, new_len), |
| 1855 |
_num_equivtype[type(self.coordarray[0][0])]) |
| 1856 |
if self._parameterized: |
| 1857 |
old_indepvars = self.indepvararray |
| 1858 |
self.indepvararray = zeros((new_len,), |
| 1859 |
_num_equivtype[type(self.indepvararray[0])]) |
| 1860 |
self.indepvararray[:new_len-1] = old_indepvars |
| 1861 |
self.indepvararray[new_len-1] = tval |
| 1862 |
for tix in range(new_len-1): |
| 1863 |
self.coordarray[:, tix] = old_coords[:, tix] |
| 1864 |
for ix in range(self.dimension): |
| 1865 |
self.coordarray[ix,new_len-1] = p(self._ix_name_map[ix]) |
| 1866 |
if len(p.labels) > 0: |
| 1867 |
self.labels.update({new_len-1: p.labels}) |
| 1868 |
elif isinstance(p,str) or isinstance(p,list): |
| 1869 |
if isinstance(p,str): |
| 1870 |
p = [p] |
| 1871 |
c = self.coordarray |
| 1872 |
l = len(p) |
| 1873 |
if hasattr(N,'resize'): |
| 1874 |
self.coordarray = N.resize(self.coordarray, |
| 1875 |
(c.shape[0]+l,c.shape[1])) |
| 1876 |
self.coordarray[self.dimension:,:] = 0 |
| 1877 |
else: |
| 1878 |
for i in range(l): |
| 1879 |
c.append(array([0]*len(c[0]))) |
| 1880 |
self.coordnames.extend(p) |
| 1881 |
self.dimension = self.dimension + l |
| 1882 |
else: |
| 1883 |
raise TypeError("append requires Point, Pointset or (list of) string argument") |
| 1884 |
self.makeIxMaps() |
| 1885 |
|
| 1886 |
|
| 1887 |
extend = append |
| 1888 |
|
| 1889 |
|
| 1890 |
def toarray(self): |
| 1891 |
if self.dimension==1: |
| 1892 |
return self.coordarray[0] |
| 1893 |
else: |
| 1894 |
return self.coordarray |
| 1895 |
|
| 1896 |
|
| 1897 |
def todict(self, aslist=False): |
| 1898 |
"""Convert Pointset to a dictionary of arrays (or of lists with aslist=True).""" |
| 1899 |
if aslist: |
| 1900 |
d = dict(zip(self._ix_name_map, self.coordarray.tolist())) |
| 1901 |
else: |
| 1902 |
d = dict(zip(self._ix_name_map, self.coordarray)) |
| 1903 |
if self._parameterized: |
| 1904 |
d[self.indepvarname] = self.indepvararray |
| 1905 |
return d |
| 1906 |
|
| 1907 |
|
| 1908 |
def _infostr(self, verbose=0): |
| 1909 |
if self.name == '': |
| 1910 |
outputStr = "Pointset <no name>" |
| 1911 |
else: |
| 1912 |
outputStr = "Pointset " + self.name |
| 1913 |
if self._parameterized: |
| 1914 |
outputStr += " (parameterized)" |
| 1915 |
else: |
| 1916 |
outputStr += " (non-parameterized)" |
| 1917 |
if verbose > 0: |
| 1918 |
precision = 8 |
| 1919 |
lenv = len(self) |
| 1920 |
if lenv > 8: |
| 1921 |
ixslo = range(0,2) |
| 1922 |
ixshi = range(lenv-2,lenv) |
| 1923 |
outputStr += "\n" |
| 1924 |
if self._parameterized: |
| 1925 |
iv = self.indepvararray |
| 1926 |
if not isinstance(iv, ndarray): |
| 1927 |
iv = array(iv, self.indepvartype) |
| 1928 |
if lenv > 8: |
| 1929 |
alo = array2string(take(iv,ixslo),precision=precision) |
| 1930 |
ahi = array2string(take(iv,ixshi),precision=precision) |
| 1931 |
ivstr = alo[:-1] + ", ..., " + ahi[1:] |
| 1932 |
else: |
| 1933 |
ivstr = array2string(iv,precision=precision) |
| 1934 |
outputStr += "Independent variable:\n" |
| 1935 |
outputStr += self.indepvarname + ': '+ivstr+"\n" |
| 1936 |
outputStr += "Coordinates:\n" |
| 1937 |
for c in self.coordnames: |
| 1938 |
v = self.coordarray[self._map_names_to_ixs(c)] |
| 1939 |
if not isinstance(v, ndarray): |
| 1940 |
|
| 1941 |
v = array([v], self.coordtype) |
| 1942 |
if lenv > 8: |
| 1943 |
alo = array2string(take(v,ixslo),precision=precision) |
| 1944 |
ahi = array2string(take(v,ixshi),precision=precision) |
| 1945 |
dvstr = alo[:-1] + ", ..., " + ahi[1:] |
| 1946 |
else: |
| 1947 |
dvstr = array2string(v, precision=precision) |
| 1948 |
outputStr += c+': '+dvstr |
| 1949 |
if c != self.coordnames[-1]: |
| 1950 |
outputStr += "\n" |
| 1951 |
outputStr += "\nLabels by index: " + self.labels._infostr(17) |
| 1952 |
return outputStr |
| 1953 |
|
| 1954 |
|
| 1955 |
def __repr__(self): |
| 1956 |
return self._infostr(verbose=1) |
| 1957 |
|
| 1958 |
|
| 1959 |
def __str__(self): |
| 1960 |
return self._infostr(verbose=0) |
| 1961 |
|
| 1962 |
|
| 1963 |
def info(self, verboselevel=1): |
| 1964 |
print(self._infostr(verboselevel)) |
| 1965 |
|
| 1966 |
|
| 1967 |
def __copy__(self): |
| 1968 |
if self._parameterized: |
| 1969 |
return Pointset({'coordarray': copy(self.coordarray), |
| 1970 |
'coordnames': copy(self.coordnames), |
| 1971 |
'indepvarname': copy(self.indepvarname), |
| 1972 |
'indepvararray': copy(self.indepvararray), |
| 1973 |
'norm': self._normord, |
| 1974 |
'labels': copy(self.labels) |
| 1975 |
}) |
| 1976 |
else: |
| 1977 |
return Pointset({'coordarray': copy(self.coordarray), |
| 1978 |
'coordnames': copy(self.coordnames), |
| 1979 |
'norm': self._normord, |
| 1980 |
'labels': copy(self.labels)}) |
| 1981 |
|
| 1982 |
copy = __copy__ |
| 1983 |
|
| 1984 |
|
| 1985 |
def __getstate__(self): |
| 1986 |
d = copy(self.__dict__) |
| 1987 |
|
| 1988 |
if not numpyimported: |
| 1989 |
importnumpy() |
| 1990 |
_num_type2name = {float64: 'float', int32: 'int', |
| 1991 |
type(1.0): 'float', type(1): 'int'} |
| 1992 |
try: |
| 1993 |
d['indepvartype'] = _num_type2name[self.indepvartype] |
| 1994 |
except KeyError: |
| 1995 |
|
| 1996 |
pass |
| 1997 |
d['coordtype'] = _num_type2name[self.coordtype] |
| 1998 |
return d |
| 1999 |
|
| 2000 |
|
| 2001 |
def __setstate__(self, state): |
| 2002 |
if not numpyimported: |
| 2003 |
importnumpy() |
| 2004 |
_num_name2type = {'float': float64, 'int': int32} |
| 2005 |
self.__dict__.update(state) |
| 2006 |
|
| 2007 |
try: |
| 2008 |
self.indepvartype = _num_name2type[self.indepvartype] |
| 2009 |
except KeyError: |
| 2010 |
|
| 2011 |
pass |
| 2012 |
self.coordtype = _num_name2type[self.coordtype] |
| 2013 |
|
| 2014 |
def _match_indepvararray(self, other): |
| 2015 |
"""Verifies the matching of independent variable arrays in two pointsets. |
| 2016 |
Does nothing if either object is not a parameterized pointset.""" |
| 2017 |
try: |
| 2018 |
if other._parameterized and self._parameterized: |
| 2019 |
if not all(self.indepvararray == other.indepvararray): |
| 2020 |
print(self.indepvararray) |
| 2021 |
print(other.indepvararray) |
| 2022 |
raise ValueError("Mismatched independent variable arrays") |
| 2023 |
except AttributeError: |
| 2024 |
pass |
| 2025 |
|
| 2026 |
def __add__(self, other): |
| 2027 |
self._match_indepvararray(other) |
| 2028 |
return Point.__add__(self, other) |
| 2029 |
|
| 2030 |
def __radd__(self, other): |
| 2031 |
self._match_indepvararray(other) |
| 2032 |
return Point.__radd__(self, other) |
| 2033 |
|
| 2034 |
def __sub__(self, other): |
| 2035 |
self._match_indepvararray(other) |
| 2036 |
return Point.__sub__(self, other) |
| 2037 |
|
| 2038 |
def __rsub__(self, other): |
| 2039 |
self._match_indepvararray(other) |
| 2040 |
return Point.__rsub__(self, other) |
| 2041 |
|
| 2042 |
def __mul__(self, other): |
| 2043 |
self._match_indepvararray(other) |
| 2044 |
return Point.__mul__(self, other) |
| 2045 |
|
| 2046 |
def __rmul__(self, other): |
| 2047 |
self._match_indepvararray(other) |
| 2048 |
return Point.__rmul__(self, other) |
| 2049 |
|
| 2050 |
def __div__(self, other): |
| 2051 |
self._match_indepvararray(other) |
| 2052 |
return Point.__div__(self, other) |
| 2053 |
|
| 2054 |
def __rdiv__(self, other): |
| 2055 |
self._match_indepvararray(other) |
| 2056 |
return Point.__rdiv__(self, other) |
| 2057 |
|
| 2058 |
def find(self, indepval, end=None): |
| 2059 |
"""find returns an integer index for where to place |
| 2060 |
a point having independent variable value <indepval> in |
| 2061 |
the Pointset, if <indepval> already exists. Otherwise, a |
| 2062 |
pair indicating the nearest independent variable values |
| 2063 |
present in the Pointset is returned. |
| 2064 |
|
| 2065 |
To ensure an integer is always returned, choose a left or |
| 2066 |
right side to choose from the pair, using end=0 or 1 respectively.""" |
| 2067 |
if not self._parameterized: |
| 2068 |
raise TypeError("Cannot find index from independent variable for " |
| 2069 |
"a non-parameterized Pointset") |
| 2070 |
try: |
| 2071 |
ix = self.indepvararray.tolist().index(indepval) |
| 2072 |
result = ix |
| 2073 |
except ValueError: |
| 2074 |
cond = less(self.indepvararray, indepval).tolist() |
| 2075 |
try: |
| 2076 |
ix = cond.index(0) |
| 2077 |
result = (ix-1, ix) |
| 2078 |
except ValueError: |
| 2079 |
result = (len(self.indepvararray)-1, len(self.indepvararray)) |
| 2080 |
if end is not None: |
| 2081 |
result = result[end] |
| 2082 |
return result |
| 2083 |
|
| 2084 |
|
| 2085 |
findIndex = find |
| 2086 |
|
| 2087 |
|
| 2088 |
|
| 2089 |
|
| 2090 |
|
| 2091 |
class PointInfo(object): |
| 2092 |
"""Structure for storing individual point labels and information |
| 2093 |
dictionaries within a Pointset object. |
| 2094 |
|
| 2095 |
This class will not know the size of the Pointset it is associated with, |
| 2096 |
so index upper limits will not be checked in advance. |
| 2097 |
|
| 2098 |
Do not use a PointInfo object as an iterator, as it is 'infinite' in size! |
| 2099 |
(It uses DefaultDicts as its internal storage, which return {} for |
| 2100 |
undefined labels.)""" |
| 2101 |
|
| 2102 |
def __init__(self, ptlabels=None): |
| 2103 |
if ptlabels is None: |
| 2104 |
self.by_label = DefaultDict({}) |
| 2105 |
self.by_index = DefaultDict({}) |
| 2106 |
elif isinstance(ptlabels, PointInfo): |
| 2107 |
self.by_label = ptlabels.by_label |
| 2108 |
self.by_index = ptlabels.by_index |
| 2109 |
elif isinstance(ptlabels, dict): |
| 2110 |
|
| 2111 |
self.by_label = DefaultDict({}) |
| 2112 |
self.by_index = DefaultDict({}) |
| 2113 |
for k, v in ptlabels.items(): |
| 2114 |
if not isinstance(k, _int_types): |
| 2115 |
raise TypeError("Initialization dictionary must be keyed " |
| 2116 |
"by integer indices") |
| 2117 |
if isinstance(v, str): |
| 2118 |
self.by_label[v][k] = {} |
| 2119 |
self.by_index[k][v] = {} |
| 2120 |
else: |
| 2121 |
for label, infodict in v.items(): |
| 2122 |
self.by_label[label][k] = infodict |
| 2123 |
self.by_index[k][label] = infodict |
| 2124 |
else: |
| 2125 |
raise TypeError("Invalid labels at initialization of PointInfo") |
| 2126 |
|
| 2127 |
|
| 2128 |
def mapIndices(self, ixMapDict): |
| 2129 |
by_index = {} |
| 2130 |
ixMap = symbolMapClass(ixMapDict) |
| 2131 |
for ix, rest in self.by_index.items(): |
| 2132 |
by_index[ixMap(ix)] = rest |
| 2133 |
self.__init__(by_index) |
| 2134 |
|
| 2135 |
|
| 2136 |
def mapNames(self, themap): |
| 2137 |
"""Map labels, using a symbol map of class symbolMapClass.""" |
| 2138 |
self.by_label = mapNames(themap, self.by_label) |
| 2139 |
new_by_index = {} |
| 2140 |
for ix, labdict in self.by_index.items(): |
| 2141 |
new_by_index[ix] = mapNames(themap, labdict) |
| 2142 |
self.by_index = new_by_index |
| 2143 |
|
| 2144 |
|
| 2145 |
def sortByIndex(self): |
| 2146 |
ixkeys = sortedDictKeys(self.by_index) |
| 2147 |
return zip(ixkeys,[self.by_index[ix] for ix in ixkeys]) |
| 2148 |
|
| 2149 |
|
| 2150 |
def sortByLabel(self): |
| 2151 |
labelkeys = sortedDictKeys(self.by_label) |
| 2152 |
return zip(labelkeys,[self.by_label[label] for label in labelkeys]) |
| 2153 |
|
| 2154 |
|
| 2155 |
def getIndices(self): |
| 2156 |
return sortedDictKeys(self.by_index) |
| 2157 |
|
| 2158 |
|
| 2159 |
def getLabels(self): |
| 2160 |
return sortedDictKeys(self.by_label) |
| 2161 |
|
| 2162 |
|
| 2163 |
def __contains__(self, key): |
| 2164 |
return key in self.by_index or key in self.by_label |
| 2165 |
|
| 2166 |
|
| 2167 |
def __getitem__(self, key): |
| 2168 |
|
| 2169 |
|
| 2170 |
|
| 2171 |
|
| 2172 |
if isinstance(key, tuple): |
| 2173 |
raise TypeError("Can only reference PointInfo with a single key") |
| 2174 |
else: |
| 2175 |
if isinstance(key, (slice, list, ndarray)): |
| 2176 |
if isinstance(key, slice): |
| 2177 |
self_ixs = self.getIndices() |
| 2178 |
if len(self_ixs) == 0: |
| 2179 |
max_ixs = 0 |
| 2180 |
else: |
| 2181 |
max_ixs = max(self_ixs) |
| 2182 |
try: |
| 2183 |
s1, s2, s3 = key.indices(max_ixs+1) |
| 2184 |
ixs = range(s1, s2, s3) |
| 2185 |
key = intersect(ixs, self_ixs) |
| 2186 |
except TypeError: |
| 2187 |
key = self_ixs |
| 2188 |
else: |
| 2189 |
if all([isinstance(k, str) for k in key]): |
| 2190 |
keylabels = intersect(key, self.getLabels()) |
| 2191 |
key = [] |
| 2192 |
for l in keylabels: |
| 2193 |
key.extend(self.by_label[l].keys()) |
| 2194 |
elif all([isinstance(k, _int_types) for k in key]): |
| 2195 |
key = intersect(key, self.getIndices()) |
| 2196 |
else: |
| 2197 |
raise TypeError("Invalid key type for PointInfo") |
| 2198 |
return PointInfo(dict(zip(key,[self.by_index[i] for i in key]))) |
| 2199 |
elif key in self.by_index: |
| 2200 |
return self.by_index[key] |
| 2201 |
elif key in self.by_label: |
| 2202 |
return self.by_label[key] |
| 2203 |
else: |
| 2204 |
return {} |
| 2205 |
|
| 2206 |
|
| 2207 |
def __setitem__(self, key1, the_rest): |
| 2208 |
if isinstance(the_rest, tuple) and len(the_rest) == 2: |
| 2209 |
if isinstance(the_rest[0], str): |
| 2210 |
label = the_rest[0] |
| 2211 |
ix = None |
| 2212 |
elif isinstance(the_rest[0], _int_types): |
| 2213 |
ix = the_rest[0] |
| 2214 |
label = None |
| 2215 |
else: |
| 2216 |
raise TypeError("String expected for label") |
| 2217 |
if isinstance(the_rest[1], dict): |
| 2218 |
info = copy(the_rest[1]) |
| 2219 |
else: |
| 2220 |
raise TypeError("Dictionary expected for info") |
| 2221 |
elif isinstance(the_rest, str): |
| 2222 |
label = the_rest |
| 2223 |
ix = None |
| 2224 |
info = {} |
| 2225 |
elif isinstance(the_rest, _int_types): |
| 2226 |
ix = the_rest |
| 2227 |
label = None |
| 2228 |
info = {} |
| 2229 |
elif isinstance(the_rest, list): |
| 2230 |
self.__setitem__(key1, the_rest[0]) |
| 2231 |
for item in the_rest[1:]: |
| 2232 |
if isinstance(item, tuple) and len(item) == 2: |
| 2233 |
self.update(key1, item[0], item[1]) |
| 2234 |
else: |
| 2235 |
self.update(key1, item) |
| 2236 |
return |
| 2237 |
else: |
| 2238 |
raise TypeError("Invalid item to set in PointInfo") |
| 2239 |
if isinstance(key1, _int_types): |
| 2240 |
if label is None: |
| 2241 |
raise TypeError("Label expected") |
| 2242 |
ix = key1 |
| 2243 |
elif isinstance(key1, str): |
| 2244 |
if ix is None: |
| 2245 |
raise TypeError("Index expected") |
| 2246 |
label = key1 |
| 2247 |
if ix < 0: |
| 2248 |
raise IndexError("Index must be non-negative") |
| 2249 |
self.by_label[label].update({ix: info}) |
| 2250 |
self.by_index[ix].update({label: info}) |
| 2251 |
|
| 2252 |
|
| 2253 |
def __len__(self): |
| 2254 |
return len(self.by_index) |
| 2255 |
|
| 2256 |
|
| 2257 |
def remove(self, key1, *key2): |
| 2258 |
"""remove one or more items, keyed either by index or label.""" |
| 2259 |
byix = key1 in self.by_index |
| 2260 |
if key2 == (): |
| 2261 |
|
| 2262 |
if byix: |
| 2263 |
key2 = self.by_index[key1].keys() |
| 2264 |
else: |
| 2265 |
key2 = self.by_label[key1].keys() |
| 2266 |
if byix: |
| 2267 |
for k in list(key2): |
| 2268 |
|
| 2269 |
if k in self.by_label: |
| 2270 |
del self.by_index[key1][k] |
| 2271 |
del self.by_label[k][key1] |
| 2272 |
else: |
| 2273 |
raise KeyError("Label not found") |
| 2274 |
if self.by_label[k] == {}: |
| 2275 |
del self.by_label[k] |
| 2276 |
if self.by_index[key1] == {}: |
| 2277 |
del self.by_index[key1] |
| 2278 |
else: |
| 2279 |
for k in key2: |
| 2280 |
|
| 2281 |
if k in self.by_index: |
| 2282 |
del self.by_index[k][key1] |
| 2283 |
del self.by_label[key1][k] |
| 2284 |
else: |
| 2285 |
raise KeyError("Index not found") |
| 2286 |
if self.by_index[k] == {}: |
| 2287 |
del self.by_index[k] |
| 2288 |
if self.by_label[key1] == {}: |
| 2289 |
del self.by_label[key1] |
| 2290 |
|
| 2291 |
|
| 2292 |
def update(self, key1, key2=None, info=None): |
| 2293 |
if isinstance(key1, PointInfo): |
| 2294 |
if key2 is None and info is None: |
| 2295 |
for k, v in key1.by_index.items(): |
| 2296 |
for vk, vv in v.items(): |
| 2297 |
self.update(k, vk, vv) |
| 2298 |
else: |
| 2299 |
raise TypeError("Invalid calling sequence to update") |
| 2300 |
elif isinstance(key1, dict): |
| 2301 |
if key2 is None and info is None: |
| 2302 |
for k, v in key1.items(): |
| 2303 |
if isinstance(k, _int_types) and k >= 0: |
| 2304 |
if isinstance(v, str): |
| 2305 |
k2 = v |
| 2306 |
k3 = {} |
| 2307 |
self.update(k, k2, k3) |
| 2308 |
elif isinstance(v, tuple) and len(v)==2: |
| 2309 |
k2 = v[0] |
| 2310 |
k3 = v[1] |
| 2311 |
self.update(k, k2, k3) |
| 2312 |
elif isinstance(v, dict): |
| 2313 |
for k2, k3 in v.items(): |
| 2314 |
self.update(k, k2, k3) |
| 2315 |
else: |
| 2316 |
raise ValueError("Invalid data for update") |
| 2317 |
else: |
| 2318 |
raise TypeError("Invalid index for label") |
| 2319 |
else: |
| 2320 |
raise TypeError("Invalid calling sequence to update") |
| 2321 |
elif isinstance(key1, _int_types): |
| 2322 |
if info is None: |
| 2323 |
info = {} |
| 2324 |
if key1 in self.by_index: |
| 2325 |
if key2 in self.by_index[key1]: |
| 2326 |
self.by_index[key1][key2].update(info) |
| 2327 |
else: |
| 2328 |
self.__setitem__(key1, (key2, info)) |
| 2329 |
else: |
| 2330 |
self.__setitem__(key1, (key2, info)) |
| 2331 |
elif isinstance(key1, str): |
| 2332 |
if info is None: |
| 2333 |
info = {} |
| 2334 |
if key1 in self.by_label: |
| 2335 |
if key2 in self.by_label[key1]: |
| 2336 |
self.by_label[key1][key2].update(info) |
| 2337 |
else: |
| 2338 |
self.__setitem__(key2, (key1, info)) |
| 2339 |
else: |
| 2340 |
self.__setitem__(key2, (key1, info)) |
| 2341 |
else: |
| 2342 |
raise TypeError("Invalid type for update") |
| 2343 |
|
| 2344 |
|
| 2345 |
def __delitem__(self, key): |
| 2346 |
if key in self.by_index: |
| 2347 |
labels = self.by_index[key].keys() |
| 2348 |
del self.by_index[key] |
| 2349 |
for label in labels: |
| 2350 |
del self.by_label[label][key] |
| 2351 |
if self.by_label[label] == {}: |
| 2352 |
del self.by_label[label] |
| 2353 |
elif key in self.by_label: |
| 2354 |
ixs = self.by_label[key].keys() |
| 2355 |
del self.by_label[key] |
| 2356 |
for ix in ixs: |
| 2357 |
del self.by_index[ix][key] |
| 2358 |
if self.by_index[ix] == {}: |
| 2359 |
del self.by_index[ix] |
| 2360 |
else: |
| 2361 |
raise KeyError("Index or label not found") |
| 2362 |
|
| 2363 |
|
| 2364 |
def __eq__(self, other): |
| 2365 |
try: |
| 2366 |
return all(self.by_index.keys() == other.by_index.keys()) and \ |
| 2367 |
all(self.by_label.keys() == other.by_label.keys()) |
| 2368 |
except AttributeError: |
| 2369 |
raise TypeError("Invalid type for comparison to PointInfo") |
| 2370 |
|
| 2371 |
|
| 2372 |
def __ne__(self, other): |
| 2373 |
return not self.__eq__(other) |
| 2374 |
|
| 2375 |
def _infostr(self, tab=0): |
| 2376 |
lenself = len(self) |
| 2377 |
tabstr = " "*tab |
| 2378 |
basestr = ",\n"+tabstr |
| 2379 |
if lenself > 0: |
| 2380 |
entries = self.sortByIndex() |
| 2381 |
if lenself > 8: |
| 2382 |
return basestr.join([_pretty_print_label(i) for i in entries[0:3]]) + ",\n" +\ |
| 2383 |
(tabstr + " .\n")*3 + tabstr +\ |
| 2384 |
basestr.join([_pretty_print_label(i) for i in entries[-3:]]) |
| 2385 |
else: |
| 2386 |
return basestr.join([_pretty_print_label(i) for i in entries]) |
| 2387 |
else: |
| 2388 |
return "Empty" |
| 2389 |
|
| 2390 |
|
| 2391 |
def __repr__(self): |
| 2392 |
return self._infostr() |
| 2393 |
|
| 2394 |
__str__ = __repr__ |
| 2395 |
|
| 2396 |
|
| 2397 |
def _pretty_print_label(d): |
| 2398 |
"""Internal utility to pretty print point label info.""" |
| 2399 |
s = " %s: "%repr(d[0]) |
| 2400 |
entry_keys = d[1].keys() |
| 2401 |
ki = 0 |
| 2402 |
kimax = len(entry_keys) |
| 2403 |
for k in entry_keys: |
| 2404 |
keys = d[1][k].keys() |
| 2405 |
if len(keys) == 0: |
| 2406 |
s += "{%s: {}}"%k |
| 2407 |
else: |
| 2408 |
s += "{%s: {keys=%s}}"%(k,",".join(keys)) |
| 2409 |
if ki < kimax-1: |
| 2410 |
s += ', ' |
| 2411 |
ki += 1 |
| 2412 |
return s |
| 2413 |
|
| 2414 |
|
| 2415 |
|
| 2416 |
|
| 2417 |
def comparePointCoords(p1, p2, fussy=False): |
| 2418 |
"""Compare two Points, Pointsets, or dictionary of point data, coordinate-wise. |
| 2419 |
If p1 or p2 are Pointsets, their independent variable values, if present, are |
| 2420 |
*not* compared. |
| 2421 |
|
| 2422 |
fussy option causes point norm order and coordinate types to be |
| 2423 |
checked too (requires both arguments to be Points or Pointsets).""" |
| 2424 |
try: |
| 2425 |
p1d = dict(p1) |
| 2426 |
p1dk = p1d.keys() |
| 2427 |
p2d = dict(p2) |
| 2428 |
p2dk = p2d.keys() |
| 2429 |
except: |
| 2430 |
raise TypeError("Invalid Points, Pointsets, or dictionaries passed " |
| 2431 |
"to comparePointCoords") |
| 2432 |
test1 = all([ks[0]==ks[1] for ks in zip(p1dk, p2dk)]) |
| 2433 |
test2 = all([vs[0]==vs[1] for vs in \ |
| 2434 |
zip([p1d[k] for k in p1dk], [p2d[k] for k in p2dk])]) |
| 2435 |
if fussy: |
| 2436 |
try: |
| 2437 |
test3 = p1._normord == p2._normord |
| 2438 |
test4 = compareNumTypes(p1.coordtype, p2.coordtype) |
| 2439 |
return test1 and test2 and test3 and test4 |
| 2440 |
except AttributeError: |
| 2441 |
raise TypeError("Invalid Points, Pointsets, or dictionaries passed " |
| 2442 |
"to comparePointCoords with fussy option") |
| 2443 |
else: |
| 2444 |
return test1 and test2 |
| 2445 |
|
| 2446 |
|
| 2447 |
def isparameterized(p): |
| 2448 |
return p._parameterized |
| 2449 |
|
| 2450 |
|
| 2451 |
def makeNonParameterized(p): |
| 2452 |
if isinstance(p, Pointset) and p._isparameterized: |
| 2453 |
return Pointset({'coordarray': copy(p.coordarray), |
| 2454 |
'coordnames': copy(p.coordnames), |
| 2455 |
'norm': p._normord, |
| 2456 |
'labels': copy(p.labels)}) |
| 2457 |
else: |
| 2458 |
raise TypeError("Must provide a parameterized Pointset") |
| 2459 |
|
| 2460 |
|
| 2461 |
def pointsToPointset(pointlist, indepvarname='', indepvararray=None, |
| 2462 |
indepvartype=float, norm=2): |
| 2463 |
"""Generate a Pointset from a list of Point objects (or a singleton Point). |
| 2464 |
|
| 2465 |
Include a name for the independent variable if constructing a |
| 2466 |
parameterized pointset. The independent variable should be a |
| 2467 |
coordinate of the Points passed, otherwise it can be passed as the |
| 2468 |
optional third argument.""" |
| 2469 |
|
| 2470 |
if not isinstance(indepvarname, str): |
| 2471 |
raise TypeError("String expected for independent variable name") |
| 2472 |
if isinstance(pointlist, Point): |
| 2473 |
pointlist = [pointlist] |
| 2474 |
coordnames = [] |
| 2475 |
ptype = '' |
| 2476 |
paramd = indepvarname != "" |
| 2477 |
if not paramd and indepvararray is not None: |
| 2478 |
raise ValueError("Must supply independent variable name for " |
| 2479 |
"parameterized Pointset") |
| 2480 |
if paramd and indepvararray is None: |
| 2481 |
iv = [] |
| 2482 |
i = 0 |
| 2483 |
labels = {} |
| 2484 |
for p in pointlist: |
| 2485 |
assert isinstance(p, Point), \ |
| 2486 |
"pointlist argument must only contain Points" |
| 2487 |
if coordnames == []: |
| 2488 |
ptype = p.coordtype |
| 2489 |
pdim = p.dimension |
| 2490 |
coordnames = p.coordnames |
| 2491 |
xcoordnames = copy(coordnames) |
| 2492 |
if paramd and indepvararray is None: |
| 2493 |
assert indepvarname in coordnames, \ |
| 2494 |
"Independent variable name missing" |
| 2495 |
del xcoordnames[xcoordnames.index(indepvarname)] |
| 2496 |
dv = {}.fromkeys(xcoordnames) |
| 2497 |
for c in xcoordnames: |
| 2498 |
dv[c] = [] |
| 2499 |
if p.labels != {}: |
| 2500 |
labels.update({0: p.labels}) |
| 2501 |
i += 1 |
| 2502 |
else: |
| 2503 |
|
| 2504 |
if compareNumTypes(ptype, int32): |
| 2505 |
if compareNumTypes(p.coordtype, float64): |
| 2506 |
ptype = float64 |
| 2507 |
elif compareNumTypes(p.coordtype, int32): |
| 2508 |
pass |
| 2509 |
else: |
| 2510 |
raise TypeError("Type mismatch in points") |
| 2511 |
elif compareNumTypes(ptype, float64): |
| 2512 |
if not compareNumTypes(p.coordtype, (float64, int32)): |
| 2513 |
raise TypeError("Type mismatch in points") |
| 2514 |
else: |
| 2515 |
raise TypeError("Type mismatch in points") |
| 2516 |
assert pdim == p.dimension, "Dimension mismatch in points" |
| 2517 |
if remain(coordnames,p.coordnames) != []: |
| 2518 |
raise ValueError("Coordinate name mismatch in points") |
| 2519 |
if p.labels != {}: |
| 2520 |
labels.update({i: p.labels}) |
| 2521 |
i += 1 |
| 2522 |
for c in xcoordnames: dv[c].append(p(c)) |
| 2523 |
if paramd and indepvararray is None: |
| 2524 |
iv.append(p(indepvarname)) |
| 2525 |
|
| 2526 |
dim = len(xcoordnames) |
| 2527 |
ca = array([dv[c] for c in xcoordnames], ptype) |
| 2528 |
argDict = {'coordarray': ca, |
| 2529 |
'coordnames': xcoordnames, |
| 2530 |
'coordtype': ptype, |
| 2531 |
'labels': labels, |
| 2532 |
'norm': norm |
| 2533 |
} |
| 2534 |
if paramd: |
| 2535 |
if indepvararray is None: |
| 2536 |
indepvararray = array(iv, ptype) |
| 2537 |
argDict.update({'indepvarname': indepvarname, |
| 2538 |
'indepvararray': indepvararray, |
| 2539 |
'indepvartype': indepvartype}) |
| 2540 |
return Pointset(argDict) |
| 2541 |
|
| 2542 |
|
| 2543 |
def arrayToPointset(a, vnames=None, ia=None, iname=""): |
| 2544 |
"""Convert an array to a non-parameterized Pointset. The inclusion of an |
| 2545 |
optional independent variable array creates a parameterized Pointset. |
| 2546 |
|
| 2547 |
Coordinate (and independent variable) names are optional: the defaults are |
| 2548 |
the array indices (and 't' for the independent variable).""" |
| 2549 |
if rank(a) > 2: |
| 2550 |
raise ValueError("Cannot convert arrays of rank > 2") |
| 2551 |
if rank(a) == 0: |
| 2552 |
raise ValueError("Cannot convert arrays of rank 0") |
| 2553 |
if vnames is None: |
| 2554 |
vnames = [str(i) for i in range(shape(a)[0])] |
| 2555 |
else: |
| 2556 |
if len(vnames) != shape(a)[0]: |
| 2557 |
raise ValueError("Mismatch between number of coordinate names and" |
| 2558 |
" number of rows in array.\nCoordinates are " |
| 2559 |
"assumed to be the rows of the array") |
| 2560 |
if ia is None: |
| 2561 |
assert iname=="", ("Independent variable name must be none if no " |
| 2562 |
"independent variable array provided") |
| 2563 |
return Pointset({'coordarray': a, |
| 2564 |
'coordnames': vnames}) |
| 2565 |
else: |
| 2566 |
if iname == "": |
| 2567 |
iname = "t" |
| 2568 |
return Pointset({'coordarray': a, |
| 2569 |
'coordnames': vnames, |
| 2570 |
'indepvararray': ia, |
| 2571 |
'indepvarname': iname}) |
| 2572 |
|
| 2573 |
|
| 2574 |
|
| 2575 |
|
| 2576 |
def test_point(): |
| 2577 |
print("\n****** Point class test ******\n") |
| 2578 |
print("x uses Python float type:") |
| 2579 |
xstr = """x = Point({'coorddict': {'x0': [1.123456789], 'x1': [-0.4], |
| 2580 |
'x2': [4000]}, |
| 2581 |
'coordtype': float})""" |
| 2582 |
print(xstr) |
| 2583 |
exec(xstr,globals()) |
| 2584 |
|
| 2585 |
print("x => %s"%repr(x)) |
| 2586 |
print("x.toarray() = %s"%x.toarray()) |
| 2587 |
print("\nprint x => %s"%x) |
| 2588 |
print("x.dimension => %s , x.coordnames => %s"%(x.dimension,x.coordnames)) |
| 2589 |
print("x.coordtype => %s"%x.coordtype) |
| 2590 |
print("x.coordtype => %s"%x.coordtype) |
| 2591 |
print("x('x1') = %s"%x('x1')) |
| 2592 |
print("x(['x1','x0']) = %s"%x(['x1','x0'])) |
| 2593 |
print("x([0,1]) = %s"%x([0,1])) |
| 2594 |
print("\nChanging x entries is done by x[index] = value:") |
| 2595 |
print("x[1] = -0.45") |
| 2596 |
x[1] = -0.45 |
| 2597 |
print("\nThe index can also be a name, a list of names, or even a dictionary:") |
| 2598 |
print("x[['x0', 'x1']] = [4.11103, -0.56])") |
| 2599 |
x[['x0', 'x1']] = [4.11103, -0.56] |
| 2600 |
print("\ny is a 1D point (with integer type):") |
| 2601 |
|
| 2602 |
ystr = """y = Point({'y': 4})""" |
| 2603 |
print(ystr) |
| 2604 |
exec(ystr,globals()) |
| 2605 |
print("print y => %s"%y) |
| 2606 |
print("y(0) = %s"%y(0)) |
| 2607 |
print("type(y(0)) => %s"%type(y(0))) |
| 2608 |
print("y([0]) = %s"%y([0])) |
| 2609 |
print("y.toarray() = %s"%y.toarray()) |
| 2610 |
assert comparePointCoords(x,(x+0)*1,fussy=True) |
| 2611 |
|
| 2612 |
return x |
| 2613 |
|
| 2614 |
|
| 2615 |
def test_pointset(): |
| 2616 |
print("\n\n****** Pointset test ******\n") |
| 2617 |
print("v is a 'singleton' pointset, to make sure this doesn't break the interface") |
| 2618 |
vstr = """v = Pointset({'coorddict': {'x0': 0.2, 'x1': -1.2}, |
| 2619 |
'indepvardict': {'t': 0.01}, |
| 2620 |
'coordtype': float64, |
| 2621 |
'indepvartype': float64 |
| 2622 |
})""" |
| 2623 |
print(vstr) |
| 2624 |
exec(vstr,globals()) |
| 2625 |
print("print v => %s"%v) |
| 2626 |
print("\nprint v(0.01) => %s"%v(0.01)) |
| 2627 |
print("and v(0.01) is a Point object\n") |
| 2628 |
print("print v(0.01, 0) => %s"%v(0.01, 0)) |
| 2629 |
print("and v(0.01, 0) is a float\n") |
| 2630 |
print("print v(0.01, 'x0') => %s"%v(0.01, 'x0')) |
| 2631 |
|
| 2632 |
print("\nk tests deprecated syntax for single-point pointset") |
| 2633 |
kstr = """k = Pointset({'coordarray': array(0.1), |
| 2634 |
'coordnames': 'k0', |
| 2635 |
'indepvarname': 't', |
| 2636 |
'indepvararray': array(0.0)})""" |
| 2637 |
print(kstr) |
| 2638 |
exec(kstr,globals()) |
| 2639 |
assert k.dimension == 1 |
| 2640 |
print("print k.toarray() => %s"%k.toarray()) |
| 2641 |
print("print k['t'] => %s"%k['t']) |
| 2642 |
print("print k(0.0) => %s"%k(0.0)) |
| 2643 |
print("print k => %s"%k) |
| 2644 |
|
| 2645 |
print("\nu tests non-parameterized pointset") |
| 2646 |
ustr = """u = Pointset({'coordarray': array([10., 20., 30., 40.])})""" |
| 2647 |
exec(ustr,globals()) |
| 2648 |
print(ustr) |
| 2649 |
print("u.toarray() => %s"%u.toarray()) |
| 2650 |
print("isparameterized(u) => %s"%isparameterized(u)) |
| 2651 |
print("print u => %s"%u) |
| 2652 |
|
| 2653 |
print("\nw tests alternative declaration syntax, and other forms of calling") |
| 2654 |
wstr = """wp = Pointset({'coordarray': array([[4.456, 2.34634, 7.3431, 5.443], |
| 2655 |
[-10.0336, -5.2235, -3.23221, -0.01], |
| 2656 |
[3e5, 3.1e5, 3.3e5, 2.8e5]], float64), |
| 2657 |
'coordnames': ['x0', 'x1', 'x2'], |
| 2658 |
'indepvarname': 't', |
| 2659 |
'indepvararray': array([0.0, 1.0, 2.0, 3.0], float64)})""" |
| 2660 |
print(wstr) |
| 2661 |
exec(wstr,globals()) |
| 2662 |
assert type(wp.coordarray)==type(array([1,2],float64)) |
| 2663 |
print("wp.dimension => %s"%wp.dimension) |
| 2664 |
print("print wp(0.0) => %s"%wp(0.0)) |
| 2665 |
print("type(wp(0.0)) => %s"%type(wp(0.0))) |
| 2666 |
print("print wp(1.0)(0) => %s"%wp(1.0)(0)) |
| 2667 |
print("print wp(2.0, 'x1') => %s"%wp(2.0, 'x1')) |
| 2668 |
print("\nprint wp(2.0, ['x2', 'x1']) => %s"%wp(2.0, ['x2', 'x1'])) |
| 2669 |
print("type(wp(2.0, ['x1', 'x2'])) => %s"%type(wp(2.0, ['x1', 'x2']))) |
| 2670 |
print("print wp[['x1','x0']] => %s"%wp[['x1','x0']]) |
| 2671 |
import sys |
| 2672 |
sys.stdout.write("\nwp.info(1) => ") |
| 2673 |
wp.info(1) |
| 2674 |
print(None) |
| 2675 |
sys.stdout.write("wp(1.0).info(1) => ") |
| 2676 |
wp(1.0).info(1) |
| 2677 |
print(None) |
| 2678 |
print("wp['t'] => %s"%wp['t']) |
| 2679 |
print("\nCall several 't' values at once (explicit values only -- no ellipses):") |
| 2680 |
print("wp([1., 2.]) => %s"%wp([1., 2.])) |
| 2681 |
print("\nExtract a coordinate (only by name) as a regular array:") |
| 2682 |
w_x0 = wp['x0'] |
| 2683 |
print("w_x0 = wp['x0'] => %s"%w_x0) |
| 2684 |
|
| 2685 |
print("\nExtract a point of w as a regular array:") |
| 2686 |
w_at_1 = wp(1.).toarray() |
| 2687 |
print("w_at_1 = wp(1.).toarray() => %s"%w_at_1) |
| 2688 |
|
| 2689 |
print("\nMany forms to access individual values or sub-arrays:") |
| 2690 |
print("wp(1., 'x1') => %s"%wp(1., 'x1')) |
| 2691 |
print("wp(1.)('x1') => %s"%wp(1.)('x1')) |
| 2692 |
print("wp(1., 1) => %s"%wp(1., 1)) |
| 2693 |
print("wp([1.,3.], 1) => %s"%wp([1.,3.], 1)) |
| 2694 |
print("wp([1.,3.])('x1') => %s"%wp([1.,3.])['x1']) |
| 2695 |
print("wp(1.)([0,1]) => %s"%wp(1.)([0,1])) |
| 2696 |
print("but ... wp([1.])(1., [0,1]) => %s"%wp([1.])(1., [0,1])) |
| 2697 |
print("... because wp([1.]) is a Pointset and wp(1.) is a Point") |
| 2698 |
print("This is why wp(1.).toarray() shows a different array shape to wp([1.]).toarray():") |
| 2699 |
print("wp(1.).toarray().shape => %s"%str(wp(1.).toarray().shape)) |
| 2700 |
print("wp([1.]).toarray().shape => %s"%str(wp([1.]).toarray().shape)) |
| 2701 |
|
| 2702 |
print("\nChange a point in w using wp[indepvar_value] = point:") |
| 2703 |
print("Old value at t=1.0: wp(1.0) => %s"%wp(1.0)) |
| 2704 |
print("wp[1] = x") |
| 2705 |
wp[1] = x |
| 2706 |
print("w has now been updated for the meshpoint at t=1.0 =>") |
| 2707 |
print("New value at t=1.0: wp(1.0) => %s"%wp(1.0)) |
| 2708 |
assert type(wp.coordarray)==type(array([1,2],float64)) |
| 2709 |
|
| 2710 |
print("\nWe can test equality between arrays, as usual:") |
| 2711 |
print("w_at_1 != wp(1.).toarray() => %s"%(w_at_1 != wp(1.).toarray())) |
| 2712 |
print("We can also compare with a Pointset object:") |
| 2713 |
print("wp(1.) != w_at_1 => %s"%(wp(1.) != w_at_1)) |
| 2714 |
print("But we can't put an array on the left-hand side if a Point or " \ |
| 2715 |
"Pointset is on the right.") |
| 2716 |
|
| 2717 |
print("\nTo demonstrate appending a Point and Pointset to another Pointset:") |
| 2718 |
vw = Pointset({'coorddict': {'x0': [0.1, 0.15], 'x1': [100., 102], 'x2': [0.2, 0.1]}, |
| 2719 |
'indepvardict': {'t': [4.5, 5.0]}, |
| 2720 |
'coordtype': float64, |
| 2721 |
'indepvartype': float64, |
| 2722 |
'labels': {1: 'c'} |
| 2723 |
}) |
| 2724 |
print("vw.labels --> %s"%vw.labels) |
| 2725 |
print("wp.append(vw)") |
| 2726 |
wp.append(vw) |
| 2727 |
print("wp.labels --> %s"%wp.labels) |
| 2728 |
assert type(wp.coordarray)==type(array([1,2],float64)) |
| 2729 |
wp.append(Point({'coorddict': {'t': 6.5, 'x0': 2, 'x1': -300, 'x2': -0.9997}})) |
| 2730 |
assert type(wp.coordarray)==type(array([1,2],float64)) |
| 2731 |
print("\nwp.toarray() -->\n%s"%wp.toarray()) |
| 2732 |
print("\nwp(4.5) -->\n%s"%wp(4.5)) |
| 2733 |
print("\nwp[[3,6]] --> %s"%wp[[3,6]]) |
| 2734 |
print("\nwp[3:5] --> %s"%wp[3:5]) |
| 2735 |
print("\nwp[2:] --> %s"%wp[2:]) |
| 2736 |
try: |
| 2737 |
|
| 2738 |
wp[10:] |
| 2739 |
except ValueError: |
| 2740 |
pass |
| 2741 |
print("\nwp[wp.findIndex(4.5)] -->\n%s"%wp[wp.findIndex(4.5)]) |
| 2742 |
print("\nwp.labels --> %s"%wp.labels) |
| 2743 |
print("\nLabels test:") |
| 2744 |
wp.labels[3] = ('a', {'bif':'SN'}) |
| 2745 |
print("wp.labels[3] --> %s"%wp.labels[3]) |
| 2746 |
wp_part = wp[3:5] |
| 2747 |
print("wp_part.labels --> %s"%wp_part.labels) |
| 2748 |
assert wp_part.labels[0] == wp.labels[3] |
| 2749 |
wpt = wp(3.) |
| 2750 |
assert wpt.labels == {'a': {'bif':'SN'}} |
| 2751 |
wp_ins = Pointset({'coorddict': {'x0': [-2.1, -4., -5., -4.5], 'x1': [50., 51., 52., 54.], 'x2': [0.01, 0.02, 0.4, 0.9]}, |
| 2752 |
'indepvardict': {'t': [1.5, 5.2, 9., 10.]}, |
| 2753 |
'coordtype': float64, |
| 2754 |
'indepvartype': float64, |
| 2755 |
'labels': {2: 'b', 3: {'a': {'bif':'H'}}} |
| 2756 |
}) |
| 2757 |
print("\nwp_ins object created to insert into wp:") |
| 2758 |
print(wp_ins) |
| 2759 |
wp.insert(wp_ins) |
| 2760 |
print("\nwp.insert(wp_ins) -->\n%s"%wp) |
| 2761 |
|
| 2762 |
print("\nTo demonstrate building a Pointset from a list of Point objects:") |
| 2763 |
codestr = """pointlist = [] |
| 2764 |
for t in wp['t']: |
| 2765 |
pointlist.append(wp(t)) |
| 2766 |
w_reconstructed = pointsToPointset(pointlist, 't', wp['t'])""" |
| 2767 |
print(codestr) |
| 2768 |
exec(codestr,globals()) |
| 2769 |
print("\nAnd to demonstrate that this yields an identical object:") |
| 2770 |
print("w_reconstructed == w => %s"%(w_reconstructed == wp)) |
| 2771 |
|
| 2772 |
try: |
| 2773 |
w_double = w_reconstructed.append(w_reconstructed) |
| 2774 |
raise RuntimeError("Internal error with Pointset class!") |
| 2775 |
except ValueError: |
| 2776 |
print("(ensure that any independent variable values to append are well-ordered)") |
| 2777 |
|
| 2778 |
print("\nTest of non-parameterized use of pointsToPointset:") |
| 2779 |
wnp = pointsToPointset(pointlist) |
| 2780 |
print("(Adding two additional labels to wnp)") |
| 2781 |
wnp.labels[0]=('b', {}) |
| 2782 |
wnp.addlabel(4, 'c', {'bif': 'H'}) |
| 2783 |
print(wnp) |
| 2784 |
print("\nwnp[:] -->\n%s"%wnp[:]) |
| 2785 |
print("-- OK!") |
| 2786 |
|
| 2787 |
print("\nCan iterate over points and pointsets:") |
| 2788 |
print("for p in wnp.bylabel('a'):\n print p\n") |
| 2789 |
for p in wnp.bylabel('a'): |
| 2790 |
print(p) |
| 2791 |
|
| 2792 |
|
| 2793 |
return wp, wnp, wpt, wp_part |
| 2794 |
|
| 2795 |
|
| 2796 |
|
| 2797 |
|
| 2798 |
if __name__ == '__main__': |
| 2799 |
x = test_point() |
| 2800 |
wp, wnp, wpt, wp_part = test_pointset() |
| 2801 |
print("\n") |
| 2802 |
print("x (point) and wp, wnp (param'd and non-param'd pointsets) are available in the global namespace, " \ |
| 2803 |
"to play with interactively now that this script has run.") |
| 2804 |
|