Changeset 1233 for trunk

Show
Ignore:
Timestamp:
08/28/08 06:04:03 (3 months ago)
Author:
dmitrey.kroshko
Message:

some changes for oofun recursive derivatives

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/openopt/scikits/openopt/Kernel/Function.py

    r1230 r1233  
    22# created by Dmitrey 
    33#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 
     4from numpy import inf, asfarray, copy, all, any, empty, atleast_2d, zeros, dot, asarray, atleast_1d, empty, ones, ndarray 
    55from oologfcn import OpenOptException 
    66from copy import deepcopy 
     
    1111    input = None # if None then x will be used 
    1212 
     13    # finite-difference aproximation step 
     14    diffInt = 1.5e-8 
     15 
    1316    def __init__(self, fun, *args, **kwargs): 
    1417        assert len(args) == 0 
     
    2730            self.inputTotalLength = None 
    2831            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] 
    3134        r = [] 
    3235        self.inputTotalLength = 0 
     
    3841            else:  r.append(item()) 
    3942            self.inputTotalLength += r[-1].size 
    40         return tuple(r) 
     43        return r 
    4144 
    4245    def __getDep__(self): 
     
    4750        else: 
    4851            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] 
    5154            for oofunInstance in self.input: 
    5255                if not hasattr(oofunInstance, 'x'): 
     
    6063            if r is not None: 
    6164                self.dep = where(r)[0] 
    62             else: 
    63                 self.dep = None 
    6465        return self.dep 
    6566 
     
    8586            else: 
    8687                self.f_val_prev = asfarray(self.fun(Input)) 
     88            self.outputTotalLength = self.f_val_prev.size # TODO: omit reassigning 
    8789            self.f_key_prev = copy(key_to_compare) 
    8890        else: 
     
    9698 
    9799    def __d(self, x=None): 
     100 
    98101        if x is None: x = self.x 
    99102        else: self.x = x 
     103 
     104        if not hasattr(self, 'outputTotalLength'): 
     105            self.__getFunc__(x) 
    100106 
    101107        dep = self.__getDep__() 
     
    109115 
    110116        if hasattr(self, 'd'): 
    111             #derivativeSelf = atleast_2d(self.d(*Input)) 
    112117            derivativeSelf = atleast_2d(self.d(*Input)) 
    113118        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 
    114149            #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') 
    116151 
    117152        ########################## 
    118153        if not hasattr(self, 'd_key_prev') or any(self.d_key_prev != key_to_compare): 
    119154            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  
    125155                ######################################## 
    126156                agregate_counter = 0 
  • trunk/openopt/scikits/openopt/Kernel/objFunRelated.py

    r1230 r1233  
    4747                if p.invertObjFunc and userFunctionType=='f': r = -r 
    4848                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 situations 
    53 #            assert p.prevVal[userFunctionType]['val'] is not None 
    54 #            r = copy(p.prevVal[userFunctionType]['val']) 
    55 #            if ind is not None: r = r[ind] 
    56 #            if p.invertObjFunc and userFunctionType=='f': r = -r 
    57 #            return r 
    58  
    5949 
    6050        args = getattr(p.args, userFunctionType) 
     
    8070                setattr(p, 'n' + userFunctionType, number) 
    8171                if p.functype[userFunctionType] == 'block': 
    82                     #setattr(p, 'arr_of_lengths_' + userFunctionType, array(arr)) 
    8372                    setattr(p, 'arr_of_indexes_' + userFunctionType, array(arr)-1) 
    8473            elif p.x0 is not None: 
     
    9483            p.prevVal[userFunctionType]['val'] = zeros(getattr(p, 'n'+userFunctionType)) 
    9584 
    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 = 1 
    103 #        elif 
    104  
    10585        if ind is None: 
    10686            nFuncsToObtain = getattr(p, 'n'+ userFunctionType) 
     
    122102        else: 
    123103            r = zeros((nFuncsToObtain, nXvectors)) 
    124  
    125         DerivativeByObject = False 
    126104 
    127105        extractInd = None 
     
    170148                if objectFlag: 
    171149                    Args = () 
    172                     #v = atleast_1d(asfarray(fun(*((x,) + args)))).flatten() 
    173150                else: 
    174151                    Args = args 
    175152 
    176153                if R is None: 
    177                     v = atleast_1d(asfarray(fun(*((x,) + Args)))).flatten(
     154                    v = ravel(fun(*((x,) + Args))
    178155                    if extractInd is not None:  v = v[extractInd] 
    179156                    if doInplaceCut: v = v[ind] 
     
    183160                        p.prevVal[userFunctionType]['val'][agregate_counter:agregate_counter+v.size] = v 
    184161 
    185                 ############   geting derivatives  ################# 
     162                """                                                 geting derivatives                                                 """ 
    186163                if getDerivative: 
    187164                    diffInt = copy(p.diffInt) 
     
    201178                        else: 
    202179                            finiteDiffNumber = p.diffInt[i] 
     180 
    203181                        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)))) 
    205184 
    206185                        assert not (extractInd is not None and doInplaceCut) 
     
    215194                        x[i] -= finiteDiffNumber 
    216195 
    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] += finiteDiffNumber 
    225 #                            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, :] = 0 
    233 #                                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] -= finiteDiffNumber 
    237 #                        if p.norm(r.flatten() - r44.flatten()): print r.flatten(),  r44.flatten(), '\n-----------------' 
    238 #                        if p.norm(r.flatten() - r44.flatten())>1: 
    239 #                            pass 
    240 #                        ############## 
    241  
    242196                    if p.diffInt.size > 1: 
    243197                        if extractInd is not None: diffInt = diffInt[extractInd] 
     
    246200            else: 
    247201                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)))
    249203                    if i==0 and (ind is None or len(funcs)==1) and not ignorePrev: 
    250204                        p.prevVal[userFunctionType]['val'][agregate_counter:agregate_counter+v.size] = v 
     
    253207                    r[agregate_counter:agregate_counter+v.size,i] = v 
    254208 
    255  
    256             #if condSequentialConstraints and any(r > p.contol): break 
    257209            agregate_counter += atleast_1d(asarray(v)).shape[0] 
    258  
    259  
    260210 
    261211#        if getDerivative and result_need_div_diffInt: