Package sfc :: Package common :: Module utilities
[hide private]
[frames] | no frames]

Source Code for Module sfc.common.utilities

  1  #!/usr/bin/env python 
  2  # -*- coding: utf-8 -*- 
  3  """ 
  4  This module contains utility functions for various stuff. 
  5  """ 
  6   
  7  # Copyright (C) 2007-2009 Martin Sandve Alnes and Simula Resarch Laboratory 
  8  # 
  9  # This file is part of SyFi. 
 10  # 
 11  # SyFi is free software: you can redistribute it and/or modify 
 12  # it under the terms of the GNU General Public License as published by 
 13  # the Free Software Foundation, either version 2 of the License, or 
 14  # (at your option) any later version. 
 15  # 
 16  # SyFi is distributed in the hope that it will be useful, 
 17  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 18  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
 19  # GNU General Public License for more details. 
 20  # 
 21  # You should have received a copy of the GNU General Public License 
 22  # along with SyFi. If not, see <http://www.gnu.org/licenses/>. 
 23  # 
 24  # First added:  2007-06-15 
 25  # Last changed: 2009-03-19 
 26   
 27  from itertools import izip 
 28  import swiginac 
 29  #import strings 
 30   
 31  import numpy.testing 
 32  _last_m = numpy.testing.memusage() 
33 -def printmem(msg):
34 global _last_m 35 m = numpy.testing.memusage() 36 diff = m - _last_m 37 print msg, diff, "b, ", diff/1024, "Kb, ", diff/1024**2, "Mb" 38 _last_m = m
39
40 -def dot_product(seq1, seq2):
41 return sum(a*b for (a,b) in izip(seq1,seq2))
42
43 -def make_name_valid(name):
44 """Filter away .[] from indexed array names.""" 45 name = name.replace(".","_") 46 name = name.replace("[","_") 47 name = name.replace("]","_") 48 return name
49
50 -def index_string(i):
51 if isinstance(i, int): 52 return str(i) 53 return "_".join(str(j) for j in i)
54
55 -def fe_is_discontinuous(fe):
56 sfc_error("FIXME") 57 58 if not isinstance(fe, str): 59 fe = strings.finite_element_classname(fe) 60 61 if "_" in fe: 62 fe = fe.split('_')[1] 63 64 return fe in ["DiscontinuousLagrange", 65 "VectorDiscontinuousLagrange", 66 "TensorDiscontinuousLagrange", 67 "ArnoldFalkWintherWeakSymU", 68 "ArnoldFalkWintherWeakSymP"]
69
70 -def fe_is_signed(fe):
71 sfc_error("FIXME") 72 73 if not isinstance(fe, str): 74 fe = strings.finite_element_classname(fe) 75 76 if "_" in fe: 77 fe = fe.split('_')[1] 78 79 return fe in ["ArnoldFalkWintherWeakSymSigma", 80 "Nedelec2Hdiv", 81 "Nedelec2HdivPtv", 82 "Nedelec", 83 "RaviartThomas", 84 "Robust", 85 "RobustPtv"]
86
87 -def check_range(i, a, b, msg="Invalid range."):
88 """Check that i is in [a,b), raise exception otherwise.""" 89 if (i < a or i >= b) and (a != b): 90 raise ValueError(msg)
91
92 -def unique(sequence):
93 s = set() 94 for i in sequence: 95 if not i in s: 96 s.add(i) 97 yield i
98
99 -def indices_subset(indices, keep):
100 newindices = [] 101 for ii in indices: 102 jj = tuple((j if keep[i] else None) for (i,j) in enumerate(ii)) 103 newindices.append(jj) 104 return tuple(unique(newindices))
105
106 -def shape(dims):
107 #if len(dims) == 0: 108 # return (1,) 109 return tuple(dims)
110
111 -def permute(shape):
112 """Returns a permutation of all multiindices within the range of a rank 0, 1, or 2 tensor shape.""" 113 if len(shape) == 0: 114 return [(0,)] 115 if len(shape) == 1: 116 return [(k,) for k in range(shape[0])] 117 if len(shape) == 2: 118 return [(k1,k2) for k1 in range(shape[0]) for k2 in range(shape[1])] 119 raise ValueError("Shapes with rank 3 or higher not implemented in permute(shape)")
120
121 -def list_items(l):
122 return zip( range(len(l)), l )
123
124 -def as_list_with_len(x, wantlen):
125 """If x is not a list type, it is repeated in a list wantlen times. 126 Otherwise checks it x the correct length. Always returns a list 127 with length wantlen or raises an exception.""" 128 if isinstance(x, tuple): 129 x = list(x) 130 if not isinstance(x, list): 131 x = [x,] 132 if len(x) == 1: 133 x = wantlen*x 134 if len(x) != (wantlen): 135 raise ValueError("Got list with size " + str(len(x)) + ", need " + str(wantlen) + ".") 136 return x
137
138 -def matrix_to_list(m):
139 return [m[i] for i in range(len(m))]
140
141 -def list_to_matrix(m, n, l):
142 if len(l) != m*n: 143 raise ValueError("Invalid sizes: %d * %d != %d" % (m, n, l)) 144 return swiginac.matrix(m, n, l)
145
146 -def list_to_vector(l):
147 return swiginac.matrix(len(l), 1, l)
148
149 -def is_function(f):
150 return hasattr(f, 'func_name')
151
152 -def is_functor(f):
153 if hasattr(f, 'func_name'): 154 return False 155 return hasattr(f, '__call__')
156
157 -def get_func_code(f):
158 """Get the func_code object from a function or functor object.""" 159 if not callable(f): 160 raise RuntimeError("Object is not callable!") 161 fc = None 162 if is_function(f): 163 fc = f.func_code 164 if is_functor(f): 165 fc = f.__call__.im_func.func_code 166 return fc
167
168 -def get_callable_name(f):
169 return get_func_code(f).co_name
170
171 -def get_callable_num_args(f):
172 return get_func_code(f).co_argcount
173