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   
 30  from sfc.common.names import finite_element_classname 
 31  from sfc.common.output import sfc_error 
 32   
 33  try: 
 34      import numpy.testing 
 35      _last_m = numpy.testing.memusage() 
 36  except: 
 37      _last_m = None 
38 -def printmem(msg):
39 global _last_m 40 if _last_m is None: 41 print "numpy memusage not available" 42 else: 43 m = numpy.testing.memusage() 44 diff = m - _last_m 45 print msg, diff, "b, ", diff/1024, "Kb, ", diff/1024**2, "Mb" 46 _last_m = m
47
48 -def dot_product(seq1, seq2):
49 return sum(a*b for (a,b) in izip(seq1,seq2))
50
51 -def make_name_valid(name):
52 """Filter away .[] from indexed array names.""" 53 name = name.replace(".","_") 54 name = name.replace("[","_") 55 name = name.replace("]","_") 56 return name
57
58 -def index_string(i):
59 if isinstance(i, int): 60 return str(i) 61 return "_".join(str(j) for j in i)
62
63 -def build_count_dict(entries):
64 d = {} 65 k = 0 66 for e in entries: 67 if not e in d: 68 d[e] = k 69 k += 1 70 return d
71
72 -def fe_is_discontinuous(fe):
73 sfc_error("FIXME") 74 75 if not isinstance(fe, str): 76 fe = finite_element_classname(fe) 77 78 if "_" in fe: 79 fe = fe.split('_')[1] 80 81 return fe in ["DiscontinuousLagrange", 82 "VectorDiscontinuousLagrange", 83 "TensorDiscontinuousLagrange", 84 "ArnoldFalkWintherWeakSymU", 85 "ArnoldFalkWintherWeakSymP"]
86
87 -def fe_is_signed(fe):
88 sfc_error("FIXME") 89 90 if not isinstance(fe, str): 91 fe = finite_element_classname(fe) 92 93 if "_" in fe: 94 fe = fe.split('_')[1] 95 96 return fe in ["ArnoldFalkWintherWeakSymSigma", 97 "Nedelec2Hdiv", 98 "Nedelec2HdivPtv", 99 "Nedelec", 100 "RaviartThomas", 101 "Robust", 102 "RobustPtv"]
103
104 -def check_range(i, a, b, msg="Invalid range."):
105 """Check that i is in [a,b), raise exception otherwise.""" 106 if (i < a or i >= b) and (a != b): 107 raise ValueError(msg)
108
109 -def unique(sequence):
110 s = set() 111 for i in sequence: 112 if not i in s: 113 s.add(i) 114 yield i
115
116 -def indices_subset(indices, keep):
117 newindices = [] 118 for ii in indices: 119 jj = tuple((j if keep[i] else None) for (i,j) in enumerate(ii)) 120 newindices.append(jj) 121 return tuple(unique(newindices))
122
123 -def shape(dims):
124 #if len(dims) == 0: 125 # return (1,) 126 return tuple(dims)
127
128 -def permute(shape):
129 """Returns a permutation of all multiindices within the range of a rank 0, 1, or 2 tensor shape.""" 130 if len(shape) == 0: 131 return [(0,)] 132 if len(shape) == 1: 133 return [(k,) for k in range(shape[0])] 134 if len(shape) == 2: 135 return [(k1,k2) for k1 in range(shape[0]) for k2 in range(shape[1])] 136 raise ValueError("Shapes with rank 3 or higher not implemented in permute(shape)")
137
138 -def list_items(l):
139 return zip( range(len(l)), l )
140
141 -def as_list_with_len(x, wantlen):
142 """If x is not a list type, it is repeated in a list wantlen times. 143 Otherwise checks it x the correct length. Always returns a list 144 with length wantlen or raises an exception.""" 145 if isinstance(x, tuple): 146 x = list(x) 147 if not isinstance(x, list): 148 x = [x,] 149 if len(x) == 1: 150 x = wantlen*x 151 if len(x) != (wantlen): 152 raise ValueError("Got list with size " + str(len(x)) + ", need " + str(wantlen) + ".") 153 return x
154
155 -def matrix_to_list(m):
156 return [m[i] for i in range(len(m))]
157
158 -def list_to_matrix(m, n, l):
159 if len(l) != m*n: 160 raise ValueError("Invalid sizes: %d * %d != %d" % (m, n, l)) 161 return swiginac.matrix(m, n, l)
162
163 -def list_to_vector(l):
164 return swiginac.matrix(len(l), 1, l)
165
166 -def is_function(f):
167 return hasattr(f, 'func_name')
168
169 -def is_functor(f):
170 if hasattr(f, 'func_name'): 171 return False 172 return hasattr(f, '__call__')
173
174 -def get_func_code(f):
175 """Get the func_code object from a function or functor object.""" 176 if not callable(f): 177 raise RuntimeError("Object is not callable!") 178 fc = None 179 if is_function(f): 180 fc = f.func_code 181 if is_functor(f): 182 fc = f.__call__.im_func.func_code 183 return fc
184
185 -def get_callable_name(f):
186 return get_func_code(f).co_name
187
188 -def get_callable_num_args(f):
189 return get_func_code(f).co_argcount
190