001/* An actor that sorts the elements of an array.
002
003 Copyright (c) 2003-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;
028
029import java.util.ArrayList;
030
031import ptolemy.data.ArrayToken;
032import ptolemy.data.BooleanToken;
033import ptolemy.data.Token;
034import ptolemy.data.expr.Parameter;
035import ptolemy.data.expr.UtilityFunctions;
036import ptolemy.data.type.ArrayType;
037import ptolemy.data.type.BaseType;
038import ptolemy.data.type.Type;
039import ptolemy.kernel.CompositeEntity;
040import ptolemy.kernel.util.IllegalActionException;
041import ptolemy.kernel.util.NameDuplicationException;
042import ptolemy.kernel.util.Workspace;
043
044///////////////////////////////////////////////////////////////////
045//// ArraySort
046
047/**
048 Sort the elements of an input array.  This actor reads an array from the
049 <i>input</i> port and sends a sorted array to the <i>output</i> port.
050 The input array is required to contain either strings or non-complex
051 scalars, or a type error will occur. The output array will have the
052 same type as the input and can can be sorted in either ascending or
053 descending order. Duplicate entries can be optionally removed.
054
055 @author Mark Oliver, Edward A. Lee
056 @version $ID: ArraySort.java,v1.0 2003/07/09
057 @since Ptolemy II 4.0
058 @Pt.ProposedRating Red (cxh)
059 @Pt.AcceptedRating Red (cxh)
060 */
061public class ArraySort extends Transformer {
062    /** Construct an actor with the given container and name.
063     *  @param container The container.
064     *  @param name The name of this actor.
065     *  @exception IllegalActionException If the actor cannot be contained
066     *   by the proposed container.
067     *  @exception NameDuplicationException If the container already has an
068     *   actor with this name.
069     */
070    public ArraySort(CompositeEntity container, String name)
071            throws NameDuplicationException, IllegalActionException {
072        super(container, name);
073
074        // Set Type Constraints.
075        input.setTypeAtLeast(ArrayType.ARRAY_BOTTOM);
076        output.setTypeAtLeast(input);
077        // FIXME: correct type constraint for length
078        output.setTypeAtLeast(ArrayType.ARRAY_UNSIZED_BOTTOM);
079
080        // NOTE: Consider constraining input element types.
081        // This is a bit complicated to do, however.
082        // Set Parameters.
083        allowDuplicates = new Parameter(this, "allowDuplicates");
084        allowDuplicates.setExpression("true");
085        allowDuplicates.setTypeEquals(BaseType.BOOLEAN);
086
087        ascending = new Parameter(this, "ascending");
088        ascending.setExpression("true");
089        ascending.setTypeEquals(BaseType.BOOLEAN);
090    }
091
092    ///////////////////////////////////////////////////////////////////
093    ////                     ports and parameters                  ////
094
095    /** Tells the actor whether or not to remove duplicate elements.
096     *  This is a boolean that defaults to true.
097     */
098    public Parameter allowDuplicates;
099
100    /** The sort order attribute.  This tells the actor whether to
101     *  sort the elements in ascending or descending order. It is a
102     *  boolean that defaults to true, which means ascending order.
103     */
104    public Parameter ascending;
105
106    ///////////////////////////////////////////////////////////////////
107    ////                         public methods                    ////
108
109    /** Override the base class to set type constraints.
110     *  @param workspace The workspace for the new object.
111     *  @return A new instance of ArrayElement.
112     *  @exception CloneNotSupportedException If a derived class contains
113     *   an attribute that cannot be cloned.
114     */
115    @Override
116    public Object clone(Workspace workspace) throws CloneNotSupportedException {
117        ArraySort newObject = (ArraySort) super.clone(workspace);
118        newObject.input.setTypeAtLeast(ArrayType.ARRAY_BOTTOM);
119        newObject.output.setTypeAtLeast(newObject.input);
120        newObject.output.setTypeAtLeast(ArrayType.ARRAY_UNSIZED_BOTTOM);
121        return newObject;
122    }
123
124    /** Consume at most one array from the input port and produce
125     *  a sorted array on the <i>output</i> port.
126     *  If there is no token on the input, then no output is produced.
127     *  If the input is an empty array, then the same empty array token
128     *  is produced on the output.
129     *  @exception IllegalActionException If there is no director, or
130     *   if sorting is not supported for the input array.
131     */
132    @Override
133    public void fire() throws IllegalActionException {
134        super.fire();
135        if (input.hasToken(0)) {
136            ArrayToken token = (ArrayToken) input.get(0);
137            Type inputElementType = token.getElementType();
138            if (token.length() == 0) {
139                output.send(0, token);
140                return;
141            }
142
143            boolean ascendingValue = ((BooleanToken) ascending.getToken())
144                    .booleanValue();
145            ArrayToken result = null;
146
147            try {
148                if (ascendingValue) {
149                    result = UtilityFunctions.sort(token);
150                } else {
151                    result = UtilityFunctions.sortDescending(token);
152                }
153            } catch (ClassCastException ex) {
154                // The call to sort() above throws ClassCastException if
155                // sorting is not supported.  This is not ideal, so we
156                // remap this to IllegalActionException.
157                throw new IllegalActionException(this, ex.getMessage());
158            }
159
160            boolean allowDuplicatesValue = ((BooleanToken) allowDuplicates
161                    .getToken()).booleanValue();
162
163            if (!allowDuplicatesValue) {
164                // Strip out duplicates.
165                ArrayList list = new ArrayList();
166                Token previous = result.getElement(0);
167                list.add(previous);
168
169                for (int i = 1; i < result.length(); i++) {
170                    Token next = result.getElement(i);
171
172                    if (!next.isEqualTo(previous).booleanValue()) {
173                        list.add(next);
174                        previous = next;
175                    }
176                }
177
178                // Dummy array to give the run-time type to toArray().
179                Token[] dummy = new Token[0];
180                result = new ArrayToken(inputElementType,
181                        (Token[]) list.toArray(dummy));
182            }
183
184            output.send(0, result);
185        }
186    }
187}