001/* An actor that dynamically applies functions to its input.
002
003 Copyright (c) 2004-2014 The Regents of the University of California.
004 All rights reserved.
005 Permission is hereby granted, without written agreement and without
006 license or royalty fees, to use, copy, modify, and distribute this
007 software and its documentation for any purpose, provided that the above
008 copyright notice and the following two paragraphs appear in all copies
009 of this software.
010
011 IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
012 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
013 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
014 THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
015 SUCH DAMAGE.
016
017 THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
018 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
019 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
020 PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
021 CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
022 ENHANCEMENTS, OR MODIFICATIONS.
023
024 PT_COPYRIGHT_VERSION_2
025 COPYRIGHTENDKEY
026 */
027package ptolemy.actor.lib.hoc;
028
029import java.util.Iterator;
030
031import ptolemy.actor.TypedAtomicActor;
032import ptolemy.actor.TypedIOPort;
033import ptolemy.actor.parameters.PortParameter;
034import ptolemy.data.BooleanToken;
035import ptolemy.data.FunctionToken;
036import ptolemy.data.Token;
037import ptolemy.data.expr.SingletonParameter;
038import ptolemy.data.type.BaseType;
039import ptolemy.data.type.FunctionType;
040import ptolemy.data.type.MonotonicFunction;
041import ptolemy.data.type.Type;
042import ptolemy.graph.InequalityTerm;
043import ptolemy.kernel.CompositeEntity;
044import ptolemy.kernel.util.IllegalActionException;
045import ptolemy.kernel.util.NameDuplicationException;
046import ptolemy.kernel.util.Workspace;
047
048///////////////////////////////////////////////////////////////////
049//// ApplyFunction
050
051/**
052 This actor applies a function to its inputs and outputs the
053 results. But rather than has the function specified statically,
054 this actor allows dynamic change to the function, which means the
055 computation of this actor can be changed during executing. Its
056 second input accept a function token for the new function's
057 definition. The function token can be given by actors in the local
058 model or remote actors.
059
060 @author Steve Neuendorffer, Yang Zhao
061 @version $Id$
062 @since Ptolemy II 4.1
063 @Pt.ProposedRating Red (eal)
064 @Pt.AcceptedRating Red (reviewmoderator)
065 */
066public class ApplyFunction extends TypedAtomicActor {
067    /** Construct a ApplyFunction in the specified workspace with
068     *  no container and an empty string as a name. You can then change
069     *  the name with setName(). If the workspace argument is null, then
070     *  use the default workspace.
071     *  @param workspace The workspace that will list the actor.
072     *  @exception IllegalActionException If the entity cannot be contained
073     *   by the proposed container.
074     *  @exception NameDuplicationException If the container already has an
075     *   actor with this name.
076     */
077    public ApplyFunction(Workspace workspace)
078            throws IllegalActionException, NameDuplicationException {
079        super(workspace);
080        output = new TypedIOPort(this, "output", false, true);
081        function = new PortParameter(this, "function");
082        new SingletonParameter(function, "_showName")
083                .setToken(BooleanToken.TRUE);
084    }
085
086    /** Construct a ApplyFunction with a name and a container.
087     *  The container argument must not be null, or a
088     *  NullPointerException will be thrown.
089     *  @param container The container.
090     *  @param name The name of this actor.
091     *  @exception IllegalActionException If the container is incompatible
092     *   with this actor.
093     *  @exception NameDuplicationException If the name coincides with
094     *   an actor already in the container.
095     */
096    public ApplyFunction(CompositeEntity container, String name)
097            throws IllegalActionException, NameDuplicationException {
098        super(container, name);
099        output = new TypedIOPort(this, "output", false, true);
100        function = new PortParameter(this, "function");
101
102        output.setTypeAtLeast(new ReturnTypeFunction());
103    }
104
105    ///////////////////////////////////////////////////////////////////
106    ////                         public variables                  ////
107
108    /** The input port for function definition. The type of this port is
109     *  undeclared, but to have this actor work, the designer has to provide
110     *  a matched function token for it.
111     *  Note: The reason that we don't declare the type for it is because
112     *  currently there is not cast supported in the FunctionType class.
113     *  we'll fix this later.
114     */
115    public PortParameter function;
116
117    /** The output port.
118     */
119    public TypedIOPort output;
120
121    ///////////////////////////////////////////////////////////////////
122    ////                         public methods                    ////
123
124    /** Clone the actor into the specified workspace. This calls the
125     *  base class and then sets the type of the output port of the
126     *  new object.
127     *  @param workspace The workspace for the new object.
128     *  @return A new actor.
129     *  @exception CloneNotSupportedException If a derived class contains
130     *   an attribute that cannot be cloned.
131     */
132    @Override
133    public Object clone(Workspace workspace) throws CloneNotSupportedException {
134        ApplyFunction newObject = (ApplyFunction) super.clone(workspace);
135        newObject.output.setTypeAtLeast(new ReturnTypeFunction());
136        return newObject;
137    }
138
139    /** If the function is not specified, then perform identity function;
140     *  otherwise, apply the specified function to its input and output
141     *  the result.
142     *  @exception IllegalActionException If there is no director, or if
143     *   the director's fire() method throws it, or if the actor is not
144     *   opaque.
145     */
146    @Override
147    public void fire() throws IllegalActionException {
148        super.fire();
149
150        // Update the function parameterPort.
151        function.update();
152
153        FunctionToken functionValue = (FunctionToken) function.getToken();
154        Token[] arguments = new Token[inputPortList().size() - 1];
155        int i = 0;
156        Iterator ports = inputPortList().iterator();
157
158        // Skip the function port.
159        ports.next();
160
161        while (ports.hasNext()) {
162            TypedIOPort port = (TypedIOPort) ports.next();
163            arguments[i++] = port.get(0);
164        }
165
166        Token t = functionValue.apply(arguments);
167        output.broadcast(t);
168    }
169
170    /** Return true if the actor either of its input port has token.
171     *  @exception IllegalActionException Not thrown in this base class.
172     */
173    @Override
174    public boolean prefire() throws IllegalActionException {
175        super.prefire();
176
177        Iterator ports = inputPortList().iterator();
178
179        // Skip the function port.
180        ports.next();
181
182        while (ports.hasNext()) {
183            TypedIOPort port = (TypedIOPort) ports.next();
184
185            if (!port.hasToken(0)) {
186                return false;
187            }
188        }
189
190        return true;
191    }
192
193    ///////////////////////////////////////////////////////////////////
194    ////                         inner classes                     ////
195
196    /** Montonic function of the function parameter that return
197     *  unknown if the function is unknown, the return type of
198     *  the function if the function is known and is a function,
199     *  and throws an exception otherwise.
200     */
201    private class ReturnTypeFunction extends MonotonicFunction {
202
203        @Override
204        public Object getValue() throws IllegalActionException {
205            Type functionType = function.getType();
206            if (functionType.equals(BaseType.UNKNOWN)) {
207                return BaseType.UNKNOWN;
208            }
209            if (functionType instanceof FunctionType) {
210                return ((FunctionType) functionType).getReturnType();
211            }
212            throw new IllegalActionException(ApplyFunction.this,
213                    "function is not a function. It is a " + functionType);
214        }
215
216        @Override
217        public InequalityTerm[] getVariables() {
218            InequalityTerm[] result = new InequalityTerm[1];
219            result[0] = function.getTypeTerm();
220            return result;
221        }
222    }
223}