- Timestamp:
- 08/28/08 06:04:03 (3 months ago)
- Files:
-
- trunk/openopt/scikits/openopt/Kernel/Function.py (modified) (9 diffs)
- trunk/openopt/scikits/openopt/Kernel/objFunRelated.py (modified) (10 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
trunk/openopt/scikits/openopt/Kernel/Function.py
r1230 r1233 2 2 # created by Dmitrey 3 3 #from numpy import copy, isnan, array, argmax, abs, zeros 4 from numpy import inf, asfarray, copy, all, any, empty, atleast_2d, zeros, dot, asarray, atleast_1d, empty, ones 4 from numpy import inf, asfarray, copy, all, any, empty, atleast_2d, zeros, dot, asarray, atleast_1d, empty, ones, ndarray 5 5 from oologfcn import OpenOptException 6 6 from copy import deepcopy … … 11 11 input = None # if None then x will be used 12 12 13 # finite-difference aproximation step 14 diffInt = 1.5e-8 15 13 16 def __init__(self, fun, *args, **kwargs): 14 17 assert len(args) == 0 … … 27 30 self.inputTotalLength = None 28 31 return None 29 elif not type(self.input) in (list, tuple):30 self.input = (self.input, )32 elif type(self.input) != list: 33 self.input = [self.input] 31 34 r = [] 32 35 self.inputTotalLength = 0 … … 38 41 else: r.append(item()) 39 42 self.inputTotalLength += r[-1].size 40 return tuple(r)43 return r 41 44 42 45 def __getDep__(self): … … 47 50 else: 48 51 r = empty(self.x.size, bool).fill(False) 49 if not type(self.input) in (list, tuple):50 self.input = (self.input, )52 if type(self.input) != list: 53 self.input = [self.input] 51 54 for oofunInstance in self.input: 52 55 if not hasattr(oofunInstance, 'x'): … … 60 63 if r is not None: 61 64 self.dep = where(r)[0] 62 else:63 self.dep = None64 65 return self.dep 65 66 … … 85 86 else: 86 87 self.f_val_prev = asfarray(self.fun(Input)) 88 self.outputTotalLength = self.f_val_prev.size # TODO: omit reassigning 87 89 self.f_key_prev = copy(key_to_compare) 88 90 else: … … 96 98 97 99 def __d(self, x=None): 100 98 101 if x is None: x = self.x 99 102 else: self.x = x 103 104 if not hasattr(self, 'outputTotalLength'): 105 self.__getFunc__(x) 100 106 101 107 dep = self.__getDep__() … … 109 115 110 116 if hasattr(self, 'd'): 111 #derivativeSelf = atleast_2d(self.d(*Input))112 117 derivativeSelf = atleast_2d(self.d(*Input)) 113 118 else: 119 derivativeSelf = zeros((self.outputTotalLength, self.inputTotalLength)) 120 agregate_counter = 0 121 val_0 = self.__getFunc__(x) 122 # TODO: mb copy self.input to prevent numerical noise -> other values -> recalculate self.__getFunc__ 123 if self.input is not None: 124 125 # !!! enumerate() returns copy and hence is unsuitable here 126 for i in xrange(len(Input)): 127 inp = Input[i] 128 129 assert asarray(inp).ndim <= 1 130 if type(inp) in (ndarray, tuple, list): 131 for j in xrange(len(inp)): # TODO: handle Python dict, mb Python class here 132 Input[i][j] += self.diffInt 133 v = atleast_1d(self.fun(*Input)) 134 Input[i][j] -= self.diffInt 135 else: 136 # TODO: ASSERT isscalar(Input[i]) 137 Input[i] += self.diffInt 138 v = atleast_1d(self.fun(*Input)) 139 Input[i] -= self.diffInt 140 derivativeSelf[agregate_counter:agregate_counter+v.shape[0]] = (v-val_0) / self.diffInt 141 agregate_counter += v.shape[0] 142 else: 143 raise 'not implemented yet' 144 pass 145 #handle dep here 146 147 148 114 149 #TODO: add numerical derivative here 115 raise OpenOptException('finite-difference derivatives aproximations for obj-funcs are not implemented yet')150 #raise OpenOptException('finite-difference derivatives aproximations for obj-funcs are not implemented yet') 116 151 117 152 ########################## 118 153 if not hasattr(self, 'd_key_prev') or any(self.d_key_prev != key_to_compare): 119 154 if self.input is not None: 120 if not hasattr(self, 'f_val_prev'):121 self.__getFunc__(x)122 123 r = zeros((self.f_val_prev.size, x.size))124 125 155 ######################################## 126 156 agregate_counter = 0 trunk/openopt/scikits/openopt/Kernel/objFunRelated.py
r1230 r1233 47 47 if p.invertObjFunc and userFunctionType=='f': r = -r 48 48 return r 49 50 51 # if not getDerivative and prevKey is not None and p.iter > 0 and all(x.shape == prevKey.shape) and all(x == prevKey) and ind is None and not ignorePrev:52 # #TODO: add counter of the situations53 # assert p.prevVal[userFunctionType]['val'] is not None54 # r = copy(p.prevVal[userFunctionType]['val'])55 # if ind is not None: r = r[ind]56 # if p.invertObjFunc and userFunctionType=='f': r = -r57 # return r58 59 49 60 50 args = getattr(p.args, userFunctionType) … … 80 70 setattr(p, 'n' + userFunctionType, number) 81 71 if p.functype[userFunctionType] == 'block': 82 #setattr(p, 'arr_of_lengths_' + userFunctionType, array(arr))83 72 setattr(p, 'arr_of_indexes_' + userFunctionType, array(arr)-1) 84 73 elif p.x0 is not None: … … 94 83 p.prevVal[userFunctionType]['val'] = zeros(getattr(p, 'n'+userFunctionType)) 95 84 96 # condSequentialConstraints = p.consMode == 'sequential' and userFunctionType== 'c'97 #98 # if condSequentialConstraints:99 # if ind is not None and len(ind)>1:100 # p.err('error in sequential constraints mode, inform developers')101 # else:102 # nFuncs = 1103 # elif104 105 85 if ind is None: 106 86 nFuncsToObtain = getattr(p, 'n'+ userFunctionType) … … 122 102 else: 123 103 r = zeros((nFuncsToObtain, nXvectors)) 124 125 DerivativeByObject = False126 104 127 105 extractInd = None … … 170 148 if objectFlag: 171 149 Args = () 172 #v = atleast_1d(asfarray(fun(*((x,) + args)))).flatten()173 150 else: 174 151 Args = args 175 152 176 153 if R is None: 177 v = atleast_1d(asfarray(fun(*((x,) + Args)))).flatten()154 v = ravel(fun(*((x,) + Args))) 178 155 if extractInd is not None: v = v[extractInd] 179 156 if doInplaceCut: v = v[ind] … … 183 160 p.prevVal[userFunctionType]['val'][agregate_counter:agregate_counter+v.size] = v 184 161 185 ############ geting derivatives #################162 """ geting derivatives """ 186 163 if getDerivative: 187 164 diffInt = copy(p.diffInt) … … 201 178 else: 202 179 finiteDiffNumber = p.diffInt[i] 180 203 181 x[i] += finiteDiffNumber 204 v = atleast_1d(asfarray(fun(*((x,) + getattr(p.args, userFunctionType))))).flatten() 182 183 v = ravel(fun(*((x,) + getattr(p.args, userFunctionType)))) 205 184 206 185 assert not (extractInd is not None and doInplaceCut) … … 215 194 x[i] -= finiteDiffNumber 216 195 217 # ##############218 # r44 = r.copy()219 # for i in xrange(p.n):220 # if p.diffInt.size == 1:221 # finiteDiffNumber = p.diffInt[0]222 # else:223 # finiteDiffNumber = p.diffInt[i]224 # x[i] += finiteDiffNumber225 # v = atleast_1d(asfarray(fun(*((x,) + getattr(p.args, userFunctionType))))).flatten()226 #227 # assert not (extractInd is None and doInplaceCut)228 #229 # if extractInd is not None: v = v[extractInd]230 # if doInplaceCut: v = v[ind]231 # if i == derivativeInd[0]:232 # r[agregate_counter:agregate_counter+v.size, :] = 0233 # if R is not None: r0 = R[agregate_counter:agregate_counter+v.size]234 # r44[agregate_counter:agregate_counter+v.size, i] = v - r0#[agregate_counter:agregate_counter+v.size]235 #236 # x[i] -= finiteDiffNumber237 # if p.norm(r.flatten() - r44.flatten()): print r.flatten(), r44.flatten(), '\n-----------------'238 # if p.norm(r.flatten() - r44.flatten())>1:239 # pass240 # ##############241 242 196 if p.diffInt.size > 1: 243 197 if extractInd is not None: diffInt = diffInt[extractInd] … … 246 200 else: 247 201 for i in xrange(nXvectors): # TODO: add vectoriezed case 248 v = atleast_1d(asfarray(fun(*((x[:,i],) + getattr(p.args, userFunctionType))))).flatten()202 v = ravel(fun(*((x[:,i],) + getattr(p.args, userFunctionType)))) 249 203 if i==0 and (ind is None or len(funcs)==1) and not ignorePrev: 250 204 p.prevVal[userFunctionType]['val'][agregate_counter:agregate_counter+v.size] = v … … 253 207 r[agregate_counter:agregate_counter+v.size,i] = v 254 208 255 256 #if condSequentialConstraints and any(r > p.contol): break257 209 agregate_counter += atleast_1d(asarray(v)).shape[0] 258 259 260 210 261 211 # if getDerivative and result_need_div_diffInt:
