source: branches/collapse/collapse_termination.py @ 855

Revision 855, 11.7 KB checked in by mmckerns, 5 months ago (diff)

updated copyright to 2016

Line 
1#!/usr/bin/env python
2#
3# Author: Lan Huong Nguyen (lanhuong @stanford)
4# Copyright (c) 2012-2016 California Institute of Technology.
5# License: 3-clause BSD.  The full license text is available at:
6#  - http://mmckerns.github.io/project/mystic/browser/mystic/LICENSE
7
8debug = False #True
9
10def CLPS_Weight(npts, tol_weight=0.05, generations=200, axisW = '', \
11                indexW = ''):
12    """ Termination condition for vanishing weights.
13    if info = False:
14       returns true if the weight for any points collapsed
15    if info = True:
16       prints out a message saying for which points the weight vanished
17       
18    In this code, weight collapse is the event where the weight of a support
19    point (its maximum accros last given number of generations) has been
20    less than or equal to the tollerance level, tol_weight.
21   
22    If axisW and index are not declared, the function returns whenever weight
23    has vanished for any point. If declared (axisW and index are tuple or
24    integer objects) then the function returns only if collapse had occured f
25    or points with given indices. Note that neither or both axisW and indexW
26    must be declared, otherwise an error is printed.
27   
28    npts = (nx, ny, ...) is the tuple of the support point numbers for each
29    input."""
30    # from mystic.tools import isNull
31    from mystic.monitors import Null, Monitor, VerboseMonitor
32    monitor = Monitor()
33    if debug: monitor = VerboseMonitor(2, 2)
34     
35
36    def _CLPS_Weight(inst, info=False):
37        ###FIXME: this should probably be in Solver #######
38        # if isNull(inst._stepmon): inst._stepmon = monitor
39        ###################################################
40       
41        ######################## TO BE DELETED##################################
42        #print "HERE I AM and the last 10 best solutions are: "
43        #print inst._stepmon.x[-10:]
44        ########################################################################         
45       
46        ############## PARAMETERS (length, and number of emasures) #############
47        hist_lg = len(inst._stepmon.x)
48        if hist_lg <= generations: return False
49       
50        from mystic.math.measures import _nested_split   
51        w_bestSolution, x_bestSolution = \
52                _nested_split(inst.bestSolution, npts)
53        ########################################################################
54        collapseWeight_msg = ''
55               
56        if isinstance(axisW, int) and isinstance(indexW, int):
57            max_weight = 0
58            for n in range(-generations, 0):
59                weights, positions = _nested_split(inst._stepmon.x[n], npts)
60                if max_weight < weights[axisW][indexW]:
61                    max_weight = weights[axisW][indexW]
62            if max_weight <= tol_weight:
63                collapseWeight_msg += 'measure: %s & index: %s, ' \
64                %(axisW,indexW)               
65           
66        elif isinstance(axisW, tuple) and isinstance(indexW, int):
67            max_weight = [0]*len(axisW)
68           
69            for n in range(-generations, 0):
70                weights, positions = _nested_split(inst._stepmon.x[n], npts)
71                for i in range(len(max_weight)):
72                    if max_weight[i] < weights[axisW[i]][indexW]:
73                        max_weight[i] = weights[axisW[i]][indexW]
74            for k in range(len(max_weight)):
75                if max_weight[k] <= tol_weight:
76                    collapseWeight_msg += 'measure: %s & index: %s, ' \
77                    %(axisW[k],indexW)   
78                   
79        elif isinstance(axisW, int) and isinstance(indexW, tuple):
80            max_weight = [0]*len(indexW)
81                       
82            for n in range(-generations, 0):
83                weights, positions = _nested_split(inst._stepmon.x[n], npts)
84                for i in range(len(max_weight)):
85                    if max_weight[i] < weights[axisW][indexW[i]]:
86                        max_weight[i] = weights[axisW][indexW[i]]
87            for k in range(len(max_weight)):
88                if max_weight[k] <= tol_weight:
89                    collapseWeight_msg += 'measure: %s & index: %s, ' \
90                    %(axisW,indexW[k])
91                   
92        elif (isinstance(axisW, tuple) and isinstance(indexW, tuple)) or \
93            (axisW == '' and indexW == ''): #Note that can't change to not axisW
94                                            # and not indexW since those can be zero indices
95            if (axisW == '' and indexW == ''):
96                max_weight = [[0] * nx for nx in npts]
97            else:
98                max_weight = [[0]*len(axisW)]*len(indexW)
99               
100            for n in range(-generations, 0):
101                weights, positions = _nested_split(inst._stepmon.x[n], npts)
102               
103                for i in range(len(max_weight)):   
104                    for j in range(len(max_weight[i])):
105                        if (axisW =='' and indexW == ''):
106                            if  max_weight[i][j] < weights[i][j]:
107                                max_weight[i][j] = weights[i][j]
108                        else:
109                            if  max_weight[i][j] < weights[axisW[i]][index[j]]:
110                                max_weight[i][j] = weights[axisW[i]][index[j]]
111                                           
112            for k in range(len(max_weight)):
113                for l in range(len(max_weight[k])):
114                    if max_weight[k][l] <= tol_weight:
115                        if (axisW == '' and indexW == ''):
116                            collapseWeight_msg += 'measure: %s & index: %s, ' \
117                            %(k,l)
118                        else:                           
119                            collapseWeight_msg += 'measure: %s & index: %s, ' \
120                            %(axisW[k],indexW[l])
121                           
122        else:
123            print 'Error, wrong arguments of CLPS_Weight'
124            return False
125                                               
126        if info:
127            if collapseWeight_msg == '': msg = ''
128            else:
129                msg0 = 'CLPS_Weight with: '
130                msg = msg0 + collapseWeight_msg
131                msg2 = msg0 + '\n npts = %s, tol_weight = %s, generations = %s: \n' \
132                % (npts, tol_weight, generations)
133                msg2 += 'vanishing weights of support points: '
134                msg2 += collapseWeight_msg
135                if debug: print msg2
136            return msg
137
138        if collapseWeight_msg == '': return False
139        else: return True
140   
141    return _CLPS_Weight
142           
143   
144                       
145def CLPS_Position(npts, tol_position, generations=200, axisP = '', \
146                  index1 = '', index2 = ''):
147   
148    """ Termination condition for collapsing positions of support points.
149    if info = False:
150       returns true if the positions collapse for any 2 support
151       points in a measure
152    if info = True:
153       prints out a message saying for which point-pairs the location collapsed.
154   
155    In this code, collapse is the event where the distance between 2 support
156    points (its maximum accros last given number of generations) has been
157    less than the tollerance level, tol_position.
158   
159    If axisP and index1 and index2 are not declared, the function returns
160    whenever any 2 points collapse in position. If declared (axisP is a tuple
161    or and integer, index1 and index2 are integers) then the function returns
162    only if collapse had occured for points with given indices.
163   
164    npts = (nx, ny, ...) is the tuple of the support point numbers for each
165    input."""
166   
167    from mystic.tools import isNull
168    from mystic.monitors import Null, Monitor, VerboseMonitor
169    monitor = Monitor()
170    if debug: monitor = VerboseMonitor(2, 2)
171   
172    # CHECK THAT index1, and index2 are integers if declared, and either none or
173    # both are empty
174   
175    def _CLPS_Position(inst, info=False):
176        ###FIXME: this should probably be in Solver #######
177        if isNull(inst._stepmon): inst._stepmon = monitor
178        ###################################################
179
180        ############## PARAMETERS (length, and number of emasures) #############
181        hist_lg = len(inst._stepmon)
182        if hist_lg <= generations: return False
183       
184        from mystic.math.measures import _nested_split 
185        w_bestSolution, x_bestSolution = \
186                _nested_split(inst.bestSolution, npts)
187       
188        if axisP == '':
189            dim = len(w_bestSolution) # Number of measures
190            axis = range(dim)
191        else:
192            axis = axisP           
193            if isinstance( axisP, int ): dim  = 1
194            else: dim = len(list(axisP))
195       
196        ########################################################################
197        collapsePairs_msg  = ''     
198       
199        from numpy import array, zeros, ones, transpose           
200        for i in range(dim):
201            if isinstance(axis, int): ax_idx = axis
202            else: ax_idx = axis[i]
203                       
204            if isinstance(index1, int):
205                if isinstance(index2, int):
206                    nx = 1
207                    max_measure_diffLoc = 0
208                else:
209                    print "Error argument declaration index2 is \
210                    empty while index1 is not"
211                    return False   #FIXME
212            else:
213                if isinstance(index2, int):
214                    print "Error argument declaration index1 is \
215                    empty while index2 is not"
216                    return False   #FIXME
217                else:
218                    nx = npts[ax_idx]
219                    max_measure_diffLoc = zeros((nx, nx))     
220                           
221            for n in range(-generations, 0):
222                weights, positions = _nested_split(inst._stepmon.x[n], npts)
223                if nx == 1:                       
224                    diffLoc = abs(positions[ax_idx][index1] - \
225                                  positions[ax_idx][index2])
226                    if max_measure_diffLoc < diffLoc:
227                                            max_measure_diffLoc= diffLoc                     
228                else:
229                    diffLoc = abs(transpose(positions[ax_idx]*ones((nx, nx))) - \
230                                      positions[ax_idx]*ones((nx, nx)))                                     
231                    for k in range(nx):
232                        for l in range(nx):
233                            if max_measure_diffLoc[(k, l)] < diffLoc[(k, l)]:
234                                max_measure_diffLoc[(k, l)] = diffLoc[(k, l)]
235
236            if nx ==1 and max_measure_diffLoc <= tol_position[ax_idx]:
237                    collapsePairs_msg += ('measure: %s & indices: (%s,%s),'\
238                                          %(ax_idx,index1,index2))
239               
240            else:           
241                for k in range(nx):
242                    for l in range(k,nx):
243                        if k != l and max_measure_diffLoc[(k,l)] <= \
244                           tol_position[ax_idx]:
245                            collapsePairs_msg += ('measure: %s & indices: (%s,%s),' \
246                            %(ax_idx,k,l))
247   
248        if info:
249            if collapsePairs_msg == '': msg = ''
250            else:
251                msg0 = 'CLPS_Position with: '
252                msg = msg0 + collapsePairs_msg
253                msg2 = msg0 + '\n npts = %s, tol_position = %s, generations = %s:\n' \
254                % (npts, tol_position, generations)
255                msg2 += 'collapse of support points: '
256                msg2 += collapsePairs_msg
257                if debug: print msg2
258            return msg
259       
260        if collapsePairs_msg == '': return False
261        else: return True
262   
263    return _CLPS_Position
264       
265
Note: See TracBrowser for help on using the repository browser.