001/* A base class for cached analyzers on graphs.
002
003 Copyright (c) 2003-2014 The University of Maryland. All rights reserved.
004 Permission is hereby granted, without written agreement and without
005 license or royalty fees, to use, copy, modify, and distribute this
006 software and its documentation for any purpose, provided that the above
007 copyright notice and the following two paragraphs appear in all copies
008 of this software.
009
010 IN NO EVENT SHALL THE UNIVERSITY OF MARYLAND BE LIABLE TO ANY PARTY
011 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
012 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
013 THE UNIVERSITY OF MARYLAND HAS BEEN ADVISED OF THE POSSIBILITY OF
014 SUCH DAMAGE.
015
016 THE UNIVERSITY OF MARYLAND SPECIFICALLY DISCLAIMS ANY WARRANTIES,
017 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
018 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
019 PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
020 MARYLAND HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
021 ENHANCEMENTS, OR MODIFICATIONS.
022
023 */
024package ptolemy.graph.analysis.strategy;
025
026import ptolemy.graph.Graph;
027import ptolemy.graph.analysis.analyzer.GraphAnalyzer;
028
029///////////////////////////////////////////////////////////////////
030//// CachedStrategy
031
032/**
033 A base class for cached analyzers on graphs. To facilitate demand-driven
034 and incremental recomputation (e.g., see [1]) of analyzers, analyzer results
035 are cached internally (see {@link #getCachedResult()}), and are recomputed only
036 when the graph has changed since the last request (via {@link #_result()}) for
037 the strategy result.
038 The status of the cache content can be queried with the {@link #obsolete()}
039 method to determine if a subsequent invocation of {@link #_result()} by the
040 derived classes will trigger recomputation of the analysis.
041 <p>
042 The graph changes tracked by an analyzer are restricted to changes in the
043 graph topology (the set of nodes and edges). For example, changes to edge/node
044 weights that may affect the result of an analysis are not tracked, since
045 analyzers have no specific knowledge of weights.  In such cases, it is the
046 responsibility of the client (or derived analyzer class) to invalidate the
047 cached result (see {@link #reset()}) when changes to graph weights or other
048 non-topology information render the cached result obsolete.  For this reason,
049 some caution is generally required when using analyzers whose results depend on
050 more than just the graph topology.<p>
051 In these cases the client should check for data consistency
052 (through the {@link #valid()} method) as well as changes in them and
053 calling the {@link #reset()} method in case of data changes.
054
055 <p> [1] G. Ramalingam. <em>Bounded Incremental Computation</em>. PhD thesis,
056 University of Wisconsin at Madison, August 1993.
057 @since Ptolemy II 4.0
058 @Pt.ProposedRating Red (cxh)
059 @Pt.AcceptedRating Red (cxh)
060 @author Shuvra S. Bhattacharyya, Ming Yung Ko and Shahrooz Shahparnia
061 @version $Id$
062 */
063abstract public class CachedStrategy extends Strategy implements GraphAnalyzer {
064    /** No instance of this object can be created as it is abstract.
065     *  The derived classes will use it to initialize its internal data
066     *  structures.
067     *
068     *  @param graph The graph which the analyzer is using to compute its
069     *  result.
070     */
071    public CachedStrategy(Graph graph) {
072        _graph = graph;
073        reset();
074    }
075
076    ///////////////////////////////////////////////////////////////////
077    ////                         public methods                    ////
078
079    /** Return the caching status of the strategy.
080     *
081     *  @return True if caching is enabled (default on instantiation)
082     */
083    public boolean cachingStatus() {
084        return _cachingEnabled;
085    }
086
087    /** Disable caching.
088     *
089     */
090    public void disableCaching() {
091        _cachingEnabled = false;
092    }
093
094    /** Enable caching.
095     *
096     */
097    public void enableCaching() {
098        _cachingEnabled = true;
099    }
100
101    /** The result of the most recent cached computation of the analysis,
102     *  as determined by {@link #_compute()}, and without
103     *  conversion by {@link #_convertResult(Object)}.
104     *  @return The result of the most recent cached computation.
105     *  @see #setCachedResult(CachedStrategy)
106     */
107    public Object getCachedResult() {
108        return _cachedResult;
109    }
110
111    /** The graph associated with the Strategy. This association is made
112     *  when the Strategy is constructed.
113     *
114     *  @return The input graph.
115     */
116    @Override
117    public Graph graph() {
118        return _graph;
119    }
120
121    /** Test whether or not the cached result of the analyzer is
122     *  obsolete relative to the associated graph. In other words, test if the
123     *  graph has changed
124     *  since the last time the analyzer was executed with an enabled cache
125     *  (i.e., since the most recent invocation of {@link #_result()}).
126     *  If the cached result is obsolete and the cache is enabled,
127     *  then a subsequent invocation of {@link #_result()}
128     *  will trigger recomputation of the analysis.
129     *  @return True if the cached result is obsolete relative to the
130     *  associated graph.
131     */
132    public boolean obsolete() {
133        return _lastComputation < graph().changeCount();
134    }
135
136    /** Reset the analyzer to invalidate any cached value (i.e., to force
137     *  recomputation the next time a result of the computation is needed).
138     */
139    public void reset() {
140        _lastComputation = -1;
141    }
142
143    /** Set the cached value of this analyzer to the cached value of another
144     *  analyzer.
145     *  @param cacher The other analyzer.
146     *  @see #getCachedResult()
147     */
148    public void setCachedResult(CachedStrategy cacher) {
149        _cachedResult = cacher.getCachedResult();
150    }
151
152    /** Return a description of the strategy.
153     *
154     * @return Return a description of the strategy.
155     */
156    @Override
157    public String toString() {
158        return "Cached strategy.";
159    }
160
161    ///////////////////////////////////////////////////////////////////
162    ////                         protected methods                 ////
163
164    /** Perform the graph analysis and return the resulting value.
165     *  Upon entry, {@link #getCachedResult()} provides the result of the
166     *  previous invocation of the analysis; this value can be
167     *  used, for example, to facilitate incremental analyses.
168     *  This method just returns null, and will typically be overridden
169     *  in each derived class to perform the appropriate graph analysis.
170     *  @return The results of the graph analysis.  In this base class,
171     *  null is returned.
172     */
173    protected Object _compute() {
174        return null;
175    }
176
177    /** Convert the cached result ({@link #getCachedResult()})
178     *  to a form that is
179     *  suitable for the client to access (via {@link #_result()}).
180     *  This base class method just returns a reference to the cached result.
181     *  However, it may be appropriate for derived classes to override this
182     *  method. For example, if the object returned by the analyzer is mutable,
183     *  one may wish to override this method to copy the cached
184     *  value (or convert it to some other form) before returning it.
185     *  Then changes made by the client to the returned value will
186     *  not affect the cached value in the analysis.
187     *  This consideration is important for incremental analyzers that
188     *  use the cached value across successive invocations of the
189     *  analyzer.
190     *  @param result The cached result to be converted.
191     *  @return The form suitable for access via {@link #_result()}.
192     */
193    protected Object _convertResult(Object result) {
194        return result;
195    }
196
197    /** Return the result (cached value) of the analyzer on the associated
198     *  graph. The cached value is updated, through recomputation of
199     *  the analysis (using {@link #_compute()}), if the graph
200     *  has changed since the last time {@link #_result()} was invoked.
201     *  Otherwise, the cache value is simply returned (in <em>O</em>(1) time).
202     *
203     *  @return The result of the analysis.
204     */
205    protected final Object _result() {
206        // Finality of this method is required to ensure analyzer computation
207        // only happens when the graph changes, as specified in the
208        // contract of the method comment. (when caching is on)
209        Object result = null;
210
211        if (_cachingEnabled && obsolete()) {
212            _cachedResult = _compute();
213            _registerComputation();
214            result = _cachedResult;
215        } else if (_cachingEnabled) {
216            result = _cachedResult;
217        } else {
218            // Do not call _registerComputation to keep the obsolete status as
219            // it is.
220            result = _compute();
221        }
222
223        return _convertResult(result);
224    }
225
226    ///////////////////////////////////////////////////////////////////
227    ////                         private methods                   ////
228
229    /** Notify the analyzer that the associated computation has been
230     *  performed. This method should be called immediately after
231     *  any invocation of the computation, if caching is enabled and the graph
232     *  is changed.
233     */
234    private void _registerComputation() {
235        _lastComputation = graph().changeCount();
236    }
237
238    ///////////////////////////////////////////////////////////////////
239    ////                         private variables                 ////
240    // The result of the most recent computation of the analysis, as determined
241    // by _compute(), and without conversion by _convertResult().
242    private Object _cachedResult = null;
243
244    // The graph that this analysis is associated with.
245    private Graph _graph;
246
247    // The change count of the associated graph that was in effect when the
248    // the analysis was last performed.
249    private long _lastComputation;
250
251    private boolean _cachingEnabled = true;
252}