Debian Codegraph @

src/drel/drel_runtime.py

raw symbols SCIP
1 # Runtime functions for dREL.
2 #
3 # dREL defines some original semantics for vector and matrix appending and removing. We implement
4 # the necessary functions here.
5 #
6 #
7 # <*>=
8 import numpy
9 from numpy.linalg import eig
10
11 # Python3 compatibility
12 if isinstance(u"abc",str): #Python 3
13 unicode = str
14
15 # Augmented assignments. aug_append returns a new object. For numpy, if
16 # both arrays have the same dimensions, they are reshaped to a
17 # larger dimension and then concatenated along the
18 # new axis. If the first array has a larger dimension, the second array is
19 # reshaped to match.
20 #
21 #
22 # <Augmented assignments>=
23 def aug_append(current,extra):
24 """Add the contents of extra to current"""
25 have_list = isinstance(current,list)
26 if have_list:
27 if not isinstance(extra, list):
28 #append a single element
29 return current + [extra]
30 else:
31 newlist = current[:]
32 newlist.append(extra)
33 return newlist
34 elif isinstance(current,numpy.ndarray):
35 if current.ndim == extra.ndim + 1:
36 extra = numpy.expand_dims(extra,axis=0)
37 elif current.ndim == extra.ndim:
38 extra = numpy.expand_dims(extra,axis=0)
39 current = numpy.expand_dims(current,axis=0)
40 else:
41 raise ValueError('Arrays have mismatching sizes for concatenating: %d and %d' % (current.ndim,extra.ndim))
42 return numpy.concatenate((current,extra))
43 raise ValueError("Cannot append %s to %s" % (repr(extra),repr(current)))
44
45 def aug_add(current,extra):
46 """Sum the contents of extra to current"""
47 have_list = isinstance(current,list)
48 if have_list:
49 if isinstance(extra, (float,int)):
50 # requires numpy
51 return numpy.array(current) + extra
52 elif isinstance(extra, list):
53 return numpy.array(current) + numpy.array(extra)
54 else:
55 return current + extra
56
57 def aug_sub(current,extra):
58 have_list = isinstance(current,(list,numpy.ndarray))
59 if have_list:
60 if isinstance(extra, (float,int)):
61 # requires numpy
62 return numpy.array(current) - extra
63 elif isinstance(extra, (list,numpy.ndarray)):
64 return numpy.array(current) - numpy.array(extra)
65 else:
66 return current - extra
67
68 def aug_remove(current,extra):
69 """Remove extra from current. Not in formal
70 specifications. Allowed to fail silently."""
71 have_list = isinstance(current,list)
72 if have_list:
73 if extra in current:
74 # not efficient as we modify in place here
75 current.remove(extra)
76 return current
77 else:
78 print('Removal Warning: %s not in %s' % (repr(extra),repr(current)))
79 return current
80 else:
81 raise ValueError("Cannot remove %s from %s" % (repr(extra),repr(current)))
82
83 # Multiplication requires some intelligence. The rules of dREL are as follows:
84 # (1) mat * mat, vec*mat is ordinary matrix multiplication
85 # (2) vec * vec is a dot product (i.e. second vector is column)
86 # (3) mat * vec is matrix multiplication with vec as a column vector
87 #
88 # dREL has 'Array' and 'Matrix' containers. An array container only allows
89 # element-wise operations, whereas matrix containers (implicitly 2-dimensional)
90 # have matrix multiplication defined for them.
91 #
92 # While the dREL specs are not explicit about this, matrix multiplication only
93 # makes sense for 2-dimensional objects, although the DDLm type known as 'matrix'
94 # describes arbitrary tensors (ddl.dic). We explicitly check that the objects
95 # that are passed to this routine satisfy the requirements, i.e. any dimension
96 # three or more object does not have multiplication defined except by a scalar.
97 #
98 # As numpy will always return a 2-dim matrix as a result, even if it is
99 # a scalar, we detect scalars and return them as such. We also must
100 # detect vectors and return them as a 1D array, so that
101 # vector-based operations can work generically. Otherwise we have the
102 # case where the second element is accessed (see function Symop for an
103 # example) and an error results, as for a vector in numpy
104 # 2D representation this element does not exist.
105 #
106 # We also attempt to maintain type when converting to/from numpy, as some
107 # routines (e.g. Symop) wish to create strings out of integers using the
108 # backtick operator.
109 #
110 #
111 # <Mathematical operators>=
112 def drel_dot(first_arg,second_arg):
113 """Perform a multiplication on two unknown types"""
114 print("Multiply %s and %s" % (repr(first_arg),repr(second_arg)))
115 def make_numpy(input_arg):
116 if hasattr(input_arg,'__iter__'):
117 try:
118 return numpy.matrix(input_arg),True
119 except ValueError:
120 raise ValueError('Attempt to multiply non-matrix object %s' % (repr(input_arg)))
121 return input_arg,False
122 fa,first_matrix = make_numpy(first_arg)
123 sa,second_matrix = make_numpy(second_arg)
124 if first_matrix and second_matrix: #mult of 2 non-scalars
125 if sa.shape[0] == 1: #is a row vector
126 as_column = sa.T
127 result = (fa * as_column).T
128 else:
129 result = fa * sa
130 # detect scalars
131 if result.size == 1:
132 return result.item(0)
133 # remove extra dimension
134 elif result.ndim == 2 and 1 in result.shape: #vector
135 return numpy.array(result).squeeze()
136 else:
137 return result
138 return fa * sa
139
140 def drel_add(first_arg,second_arg):
141 """Separate string addition from the rest"""
142 if isinstance(first_arg,(unicode,str)) and isinstance(second_arg,(unicode,str)):
143 return first_arg+second_arg
144 else:
145 result = numpy.add(first_arg,second_arg)
146 return result
147
148
149 # Other mathematical functions. dREL defines some linear algebra type functions,
150 # which we have to wrap because e.g. the eigenvalues should be sorted. Note that we
151 # are assuming the right eigenvalues, not the left eigenvalues.
152 #
153 #
154 # <Extra mathematical functions>=
155 def drel_eigen(in_matrix):
156 """Return 3 lists of form [a,v1,v2,v3], corresponding to the 3 eigenvalues
157 and eigenvector components of a 3x3 matrix"""
158 vals,vects = eig(in_matrix)
159 move = list(numpy.argsort(vals))
160 move.reverse()
161 vals = vals[move]
162 vects = vects[move]
163 vects = list([[a]+list(numpy.asarray(v).ravel()) for a,v in zip(vals,vects)]) #Eigen returns 4-list
164 return vects
165
166 def drel_int(in_val):
167 """Return in_val as an integer"""
168 try:
169 return in_val.astype('int')
170 except:
171 return int(in_val)
172
173 # List operations. We deduce that Strip actually returns the nth
174 # element of each list element (??) based on its use in the model_site
175 # category functions.
176 #
177 #
178 # <List operations>=
179 def drel_strip(in_list,element):
180 """Return the nth element from the list"""
181 return [a[element] for a in in_list]
182