Class FunUtil

  • Direct Known Subclasses:
    FunDefBase, MultiResolver, ResolverBase

    public class FunUtil
    extends Util
    FunUtil contains a set of methods useful within the mondrian.olap.fun package.
    Since:
    1.0
    Author:
    jhyde
    • Field Detail

      • emptyStringArray

        static final String[] emptyStringArray
      • NullMember

        public static final mondrian.olap.fun.FunUtil.NullMember NullMember
      • DoubleNull

        public static final double DoubleNull
        Special value which indicates that a double computation has returned the MDX null value. See DoubleCalc.
        See Also:
        Constant Field Values
      • DoubleEmpty

        public static final double DoubleEmpty
        Special value which indicates that a double computation has returned the MDX EMPTY value. See DoubleCalc.
        See Also:
        Constant Field Values
      • IntegerNull

        public static final int IntegerNull
        Special value which indicates that an int computation has returned the MDX null value. See IntegerCalc.
        See Also:
        Constant Field Values
      • BooleanNull

        public static final boolean BooleanNull
        Null value in three-valued boolean logic. Actually, a placeholder until we actually implement 3VL.
        See Also:
        Constant Field Values
    • Constructor Detail

      • FunUtil

        public FunUtil()
    • Method Detail

      • newEvalException

        public static RuntimeException newEvalException​(FunDef funDef,
                                                        String message)
        Creates an exception which indicates that an error has occurred while executing a given function.
        Parameters:
        funDef - Function being executed
        message - Explanatory message
        Returns:
        Exception that can be used as a cell result
      • newEvalException

        public static RuntimeException newEvalException​(Throwable throwable)
        Creates an exception which indicates that an error has occurred while executing a given function.
        Parameters:
        throwable - Exception
        Returns:
        Exception that can be used as a cell result
      • newEvalException

        public static RuntimeException newEvalException​(String message,
                                                        Throwable throwable)
        Creates an exception which indicates that an error has occurred while executing a given function.
        Parameters:
        message - Explanatory message
        throwable - Exception
        Returns:
        Exception that can be used as a cell result
      • checkIterListResultStyles

        public static void checkIterListResultStyles​(Calc calc)
      • checkListResultStyles

        public static void checkListResultStyles​(Calc calc)
      • getLiteralArg

        static String getLiteralArg​(ResolvedFunCall call,
                                    int i,
                                    String defaultValue,
                                    String[] allowedValues)
        Returns an argument whose value is a literal.
      • getLiteralArg

        static <E extends Enum<E>> E getLiteralArg​(ResolvedFunCall call,
                                                   int i,
                                                   E defaultValue,
                                                   Class<E> allowedValues)
        Returns the ordinal of a literal argument. If the argument does not belong to the supplied enumeration, returns -1.
      • checkCompatible

        static void checkCompatible​(Exp left,
                                    Exp right,
                                    FunDef funDef)
        Throws an error if the expressions don't have the same hierarchy.
        Throws:
        MondrianEvaluationException - if expressions don't have the same hierarchy
      • addUnique

        static void addUnique​(TupleList left,
                              TupleList right,
                              Set<List<Member>> set)
        Adds every element of right which is not in set to both set and left.
      • removeCalculatedMembers

        static List<Member> removeCalculatedMembers​(List<Member> memberList)
        Removes every member from a list which is calculated. The list must not be null, and must consist only of members.
        Parameters:
        memberList - Member list
        Returns:
        List of non-calculated members
      • removeCalculatedMembers

        static TupleList removeCalculatedMembers​(TupleList memberList)
        Removes every tuple from a list which is calculated. The list must not be null, and must consist only of members.
        Parameters:
        memberList - Member list
        Returns:
        List of non-calculated members
      • isAncestorOf

        static boolean isAncestorOf​(Member m0,
                                    Member m1,
                                    boolean strict)
        Returns whether m0 is an ancestor of m1.
        Parameters:
        strict - if true, a member is not an ancestor of itself
      • evaluateMembers

        static Map<Member,​Object> evaluateMembers​(Evaluator evaluator,
                                                        Calc exp,
                                                        Iterable<Member> memberIter,
                                                        List<Member> memberList,
                                                        boolean parentsToo)
        For each member in a list, evaluates an expression and creates a map from members to values.

        If the list contains tuples, use evaluateTuples(mondrian.olap.Evaluator, mondrian.calc.Calc, mondrian.calc.TupleList).

        Parameters:
        evaluator - Evaluation context
        exp - Expression to evaluate
        memberIter - Iterable over the collection of members
        memberList - List to be populated with members, or null
        parentsToo - If true, evaluate the expression for all ancestors of the members as well
        Pre-condition:
        exp != null, exp.getType() instanceof ScalarType
      • evaluateTuples

        static Map<List<Member>,​Object> evaluateTuples​(Evaluator evaluator,
                                                             Calc exp,
                                                             TupleList tuples)
        For each tuple in a list, evaluates an expression and creates a map from tuples to values.
        Parameters:
        evaluator - Evaluation context
        exp - Expression to evaluate
        tuples - List of tuples
        Pre-condition:
        exp != null, exp.getType() instanceof ScalarType
      • sortMembers

        static List<Member> sortMembers​(Evaluator evaluator,
                                        Iterable<Member> memberIter,
                                        List<Member> memberList,
                                        Calc exp,
                                        boolean desc,
                                        boolean brk)
        Helper function to sort a list of members according to an expression.

        NOTE: This function does not preserve the contents of the validator.

        If you do not specify memberList, the method will build its own member list as it iterates over memberIter. It is acceptable if memberList and memberIter are the same list object.

        If you specify memberList, the list is sorted in place, and memberList is returned.

        Parameters:
        evaluator - Evaluator
        memberIter - Iterable over members
        memberList - List of members
        exp - Expression to sort on
        desc - Whether to sort descending
        brk - Whether to break
        Returns:
        sorted list (never null)
      • sortMembers

        static List<Member> sortMembers​(Evaluator evaluator,
                                        Iterable<Member> memberIter,
                                        List<Member> memberList,
                                        List<FunUtil.SortKeySpec> keySpecList)
        Sorts a list of members according to a list of SortKeySpecs. An in-place, Stable sort. Helper function for MDX OrderSet function.

        NOTE: Does not preserve the contents of the validator.

      • sortTuples

        public static TupleList sortTuples​(Evaluator evaluator,
                                           TupleIterable tupleIterable,
                                           TupleList tupleList,
                                           Calc exp,
                                           boolean desc,
                                           boolean brk,
                                           int arity)
        Sorts a list of Tuples by the value of an applied expression. Stable sort.

        Helper function for MDX functions TopCount, TopSum, TopPercent, BottomCount, BottomSum, BottomPercent, but not the MDX function Order.

        NOTE: This function does not preserve the contents of the validator.

        If you specify tupleList, the list is sorted in place, and tupleList is returned.

        Parameters:
        evaluator - Evaluator
        tupleIterable - Iterator over tuples
        tupleList - List of tuples, if known, otherwise null
        exp - Expression to sort on
        desc - Whether to sort descending
        brk - Whether to break
        arity - Number of members in each tuple
        Returns:
        sorted list (never null)
      • partiallySortMembers

        public static List<Member> partiallySortMembers​(Evaluator evaluator,
                                                        List<Member> list,
                                                        Calc exp,
                                                        int limit,
                                                        boolean desc)
        Partially sorts a list of Members by the value of an applied expression.

        Avoids sorting the whole list, finds only the ntop (or bottom) valued Members, and returns them as a new List. Helper function for MDX functions TopCount and BottomCount.

        NOTE: Does not preserve the contents of the validator.

        Parameters:
        list - a list of members
        exp - a Calc applied to each member to find its sort-key
        evaluator - Evaluator
        limit - maximum count of members to return.
        desc - true to sort descending (and find TopCount), false to sort ascending (and find BottomCount).
        Returns:
        the top or bottom members, as a new list.
      • sortTuples

        static TupleList sortTuples​(Evaluator evaluator,
                                    TupleIterable tupleIter,
                                    TupleList tupleList,
                                    List<FunUtil.SortKeySpec> keySpecList,
                                    int arity)
        Helper function to sort a list of tuples according to a list of expressions and a list of sorting flags.

        NOTE: This function does not preserve the contents of the validator.

      • partiallySortTuples

        public static List<List<Member>> partiallySortTuples​(Evaluator evaluator,
                                                             TupleList list,
                                                             Calc exp,
                                                             int limit,
                                                             boolean desc)
        Partially sorts a list of Tuples by the value of an applied expression.

        Avoids sorting the whole list, finds only the n top (or bottom) valued Tuples, and returns them as a new List. Helper function for MDX functions TopCount and BottomCount.

        NOTE: Does not preserve the contents of the validator. The returned list is immutable.

        Parameters:
        evaluator - Evaluator
        list - a list of tuples
        exp - a Calc applied to each tuple to find its sort-key
        limit - maximum count of tuples to return.
        desc - true to sort descending (and find TopCount), false to sort ascending (and find BottomCount).
        Returns:
        the top or bottom tuples, as a new list.
      • hierarchizeMemberList

        public static void hierarchizeMemberList​(List<Member> memberList,
                                                 boolean post)
        Sorts a list of members into hierarchical order. The members must belong to the same dimension.
        Parameters:
        memberList - List of members
        post - Whether to sort in post order; if false, sorts in pre order
        See Also:
        hierarchizeTupleList(mondrian.calc.TupleList, boolean)
      • hierarchizeTupleList

        public static TupleList hierarchizeTupleList​(TupleList tupleList,
                                                     boolean post)
        Sorts a list of tuples into hierarchical order.
        Parameters:
        tupleList - List of tuples
        post - Whether to sort in post order; if false, sorts in pre order
        See Also:
        hierarchizeMemberList(java.util.List, boolean)
      • compareValues

        public static int compareValues​(double d1,
                                        double d2)
        Compares double-precision values according to MDX semantics.

        MDX requires a total order:

        -inf < NULL < ... < -1 < ... < 0 < ... < NaN < +inf
        but this is different than Java semantics, specifically with regard to Double.NaN.
      • compareValues

        public static int compareValues​(Object value0,
                                        Object value1)
        Compares two cell values.

        Nulls compare last, exceptions (including the object which indicates the the cell is not in the cache yet) next, then numbers and strings are compared by value.

        Parameters:
        value0 - First cell value
        value1 - Second cell value
        Returns:
        -1, 0, or 1, depending upon whether first cell value is less than, equal to, or greater than the second
      • toPercent

        static void toPercent​(TupleList members,
                              Map<List<Member>,​Object> mapMemberToValue)
        Turns the mapped values into relative values (percentages) for easy use by the general topOrBottom function. This might also be a useful function in itself.
      • decodeSyntacticType

        public static Syntax decodeSyntacticType​(String flags)
        Decodes the syntactic type of an operator.
        Parameters:
        flags - A encoded string which represents an operator signature, as used by the flags parameter used to construct a FunDefBase.
        Returns:
        A Syntax
      • decodeReturnCategory

        public static int decodeReturnCategory​(String flags)
        Decodes the signature of a function into a category code which describes the return type of the operator.

        For example, decodeReturnType("fnx") returns Category.Numeric, indicating this function has a numeric return value.

        Parameters:
        flags - The signature of an operator, as used by the flags parameter used to construct a FunDefBase.
        Returns:
        An array Category codes.
      • decodeParameterCategories

        public static int[] decodeParameterCategories​(String flags)
        Decodes a string of parameter types into an array of type codes.

        Each character is decoded using decodeCategory(String, int). For example, decodeParameterTypes("nx") returns {Category.Numeric, Category.Set}.

        Parameters:
        flags - The signature of an operator, as used by the flags parameter used to construct a FunDefBase.
        Returns:
        An array Category codes.
      • box

        public static Double box​(double d)
        Converts a double (primitive) value to a Double. DoubleNull becomes null.
      • box

        public static Integer box​(int n)
        Converts an int (primitive) value to an Integer. IntegerNull becomes null.
      • quartile

        protected static double quartile​(Evaluator evaluator,
                                         TupleList members,
                                         Calc exp,
                                         int range)
        Returns the member which lies upon a particular quartile according to a given expression.
        Parameters:
        evaluator - Evaluator
        members - List of members
        exp - Expression to rank members
        range - Quartile (1, 2 or 3)
        Pre-condition:
        range >= 1 && range <= 3
      • evaluateSet

        static FunUtil.SetWrapper[] evaluateSet​(Evaluator evaluator,
                                                TupleList list,
                                                DoubleCalc[] calcs)
        Evaluates one or more expressions against the member list returning a SetWrapper array. Where this differs very significantly from the above evaluateSet methods is how it count null values and Throwables; this method adds nulls to the SetWrapper Vector rather than not adding anything - as the above method does. The impact of this is that if, for example, one was creating a list of x,y values then each list will have the same number of values (though some might be null) - this allows higher level code to determine how to handle the lack of data rather than having a non-equal number (if one is plotting x,y values it helps to have the same number and know where a potential gap is the data is.
      • cousin

        static Member cousin​(SchemaReader schemaReader,
                             Member member,
                             Member ancestorMember)
        Returns the member under ancestorMember having the same relative position under member's parent.

        For exmaple, cousin([Feb 2001], [Q3 2001]) is [August 2001].

        Parameters:
        schemaReader - The reader to use
        member - The member for which we'll find the cousin.
        ancestorMember - The cousin's ancestor.
        Returns:
        The child of ancestorMember in the same position under ancestorMember as member is under its parent.
      • ancestor

        static Member ancestor​(Evaluator evaluator,
                               Member member,
                               int distance,
                               Level targetLevel)
        Returns the ancestor of member at the given level or distance. It is assumed that any error checking required has been done prior to calling this function.

        This method takes into consideration the fact that there may be intervening hidden members between member and the ancestor. If targetLevel is not null, then the method will only return a member if the level at distance from the member is actually the targetLevel specified.

        Parameters:
        evaluator - The evaluation context
        member - The member for which the ancestor is to be found
        distance - The distance up the chain the ancestor is to be found.
        targetLevel - The desired targetLevel of the ancestor. If null, then the distance completely determines the desired ancestor.
        Returns:
        The ancestor member, or null if no such ancestor exists.
      • compareHierarchically

        public static int compareHierarchically​(Member m1,
                                                Member m2,
                                                boolean post)
        Compares a pair of members according to their positions in a prefix-order (or postfix-order, if post is true) walk over a hierarchy.
        Parameters:
        m1 - First member
        m2 - Second member
        post - Whether to sortMembers in postfix order. If true, a parent will sortMembers immediately after its last child. If false, a parent will sortMembers immediately before its first child.
        Returns:
        -1 if m1 collates before m2, 0 if m1 equals m2, 1 if m1 collates after m2
      • compareSiblingMembers

        public static int compareSiblingMembers​(Member m1,
                                                Member m2)
        Compares two members which are known to have the same parent. First, compare by ordinal. This is only valid now we know they're siblings, because ordinals are only unique within a parent. If the dimension does not use ordinals, both ordinals will be -1.

        If the ordinals do not differ, compare using regular member comparison.

        Parameters:
        m1 - First member
        m2 - Second member
        Returns:
        -1 if m1 collates less than m2, 1 if m1 collates after m2, 0 if m1 == m2.
      • tupleContainsNullMember

        public static boolean tupleContainsNullMember​(Member[] tuple)
        Returns whether one of the members in a tuple is null.
      • tupleContainsNullMember

        public static boolean tupleContainsNullMember​(List<Member> tuple)
        Returns whether one of the members in a tuple is null.
      • makeNullTuple

        public static Member[] makeNullTuple​(TupleType tupleType)
      • resolveFunArgs

        public static FunDef resolveFunArgs​(Validator validator,
                                            FunDef funDef,
                                            Exp[] args,
                                            Exp[] newArgs,
                                            String name,
                                            Syntax syntax)
        Validates the arguments to a function and resolves the function.
        Parameters:
        validator - Validator used to validate function arguments and resolve the function
        funDef - Function definition, or null to deduce definition from name, syntax and argument types
        args - Arguments to the function
        newArgs - Output parameter for the resolved arguments
        name - Function name
        syntax - Syntax style used to invoke function
        Returns:
        resolved function definition
      • equalTuple

        static boolean equalTuple​(Member[] members0,
                                  Member[] members1)
        Returns whether two tuples are equal.

        The members are allowed to be in different positions. For example, ([Gender].[M], [Store].[USA]) IS ([Store].[USA], [Gender].[M]) returns true.

      • createDummyFunDef

        static FunDef createDummyFunDef​(Resolver resolver,
                                        int returnCategory,
                                        Exp[] args)
      • getNonEmptyMemberChildrenWithDetails

        public static Map<Member,​Access> getNonEmptyMemberChildrenWithDetails​(Evaluator evaluator,
                                                                                    Member member)
      • getNonEmptyLevelMembers

        static List<Member> getNonEmptyLevelMembers​(Evaluator evaluator,
                                                    Level level,
                                                    boolean includeCalcMembers)
        Returns members of a level which are not empty (according to the criteria expressed by the evaluator).
        Parameters:
        evaluator - Evaluator, determines non-empty criteria
        level - Level
        includeCalcMembers - Whether to include calculated members
      • partialSort

        static <T> void partialSort​(T[] items,
                                    Comparator<T> comp,
                                    int limit)
        Partial Sort: sorts in place an array of Objects using a given Comparator, but only enough so that the N biggest (or smallest) items are at the start of the array. Not a stable sort, unless the Comparator is so contrived.
        Parameters:
        items - will be partially-sorted in place
        comp - a Comparator; null means use natural comparison
      • stablePartialSort

        public static <T> List<T> stablePartialSort​(List<T> list,
                                                    Comparator<T> comp,
                                                    int limit)
        Stable partial sort of a list. Returns the desired head of the list.
      • stablePartialSort

        public static <T> List<T> stablePartialSort​(List<T> list,
                                                    Comparator<T> comp,
                                                    int limit,
                                                    int algorithm)
        Stable partial sort of a list, using a specified algorithm.
      • stablePartialSortArray

        public static <T> List<T> stablePartialSortArray​(List<T> list,
                                                         Comparator<T> comp,
                                                         int limit)
        Partial sort an array by sorting it and returning the first limit elements. Fastest approach if limit is a significant fraction of the list.
      • stablePartialSortPedro

        public static <T> List<T> stablePartialSortPedro​(List<T> list,
                                                         Comparator<T> comp,
                                                         int limit)
        Pedro's algorithm for stably sorting the top limit items in a list.
      • stablePartialSortJulian

        public static <T> List<T> stablePartialSortJulian​(List<T> list,
                                                          Comparator<T> comp,
                                                          int limit)
        Julian's algorithm for stable partial sort. Improves Pedro's algorithm by using a heap (priority queue) for the top limit items seen. The items on the priority queue have an ordinal field, so the queue can be used to generate a list of stably sorted items. (Heap sort is not normally stable.)
        Type Parameters:
        T - Element type
        Parameters:
        list - List to sort
        comp - Comparator
        limit - Maximum number of items to return
        Returns:
        Sorted list, containing at most limit items
      • parseTuple

        static Member[] parseTuple​(Evaluator evaluator,
                                   String string,
                                   List<Hierarchy> hierarchies)
        Parses a tuple, such as "([Gender].[M], [Marital Status].[S])".
        Parameters:
        evaluator - Evaluator, provides a SchemaReader and Cube
        string - String to parse
        hierarchies - Hierarchies of the members
        Returns:
        Tuple represented as array of members
      • worthCaching

        public static boolean worthCaching​(Exp exp)
        Returns whether an expression is worth wrapping in "Cache( ... )".
        Parameters:
        exp - Expression
        Returns:
        Whether worth caching