diff --git a/.gitattributes b/.gitattributes index f531008552388fc64ac694b1f679e9d01625df1c..ec1ecbc059acbddcf85e78268de70e2b69bf956d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -551,3 +551,15 @@ falcon/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvese falcon/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text evalkit_tf437/lib/python3.10/site-packages/transformers/__pycache__/modeling_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text evalkit_tf437/lib/python3.10/site-packages/pyarrow/libarrow_python.so filter=lfs diff=lfs merge=lfs -text +evalkit_tf437/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/tree/_tree.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/tree/_splitter.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/svm/_libsvm_sparse.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/tree/_criterion.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_lloyd.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/accelerate/__pycache__/accelerator.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fffd8364effc85d3dcb6d96e3bef4da78d5262c4 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..723c136ef44418b2aab76965f2cacf68504336ff Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/baseclasses.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cddf1649285dfd76435a67a0487f1b24982b8aa Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/__pycache__/diagram_drawing.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/baseclasses.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/baseclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ab5153ae4e95f193030864c8f32a52254f2458 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/baseclasses.py @@ -0,0 +1,978 @@ +from sympy.core import S, Basic, Dict, Symbol, Tuple, sympify +from sympy.core.symbol import Str +from sympy.sets import Set, FiniteSet, EmptySet +from sympy.utilities.iterables import iterable + + +class Class(Set): + r""" + The base class for any kind of class in the set-theoretic sense. + + Explanation + =========== + + In axiomatic set theories, everything is a class. A class which + can be a member of another class is a set. A class which is not a + member of another class is a proper class. The class `\{1, 2\}` + is a set; the class of all sets is a proper class. + + This class is essentially a synonym for :class:`sympy.core.Set`. + The goal of this class is to assure easier migration to the + eventual proper implementation of set theory. + """ + is_proper = False + + +class Object(Symbol): + """ + The base class for any kind of object in an abstract category. + + Explanation + =========== + + While technically any instance of :class:`~.Basic` will do, this + class is the recommended way to create abstract objects in + abstract categories. + """ + + +class Morphism(Basic): + """ + The base class for any morphism in an abstract category. + + Explanation + =========== + + In abstract categories, a morphism is an arrow between two + category objects. The object where the arrow starts is called the + domain, while the object where the arrow ends is called the + codomain. + + Two morphisms between the same pair of objects are considered to + be the same morphisms. To distinguish between morphisms between + the same objects use :class:`NamedMorphism`. + + It is prohibited to instantiate this class. Use one of the + derived classes instead. + + See Also + ======== + + IdentityMorphism, NamedMorphism, CompositeMorphism + """ + def __new__(cls, domain, codomain): + raise(NotImplementedError( + "Cannot instantiate Morphism. Use derived classes instead.")) + + @property + def domain(self): + """ + Returns the domain of the morphism. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> f = NamedMorphism(A, B, "f") + >>> f.domain + Object("A") + + """ + return self.args[0] + + @property + def codomain(self): + """ + Returns the codomain of the morphism. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> f = NamedMorphism(A, B, "f") + >>> f.codomain + Object("B") + + """ + return self.args[1] + + def compose(self, other): + r""" + Composes self with the supplied morphism. + + The order of elements in the composition is the usual order, + i.e., to construct `g\circ f` use ``g.compose(f)``. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> g * f + CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"), + NamedMorphism(Object("B"), Object("C"), "g"))) + >>> (g * f).domain + Object("A") + >>> (g * f).codomain + Object("C") + + """ + return CompositeMorphism(other, self) + + def __mul__(self, other): + r""" + Composes self with the supplied morphism. + + The semantics of this operation is given by the following + equation: ``g * f == g.compose(f)`` for composable morphisms + ``g`` and ``f``. + + See Also + ======== + + compose + """ + return self.compose(other) + + +class IdentityMorphism(Morphism): + """ + Represents an identity morphism. + + Explanation + =========== + + An identity morphism is a morphism with equal domain and codomain, + which acts as an identity with respect to composition. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, IdentityMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> f = NamedMorphism(A, B, "f") + >>> id_A = IdentityMorphism(A) + >>> id_B = IdentityMorphism(B) + >>> f * id_A == f + True + >>> id_B * f == f + True + + See Also + ======== + + Morphism + """ + def __new__(cls, domain): + return Basic.__new__(cls, domain) + + @property + def codomain(self): + return self.domain + + +class NamedMorphism(Morphism): + """ + Represents a morphism which has a name. + + Explanation + =========== + + Names are used to distinguish between morphisms which have the + same domain and codomain: two named morphisms are equal if they + have the same domains, codomains, and names. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> f = NamedMorphism(A, B, "f") + >>> f + NamedMorphism(Object("A"), Object("B"), "f") + >>> f.name + 'f' + + See Also + ======== + + Morphism + """ + def __new__(cls, domain, codomain, name): + if not name: + raise ValueError("Empty morphism names not allowed.") + + if not isinstance(name, Str): + name = Str(name) + + return Basic.__new__(cls, domain, codomain, name) + + @property + def name(self): + """ + Returns the name of the morphism. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> f = NamedMorphism(A, B, "f") + >>> f.name + 'f' + + """ + return self.args[2].name + + +class CompositeMorphism(Morphism): + r""" + Represents a morphism which is a composition of other morphisms. + + Explanation + =========== + + Two composite morphisms are equal if the morphisms they were + obtained from (components) are the same and were listed in the + same order. + + The arguments to the constructor for this class should be listed + in diagram order: to obtain the composition `g\circ f` from the + instances of :class:`Morphism` ``g`` and ``f`` use + ``CompositeMorphism(f, g)``. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, CompositeMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> g * f + CompositeMorphism((NamedMorphism(Object("A"), Object("B"), "f"), + NamedMorphism(Object("B"), Object("C"), "g"))) + >>> CompositeMorphism(f, g) == g * f + True + + """ + @staticmethod + def _add_morphism(t, morphism): + """ + Intelligently adds ``morphism`` to tuple ``t``. + + Explanation + =========== + + If ``morphism`` is a composite morphism, its components are + added to the tuple. If ``morphism`` is an identity, nothing + is added to the tuple. + + No composability checks are performed. + """ + if isinstance(morphism, CompositeMorphism): + # ``morphism`` is a composite morphism; we have to + # denest its components. + return t + morphism.components + elif isinstance(morphism, IdentityMorphism): + # ``morphism`` is an identity. Nothing happens. + return t + else: + return t + Tuple(morphism) + + def __new__(cls, *components): + if components and not isinstance(components[0], Morphism): + # Maybe the user has explicitly supplied a list of + # morphisms. + return CompositeMorphism.__new__(cls, *components[0]) + + normalised_components = Tuple() + + for current, following in zip(components, components[1:]): + if not isinstance(current, Morphism) or \ + not isinstance(following, Morphism): + raise TypeError("All components must be morphisms.") + + if current.codomain != following.domain: + raise ValueError("Uncomposable morphisms.") + + normalised_components = CompositeMorphism._add_morphism( + normalised_components, current) + + # We haven't added the last morphism to the list of normalised + # components. Add it now. + normalised_components = CompositeMorphism._add_morphism( + normalised_components, components[-1]) + + if not normalised_components: + # If ``normalised_components`` is empty, only identities + # were supplied. Since they all were composable, they are + # all the same identities. + return components[0] + elif len(normalised_components) == 1: + # No sense to construct a whole CompositeMorphism. + return normalised_components[0] + + return Basic.__new__(cls, normalised_components) + + @property + def components(self): + """ + Returns the components of this composite morphism. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> (g * f).components + (NamedMorphism(Object("A"), Object("B"), "f"), + NamedMorphism(Object("B"), Object("C"), "g")) + + """ + return self.args[0] + + @property + def domain(self): + """ + Returns the domain of this composite morphism. + + The domain of the composite morphism is the domain of its + first component. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> (g * f).domain + Object("A") + + """ + return self.components[0].domain + + @property + def codomain(self): + """ + Returns the codomain of this composite morphism. + + The codomain of the composite morphism is the codomain of its + last component. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> (g * f).codomain + Object("C") + + """ + return self.components[-1].codomain + + def flatten(self, new_name): + """ + Forgets the composite structure of this morphism. + + Explanation + =========== + + If ``new_name`` is not empty, returns a :class:`NamedMorphism` + with the supplied name, otherwise returns a :class:`Morphism`. + In both cases the domain of the new morphism is the domain of + this composite morphism and the codomain of the new morphism + is the codomain of this composite morphism. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> (g * f).flatten("h") + NamedMorphism(Object("A"), Object("C"), "h") + + """ + return NamedMorphism(self.domain, self.codomain, new_name) + + +class Category(Basic): + r""" + An (abstract) category. + + Explanation + =========== + + A category [JoyOfCats] is a quadruple `\mbox{K} = (O, \hom, id, + \circ)` consisting of + + * a (set-theoretical) class `O`, whose members are called + `K`-objects, + + * for each pair `(A, B)` of `K`-objects, a set `\hom(A, B)` whose + members are called `K`-morphisms from `A` to `B`, + + * for a each `K`-object `A`, a morphism `id:A\rightarrow A`, + called the `K`-identity of `A`, + + * a composition law `\circ` associating with every `K`-morphisms + `f:A\rightarrow B` and `g:B\rightarrow C` a `K`-morphism `g\circ + f:A\rightarrow C`, called the composite of `f` and `g`. + + Composition is associative, `K`-identities are identities with + respect to composition, and the sets `\hom(A, B)` are pairwise + disjoint. + + This class knows nothing about its objects and morphisms. + Concrete cases of (abstract) categories should be implemented as + classes derived from this one. + + Certain instances of :class:`Diagram` can be asserted to be + commutative in a :class:`Category` by supplying the argument + ``commutative_diagrams`` in the constructor. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram, Category + >>> from sympy import FiniteSet + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g]) + >>> K = Category("K", commutative_diagrams=[d]) + >>> K.commutative_diagrams == FiniteSet(d) + True + + See Also + ======== + + Diagram + """ + def __new__(cls, name, objects=EmptySet, commutative_diagrams=EmptySet): + if not name: + raise ValueError("A Category cannot have an empty name.") + + if not isinstance(name, Str): + name = Str(name) + + if not isinstance(objects, Class): + objects = Class(objects) + + new_category = Basic.__new__(cls, name, objects, + FiniteSet(*commutative_diagrams)) + return new_category + + @property + def name(self): + """ + Returns the name of this category. + + Examples + ======== + + >>> from sympy.categories import Category + >>> K = Category("K") + >>> K.name + 'K' + + """ + return self.args[0].name + + @property + def objects(self): + """ + Returns the class of objects of this category. + + Examples + ======== + + >>> from sympy.categories import Object, Category + >>> from sympy import FiniteSet + >>> A = Object("A") + >>> B = Object("B") + >>> K = Category("K", FiniteSet(A, B)) + >>> K.objects + Class({Object("A"), Object("B")}) + + """ + return self.args[1] + + @property + def commutative_diagrams(self): + """ + Returns the :class:`~.FiniteSet` of diagrams which are known to + be commutative in this category. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram, Category + >>> from sympy import FiniteSet + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g]) + >>> K = Category("K", commutative_diagrams=[d]) + >>> K.commutative_diagrams == FiniteSet(d) + True + + """ + return self.args[2] + + def hom(self, A, B): + raise NotImplementedError( + "hom-sets are not implemented in Category.") + + def all_morphisms(self): + raise NotImplementedError( + "Obtaining the class of morphisms is not implemented in Category.") + + +class Diagram(Basic): + r""" + Represents a diagram in a certain category. + + Explanation + =========== + + Informally, a diagram is a collection of objects of a category and + certain morphisms between them. A diagram is still a monoid with + respect to morphism composition; i.e., identity morphisms, as well + as all composites of morphisms included in the diagram belong to + the diagram. For a more formal approach to this notion see + [Pare1970]. + + The components of composite morphisms are also added to the + diagram. No properties are assigned to such morphisms by default. + + A commutative diagram is often accompanied by a statement of the + following kind: "if such morphisms with such properties exist, + then such morphisms which such properties exist and the diagram is + commutative". To represent this, an instance of :class:`Diagram` + includes a collection of morphisms which are the premises and + another collection of conclusions. ``premises`` and + ``conclusions`` associate morphisms belonging to the corresponding + categories with the :class:`~.FiniteSet`'s of their properties. + + The set of properties of a composite morphism is the intersection + of the sets of properties of its components. The domain and + codomain of a conclusion morphism should be among the domains and + codomains of the morphisms listed as the premises of a diagram. + + No checks are carried out of whether the supplied object and + morphisms do belong to one and the same category. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> from sympy import pprint, default_sort_key + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g]) + >>> premises_keys = sorted(d.premises.keys(), key=default_sort_key) + >>> pprint(premises_keys, use_unicode=False) + [g*f:A-->C, id:A-->A, id:B-->B, id:C-->C, f:A-->B, g:B-->C] + >>> pprint(d.premises, use_unicode=False) + {g*f:A-->C: EmptySet, id:A-->A: EmptySet, id:B-->B: EmptySet, + id:C-->C: EmptySet, f:A-->B: EmptySet, g:B-->C: EmptySet} + >>> d = Diagram([f, g], {g * f: "unique"}) + >>> pprint(d.conclusions,use_unicode=False) + {g*f:A-->C: {unique}} + + References + ========== + + [Pare1970] B. Pareigis: Categories and functors. Academic Press, 1970. + + """ + @staticmethod + def _set_dict_union(dictionary, key, value): + """ + If ``key`` is in ``dictionary``, set the new value of ``key`` + to be the union between the old value and ``value``. + Otherwise, set the value of ``key`` to ``value. + + Returns ``True`` if the key already was in the dictionary and + ``False`` otherwise. + """ + if key in dictionary: + dictionary[key] = dictionary[key] | value + return True + else: + dictionary[key] = value + return False + + @staticmethod + def _add_morphism_closure(morphisms, morphism, props, add_identities=True, + recurse_composites=True): + """ + Adds a morphism and its attributes to the supplied dictionary + ``morphisms``. If ``add_identities`` is True, also adds the + identity morphisms for the domain and the codomain of + ``morphism``. + """ + if not Diagram._set_dict_union(morphisms, morphism, props): + # We have just added a new morphism. + + if isinstance(morphism, IdentityMorphism): + if props: + # Properties for identity morphisms don't really + # make sense, because very much is known about + # identity morphisms already, so much that they + # are trivial. Having properties for identity + # morphisms would only be confusing. + raise ValueError( + "Instances of IdentityMorphism cannot have properties.") + return + + if add_identities: + empty = EmptySet + + id_dom = IdentityMorphism(morphism.domain) + id_cod = IdentityMorphism(morphism.codomain) + + Diagram._set_dict_union(morphisms, id_dom, empty) + Diagram._set_dict_union(morphisms, id_cod, empty) + + for existing_morphism, existing_props in list(morphisms.items()): + new_props = existing_props & props + if morphism.domain == existing_morphism.codomain: + left = morphism * existing_morphism + Diagram._set_dict_union(morphisms, left, new_props) + if morphism.codomain == existing_morphism.domain: + right = existing_morphism * morphism + Diagram._set_dict_union(morphisms, right, new_props) + + if isinstance(morphism, CompositeMorphism) and recurse_composites: + # This is a composite morphism, add its components as + # well. + empty = EmptySet + for component in morphism.components: + Diagram._add_morphism_closure(morphisms, component, empty, + add_identities) + + def __new__(cls, *args): + """ + Construct a new instance of Diagram. + + Explanation + =========== + + If no arguments are supplied, an empty diagram is created. + + If at least an argument is supplied, ``args[0]`` is + interpreted as the premises of the diagram. If ``args[0]`` is + a list, it is interpreted as a list of :class:`Morphism`'s, in + which each :class:`Morphism` has an empty set of properties. + If ``args[0]`` is a Python dictionary or a :class:`Dict`, it + is interpreted as a dictionary associating to some + :class:`Morphism`'s some properties. + + If at least two arguments are supplied ``args[1]`` is + interpreted as the conclusions of the diagram. The type of + ``args[1]`` is interpreted in exactly the same way as the type + of ``args[0]``. If only one argument is supplied, the diagram + has no conclusions. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import IdentityMorphism, Diagram + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g]) + >>> IdentityMorphism(A) in d.premises.keys() + True + >>> g * f in d.premises.keys() + True + >>> d = Diagram([f, g], {g * f: "unique"}) + >>> d.conclusions[g * f] + {unique} + + """ + premises = {} + conclusions = {} + + # Here we will keep track of the objects which appear in the + # premises. + objects = EmptySet + + if len(args) >= 1: + # We've got some premises in the arguments. + premises_arg = args[0] + + if isinstance(premises_arg, list): + # The user has supplied a list of morphisms, none of + # which have any attributes. + empty = EmptySet + + for morphism in premises_arg: + objects |= FiniteSet(morphism.domain, morphism.codomain) + Diagram._add_morphism_closure(premises, morphism, empty) + elif isinstance(premises_arg, (dict, Dict)): + # The user has supplied a dictionary of morphisms and + # their properties. + for morphism, props in premises_arg.items(): + objects |= FiniteSet(morphism.domain, morphism.codomain) + Diagram._add_morphism_closure( + premises, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props)) + + if len(args) >= 2: + # We also have some conclusions. + conclusions_arg = args[1] + + if isinstance(conclusions_arg, list): + # The user has supplied a list of morphisms, none of + # which have any attributes. + empty = EmptySet + + for morphism in conclusions_arg: + # Check that no new objects appear in conclusions. + if ((sympify(objects.contains(morphism.domain)) is S.true) and + (sympify(objects.contains(morphism.codomain)) is S.true)): + # No need to add identities and recurse + # composites this time. + Diagram._add_morphism_closure( + conclusions, morphism, empty, add_identities=False, + recurse_composites=False) + elif isinstance(conclusions_arg, (dict, Dict)): + # The user has supplied a dictionary of morphisms and + # their properties. + for morphism, props in conclusions_arg.items(): + # Check that no new objects appear in conclusions. + if (morphism.domain in objects) and \ + (morphism.codomain in objects): + # No need to add identities and recurse + # composites this time. + Diagram._add_morphism_closure( + conclusions, morphism, FiniteSet(*props) if iterable(props) else FiniteSet(props), + add_identities=False, recurse_composites=False) + + return Basic.__new__(cls, Dict(premises), Dict(conclusions), objects) + + @property + def premises(self): + """ + Returns the premises of this diagram. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import IdentityMorphism, Diagram + >>> from sympy import pretty + >>> A = Object("A") + >>> B = Object("B") + >>> f = NamedMorphism(A, B, "f") + >>> id_A = IdentityMorphism(A) + >>> id_B = IdentityMorphism(B) + >>> d = Diagram([f]) + >>> print(pretty(d.premises, use_unicode=False)) + {id:A-->A: EmptySet, id:B-->B: EmptySet, f:A-->B: EmptySet} + + """ + return self.args[0] + + @property + def conclusions(self): + """ + Returns the conclusions of this diagram. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import IdentityMorphism, Diagram + >>> from sympy import FiniteSet + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g]) + >>> IdentityMorphism(A) in d.premises.keys() + True + >>> g * f in d.premises.keys() + True + >>> d = Diagram([f, g], {g * f: "unique"}) + >>> d.conclusions[g * f] == FiniteSet("unique") + True + + """ + return self.args[1] + + @property + def objects(self): + """ + Returns the :class:`~.FiniteSet` of objects that appear in this + diagram. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g]) + >>> d.objects + {Object("A"), Object("B"), Object("C")} + + """ + return self.args[2] + + def hom(self, A, B): + """ + Returns a 2-tuple of sets of morphisms between objects ``A`` and + ``B``: one set of morphisms listed as premises, and the other set + of morphisms listed as conclusions. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> from sympy import pretty + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g], {g * f: "unique"}) + >>> print(pretty(d.hom(A, C), use_unicode=False)) + ({g*f:A-->C}, {g*f:A-->C}) + + See Also + ======== + Object, Morphism + """ + premises = EmptySet + conclusions = EmptySet + + for morphism in self.premises.keys(): + if (morphism.domain == A) and (morphism.codomain == B): + premises |= FiniteSet(morphism) + for morphism in self.conclusions.keys(): + if (morphism.domain == A) and (morphism.codomain == B): + conclusions |= FiniteSet(morphism) + + return (premises, conclusions) + + def is_subdiagram(self, diagram): + """ + Checks whether ``diagram`` is a subdiagram of ``self``. + Diagram `D'` is a subdiagram of `D` if all premises + (conclusions) of `D'` are contained in the premises + (conclusions) of `D`. The morphisms contained + both in `D'` and `D` should have the same properties for `D'` + to be a subdiagram of `D`. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g], {g * f: "unique"}) + >>> d1 = Diagram([f]) + >>> d.is_subdiagram(d1) + True + >>> d1.is_subdiagram(d) + False + """ + premises = all((m in self.premises) and + (diagram.premises[m] == self.premises[m]) + for m in diagram.premises) + if not premises: + return False + + conclusions = all((m in self.conclusions) and + (diagram.conclusions[m] == self.conclusions[m]) + for m in diagram.conclusions) + + # Premises is surely ``True`` here. + return conclusions + + def subdiagram_from_objects(self, objects): + """ + If ``objects`` is a subset of the objects of ``self``, returns + a diagram which has as premises all those premises of ``self`` + which have a domains and codomains in ``objects``, likewise + for conclusions. Properties are preserved. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> from sympy import FiniteSet + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g], {f: "unique", g*f: "veryunique"}) + >>> d1 = d.subdiagram_from_objects(FiniteSet(A, B)) + >>> d1 == Diagram([f], {f: "unique"}) + True + """ + if not objects.is_subset(self.objects): + raise ValueError( + "Supplied objects should all belong to the diagram.") + + new_premises = {} + for morphism, props in self.premises.items(): + if ((sympify(objects.contains(morphism.domain)) is S.true) and + (sympify(objects.contains(morphism.codomain)) is S.true)): + new_premises[morphism] = props + + new_conclusions = {} + for morphism, props in self.conclusions.items(): + if ((sympify(objects.contains(morphism.domain)) is S.true) and + (sympify(objects.contains(morphism.codomain)) is S.true)): + new_conclusions[morphism] = props + + return Diagram(new_premises, new_conclusions) diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py new file mode 100644 index 0000000000000000000000000000000000000000..97997d1b934e7393fc8fb29211eff6a55f29a90c --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/diagram_drawing.py @@ -0,0 +1,2582 @@ +r""" +This module contains the functionality to arrange the nodes of a +diagram on an abstract grid, and then to produce a graphical +representation of the grid. + +The currently supported back-ends are Xy-pic [Xypic]. + +Layout Algorithm +================ + +This section provides an overview of the algorithms implemented in +:class:`DiagramGrid` to lay out diagrams. + +The first step of the algorithm is the removal composite and identity +morphisms which do not have properties in the supplied diagram. The +premises and conclusions of the diagram are then merged. + +The generic layout algorithm begins with the construction of the +"skeleton" of the diagram. The skeleton is an undirected graph which +has the objects of the diagram as vertices and has an (undirected) +edge between each pair of objects between which there exist morphisms. +The direction of the morphisms does not matter at this stage. The +skeleton also includes an edge between each pair of vertices `A` and +`C` such that there exists an object `B` which is connected via +a morphism to `A`, and via a morphism to `C`. + +The skeleton constructed in this way has the property that every +object is a vertex of a triangle formed by three edges of the +skeleton. This property lies at the base of the generic layout +algorithm. + +After the skeleton has been constructed, the algorithm lists all +triangles which can be formed. Note that some triangles will not have +all edges corresponding to morphisms which will actually be drawn. +Triangles which have only one edge or less which will actually be +drawn are immediately discarded. + +The list of triangles is sorted according to the number of edges which +correspond to morphisms, then the triangle with the least number of such +edges is selected. One of such edges is picked and the corresponding +objects are placed horizontally, on a grid. This edge is recorded to +be in the fringe. The algorithm then finds a "welding" of a triangle +to the fringe. A welding is an edge in the fringe where a triangle +could be attached. If the algorithm succeeds in finding such a +welding, it adds to the grid that vertex of the triangle which was not +yet included in any edge in the fringe and records the two new edges in +the fringe. This process continues iteratively until all objects of +the diagram has been placed or until no more weldings can be found. + +An edge is only removed from the fringe when a welding to this edge +has been found, and there is no room around this edge to place +another vertex. + +When no more weldings can be found, but there are still triangles +left, the algorithm searches for a possibility of attaching one of the +remaining triangles to the existing structure by a vertex. If such a +possibility is found, the corresponding edge of the found triangle is +placed in the found space and the iterative process of welding +triangles restarts. + +When logical groups are supplied, each of these groups is laid out +independently. Then a diagram is constructed in which groups are +objects and any two logical groups between which there exist morphisms +are connected via a morphism. This diagram is laid out. Finally, +the grid which includes all objects of the initial diagram is +constructed by replacing the cells which contain logical groups with +the corresponding laid out grids, and by correspondingly expanding the +rows and columns. + +The sequential layout algorithm begins by constructing the +underlying undirected graph defined by the morphisms obtained after +simplifying premises and conclusions and merging them (see above). +The vertex with the minimal degree is then picked up and depth-first +search is started from it. All objects which are located at distance +`n` from the root in the depth-first search tree, are positioned in +the `n`-th column of the resulting grid. The sequential layout will +therefore attempt to lay the objects out along a line. + +References +========== + +.. [Xypic] https://xy-pic.sourceforge.net/ + +""" +from sympy.categories import (CompositeMorphism, IdentityMorphism, + NamedMorphism, Diagram) +from sympy.core import Dict, Symbol, default_sort_key +from sympy.printing.latex import latex +from sympy.sets import FiniteSet +from sympy.utilities.iterables import iterable +from sympy.utilities.decorator import doctest_depends_on + +from itertools import chain + + +__doctest_requires__ = {('preview_diagram',): 'pyglet'} + + +class _GrowableGrid: + """ + Holds a growable grid of objects. + + Explanation + =========== + + It is possible to append or prepend a row or a column to the grid + using the corresponding methods. Prepending rows or columns has + the effect of changing the coordinates of the already existing + elements. + + This class currently represents a naive implementation of the + functionality with little attempt at optimisation. + """ + def __init__(self, width, height): + self._width = width + self._height = height + + self._array = [[None for j in range(width)] for i in range(height)] + + @property + def width(self): + return self._width + + @property + def height(self): + return self._height + + def __getitem__(self, i_j): + """ + Returns the element located at in the i-th line and j-th + column. + """ + i, j = i_j + return self._array[i][j] + + def __setitem__(self, i_j, newvalue): + """ + Sets the element located at in the i-th line and j-th + column. + """ + i, j = i_j + self._array[i][j] = newvalue + + def append_row(self): + """ + Appends an empty row to the grid. + """ + self._height += 1 + self._array.append([None for j in range(self._width)]) + + def append_column(self): + """ + Appends an empty column to the grid. + """ + self._width += 1 + for i in range(self._height): + self._array[i].append(None) + + def prepend_row(self): + """ + Prepends the grid with an empty row. + """ + self._height += 1 + self._array.insert(0, [None for j in range(self._width)]) + + def prepend_column(self): + """ + Prepends the grid with an empty column. + """ + self._width += 1 + for i in range(self._height): + self._array[i].insert(0, None) + + +class DiagramGrid: + r""" + Constructs and holds the fitting of the diagram into a grid. + + Explanation + =========== + + The mission of this class is to analyse the structure of the + supplied diagram and to place its objects on a grid such that, + when the objects and the morphisms are actually drawn, the diagram + would be "readable", in the sense that there will not be many + intersections of moprhisms. This class does not perform any + actual drawing. It does strive nevertheless to offer sufficient + metadata to draw a diagram. + + Consider the following simple diagram. + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import Diagram, DiagramGrid + >>> from sympy import pprint + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g]) + + The simplest way to have a diagram laid out is the following: + + >>> grid = DiagramGrid(diagram) + >>> (grid.width, grid.height) + (2, 2) + >>> pprint(grid) + A B + + C + + Sometimes one sees the diagram as consisting of logical groups. + One can advise ``DiagramGrid`` as to such groups by employing the + ``groups`` keyword argument. + + Consider the following diagram: + + >>> D = Object("D") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> h = NamedMorphism(D, A, "h") + >>> k = NamedMorphism(D, B, "k") + >>> diagram = Diagram([f, g, h, k]) + + Lay it out with generic layout: + + >>> grid = DiagramGrid(diagram) + >>> pprint(grid) + A B D + + C + + Now, we can group the objects `A` and `D` to have them near one + another: + + >>> grid = DiagramGrid(diagram, groups=[[A, D], B, C]) + >>> pprint(grid) + B C + + A D + + Note how the positioning of the other objects changes. + + Further indications can be supplied to the constructor of + :class:`DiagramGrid` using keyword arguments. The currently + supported hints are explained in the following paragraphs. + + :class:`DiagramGrid` does not automatically guess which layout + would suit the supplied diagram better. Consider, for example, + the following linear diagram: + + >>> E = Object("E") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> h = NamedMorphism(C, D, "h") + >>> i = NamedMorphism(D, E, "i") + >>> diagram = Diagram([f, g, h, i]) + + When laid out with the generic layout, it does not get to look + linear: + + >>> grid = DiagramGrid(diagram) + >>> pprint(grid) + A B + + C D + + E + + To get it laid out in a line, use ``layout="sequential"``: + + >>> grid = DiagramGrid(diagram, layout="sequential") + >>> pprint(grid) + A B C D E + + One may sometimes need to transpose the resulting layout. While + this can always be done by hand, :class:`DiagramGrid` provides a + hint for that purpose: + + >>> grid = DiagramGrid(diagram, layout="sequential", transpose=True) + >>> pprint(grid) + A + + B + + C + + D + + E + + Separate hints can also be provided for each group. For an + example, refer to ``tests/test_drawing.py``, and see the different + ways in which the five lemma [FiveLemma] can be laid out. + + See Also + ======== + + Diagram + + References + ========== + + .. [FiveLemma] https://en.wikipedia.org/wiki/Five_lemma + """ + @staticmethod + def _simplify_morphisms(morphisms): + """ + Given a dictionary mapping morphisms to their properties, + returns a new dictionary in which there are no morphisms which + do not have properties, and which are compositions of other + morphisms included in the dictionary. Identities are dropped + as well. + """ + newmorphisms = {} + for morphism, props in morphisms.items(): + if isinstance(morphism, CompositeMorphism) and not props: + continue + elif isinstance(morphism, IdentityMorphism): + continue + else: + newmorphisms[morphism] = props + return newmorphisms + + @staticmethod + def _merge_premises_conclusions(premises, conclusions): + """ + Given two dictionaries of morphisms and their properties, + produces a single dictionary which includes elements from both + dictionaries. If a morphism has some properties in premises + and also in conclusions, the properties in conclusions take + priority. + """ + return dict(chain(premises.items(), conclusions.items())) + + @staticmethod + def _juxtapose_edges(edge1, edge2): + """ + If ``edge1`` and ``edge2`` have precisely one common endpoint, + returns an edge which would form a triangle with ``edge1`` and + ``edge2``. + + If ``edge1`` and ``edge2`` do not have a common endpoint, + returns ``None``. + + If ``edge1`` and ``edge`` are the same edge, returns ``None``. + """ + intersection = edge1 & edge2 + if len(intersection) != 1: + # The edges either have no common points or are equal. + return None + + # The edges have a common endpoint. Extract the different + # endpoints and set up the new edge. + return (edge1 - intersection) | (edge2 - intersection) + + @staticmethod + def _add_edge_append(dictionary, edge, elem): + """ + If ``edge`` is not in ``dictionary``, adds ``edge`` to the + dictionary and sets its value to ``[elem]``. Otherwise + appends ``elem`` to the value of existing entry. + + Note that edges are undirected, thus `(A, B) = (B, A)`. + """ + if edge in dictionary: + dictionary[edge].append(elem) + else: + dictionary[edge] = [elem] + + @staticmethod + def _build_skeleton(morphisms): + """ + Creates a dictionary which maps edges to corresponding + morphisms. Thus for a morphism `f:A\rightarrow B`, the edge + `(A, B)` will be associated with `f`. This function also adds + to the list those edges which are formed by juxtaposition of + two edges already in the list. These new edges are not + associated with any morphism and are only added to assure that + the diagram can be decomposed into triangles. + """ + edges = {} + # Create edges for morphisms. + for morphism in morphisms: + DiagramGrid._add_edge_append( + edges, frozenset([morphism.domain, morphism.codomain]), morphism) + + # Create new edges by juxtaposing existing edges. + edges1 = dict(edges) + for w in edges1: + for v in edges1: + wv = DiagramGrid._juxtapose_edges(w, v) + if wv and wv not in edges: + edges[wv] = [] + + return edges + + @staticmethod + def _list_triangles(edges): + """ + Builds the set of triangles formed by the supplied edges. The + triangles are arbitrary and need not be commutative. A + triangle is a set that contains all three of its sides. + """ + triangles = set() + + for w in edges: + for v in edges: + wv = DiagramGrid._juxtapose_edges(w, v) + if wv and wv in edges: + triangles.add(frozenset([w, v, wv])) + + return triangles + + @staticmethod + def _drop_redundant_triangles(triangles, skeleton): + """ + Returns a list which contains only those triangles who have + morphisms associated with at least two edges. + """ + return [tri for tri in triangles + if len([e for e in tri if skeleton[e]]) >= 2] + + @staticmethod + def _morphism_length(morphism): + """ + Returns the length of a morphism. The length of a morphism is + the number of components it consists of. A non-composite + morphism is of length 1. + """ + if isinstance(morphism, CompositeMorphism): + return len(morphism.components) + else: + return 1 + + @staticmethod + def _compute_triangle_min_sizes(triangles, edges): + r""" + Returns a dictionary mapping triangles to their minimal sizes. + The minimal size of a triangle is the sum of maximal lengths + of morphisms associated to the sides of the triangle. The + length of a morphism is the number of components it consists + of. A non-composite morphism is of length 1. + + Sorting triangles by this metric attempts to address two + aspects of layout. For triangles with only simple morphisms + in the edge, this assures that triangles with all three edges + visible will get typeset after triangles with less visible + edges, which sometimes minimizes the necessity in diagonal + arrows. For triangles with composite morphisms in the edges, + this assures that objects connected with shorter morphisms + will be laid out first, resulting the visual proximity of + those objects which are connected by shorter morphisms. + """ + triangle_sizes = {} + for triangle in triangles: + size = 0 + for e in triangle: + morphisms = edges[e] + if morphisms: + size += max(DiagramGrid._morphism_length(m) + for m in morphisms) + triangle_sizes[triangle] = size + return triangle_sizes + + @staticmethod + def _triangle_objects(triangle): + """ + Given a triangle, returns the objects included in it. + """ + # A triangle is a frozenset of three two-element frozensets + # (the edges). This chains the three edges together and + # creates a frozenset from the iterator, thus producing a + # frozenset of objects of the triangle. + return frozenset(chain(*tuple(triangle))) + + @staticmethod + def _other_vertex(triangle, edge): + """ + Given a triangle and an edge of it, returns the vertex which + opposes the edge. + """ + # This gets the set of objects of the triangle and then + # subtracts the set of objects employed in ``edge`` to get the + # vertex opposite to ``edge``. + return list(DiagramGrid._triangle_objects(triangle) - set(edge))[0] + + @staticmethod + def _empty_point(pt, grid): + """ + Checks if the cell at coordinates ``pt`` is either empty or + out of the bounds of the grid. + """ + if (pt[0] < 0) or (pt[1] < 0) or \ + (pt[0] >= grid.height) or (pt[1] >= grid.width): + return True + return grid[pt] is None + + @staticmethod + def _put_object(coords, obj, grid, fringe): + """ + Places an object at the coordinate ``cords`` in ``grid``, + growing the grid and updating ``fringe``, if necessary. + Returns (0, 0) if no row or column has been prepended, (1, 0) + if a row was prepended, (0, 1) if a column was prepended and + (1, 1) if both a column and a row were prepended. + """ + (i, j) = coords + offset = (0, 0) + if i == -1: + grid.prepend_row() + i = 0 + offset = (1, 0) + for k in range(len(fringe)): + ((i1, j1), (i2, j2)) = fringe[k] + fringe[k] = ((i1 + 1, j1), (i2 + 1, j2)) + elif i == grid.height: + grid.append_row() + + if j == -1: + j = 0 + offset = (offset[0], 1) + grid.prepend_column() + for k in range(len(fringe)): + ((i1, j1), (i2, j2)) = fringe[k] + fringe[k] = ((i1, j1 + 1), (i2, j2 + 1)) + elif j == grid.width: + grid.append_column() + + grid[i, j] = obj + return offset + + @staticmethod + def _choose_target_cell(pt1, pt2, edge, obj, skeleton, grid): + """ + Given two points, ``pt1`` and ``pt2``, and the welding edge + ``edge``, chooses one of the two points to place the opposing + vertex ``obj`` of the triangle. If neither of this points + fits, returns ``None``. + """ + pt1_empty = DiagramGrid._empty_point(pt1, grid) + pt2_empty = DiagramGrid._empty_point(pt2, grid) + + if pt1_empty and pt2_empty: + # Both cells are empty. Of these two, choose that cell + # which will assure that a visible edge of the triangle + # will be drawn perpendicularly to the current welding + # edge. + + A = grid[edge[0]] + + if skeleton.get(frozenset([A, obj])): + return pt1 + else: + return pt2 + if pt1_empty: + return pt1 + elif pt2_empty: + return pt2 + else: + return None + + @staticmethod + def _find_triangle_to_weld(triangles, fringe, grid): + """ + Finds, if possible, a triangle and an edge in the ``fringe`` to + which the triangle could be attached. Returns the tuple + containing the triangle and the index of the corresponding + edge in the ``fringe``. + + This function relies on the fact that objects are unique in + the diagram. + """ + for triangle in triangles: + for (a, b) in fringe: + if frozenset([grid[a], grid[b]]) in triangle: + return (triangle, (a, b)) + return None + + @staticmethod + def _weld_triangle(tri, welding_edge, fringe, grid, skeleton): + """ + If possible, welds the triangle ``tri`` to ``fringe`` and + returns ``False``. If this method encounters a degenerate + situation in the fringe and corrects it such that a restart of + the search is required, it returns ``True`` (which means that + a restart in finding triangle weldings is required). + + A degenerate situation is a situation when an edge listed in + the fringe does not belong to the visual boundary of the + diagram. + """ + a, b = welding_edge + target_cell = None + + obj = DiagramGrid._other_vertex(tri, (grid[a], grid[b])) + + # We now have a triangle and an edge where it can be welded to + # the fringe. Decide where to place the other vertex of the + # triangle and check for degenerate situations en route. + + if (abs(a[0] - b[0]) == 1) and (abs(a[1] - b[1]) == 1): + # A diagonal edge. + target_cell = (a[0], b[1]) + if grid[target_cell]: + # That cell is already occupied. + target_cell = (b[0], a[1]) + + if grid[target_cell]: + # Degenerate situation, this edge is not + # on the actual fringe. Correct the + # fringe and go on. + fringe.remove((a, b)) + return True + elif a[0] == b[0]: + # A horizontal edge. We first attempt to build the + # triangle in the downward direction. + + down_left = a[0] + 1, a[1] + down_right = a[0] + 1, b[1] + + target_cell = DiagramGrid._choose_target_cell( + down_left, down_right, (a, b), obj, skeleton, grid) + + if not target_cell: + # No room below this edge. Check above. + up_left = a[0] - 1, a[1] + up_right = a[0] - 1, b[1] + + target_cell = DiagramGrid._choose_target_cell( + up_left, up_right, (a, b), obj, skeleton, grid) + + if not target_cell: + # This edge is not in the fringe, remove it + # and restart. + fringe.remove((a, b)) + return True + elif a[1] == b[1]: + # A vertical edge. We will attempt to place the other + # vertex of the triangle to the right of this edge. + right_up = a[0], a[1] + 1 + right_down = b[0], a[1] + 1 + + target_cell = DiagramGrid._choose_target_cell( + right_up, right_down, (a, b), obj, skeleton, grid) + + if not target_cell: + # No room to the left. See what's to the right. + left_up = a[0], a[1] - 1 + left_down = b[0], a[1] - 1 + + target_cell = DiagramGrid._choose_target_cell( + left_up, left_down, (a, b), obj, skeleton, grid) + + if not target_cell: + # This edge is not in the fringe, remove it + # and restart. + fringe.remove((a, b)) + return True + + # We now know where to place the other vertex of the + # triangle. + offset = DiagramGrid._put_object(target_cell, obj, grid, fringe) + + # Take care of the displacement of coordinates if a row or + # a column was prepended. + target_cell = (target_cell[0] + offset[0], + target_cell[1] + offset[1]) + a = (a[0] + offset[0], a[1] + offset[1]) + b = (b[0] + offset[0], b[1] + offset[1]) + + fringe.extend([(a, target_cell), (b, target_cell)]) + + # No restart is required. + return False + + @staticmethod + def _triangle_key(tri, triangle_sizes): + """ + Returns a key for the supplied triangle. It should be the + same independently of the hash randomisation. + """ + objects = sorted( + DiagramGrid._triangle_objects(tri), key=default_sort_key) + return (triangle_sizes[tri], default_sort_key(objects)) + + @staticmethod + def _pick_root_edge(tri, skeleton): + """ + For a given triangle always picks the same root edge. The + root edge is the edge that will be placed first on the grid. + """ + candidates = [sorted(e, key=default_sort_key) + for e in tri if skeleton[e]] + sorted_candidates = sorted(candidates, key=default_sort_key) + # Don't forget to assure the proper ordering of the vertices + # in this edge. + return tuple(sorted(sorted_candidates[0], key=default_sort_key)) + + @staticmethod + def _drop_irrelevant_triangles(triangles, placed_objects): + """ + Returns only those triangles whose set of objects is not + completely included in ``placed_objects``. + """ + return [tri for tri in triangles if not placed_objects.issuperset( + DiagramGrid._triangle_objects(tri))] + + @staticmethod + def _grow_pseudopod(triangles, fringe, grid, skeleton, placed_objects): + """ + Starting from an object in the existing structure on the ``grid``, + adds an edge to which a triangle from ``triangles`` could be + welded. If this method has found a way to do so, it returns + the object it has just added. + + This method should be applied when ``_weld_triangle`` cannot + find weldings any more. + """ + for i in range(grid.height): + for j in range(grid.width): + obj = grid[i, j] + if not obj: + continue + + # Here we need to choose a triangle which has only + # ``obj`` in common with the existing structure. The + # situations when this is not possible should be + # handled elsewhere. + + def good_triangle(tri): + objs = DiagramGrid._triangle_objects(tri) + return obj in objs and \ + placed_objects & (objs - {obj}) == set() + + tris = [tri for tri in triangles if good_triangle(tri)] + if not tris: + # This object is not interesting. + continue + + # Pick the "simplest" of the triangles which could be + # attached. Remember that the list of triangles is + # sorted according to their "simplicity" (see + # _compute_triangle_min_sizes for the metric). + # + # Note that ``tris`` are sequentially built from + # ``triangles``, so we don't have to worry about hash + # randomisation. + tri = tris[0] + + # We have found a triangle which could be attached to + # the existing structure by a vertex. + + candidates = sorted([e for e in tri if skeleton[e]], + key=lambda e: FiniteSet(*e).sort_key()) + edges = [e for e in candidates if obj in e] + + # Note that a meaningful edge (i.e., and edge that is + # associated with a morphism) containing ``obj`` + # always exists. That's because all triangles are + # guaranteed to have at least two meaningful edges. + # See _drop_redundant_triangles. + + # Get the object at the other end of the edge. + edge = edges[0] + other_obj = tuple(edge - frozenset([obj]))[0] + + # Now check for free directions. When checking for + # free directions, prefer the horizontal and vertical + # directions. + neighbours = [(i - 1, j), (i, j + 1), (i + 1, j), (i, j - 1), + (i - 1, j - 1), (i - 1, j + 1), (i + 1, j - 1), (i + 1, j + 1)] + + for pt in neighbours: + if DiagramGrid._empty_point(pt, grid): + # We have a found a place to grow the + # pseudopod into. + offset = DiagramGrid._put_object( + pt, other_obj, grid, fringe) + + i += offset[0] + j += offset[1] + pt = (pt[0] + offset[0], pt[1] + offset[1]) + fringe.append(((i, j), pt)) + + return other_obj + + # This diagram is actually cooler that I can handle. Fail cowardly. + return None + + @staticmethod + def _handle_groups(diagram, groups, merged_morphisms, hints): + """ + Given the slightly preprocessed morphisms of the diagram, + produces a grid laid out according to ``groups``. + + If a group has hints, it is laid out with those hints only, + without any influence from ``hints``. Otherwise, it is laid + out with ``hints``. + """ + def lay_out_group(group, local_hints): + """ + If ``group`` is a set of objects, uses a ``DiagramGrid`` + to lay it out and returns the grid. Otherwise returns the + object (i.e., ``group``). If ``local_hints`` is not + empty, it is supplied to ``DiagramGrid`` as the dictionary + of hints. Otherwise, the ``hints`` argument of + ``_handle_groups`` is used. + """ + if isinstance(group, FiniteSet): + # Set up the corresponding object-to-group + # mappings. + for obj in group: + obj_groups[obj] = group + + # Lay out the current group. + if local_hints: + groups_grids[group] = DiagramGrid( + diagram.subdiagram_from_objects(group), **local_hints) + else: + groups_grids[group] = DiagramGrid( + diagram.subdiagram_from_objects(group), **hints) + else: + obj_groups[group] = group + + def group_to_finiteset(group): + """ + Converts ``group`` to a :class:``FiniteSet`` if it is an + iterable. + """ + if iterable(group): + return FiniteSet(*group) + else: + return group + + obj_groups = {} + groups_grids = {} + + # We would like to support various containers to represent + # groups. To achieve that, before laying each group out, it + # should be converted to a FiniteSet, because that is what the + # following code expects. + + if isinstance(groups, (dict, Dict)): + finiteset_groups = {} + for group, local_hints in groups.items(): + finiteset_group = group_to_finiteset(group) + finiteset_groups[finiteset_group] = local_hints + lay_out_group(group, local_hints) + groups = finiteset_groups + else: + finiteset_groups = [] + for group in groups: + finiteset_group = group_to_finiteset(group) + finiteset_groups.append(finiteset_group) + lay_out_group(finiteset_group, None) + groups = finiteset_groups + + new_morphisms = [] + for morphism in merged_morphisms: + dom = obj_groups[morphism.domain] + cod = obj_groups[morphism.codomain] + # Note that we are not really interested in morphisms + # which do not employ two different groups, because + # these do not influence the layout. + if dom != cod: + # These are essentially unnamed morphisms; they are + # not going to mess in the final layout. By giving + # them the same names, we avoid unnecessary + # duplicates. + new_morphisms.append(NamedMorphism(dom, cod, "dummy")) + + # Lay out the new diagram. Since these are dummy morphisms, + # properties and conclusions are irrelevant. + top_grid = DiagramGrid(Diagram(new_morphisms)) + + # We now have to substitute the groups with the corresponding + # grids, laid out at the beginning of this function. Compute + # the size of each row and column in the grid, so that all + # nested grids fit. + + def group_size(group): + """ + For the supplied group (or object, eventually), returns + the size of the cell that will hold this group (object). + """ + if group in groups_grids: + grid = groups_grids[group] + return (grid.height, grid.width) + else: + return (1, 1) + + row_heights = [max(group_size(top_grid[i, j])[0] + for j in range(top_grid.width)) + for i in range(top_grid.height)] + + column_widths = [max(group_size(top_grid[i, j])[1] + for i in range(top_grid.height)) + for j in range(top_grid.width)] + + grid = _GrowableGrid(sum(column_widths), sum(row_heights)) + + real_row = 0 + real_column = 0 + for logical_row in range(top_grid.height): + for logical_column in range(top_grid.width): + obj = top_grid[logical_row, logical_column] + + if obj in groups_grids: + # This is a group. Copy the corresponding grid in + # place. + local_grid = groups_grids[obj] + for i in range(local_grid.height): + for j in range(local_grid.width): + grid[real_row + i, + real_column + j] = local_grid[i, j] + else: + # This is an object. Just put it there. + grid[real_row, real_column] = obj + + real_column += column_widths[logical_column] + real_column = 0 + real_row += row_heights[logical_row] + + return grid + + @staticmethod + def _generic_layout(diagram, merged_morphisms): + """ + Produces the generic layout for the supplied diagram. + """ + all_objects = set(diagram.objects) + if len(all_objects) == 1: + # There only one object in the diagram, just put in on 1x1 + # grid. + grid = _GrowableGrid(1, 1) + grid[0, 0] = tuple(all_objects)[0] + return grid + + skeleton = DiagramGrid._build_skeleton(merged_morphisms) + + grid = _GrowableGrid(2, 1) + + if len(skeleton) == 1: + # This diagram contains only one morphism. Draw it + # horizontally. + objects = sorted(all_objects, key=default_sort_key) + grid[0, 0] = objects[0] + grid[0, 1] = objects[1] + + return grid + + triangles = DiagramGrid._list_triangles(skeleton) + triangles = DiagramGrid._drop_redundant_triangles(triangles, skeleton) + triangle_sizes = DiagramGrid._compute_triangle_min_sizes( + triangles, skeleton) + + triangles = sorted(triangles, key=lambda tri: + DiagramGrid._triangle_key(tri, triangle_sizes)) + + # Place the first edge on the grid. + root_edge = DiagramGrid._pick_root_edge(triangles[0], skeleton) + grid[0, 0], grid[0, 1] = root_edge + fringe = [((0, 0), (0, 1))] + + # Record which objects we now have on the grid. + placed_objects = set(root_edge) + + while placed_objects != all_objects: + welding = DiagramGrid._find_triangle_to_weld( + triangles, fringe, grid) + + if welding: + (triangle, welding_edge) = welding + + restart_required = DiagramGrid._weld_triangle( + triangle, welding_edge, fringe, grid, skeleton) + if restart_required: + continue + + placed_objects.update( + DiagramGrid._triangle_objects(triangle)) + else: + # No more weldings found. Try to attach triangles by + # vertices. + new_obj = DiagramGrid._grow_pseudopod( + triangles, fringe, grid, skeleton, placed_objects) + + if not new_obj: + # No more triangles can be attached, not even by + # the edge. We will set up a new diagram out of + # what has been left, laid it out independently, + # and then attach it to this one. + + remaining_objects = all_objects - placed_objects + + remaining_diagram = diagram.subdiagram_from_objects( + FiniteSet(*remaining_objects)) + remaining_grid = DiagramGrid(remaining_diagram) + + # Now, let's glue ``remaining_grid`` to ``grid``. + final_width = grid.width + remaining_grid.width + final_height = max(grid.height, remaining_grid.height) + final_grid = _GrowableGrid(final_width, final_height) + + for i in range(grid.width): + for j in range(grid.height): + final_grid[i, j] = grid[i, j] + + start_j = grid.width + for i in range(remaining_grid.height): + for j in range(remaining_grid.width): + final_grid[i, start_j + j] = remaining_grid[i, j] + + return final_grid + + placed_objects.add(new_obj) + + triangles = DiagramGrid._drop_irrelevant_triangles( + triangles, placed_objects) + + return grid + + @staticmethod + def _get_undirected_graph(objects, merged_morphisms): + """ + Given the objects and the relevant morphisms of a diagram, + returns the adjacency lists of the underlying undirected + graph. + """ + adjlists = {} + for obj in objects: + adjlists[obj] = [] + + for morphism in merged_morphisms: + adjlists[morphism.domain].append(morphism.codomain) + adjlists[morphism.codomain].append(morphism.domain) + + # Assure that the objects in the adjacency list are always in + # the same order. + for obj in adjlists.keys(): + adjlists[obj].sort(key=default_sort_key) + + return adjlists + + @staticmethod + def _sequential_layout(diagram, merged_morphisms): + r""" + Lays out the diagram in "sequential" layout. This method + will attempt to produce a result as close to a line as + possible. For linear diagrams, the result will actually be a + line. + """ + objects = diagram.objects + sorted_objects = sorted(objects, key=default_sort_key) + + # Set up the adjacency lists of the underlying undirected + # graph of ``merged_morphisms``. + adjlists = DiagramGrid._get_undirected_graph(objects, merged_morphisms) + + root = min(sorted_objects, key=lambda x: len(adjlists[x])) + grid = _GrowableGrid(1, 1) + grid[0, 0] = root + + placed_objects = {root} + + def place_objects(pt, placed_objects): + """ + Does depth-first search in the underlying graph of the + diagram and places the objects en route. + """ + # We will start placing new objects from here. + new_pt = (pt[0], pt[1] + 1) + + for adjacent_obj in adjlists[grid[pt]]: + if adjacent_obj in placed_objects: + # This object has already been placed. + continue + + DiagramGrid._put_object(new_pt, adjacent_obj, grid, []) + placed_objects.add(adjacent_obj) + placed_objects.update(place_objects(new_pt, placed_objects)) + + new_pt = (new_pt[0] + 1, new_pt[1]) + + return placed_objects + + place_objects((0, 0), placed_objects) + + return grid + + @staticmethod + def _drop_inessential_morphisms(merged_morphisms): + r""" + Removes those morphisms which should appear in the diagram, + but which have no relevance to object layout. + + Currently this removes "loop" morphisms: the non-identity + morphisms with the same domains and codomains. + """ + morphisms = [m for m in merged_morphisms if m.domain != m.codomain] + return morphisms + + @staticmethod + def _get_connected_components(objects, merged_morphisms): + """ + Given a container of morphisms, returns a list of connected + components formed by these morphisms. A connected component + is represented by a diagram consisting of the corresponding + morphisms. + """ + component_index = {} + for o in objects: + component_index[o] = None + + # Get the underlying undirected graph of the diagram. + adjlist = DiagramGrid._get_undirected_graph(objects, merged_morphisms) + + def traverse_component(object, current_index): + """ + Does a depth-first search traversal of the component + containing ``object``. + """ + component_index[object] = current_index + for o in adjlist[object]: + if component_index[o] is None: + traverse_component(o, current_index) + + # Traverse all components. + current_index = 0 + for o in adjlist: + if component_index[o] is None: + traverse_component(o, current_index) + current_index += 1 + + # List the objects of the components. + component_objects = [[] for i in range(current_index)] + for o, idx in component_index.items(): + component_objects[idx].append(o) + + # Finally, list the morphisms belonging to each component. + # + # Note: If some objects are isolated, they will not get any + # morphisms at this stage, and since the layout algorithm + # relies, we are essentially going to lose this object. + # Therefore, check if there are isolated objects and, for each + # of them, provide the trivial identity morphism. It will get + # discarded later, but the object will be there. + + component_morphisms = [] + for component in component_objects: + current_morphisms = {} + for m in merged_morphisms: + if (m.domain in component) and (m.codomain in component): + current_morphisms[m] = merged_morphisms[m] + + if len(component) == 1: + # Let's add an identity morphism, for the sake of + # surely having morphisms in this component. + current_morphisms[IdentityMorphism(component[0])] = FiniteSet() + + component_morphisms.append(Diagram(current_morphisms)) + + return component_morphisms + + def __init__(self, diagram, groups=None, **hints): + premises = DiagramGrid._simplify_morphisms(diagram.premises) + conclusions = DiagramGrid._simplify_morphisms(diagram.conclusions) + all_merged_morphisms = DiagramGrid._merge_premises_conclusions( + premises, conclusions) + merged_morphisms = DiagramGrid._drop_inessential_morphisms( + all_merged_morphisms) + + # Store the merged morphisms for later use. + self._morphisms = all_merged_morphisms + + components = DiagramGrid._get_connected_components( + diagram.objects, all_merged_morphisms) + + if groups and (groups != diagram.objects): + # Lay out the diagram according to the groups. + self._grid = DiagramGrid._handle_groups( + diagram, groups, merged_morphisms, hints) + elif len(components) > 1: + # Note that we check for connectedness _before_ checking + # the layout hints because the layout strategies don't + # know how to deal with disconnected diagrams. + + # The diagram is disconnected. Lay out the components + # independently. + grids = [] + + # Sort the components to eventually get the grids arranged + # in a fixed, hash-independent order. + components = sorted(components, key=default_sort_key) + + for component in components: + grid = DiagramGrid(component, **hints) + grids.append(grid) + + # Throw the grids together, in a line. + total_width = sum(g.width for g in grids) + total_height = max(g.height for g in grids) + + grid = _GrowableGrid(total_width, total_height) + start_j = 0 + for g in grids: + for i in range(g.height): + for j in range(g.width): + grid[i, start_j + j] = g[i, j] + + start_j += g.width + + self._grid = grid + elif "layout" in hints: + if hints["layout"] == "sequential": + self._grid = DiagramGrid._sequential_layout( + diagram, merged_morphisms) + else: + self._grid = DiagramGrid._generic_layout(diagram, merged_morphisms) + + if hints.get("transpose"): + # Transpose the resulting grid. + grid = _GrowableGrid(self._grid.height, self._grid.width) + for i in range(self._grid.height): + for j in range(self._grid.width): + grid[j, i] = self._grid[i, j] + self._grid = grid + + @property + def width(self): + """ + Returns the number of columns in this diagram layout. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import Diagram, DiagramGrid + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g]) + >>> grid = DiagramGrid(diagram) + >>> grid.width + 2 + + """ + return self._grid.width + + @property + def height(self): + """ + Returns the number of rows in this diagram layout. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import Diagram, DiagramGrid + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g]) + >>> grid = DiagramGrid(diagram) + >>> grid.height + 2 + + """ + return self._grid.height + + def __getitem__(self, i_j): + """ + Returns the object placed in the row ``i`` and column ``j``. + The indices are 0-based. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import Diagram, DiagramGrid + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g]) + >>> grid = DiagramGrid(diagram) + >>> (grid[0, 0], grid[0, 1]) + (Object("A"), Object("B")) + >>> (grid[1, 0], grid[1, 1]) + (None, Object("C")) + + """ + i, j = i_j + return self._grid[i, j] + + @property + def morphisms(self): + """ + Returns those morphisms (and their properties) which are + sufficiently meaningful to be drawn. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import Diagram, DiagramGrid + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g]) + >>> grid = DiagramGrid(diagram) + >>> grid.morphisms + {NamedMorphism(Object("A"), Object("B"), "f"): EmptySet, + NamedMorphism(Object("B"), Object("C"), "g"): EmptySet} + + """ + return self._morphisms + + def __str__(self): + """ + Produces a string representation of this class. + + This method returns a string representation of the underlying + list of lists of objects. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism + >>> from sympy.categories import Diagram, DiagramGrid + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g]) + >>> grid = DiagramGrid(diagram) + >>> print(grid) + [[Object("A"), Object("B")], + [None, Object("C")]] + + """ + return repr(self._grid._array) + + +class ArrowStringDescription: + r""" + Stores the information necessary for producing an Xy-pic + description of an arrow. + + The principal goal of this class is to abstract away the string + representation of an arrow and to also provide the functionality + to produce the actual Xy-pic string. + + ``unit`` sets the unit which will be used to specify the amount of + curving and other distances. ``horizontal_direction`` should be a + string of ``"r"`` or ``"l"`` specifying the horizontal offset of the + target cell of the arrow relatively to the current one. + ``vertical_direction`` should specify the vertical offset using a + series of either ``"d"`` or ``"u"``. ``label_position`` should be + either ``"^"``, ``"_"``, or ``"|"`` to specify that the label should + be positioned above the arrow, below the arrow or just over the arrow, + in a break. Note that the notions "above" and "below" are relative + to arrow direction. ``label`` stores the morphism label. + + This works as follows (disregard the yet unexplained arguments): + + >>> from sympy.categories.diagram_drawing import ArrowStringDescription + >>> astr = ArrowStringDescription( + ... unit="mm", curving=None, curving_amount=None, + ... looping_start=None, looping_end=None, horizontal_direction="d", + ... vertical_direction="r", label_position="_", label="f") + >>> print(str(astr)) + \ar[dr]_{f} + + ``curving`` should be one of ``"^"``, ``"_"`` to specify in which + direction the arrow is going to curve. ``curving_amount`` is a number + describing how many ``unit``'s the morphism is going to curve: + + >>> astr = ArrowStringDescription( + ... unit="mm", curving="^", curving_amount=12, + ... looping_start=None, looping_end=None, horizontal_direction="d", + ... vertical_direction="r", label_position="_", label="f") + >>> print(str(astr)) + \ar@/^12mm/[dr]_{f} + + ``looping_start`` and ``looping_end`` are currently only used for + loop morphisms, those which have the same domain and codomain. + These two attributes should store a valid Xy-pic direction and + specify, correspondingly, the direction the arrow gets out into + and the direction the arrow gets back from: + + >>> astr = ArrowStringDescription( + ... unit="mm", curving=None, curving_amount=None, + ... looping_start="u", looping_end="l", horizontal_direction="", + ... vertical_direction="", label_position="_", label="f") + >>> print(str(astr)) + \ar@(u,l)[]_{f} + + ``label_displacement`` controls how far the arrow label is from + the ends of the arrow. For example, to position the arrow label + near the arrow head, use ">": + + >>> astr = ArrowStringDescription( + ... unit="mm", curving="^", curving_amount=12, + ... looping_start=None, looping_end=None, horizontal_direction="d", + ... vertical_direction="r", label_position="_", label="f") + >>> astr.label_displacement = ">" + >>> print(str(astr)) + \ar@/^12mm/[dr]_>{f} + + Finally, ``arrow_style`` is used to specify the arrow style. To + get a dashed arrow, for example, use "{-->}" as arrow style: + + >>> astr = ArrowStringDescription( + ... unit="mm", curving="^", curving_amount=12, + ... looping_start=None, looping_end=None, horizontal_direction="d", + ... vertical_direction="r", label_position="_", label="f") + >>> astr.arrow_style = "{-->}" + >>> print(str(astr)) + \ar@/^12mm/@{-->}[dr]_{f} + + Notes + ===== + + Instances of :class:`ArrowStringDescription` will be constructed + by :class:`XypicDiagramDrawer` and provided for further use in + formatters. The user is not expected to construct instances of + :class:`ArrowStringDescription` themselves. + + To be able to properly utilise this class, the reader is encouraged + to checkout the Xy-pic user guide, available at [Xypic]. + + See Also + ======== + + XypicDiagramDrawer + + References + ========== + + .. [Xypic] https://xy-pic.sourceforge.net/ + """ + def __init__(self, unit, curving, curving_amount, looping_start, + looping_end, horizontal_direction, vertical_direction, + label_position, label): + self.unit = unit + self.curving = curving + self.curving_amount = curving_amount + self.looping_start = looping_start + self.looping_end = looping_end + self.horizontal_direction = horizontal_direction + self.vertical_direction = vertical_direction + self.label_position = label_position + self.label = label + + self.label_displacement = "" + self.arrow_style = "" + + # This flag shows that the position of the label of this + # morphism was set while typesetting a curved morphism and + # should not be modified later. + self.forced_label_position = False + + def __str__(self): + if self.curving: + curving_str = "@/%s%d%s/" % (self.curving, self.curving_amount, + self.unit) + else: + curving_str = "" + + if self.looping_start and self.looping_end: + looping_str = "@(%s,%s)" % (self.looping_start, self.looping_end) + else: + looping_str = "" + + if self.arrow_style: + + style_str = "@" + self.arrow_style + else: + style_str = "" + + return "\\ar%s%s%s[%s%s]%s%s{%s}" % \ + (curving_str, looping_str, style_str, self.horizontal_direction, + self.vertical_direction, self.label_position, + self.label_displacement, self.label) + + +class XypicDiagramDrawer: + r""" + Given a :class:`~.Diagram` and the corresponding + :class:`DiagramGrid`, produces the Xy-pic representation of the + diagram. + + The most important method in this class is ``draw``. Consider the + following triangle diagram: + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g], {g * f: "unique"}) + + To draw this diagram, its objects need to be laid out with a + :class:`DiagramGrid`:: + + >>> grid = DiagramGrid(diagram) + + Finally, the drawing: + + >>> drawer = XypicDiagramDrawer() + >>> print(drawer.draw(diagram, grid)) + \xymatrix{ + A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ + C & + } + + For further details see the docstring of this method. + + To control the appearance of the arrows, formatters are used. The + dictionary ``arrow_formatters`` maps morphisms to formatter + functions. A formatter is accepts an + :class:`ArrowStringDescription` and is allowed to modify any of + the arrow properties exposed thereby. For example, to have all + morphisms with the property ``unique`` appear as dashed arrows, + and to have their names prepended with `\exists !`, the following + should be done: + + >>> def formatter(astr): + ... astr.label = r"\exists !" + astr.label + ... astr.arrow_style = "{-->}" + >>> drawer.arrow_formatters["unique"] = formatter + >>> print(drawer.draw(diagram, grid)) + \xymatrix{ + A \ar@{-->}[d]_{\exists !g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ + C & + } + + To modify the appearance of all arrows in the diagram, set + ``default_arrow_formatter``. For example, to place all morphism + labels a little bit farther from the arrow head so that they look + more centred, do as follows: + + >>> def default_formatter(astr): + ... astr.label_displacement = "(0.45)" + >>> drawer.default_arrow_formatter = default_formatter + >>> print(drawer.draw(diagram, grid)) + \xymatrix{ + A \ar@{-->}[d]_(0.45){\exists !g\circ f} \ar[r]^(0.45){f} & B \ar[ld]^(0.45){g} \\ + C & + } + + In some diagrams some morphisms are drawn as curved arrows. + Consider the following diagram: + + >>> D = Object("D") + >>> E = Object("E") + >>> h = NamedMorphism(D, A, "h") + >>> k = NamedMorphism(D, B, "k") + >>> diagram = Diagram([f, g, h, k]) + >>> grid = DiagramGrid(diagram) + >>> drawer = XypicDiagramDrawer() + >>> print(drawer.draw(diagram, grid)) + \xymatrix{ + A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_3mm/[ll]_{h} \\ + & C & + } + + To control how far the morphisms are curved by default, one can + use the ``unit`` and ``default_curving_amount`` attributes: + + >>> drawer.unit = "cm" + >>> drawer.default_curving_amount = 1 + >>> print(drawer.draw(diagram, grid)) + \xymatrix{ + A \ar[r]_{f} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_1cm/[ll]_{h} \\ + & C & + } + + In some diagrams, there are multiple curved morphisms between the + same two objects. To control by how much the curving changes + between two such successive morphisms, use + ``default_curving_step``: + + >>> drawer.default_curving_step = 1 + >>> h1 = NamedMorphism(A, D, "h1") + >>> diagram = Diagram([f, g, h, k, h1]) + >>> grid = DiagramGrid(diagram) + >>> print(drawer.draw(diagram, grid)) + \xymatrix{ + A \ar[r]_{f} \ar@/^1cm/[rr]^{h_{1}} & B \ar[d]^{g} & D \ar[l]^{k} \ar@/_2cm/[ll]_{h} \\ + & C & + } + + The default value of ``default_curving_step`` is 4 units. + + See Also + ======== + + draw, ArrowStringDescription + """ + def __init__(self): + self.unit = "mm" + self.default_curving_amount = 3 + self.default_curving_step = 4 + + # This dictionary maps properties to the corresponding arrow + # formatters. + self.arrow_formatters = {} + + # This is the default arrow formatter which will be applied to + # each arrow independently of its properties. + self.default_arrow_formatter = None + + @staticmethod + def _process_loop_morphism(i, j, grid, morphisms_str_info, object_coords): + """ + Produces the information required for constructing the string + representation of a loop morphism. This function is invoked + from ``_process_morphism``. + + See Also + ======== + + _process_morphism + """ + curving = "" + label_pos = "^" + looping_start = "" + looping_end = "" + + # This is a loop morphism. Count how many morphisms stick + # in each of the four quadrants. Note that straight + # vertical and horizontal morphisms count in two quadrants + # at the same time (i.e., a morphism going up counts both + # in the first and the second quadrants). + + # The usual numbering (counterclockwise) of quadrants + # applies. + quadrant = [0, 0, 0, 0] + + obj = grid[i, j] + + for m, m_str_info in morphisms_str_info.items(): + if (m.domain == obj) and (m.codomain == obj): + # That's another loop morphism. Check how it + # loops and mark the corresponding quadrants as + # busy. + (l_s, l_e) = (m_str_info.looping_start, m_str_info.looping_end) + + if (l_s, l_e) == ("r", "u"): + quadrant[0] += 1 + elif (l_s, l_e) == ("u", "l"): + quadrant[1] += 1 + elif (l_s, l_e) == ("l", "d"): + quadrant[2] += 1 + elif (l_s, l_e) == ("d", "r"): + quadrant[3] += 1 + + continue + if m.domain == obj: + (end_i, end_j) = object_coords[m.codomain] + goes_out = True + elif m.codomain == obj: + (end_i, end_j) = object_coords[m.domain] + goes_out = False + else: + continue + + d_i = end_i - i + d_j = end_j - j + m_curving = m_str_info.curving + + if (d_i != 0) and (d_j != 0): + # This is really a diagonal morphism. Detect the + # quadrant. + if (d_i > 0) and (d_j > 0): + quadrant[0] += 1 + elif (d_i > 0) and (d_j < 0): + quadrant[1] += 1 + elif (d_i < 0) and (d_j < 0): + quadrant[2] += 1 + elif (d_i < 0) and (d_j > 0): + quadrant[3] += 1 + elif d_i == 0: + # Knowing where the other end of the morphism is + # and which way it goes, we now have to decide + # which quadrant is now the upper one and which is + # the lower one. + if d_j > 0: + if goes_out: + upper_quadrant = 0 + lower_quadrant = 3 + else: + upper_quadrant = 3 + lower_quadrant = 0 + else: + if goes_out: + upper_quadrant = 2 + lower_quadrant = 1 + else: + upper_quadrant = 1 + lower_quadrant = 2 + + if m_curving: + if m_curving == "^": + quadrant[upper_quadrant] += 1 + elif m_curving == "_": + quadrant[lower_quadrant] += 1 + else: + # This morphism counts in both upper and lower + # quadrants. + quadrant[upper_quadrant] += 1 + quadrant[lower_quadrant] += 1 + elif d_j == 0: + # Knowing where the other end of the morphism is + # and which way it goes, we now have to decide + # which quadrant is now the left one and which is + # the right one. + if d_i < 0: + if goes_out: + left_quadrant = 1 + right_quadrant = 0 + else: + left_quadrant = 0 + right_quadrant = 1 + else: + if goes_out: + left_quadrant = 3 + right_quadrant = 2 + else: + left_quadrant = 2 + right_quadrant = 3 + + if m_curving: + if m_curving == "^": + quadrant[left_quadrant] += 1 + elif m_curving == "_": + quadrant[right_quadrant] += 1 + else: + # This morphism counts in both upper and lower + # quadrants. + quadrant[left_quadrant] += 1 + quadrant[right_quadrant] += 1 + + # Pick the freest quadrant to curve our morphism into. + freest_quadrant = 0 + for i in range(4): + if quadrant[i] < quadrant[freest_quadrant]: + freest_quadrant = i + + # Now set up proper looping. + (looping_start, looping_end) = [("r", "u"), ("u", "l"), ("l", "d"), + ("d", "r")][freest_quadrant] + + return (curving, label_pos, looping_start, looping_end) + + @staticmethod + def _process_horizontal_morphism(i, j, target_j, grid, morphisms_str_info, + object_coords): + """ + Produces the information required for constructing the string + representation of a horizontal morphism. This function is + invoked from ``_process_morphism``. + + See Also + ======== + + _process_morphism + """ + # The arrow is horizontal. Check if it goes from left to + # right (``backwards == False``) or from right to left + # (``backwards == True``). + backwards = False + start = j + end = target_j + if end < start: + (start, end) = (end, start) + backwards = True + + # Let's see which objects are there between ``start`` and + # ``end``, and then count how many morphisms stick out + # upwards, and how many stick out downwards. + # + # For example, consider the situation: + # + # B1 C1 + # | | + # A--B--C--D + # | + # B2 + # + # Between the objects `A` and `D` there are two objects: + # `B` and `C`. Further, there are two morphisms which + # stick out upward (the ones between `B1` and `B` and + # between `C` and `C1`) and one morphism which sticks out + # downward (the one between `B and `B2`). + # + # We need this information to decide how to curve the + # arrow between `A` and `D`. First of all, since there + # are two objects between `A` and `D``, we must curve the + # arrow. Then, we will have it curve downward, because + # there is more space (less morphisms stick out downward + # than upward). + up = [] + down = [] + straight_horizontal = [] + for k in range(start + 1, end): + obj = grid[i, k] + if not obj: + continue + + for m in morphisms_str_info: + if m.domain == obj: + (end_i, end_j) = object_coords[m.codomain] + elif m.codomain == obj: + (end_i, end_j) = object_coords[m.domain] + else: + continue + + if end_i > i: + down.append(m) + elif end_i < i: + up.append(m) + elif not morphisms_str_info[m].curving: + # This is a straight horizontal morphism, + # because it has no curving. + straight_horizontal.append(m) + + if len(up) < len(down): + # More morphisms stick out downward than upward, let's + # curve the morphism up. + if backwards: + curving = "_" + label_pos = "_" + else: + curving = "^" + label_pos = "^" + + # Assure that the straight horizontal morphisms have + # their labels on the lower side of the arrow. + for m in straight_horizontal: + (i1, j1) = object_coords[m.domain] + (i2, j2) = object_coords[m.codomain] + + m_str_info = morphisms_str_info[m] + if j1 < j2: + m_str_info.label_position = "_" + else: + m_str_info.label_position = "^" + + # Don't allow any further modifications of the + # position of this label. + m_str_info.forced_label_position = True + else: + # More morphisms stick out downward than upward, let's + # curve the morphism up. + if backwards: + curving = "^" + label_pos = "^" + else: + curving = "_" + label_pos = "_" + + # Assure that the straight horizontal morphisms have + # their labels on the upper side of the arrow. + for m in straight_horizontal: + (i1, j1) = object_coords[m.domain] + (i2, j2) = object_coords[m.codomain] + + m_str_info = morphisms_str_info[m] + if j1 < j2: + m_str_info.label_position = "^" + else: + m_str_info.label_position = "_" + + # Don't allow any further modifications of the + # position of this label. + m_str_info.forced_label_position = True + + return (curving, label_pos) + + @staticmethod + def _process_vertical_morphism(i, j, target_i, grid, morphisms_str_info, + object_coords): + """ + Produces the information required for constructing the string + representation of a vertical morphism. This function is + invoked from ``_process_morphism``. + + See Also + ======== + + _process_morphism + """ + # This arrow is vertical. Check if it goes from top to + # bottom (``backwards == False``) or from bottom to top + # (``backwards == True``). + backwards = False + start = i + end = target_i + if end < start: + (start, end) = (end, start) + backwards = True + + # Let's see which objects are there between ``start`` and + # ``end``, and then count how many morphisms stick out to + # the left, and how many stick out to the right. + # + # See the corresponding comment in the previous branch of + # this if-statement for more details. + left = [] + right = [] + straight_vertical = [] + for k in range(start + 1, end): + obj = grid[k, j] + if not obj: + continue + + for m in morphisms_str_info: + if m.domain == obj: + (end_i, end_j) = object_coords[m.codomain] + elif m.codomain == obj: + (end_i, end_j) = object_coords[m.domain] + else: + continue + + if end_j > j: + right.append(m) + elif end_j < j: + left.append(m) + elif not morphisms_str_info[m].curving: + # This is a straight vertical morphism, + # because it has no curving. + straight_vertical.append(m) + + if len(left) < len(right): + # More morphisms stick out to the left than to the + # right, let's curve the morphism to the right. + if backwards: + curving = "^" + label_pos = "^" + else: + curving = "_" + label_pos = "_" + + # Assure that the straight vertical morphisms have + # their labels on the left side of the arrow. + for m in straight_vertical: + (i1, j1) = object_coords[m.domain] + (i2, j2) = object_coords[m.codomain] + + m_str_info = morphisms_str_info[m] + if i1 < i2: + m_str_info.label_position = "^" + else: + m_str_info.label_position = "_" + + # Don't allow any further modifications of the + # position of this label. + m_str_info.forced_label_position = True + else: + # More morphisms stick out to the right than to the + # left, let's curve the morphism to the left. + if backwards: + curving = "_" + label_pos = "_" + else: + curving = "^" + label_pos = "^" + + # Assure that the straight vertical morphisms have + # their labels on the right side of the arrow. + for m in straight_vertical: + (i1, j1) = object_coords[m.domain] + (i2, j2) = object_coords[m.codomain] + + m_str_info = morphisms_str_info[m] + if i1 < i2: + m_str_info.label_position = "_" + else: + m_str_info.label_position = "^" + + # Don't allow any further modifications of the + # position of this label. + m_str_info.forced_label_position = True + + return (curving, label_pos) + + def _process_morphism(self, diagram, grid, morphism, object_coords, + morphisms, morphisms_str_info): + """ + Given the required information, produces the string + representation of ``morphism``. + """ + def repeat_string_cond(times, str_gt, str_lt): + """ + If ``times > 0``, repeats ``str_gt`` ``times`` times. + Otherwise, repeats ``str_lt`` ``-times`` times. + """ + if times > 0: + return str_gt * times + else: + return str_lt * (-times) + + def count_morphisms_undirected(A, B): + """ + Counts how many processed morphisms there are between the + two supplied objects. + """ + return len([m for m in morphisms_str_info + if {m.domain, m.codomain} == {A, B}]) + + def count_morphisms_filtered(dom, cod, curving): + """ + Counts the processed morphisms which go out of ``dom`` + into ``cod`` with curving ``curving``. + """ + return len([m for m, m_str_info in morphisms_str_info.items() + if (m.domain, m.codomain) == (dom, cod) and + (m_str_info.curving == curving)]) + + (i, j) = object_coords[morphism.domain] + (target_i, target_j) = object_coords[morphism.codomain] + + # We now need to determine the direction of + # the arrow. + delta_i = target_i - i + delta_j = target_j - j + vertical_direction = repeat_string_cond(delta_i, + "d", "u") + horizontal_direction = repeat_string_cond(delta_j, + "r", "l") + + curving = "" + label_pos = "^" + looping_start = "" + looping_end = "" + + if (delta_i == 0) and (delta_j == 0): + # This is a loop morphism. + (curving, label_pos, looping_start, + looping_end) = XypicDiagramDrawer._process_loop_morphism( + i, j, grid, morphisms_str_info, object_coords) + elif (delta_i == 0) and (abs(j - target_j) > 1): + # This is a horizontal morphism. + (curving, label_pos) = XypicDiagramDrawer._process_horizontal_morphism( + i, j, target_j, grid, morphisms_str_info, object_coords) + elif (delta_j == 0) and (abs(i - target_i) > 1): + # This is a vertical morphism. + (curving, label_pos) = XypicDiagramDrawer._process_vertical_morphism( + i, j, target_i, grid, morphisms_str_info, object_coords) + + count = count_morphisms_undirected(morphism.domain, morphism.codomain) + curving_amount = "" + if curving: + # This morphisms should be curved anyway. + curving_amount = self.default_curving_amount + count * \ + self.default_curving_step + elif count: + # There are no objects between the domain and codomain of + # the current morphism, but this is not there already are + # some morphisms with the same domain and codomain, so we + # have to curve this one. + curving = "^" + filtered_morphisms = count_morphisms_filtered( + morphism.domain, morphism.codomain, curving) + curving_amount = self.default_curving_amount + \ + filtered_morphisms * \ + self.default_curving_step + + # Let's now get the name of the morphism. + morphism_name = "" + if isinstance(morphism, IdentityMorphism): + morphism_name = "id_{%s}" + latex(grid[i, j]) + elif isinstance(morphism, CompositeMorphism): + component_names = [latex(Symbol(component.name)) for + component in morphism.components] + component_names.reverse() + morphism_name = "\\circ ".join(component_names) + elif isinstance(morphism, NamedMorphism): + morphism_name = latex(Symbol(morphism.name)) + + return ArrowStringDescription( + self.unit, curving, curving_amount, looping_start, + looping_end, horizontal_direction, vertical_direction, + label_pos, morphism_name) + + @staticmethod + def _check_free_space_horizontal(dom_i, dom_j, cod_j, grid): + """ + For a horizontal morphism, checks whether there is free space + (i.e., space not occupied by any objects) above the morphism + or below it. + """ + if dom_j < cod_j: + (start, end) = (dom_j, cod_j) + backwards = False + else: + (start, end) = (cod_j, dom_j) + backwards = True + + # Check for free space above. + if dom_i == 0: + free_up = True + else: + free_up = all(grid[dom_i - 1, j] for j in + range(start, end + 1)) + + # Check for free space below. + if dom_i == grid.height - 1: + free_down = True + else: + free_down = not any(grid[dom_i + 1, j] for j in + range(start, end + 1)) + + return (free_up, free_down, backwards) + + @staticmethod + def _check_free_space_vertical(dom_i, cod_i, dom_j, grid): + """ + For a vertical morphism, checks whether there is free space + (i.e., space not occupied by any objects) to the left of the + morphism or to the right of it. + """ + if dom_i < cod_i: + (start, end) = (dom_i, cod_i) + backwards = False + else: + (start, end) = (cod_i, dom_i) + backwards = True + + # Check if there's space to the left. + if dom_j == 0: + free_left = True + else: + free_left = not any(grid[i, dom_j - 1] for i in + range(start, end + 1)) + + if dom_j == grid.width - 1: + free_right = True + else: + free_right = not any(grid[i, dom_j + 1] for i in + range(start, end + 1)) + + return (free_left, free_right, backwards) + + @staticmethod + def _check_free_space_diagonal(dom_i, cod_i, dom_j, cod_j, grid): + """ + For a diagonal morphism, checks whether there is free space + (i.e., space not occupied by any objects) above the morphism + or below it. + """ + def abs_xrange(start, end): + if start < end: + return range(start, end + 1) + else: + return range(end, start + 1) + + if dom_i < cod_i and dom_j < cod_j: + # This morphism goes from top-left to + # bottom-right. + (start_i, start_j) = (dom_i, dom_j) + (end_i, end_j) = (cod_i, cod_j) + backwards = False + elif dom_i > cod_i and dom_j > cod_j: + # This morphism goes from bottom-right to + # top-left. + (start_i, start_j) = (cod_i, cod_j) + (end_i, end_j) = (dom_i, dom_j) + backwards = True + if dom_i < cod_i and dom_j > cod_j: + # This morphism goes from top-right to + # bottom-left. + (start_i, start_j) = (dom_i, dom_j) + (end_i, end_j) = (cod_i, cod_j) + backwards = True + elif dom_i > cod_i and dom_j < cod_j: + # This morphism goes from bottom-left to + # top-right. + (start_i, start_j) = (cod_i, cod_j) + (end_i, end_j) = (dom_i, dom_j) + backwards = False + + # This is an attempt at a fast and furious strategy to + # decide where there is free space on the two sides of + # a diagonal morphism. For a diagonal morphism + # starting at ``(start_i, start_j)`` and ending at + # ``(end_i, end_j)`` the rectangle defined by these + # two points is considered. The slope of the diagonal + # ``alpha`` is then computed. Then, for every cell + # ``(i, j)`` within the rectangle, the slope + # ``alpha1`` of the line through ``(start_i, + # start_j)`` and ``(i, j)`` is considered. If + # ``alpha1`` is between 0 and ``alpha``, the point + # ``(i, j)`` is above the diagonal, if ``alpha1`` is + # between ``alpha`` and infinity, the point is below + # the diagonal. Also note that, with some beforehand + # precautions, this trick works for both the main and + # the secondary diagonals of the rectangle. + + # I have considered the possibility to only follow the + # shorter diagonals immediately above and below the + # main (or secondary) diagonal. This, however, + # wouldn't have resulted in much performance gain or + # better detection of outer edges, because of + # relatively small sizes of diagram grids, while the + # code would have become harder to understand. + + alpha = float(end_i - start_i)/(end_j - start_j) + free_up = True + free_down = True + for i in abs_xrange(start_i, end_i): + if not free_up and not free_down: + break + + for j in abs_xrange(start_j, end_j): + if not free_up and not free_down: + break + + if (i, j) == (start_i, start_j): + continue + + if j == start_j: + alpha1 = "inf" + else: + alpha1 = float(i - start_i)/(j - start_j) + + if grid[i, j]: + if (alpha1 == "inf") or (abs(alpha1) > abs(alpha)): + free_down = False + elif abs(alpha1) < abs(alpha): + free_up = False + + return (free_up, free_down, backwards) + + def _push_labels_out(self, morphisms_str_info, grid, object_coords): + """ + For all straight morphisms which form the visual boundary of + the laid out diagram, puts their labels on their outer sides. + """ + def set_label_position(free1, free2, pos1, pos2, backwards, m_str_info): + """ + Given the information about room available to one side and + to the other side of a morphism (``free1`` and ``free2``), + sets the position of the morphism label in such a way that + it is on the freer side. This latter operations involves + choice between ``pos1`` and ``pos2``, taking ``backwards`` + in consideration. + + Thus this function will do nothing if either both ``free1 + == True`` and ``free2 == True`` or both ``free1 == False`` + and ``free2 == False``. In either case, choosing one side + over the other presents no advantage. + """ + if backwards: + (pos1, pos2) = (pos2, pos1) + + if free1 and not free2: + m_str_info.label_position = pos1 + elif free2 and not free1: + m_str_info.label_position = pos2 + + for m, m_str_info in morphisms_str_info.items(): + if m_str_info.curving or m_str_info.forced_label_position: + # This is either a curved morphism, and curved + # morphisms have other magic, or the position of this + # label has already been fixed. + continue + + if m.domain == m.codomain: + # This is a loop morphism, their labels, again have a + # different magic. + continue + + (dom_i, dom_j) = object_coords[m.domain] + (cod_i, cod_j) = object_coords[m.codomain] + + if dom_i == cod_i: + # Horizontal morphism. + (free_up, free_down, + backwards) = XypicDiagramDrawer._check_free_space_horizontal( + dom_i, dom_j, cod_j, grid) + + set_label_position(free_up, free_down, "^", "_", + backwards, m_str_info) + elif dom_j == cod_j: + # Vertical morphism. + (free_left, free_right, + backwards) = XypicDiagramDrawer._check_free_space_vertical( + dom_i, cod_i, dom_j, grid) + + set_label_position(free_left, free_right, "_", "^", + backwards, m_str_info) + else: + # A diagonal morphism. + (free_up, free_down, + backwards) = XypicDiagramDrawer._check_free_space_diagonal( + dom_i, cod_i, dom_j, cod_j, grid) + + set_label_position(free_up, free_down, "^", "_", + backwards, m_str_info) + + @staticmethod + def _morphism_sort_key(morphism, object_coords): + """ + Provides a morphism sorting key such that horizontal or + vertical morphisms between neighbouring objects come + first, then horizontal or vertical morphisms between more + far away objects, and finally, all other morphisms. + """ + (i, j) = object_coords[morphism.domain] + (target_i, target_j) = object_coords[morphism.codomain] + + if morphism.domain == morphism.codomain: + # Loop morphisms should get after diagonal morphisms + # so that the proper direction in which to curve the + # loop can be determined. + return (3, 0, default_sort_key(morphism)) + + if target_i == i: + return (1, abs(target_j - j), default_sort_key(morphism)) + + if target_j == j: + return (1, abs(target_i - i), default_sort_key(morphism)) + + # Diagonal morphism. + return (2, 0, default_sort_key(morphism)) + + @staticmethod + def _build_xypic_string(diagram, grid, morphisms, + morphisms_str_info, diagram_format): + """ + Given a collection of :class:`ArrowStringDescription` + describing the morphisms of a diagram and the object layout + information of a diagram, produces the final Xy-pic picture. + """ + # Build the mapping between objects and morphisms which have + # them as domains. + object_morphisms = {} + for obj in diagram.objects: + object_morphisms[obj] = [] + for morphism in morphisms: + object_morphisms[morphism.domain].append(morphism) + + result = "\\xymatrix%s{\n" % diagram_format + + for i in range(grid.height): + for j in range(grid.width): + obj = grid[i, j] + if obj: + result += latex(obj) + " " + + morphisms_to_draw = object_morphisms[obj] + for morphism in morphisms_to_draw: + result += str(morphisms_str_info[morphism]) + " " + + # Don't put the & after the last column. + if j < grid.width - 1: + result += "& " + + # Don't put the line break after the last row. + if i < grid.height - 1: + result += "\\\\" + result += "\n" + + result += "}\n" + + return result + + def draw(self, diagram, grid, masked=None, diagram_format=""): + r""" + Returns the Xy-pic representation of ``diagram`` laid out in + ``grid``. + + Consider the following simple triangle diagram. + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> from sympy.categories import DiagramGrid, XypicDiagramDrawer + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g], {g * f: "unique"}) + + To draw this diagram, its objects need to be laid out with a + :class:`DiagramGrid`:: + + >>> grid = DiagramGrid(diagram) + + Finally, the drawing: + + >>> drawer = XypicDiagramDrawer() + >>> print(drawer.draw(diagram, grid)) + \xymatrix{ + A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ + C & + } + + The argument ``masked`` can be used to skip morphisms in the + presentation of the diagram: + + >>> print(drawer.draw(diagram, grid, masked=[g * f])) + \xymatrix{ + A \ar[r]^{f} & B \ar[ld]^{g} \\ + C & + } + + Finally, the ``diagram_format`` argument can be used to + specify the format string of the diagram. For example, to + increase the spacing by 1 cm, proceeding as follows: + + >>> print(drawer.draw(diagram, grid, diagram_format="@+1cm")) + \xymatrix@+1cm{ + A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ + C & + } + + """ + # This method works in several steps. It starts by removing + # the masked morphisms, if necessary, and then maps objects to + # their positions in the grid (coordinate tuples). Remember + # that objects are unique in ``Diagram`` and in the layout + # produced by ``DiagramGrid``, so every object is mapped to a + # single coordinate pair. + # + # The next step is the central step and is concerned with + # analysing the morphisms of the diagram and deciding how to + # draw them. For example, how to curve the arrows is decided + # at this step. The bulk of the analysis is implemented in + # ``_process_morphism``, to the result of which the + # appropriate formatters are applied. + # + # The result of the previous step is a list of + # ``ArrowStringDescription``. After the analysis and + # application of formatters, some extra logic tries to assure + # better positioning of morphism labels (for example, an + # attempt is made to avoid the situations when arrows cross + # labels). This functionality constitutes the next step and + # is implemented in ``_push_labels_out``. Note that label + # positions which have been set via a formatter are not + # affected in this step. + # + # Finally, at the closing step, the array of + # ``ArrowStringDescription`` and the layout information + # incorporated in ``DiagramGrid`` are combined to produce the + # resulting Xy-pic picture. This part of code lies in + # ``_build_xypic_string``. + + if not masked: + morphisms_props = grid.morphisms + else: + morphisms_props = {} + for m, props in grid.morphisms.items(): + if m in masked: + continue + morphisms_props[m] = props + + # Build the mapping between objects and their position in the + # grid. + object_coords = {} + for i in range(grid.height): + for j in range(grid.width): + if grid[i, j]: + object_coords[grid[i, j]] = (i, j) + + morphisms = sorted(morphisms_props, + key=lambda m: XypicDiagramDrawer._morphism_sort_key( + m, object_coords)) + + # Build the tuples defining the string representations of + # morphisms. + morphisms_str_info = {} + for morphism in morphisms: + string_description = self._process_morphism( + diagram, grid, morphism, object_coords, morphisms, + morphisms_str_info) + + if self.default_arrow_formatter: + self.default_arrow_formatter(string_description) + + for prop in morphisms_props[morphism]: + # prop is a Symbol. TODO: Find out why. + if prop.name in self.arrow_formatters: + formatter = self.arrow_formatters[prop.name] + formatter(string_description) + + morphisms_str_info[morphism] = string_description + + # Reposition the labels a bit. + self._push_labels_out(morphisms_str_info, grid, object_coords) + + return XypicDiagramDrawer._build_xypic_string( + diagram, grid, morphisms, morphisms_str_info, diagram_format) + + +def xypic_draw_diagram(diagram, masked=None, diagram_format="", + groups=None, **hints): + r""" + Provides a shortcut combining :class:`DiagramGrid` and + :class:`XypicDiagramDrawer`. Returns an Xy-pic presentation of + ``diagram``. The argument ``masked`` is a list of morphisms which + will be not be drawn. The argument ``diagram_format`` is the + format string inserted after "\xymatrix". ``groups`` should be a + set of logical groups. The ``hints`` will be passed directly to + the constructor of :class:`DiagramGrid`. + + For more information about the arguments, see the docstrings of + :class:`DiagramGrid` and ``XypicDiagramDrawer.draw``. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> from sympy.categories import xypic_draw_diagram + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> diagram = Diagram([f, g], {g * f: "unique"}) + >>> print(xypic_draw_diagram(diagram)) + \xymatrix{ + A \ar[d]_{g\circ f} \ar[r]^{f} & B \ar[ld]^{g} \\ + C & + } + + See Also + ======== + + XypicDiagramDrawer, DiagramGrid + """ + grid = DiagramGrid(diagram, groups, **hints) + drawer = XypicDiagramDrawer() + return drawer.draw(diagram, grid, masked, diagram_format) + + +@doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',)) +def preview_diagram(diagram, masked=None, diagram_format="", groups=None, + output='png', viewer=None, euler=True, **hints): + """ + Combines the functionality of ``xypic_draw_diagram`` and + ``sympy.printing.preview``. The arguments ``masked``, + ``diagram_format``, ``groups``, and ``hints`` are passed to + ``xypic_draw_diagram``, while ``output``, ``viewer, and ``euler`` + are passed to ``preview``. + + Examples + ======== + + >>> from sympy.categories import Object, NamedMorphism, Diagram + >>> from sympy.categories import preview_diagram + >>> A = Object("A") + >>> B = Object("B") + >>> C = Object("C") + >>> f = NamedMorphism(A, B, "f") + >>> g = NamedMorphism(B, C, "g") + >>> d = Diagram([f, g], {g * f: "unique"}) + >>> preview_diagram(d) + + See Also + ======== + + XypicDiagramDrawer + """ + from sympy.printing import preview + latex_output = xypic_draw_diagram(diagram, masked, diagram_format, + groups, **hints) + preview(latex_output, output, viewer, euler, ("xypic",)) diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__init__.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf62321980dbf488bdee39fdb74fac2c9c7a70d5 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3febbf9b1a8bec464c6aeb43797f3b4ecf7d0c22 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7f088f63108ff8f03e7e5465deca537e7b2fb7c Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..cfac32229768fb5903b23b11ffb236912c0b931e --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/test_baseclasses.py @@ -0,0 +1,209 @@ +from sympy.categories import (Object, Morphism, IdentityMorphism, + NamedMorphism, CompositeMorphism, + Diagram, Category) +from sympy.categories.baseclasses import Class +from sympy.testing.pytest import raises +from sympy.core.containers import (Dict, Tuple) +from sympy.sets import EmptySet +from sympy.sets.sets import FiniteSet + + +def test_morphisms(): + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + + # Test the base morphism. + f = NamedMorphism(A, B, "f") + assert f.domain == A + assert f.codomain == B + assert f == NamedMorphism(A, B, "f") + + # Test identities. + id_A = IdentityMorphism(A) + id_B = IdentityMorphism(B) + assert id_A.domain == A + assert id_A.codomain == A + assert id_A == IdentityMorphism(A) + assert id_A != id_B + + # Test named morphisms. + g = NamedMorphism(B, C, "g") + assert g.name == "g" + assert g != f + assert g == NamedMorphism(B, C, "g") + assert g != NamedMorphism(B, C, "f") + + # Test composite morphisms. + assert f == CompositeMorphism(f) + + k = g.compose(f) + assert k.domain == A + assert k.codomain == C + assert k.components == Tuple(f, g) + assert g * f == k + assert CompositeMorphism(f, g) == k + + assert CompositeMorphism(g * f) == g * f + + # Test the associativity of composition. + h = NamedMorphism(C, D, "h") + + p = h * g + u = h * g * f + + assert h * k == u + assert p * f == u + assert CompositeMorphism(f, g, h) == u + + # Test flattening. + u2 = u.flatten("u") + assert isinstance(u2, NamedMorphism) + assert u2.name == "u" + assert u2.domain == A + assert u2.codomain == D + + # Test identities. + assert f * id_A == f + assert id_B * f == f + assert id_A * id_A == id_A + assert CompositeMorphism(id_A) == id_A + + # Test bad compositions. + raises(ValueError, lambda: f * g) + + raises(TypeError, lambda: f.compose(None)) + raises(TypeError, lambda: id_A.compose(None)) + raises(TypeError, lambda: f * None) + raises(TypeError, lambda: id_A * None) + + raises(TypeError, lambda: CompositeMorphism(f, None, 1)) + + raises(ValueError, lambda: NamedMorphism(A, B, "")) + raises(NotImplementedError, lambda: Morphism(A, B)) + + +def test_diagram(): + A = Object("A") + B = Object("B") + C = Object("C") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + id_A = IdentityMorphism(A) + id_B = IdentityMorphism(B) + + empty = EmptySet + + # Test the addition of identities. + d1 = Diagram([f]) + + assert d1.objects == FiniteSet(A, B) + assert d1.hom(A, B) == (FiniteSet(f), empty) + assert d1.hom(A, A) == (FiniteSet(id_A), empty) + assert d1.hom(B, B) == (FiniteSet(id_B), empty) + + assert d1 == Diagram([id_A, f]) + assert d1 == Diagram([f, f]) + + # Test the addition of composites. + d2 = Diagram([f, g]) + homAC = d2.hom(A, C)[0] + + assert d2.objects == FiniteSet(A, B, C) + assert g * f in d2.premises.keys() + assert homAC == FiniteSet(g * f) + + # Test equality, inequality and hash. + d11 = Diagram([f]) + + assert d1 == d11 + assert d1 != d2 + assert hash(d1) == hash(d11) + + d11 = Diagram({f: "unique"}) + assert d1 != d11 + + # Make sure that (re-)adding composites (with new properties) + # works as expected. + d = Diagram([f, g], {g * f: "unique"}) + assert d.conclusions == Dict({g * f: FiniteSet("unique")}) + + # Check the hom-sets when there are premises and conclusions. + assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) + d = Diagram([f, g], [g * f]) + assert d.hom(A, C) == (FiniteSet(g * f), FiniteSet(g * f)) + + # Check how the properties of composite morphisms are computed. + d = Diagram({f: ["unique", "isomorphism"], g: "unique"}) + assert d.premises[g * f] == FiniteSet("unique") + + # Check that conclusion morphisms with new objects are not allowed. + d = Diagram([f], [g]) + assert d.conclusions == Dict({}) + + # Test an empty diagram. + d = Diagram() + assert d.premises == Dict({}) + assert d.conclusions == Dict({}) + assert d.objects == empty + + # Check a SymPy Dict object. + d = Diagram(Dict({f: FiniteSet("unique", "isomorphism"), g: "unique"})) + assert d.premises[g * f] == FiniteSet("unique") + + # Check the addition of components of composite morphisms. + d = Diagram([g * f]) + assert f in d.premises + assert g in d.premises + + # Check subdiagrams. + d = Diagram([f, g], {g * f: "unique"}) + + d1 = Diagram([f]) + assert d.is_subdiagram(d1) + assert not d1.is_subdiagram(d) + + d = Diagram([NamedMorphism(B, A, "f'")]) + assert not d.is_subdiagram(d1) + assert not d1.is_subdiagram(d) + + d1 = Diagram([f, g], {g * f: ["unique", "something"]}) + assert not d.is_subdiagram(d1) + assert not d1.is_subdiagram(d) + + d = Diagram({f: "blooh"}) + d1 = Diagram({f: "bleeh"}) + assert not d.is_subdiagram(d1) + assert not d1.is_subdiagram(d) + + d = Diagram([f, g], {f: "unique", g * f: "veryunique"}) + d1 = d.subdiagram_from_objects(FiniteSet(A, B)) + assert d1 == Diagram([f], {f: "unique"}) + raises(ValueError, lambda: d.subdiagram_from_objects(FiniteSet(A, + Object("D")))) + + raises(ValueError, lambda: Diagram({IdentityMorphism(A): "unique"})) + + +def test_category(): + A = Object("A") + B = Object("B") + C = Object("C") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + + d1 = Diagram([f, g]) + d2 = Diagram([f]) + + objects = d1.objects | d2.objects + + K = Category("K", objects, commutative_diagrams=[d1, d2]) + + assert K.name == "K" + assert K.objects == Class(objects) + assert K.commutative_diagrams == FiniteSet(d1, d2) + + raises(ValueError, lambda: Category("")) diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py new file mode 100644 index 0000000000000000000000000000000000000000..63a13266cd6b58f6a85aad4af0813b395acbb5e1 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py @@ -0,0 +1,919 @@ +from sympy.categories.diagram_drawing import _GrowableGrid, ArrowStringDescription +from sympy.categories import (DiagramGrid, Object, NamedMorphism, + Diagram, XypicDiagramDrawer, xypic_draw_diagram) +from sympy.sets.sets import FiniteSet + + +def test_GrowableGrid(): + grid = _GrowableGrid(1, 2) + + # Check dimensions. + assert grid.width == 1 + assert grid.height == 2 + + # Check initialization of elements. + assert grid[0, 0] is None + assert grid[1, 0] is None + + # Check assignment to elements. + grid[0, 0] = 1 + grid[1, 0] = "two" + + assert grid[0, 0] == 1 + assert grid[1, 0] == "two" + + # Check appending a row. + grid.append_row() + + assert grid.width == 1 + assert grid.height == 3 + + assert grid[0, 0] == 1 + assert grid[1, 0] == "two" + assert grid[2, 0] is None + + # Check appending a column. + grid.append_column() + assert grid.width == 2 + assert grid.height == 3 + + assert grid[0, 0] == 1 + assert grid[1, 0] == "two" + assert grid[2, 0] is None + + assert grid[0, 1] is None + assert grid[1, 1] is None + assert grid[2, 1] is None + + grid = _GrowableGrid(1, 2) + grid[0, 0] = 1 + grid[1, 0] = "two" + + # Check prepending a row. + grid.prepend_row() + assert grid.width == 1 + assert grid.height == 3 + + assert grid[0, 0] is None + assert grid[1, 0] == 1 + assert grid[2, 0] == "two" + + # Check prepending a column. + grid.prepend_column() + assert grid.width == 2 + assert grid.height == 3 + + assert grid[0, 0] is None + assert grid[1, 0] is None + assert grid[2, 0] is None + + assert grid[0, 1] is None + assert grid[1, 1] == 1 + assert grid[2, 1] == "two" + + +def test_DiagramGrid(): + # Set up some objects and morphisms. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + E = Object("E") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(D, A, "h") + k = NamedMorphism(D, B, "k") + + # A one-morphism diagram. + d = Diagram([f]) + grid = DiagramGrid(d) + + assert grid.width == 2 + assert grid.height == 1 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid.morphisms == {f: FiniteSet()} + + # A triangle. + d = Diagram([f, g], {g * f: "unique"}) + grid = DiagramGrid(d) + + assert grid.width == 2 + assert grid.height == 2 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[1, 0] == C + assert grid[1, 1] is None + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), + g * f: FiniteSet("unique")} + + # A triangle with a "loop" morphism. + l_A = NamedMorphism(A, A, "l_A") + d = Diagram([f, g, l_A]) + grid = DiagramGrid(d) + + assert grid.width == 2 + assert grid.height == 2 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[1, 0] is None + assert grid[1, 1] == C + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), l_A: FiniteSet()} + + # A simple diagram. + d = Diagram([f, g, h, k]) + grid = DiagramGrid(d) + + assert grid.width == 3 + assert grid.height == 2 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] == D + assert grid[1, 0] is None + assert grid[1, 1] == C + assert grid[1, 2] is None + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), + k: FiniteSet()} + + assert str(grid) == '[[Object("A"), Object("B"), Object("D")], ' \ + '[None, Object("C"), None]]' + + # A chain of morphisms. + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(C, D, "h") + k = NamedMorphism(D, E, "k") + d = Diagram([f, g, h, k]) + grid = DiagramGrid(d) + + assert grid.width == 3 + assert grid.height == 3 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] is None + assert grid[1, 0] is None + assert grid[1, 1] == C + assert grid[1, 2] == D + assert grid[2, 0] is None + assert grid[2, 1] is None + assert grid[2, 2] == E + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), + k: FiniteSet()} + + # A square. + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, D, "g") + h = NamedMorphism(A, C, "h") + k = NamedMorphism(C, D, "k") + d = Diagram([f, g, h, k]) + grid = DiagramGrid(d) + + assert grid.width == 2 + assert grid.height == 2 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[1, 0] == C + assert grid[1, 1] == D + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), + k: FiniteSet()} + + # A strange diagram which resulted from a typo when creating a + # test for five lemma, but which allowed to stop one extra problem + # in the algorithm. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + E = Object("E") + A_ = Object("A'") + B_ = Object("B'") + C_ = Object("C'") + D_ = Object("D'") + E_ = Object("E'") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(C, D, "h") + i = NamedMorphism(D, E, "i") + + # These 4 morphisms should be between primed objects. + j = NamedMorphism(A, B, "j") + k = NamedMorphism(B, C, "k") + l = NamedMorphism(C, D, "l") + m = NamedMorphism(D, E, "m") + + o = NamedMorphism(A, A_, "o") + p = NamedMorphism(B, B_, "p") + q = NamedMorphism(C, C_, "q") + r = NamedMorphism(D, D_, "r") + s = NamedMorphism(E, E_, "s") + + d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s]) + grid = DiagramGrid(d) + + assert grid.width == 3 + assert grid.height == 4 + assert grid[0, 0] is None + assert grid[0, 1] == A + assert grid[0, 2] == A_ + assert grid[1, 0] == C + assert grid[1, 1] == B + assert grid[1, 2] == B_ + assert grid[2, 0] == C_ + assert grid[2, 1] == D + assert grid[2, 2] == D_ + assert grid[3, 0] is None + assert grid[3, 1] == E + assert grid[3, 2] == E_ + + morphisms = {} + for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]: + morphisms[m] = FiniteSet() + assert grid.morphisms == morphisms + + # A cube. + A1 = Object("A1") + A2 = Object("A2") + A3 = Object("A3") + A4 = Object("A4") + A5 = Object("A5") + A6 = Object("A6") + A7 = Object("A7") + A8 = Object("A8") + + # The top face of the cube. + f1 = NamedMorphism(A1, A2, "f1") + f2 = NamedMorphism(A1, A3, "f2") + f3 = NamedMorphism(A2, A4, "f3") + f4 = NamedMorphism(A3, A4, "f3") + + # The bottom face of the cube. + f5 = NamedMorphism(A5, A6, "f5") + f6 = NamedMorphism(A5, A7, "f6") + f7 = NamedMorphism(A6, A8, "f7") + f8 = NamedMorphism(A7, A8, "f8") + + # The remaining morphisms. + f9 = NamedMorphism(A1, A5, "f9") + f10 = NamedMorphism(A2, A6, "f10") + f11 = NamedMorphism(A3, A7, "f11") + f12 = NamedMorphism(A4, A8, "f11") + + d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]) + grid = DiagramGrid(d) + + assert grid.width == 4 + assert grid.height == 3 + assert grid[0, 0] is None + assert grid[0, 1] == A5 + assert grid[0, 2] == A6 + assert grid[0, 3] is None + assert grid[1, 0] is None + assert grid[1, 1] == A1 + assert grid[1, 2] == A2 + assert grid[1, 3] is None + assert grid[2, 0] == A7 + assert grid[2, 1] == A3 + assert grid[2, 2] == A4 + assert grid[2, 3] == A8 + + morphisms = {} + for m in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]: + morphisms[m] = FiniteSet() + assert grid.morphisms == morphisms + + # A line diagram. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + E = Object("E") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(C, D, "h") + i = NamedMorphism(D, E, "i") + d = Diagram([f, g, h, i]) + grid = DiagramGrid(d, layout="sequential") + + assert grid.width == 5 + assert grid.height == 1 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] == C + assert grid[0, 3] == D + assert grid[0, 4] == E + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), + i: FiniteSet()} + + # Test the transposed version. + grid = DiagramGrid(d, layout="sequential", transpose=True) + + assert grid.width == 1 + assert grid.height == 5 + assert grid[0, 0] == A + assert grid[1, 0] == B + assert grid[2, 0] == C + assert grid[3, 0] == D + assert grid[4, 0] == E + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(), + i: FiniteSet()} + + # A pullback. + m1 = NamedMorphism(A, B, "m1") + m2 = NamedMorphism(A, C, "m2") + s1 = NamedMorphism(B, D, "s1") + s2 = NamedMorphism(C, D, "s2") + f1 = NamedMorphism(E, B, "f1") + f2 = NamedMorphism(E, C, "f2") + g = NamedMorphism(E, A, "g") + + d = Diagram([m1, m2, s1, s2, f1, f2], {g: "unique"}) + grid = DiagramGrid(d) + + assert grid.width == 3 + assert grid.height == 2 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] == E + assert grid[1, 0] == C + assert grid[1, 1] == D + assert grid[1, 2] is None + + morphisms = {g: FiniteSet("unique")} + for m in [m1, m2, s1, s2, f1, f2]: + morphisms[m] = FiniteSet() + assert grid.morphisms == morphisms + + # Test the pullback with sequential layout, just for stress + # testing. + grid = DiagramGrid(d, layout="sequential") + + assert grid.width == 5 + assert grid.height == 1 + assert grid[0, 0] == D + assert grid[0, 1] == B + assert grid[0, 2] == A + assert grid[0, 3] == C + assert grid[0, 4] == E + assert grid.morphisms == morphisms + + # Test a pullback with object grouping. + grid = DiagramGrid(d, groups=FiniteSet(E, FiniteSet(A, B, C, D))) + + assert grid.width == 3 + assert grid.height == 2 + assert grid[0, 0] == E + assert grid[0, 1] == A + assert grid[0, 2] == B + assert grid[1, 0] is None + assert grid[1, 1] == C + assert grid[1, 2] == D + assert grid.morphisms == morphisms + + # Five lemma, actually. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + E = Object("E") + A_ = Object("A'") + B_ = Object("B'") + C_ = Object("C'") + D_ = Object("D'") + E_ = Object("E'") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(C, D, "h") + i = NamedMorphism(D, E, "i") + + j = NamedMorphism(A_, B_, "j") + k = NamedMorphism(B_, C_, "k") + l = NamedMorphism(C_, D_, "l") + m = NamedMorphism(D_, E_, "m") + + o = NamedMorphism(A, A_, "o") + p = NamedMorphism(B, B_, "p") + q = NamedMorphism(C, C_, "q") + r = NamedMorphism(D, D_, "r") + s = NamedMorphism(E, E_, "s") + + d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s]) + grid = DiagramGrid(d) + + assert grid.width == 5 + assert grid.height == 3 + assert grid[0, 0] is None + assert grid[0, 1] == A + assert grid[0, 2] == A_ + assert grid[0, 3] is None + assert grid[0, 4] is None + assert grid[1, 0] == C + assert grid[1, 1] == B + assert grid[1, 2] == B_ + assert grid[1, 3] == C_ + assert grid[1, 4] is None + assert grid[2, 0] == D + assert grid[2, 1] == E + assert grid[2, 2] is None + assert grid[2, 3] == D_ + assert grid[2, 4] == E_ + + morphisms = {} + for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]: + morphisms[m] = FiniteSet() + assert grid.morphisms == morphisms + + # Test the five lemma with object grouping. + grid = DiagramGrid(d, FiniteSet( + FiniteSet(A, B, C, D, E), FiniteSet(A_, B_, C_, D_, E_))) + + assert grid.width == 6 + assert grid.height == 3 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] is None + assert grid[0, 3] == A_ + assert grid[0, 4] == B_ + assert grid[0, 5] is None + assert grid[1, 0] is None + assert grid[1, 1] == C + assert grid[1, 2] == D + assert grid[1, 3] is None + assert grid[1, 4] == C_ + assert grid[1, 5] == D_ + assert grid[2, 0] is None + assert grid[2, 1] is None + assert grid[2, 2] == E + assert grid[2, 3] is None + assert grid[2, 4] is None + assert grid[2, 5] == E_ + assert grid.morphisms == morphisms + + # Test the five lemma with object grouping, but mixing containers + # to represent groups. + grid = DiagramGrid(d, [(A, B, C, D, E), {A_, B_, C_, D_, E_}]) + + assert grid.width == 6 + assert grid.height == 3 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] is None + assert grid[0, 3] == A_ + assert grid[0, 4] == B_ + assert grid[0, 5] is None + assert grid[1, 0] is None + assert grid[1, 1] == C + assert grid[1, 2] == D + assert grid[1, 3] is None + assert grid[1, 4] == C_ + assert grid[1, 5] == D_ + assert grid[2, 0] is None + assert grid[2, 1] is None + assert grid[2, 2] == E + assert grid[2, 3] is None + assert grid[2, 4] is None + assert grid[2, 5] == E_ + assert grid.morphisms == morphisms + + # Test the five lemma with object grouping and hints. + grid = DiagramGrid(d, { + FiniteSet(A, B, C, D, E): {"layout": "sequential", + "transpose": True}, + FiniteSet(A_, B_, C_, D_, E_): {"layout": "sequential", + "transpose": True}}, + transpose=True) + + assert grid.width == 5 + assert grid.height == 2 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] == C + assert grid[0, 3] == D + assert grid[0, 4] == E + assert grid[1, 0] == A_ + assert grid[1, 1] == B_ + assert grid[1, 2] == C_ + assert grid[1, 3] == D_ + assert grid[1, 4] == E_ + assert grid.morphisms == morphisms + + # A two-triangle disconnected diagram. + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + f_ = NamedMorphism(A_, B_, "f") + g_ = NamedMorphism(B_, C_, "g") + d = Diagram([f, g, f_, g_], {g * f: "unique", g_ * f_: "unique"}) + grid = DiagramGrid(d) + + assert grid.width == 4 + assert grid.height == 2 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] == A_ + assert grid[0, 3] == B_ + assert grid[1, 0] == C + assert grid[1, 1] is None + assert grid[1, 2] == C_ + assert grid[1, 3] is None + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), f_: FiniteSet(), + g_: FiniteSet(), g * f: FiniteSet("unique"), + g_ * f_: FiniteSet("unique")} + + # A two-morphism disconnected diagram. + f = NamedMorphism(A, B, "f") + g = NamedMorphism(C, D, "g") + d = Diagram([f, g]) + grid = DiagramGrid(d) + + assert grid.width == 4 + assert grid.height == 1 + assert grid[0, 0] == A + assert grid[0, 1] == B + assert grid[0, 2] == C + assert grid[0, 3] == D + assert grid.morphisms == {f: FiniteSet(), g: FiniteSet()} + + # Test a one-object diagram. + f = NamedMorphism(A, A, "f") + d = Diagram([f]) + grid = DiagramGrid(d) + + assert grid.width == 1 + assert grid.height == 1 + assert grid[0, 0] == A + + # Test a two-object disconnected diagram. + g = NamedMorphism(B, B, "g") + d = Diagram([f, g]) + grid = DiagramGrid(d) + + assert grid.width == 2 + assert grid.height == 1 + assert grid[0, 0] == A + assert grid[0, 1] == B + + +def test_DiagramGrid_pseudopod(): + # Test a diagram in which even growing a pseudopod does not + # eventually help. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + E = Object("E") + F = Object("F") + A_ = Object("A'") + B_ = Object("B'") + C_ = Object("C'") + D_ = Object("D'") + E_ = Object("E'") + + f1 = NamedMorphism(A, B, "f1") + f2 = NamedMorphism(A, C, "f2") + f3 = NamedMorphism(A, D, "f3") + f4 = NamedMorphism(A, E, "f4") + f5 = NamedMorphism(A, A_, "f5") + f6 = NamedMorphism(A, B_, "f6") + f7 = NamedMorphism(A, C_, "f7") + f8 = NamedMorphism(A, D_, "f8") + f9 = NamedMorphism(A, E_, "f9") + f10 = NamedMorphism(A, F, "f10") + d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]) + grid = DiagramGrid(d) + + assert grid.width == 5 + assert grid.height == 3 + assert grid[0, 0] == E + assert grid[0, 1] == C + assert grid[0, 2] == C_ + assert grid[0, 3] == E_ + assert grid[0, 4] == F + assert grid[1, 0] == D + assert grid[1, 1] == A + assert grid[1, 2] == A_ + assert grid[1, 3] is None + assert grid[1, 4] is None + assert grid[2, 0] == D_ + assert grid[2, 1] == B + assert grid[2, 2] == B_ + assert grid[2, 3] is None + assert grid[2, 4] is None + + morphisms = {} + for f in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]: + morphisms[f] = FiniteSet() + assert grid.morphisms == morphisms + + +def test_ArrowStringDescription(): + astr = ArrowStringDescription("cm", "", None, "", "", "d", "r", "_", "f") + assert str(astr) == "\\ar[dr]_{f}" + + astr = ArrowStringDescription("cm", "", 12, "", "", "d", "r", "_", "f") + assert str(astr) == "\\ar[dr]_{f}" + + astr = ArrowStringDescription("cm", "^", 12, "", "", "d", "r", "_", "f") + assert str(astr) == "\\ar@/^12cm/[dr]_{f}" + + astr = ArrowStringDescription("cm", "", 12, "r", "", "d", "r", "_", "f") + assert str(astr) == "\\ar[dr]_{f}" + + astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f") + assert str(astr) == "\\ar@(r,u)[dr]_{f}" + + astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f") + assert str(astr) == "\\ar@(r,u)[dr]_{f}" + + astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f") + astr.arrow_style = "{-->}" + assert str(astr) == "\\ar@(r,u)@{-->}[dr]_{f}" + + astr = ArrowStringDescription("cm", "_", 12, "", "", "d", "r", "_", "f") + astr.arrow_style = "{-->}" + assert str(astr) == "\\ar@/_12cm/@{-->}[dr]_{f}" + + +def test_XypicDiagramDrawer_line(): + # A linear diagram. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + E = Object("E") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(C, D, "h") + i = NamedMorphism(D, E, "i") + d = Diagram([f, g, h, i]) + grid = DiagramGrid(d, layout="sequential") + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[r]^{f} & B \\ar[r]^{g} & C \\ar[r]^{h} & D \\ar[r]^{i} & E \n" \ + "}\n" + + # The same diagram, transposed. + grid = DiagramGrid(d, layout="sequential", transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[d]^{f} \\\\\n" \ + "B \\ar[d]^{g} \\\\\n" \ + "C \\ar[d]^{h} \\\\\n" \ + "D \\ar[d]^{i} \\\\\n" \ + "E \n" \ + "}\n" + + +def test_XypicDiagramDrawer_triangle(): + # A triangle diagram. + A = Object("A") + B = Object("B") + C = Object("C") + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + + d = Diagram([f, g], {g * f: "unique"}) + grid = DiagramGrid(d) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[d]_{g\\circ f} \\ar[r]^{f} & B \\ar[ld]^{g} \\\\\n" \ + "C & \n" \ + "}\n" + + # The same diagram, transposed. + grid = DiagramGrid(d, transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \ + "B \\ar[ru]_{g} & \n" \ + "}\n" + + # The same diagram, with a masked morphism. + assert drawer.draw(d, grid, masked=[g]) == "\\xymatrix{\n" \ + "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \ + "B & \n" \ + "}\n" + + # The same diagram with a formatter for "unique". + def formatter(astr): + astr.label = "\\exists !" + astr.label + astr.arrow_style = "{-->}" + + drawer.arrow_formatters["unique"] = formatter + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar@{-->}[r]^{\\exists !g\\circ f} \\ar[d]_{f} & C \\\\\n" \ + "B \\ar[ru]_{g} & \n" \ + "}\n" + + # The same diagram with a default formatter. + def default_formatter(astr): + astr.label_displacement = "(0.45)" + + drawer.default_arrow_formatter = default_formatter + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar@{-->}[r]^(0.45){\\exists !g\\circ f} \\ar[d]_(0.45){f} & C \\\\\n" \ + "B \\ar[ru]_(0.45){g} & \n" \ + "}\n" + + # A triangle diagram with a lot of morphisms between the same + # objects. + f1 = NamedMorphism(B, A, "f1") + f2 = NamedMorphism(A, B, "f2") + g1 = NamedMorphism(C, B, "g1") + g2 = NamedMorphism(B, C, "g2") + d = Diagram([f, f1, f2, g, g1, g2], {f1 * g1: "unique", g2 * f2: "unique"}) + + grid = DiagramGrid(d, transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid, masked=[f1*g1*g2*f2, g2*f2*f1*g1]) == \ + "\\xymatrix{\n" \ + "A \\ar[r]^{g_{2}\\circ f_{2}} \\ar[d]_{f} \\ar@/^3mm/[d]^{f_{2}} " \ + "& C \\ar@/^3mm/[l]^{f_{1}\\circ g_{1}} \\ar@/^3mm/[ld]^{g_{1}} \\\\\n" \ + "B \\ar@/^3mm/[u]^{f_{1}} \\ar[ru]_{g} \\ar@/^3mm/[ru]^{g_{2}} & \n" \ + "}\n" + + +def test_XypicDiagramDrawer_cube(): + # A cube diagram. + A1 = Object("A1") + A2 = Object("A2") + A3 = Object("A3") + A4 = Object("A4") + A5 = Object("A5") + A6 = Object("A6") + A7 = Object("A7") + A8 = Object("A8") + + # The top face of the cube. + f1 = NamedMorphism(A1, A2, "f1") + f2 = NamedMorphism(A1, A3, "f2") + f3 = NamedMorphism(A2, A4, "f3") + f4 = NamedMorphism(A3, A4, "f3") + + # The bottom face of the cube. + f5 = NamedMorphism(A5, A6, "f5") + f6 = NamedMorphism(A5, A7, "f6") + f7 = NamedMorphism(A6, A8, "f7") + f8 = NamedMorphism(A7, A8, "f8") + + # The remaining morphisms. + f9 = NamedMorphism(A1, A5, "f9") + f10 = NamedMorphism(A2, A6, "f10") + f11 = NamedMorphism(A3, A7, "f11") + f12 = NamedMorphism(A4, A8, "f11") + + d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]) + grid = DiagramGrid(d) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "& A_{5} \\ar[r]^{f_{5}} \\ar[ldd]_{f_{6}} & A_{6} \\ar[rdd]^{f_{7}} " \ + "& \\\\\n" \ + "& A_{1} \\ar[r]^{f_{1}} \\ar[d]^{f_{2}} \\ar[u]^{f_{9}} & A_{2} " \ + "\\ar[d]^{f_{3}} \\ar[u]_{f_{10}} & \\\\\n" \ + "A_{7} \\ar@/_3mm/[rrr]_{f_{8}} & A_{3} \\ar[r]^{f_{3}} \\ar[l]_{f_{11}} " \ + "& A_{4} \\ar[r]^{f_{11}} & A_{8} \n" \ + "}\n" + + # The same diagram, transposed. + grid = DiagramGrid(d, transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "& & A_{7} \\ar@/^3mm/[ddd]^{f_{8}} \\\\\n" \ + "A_{5} \\ar[d]_{f_{5}} \\ar[rru]^{f_{6}} & A_{1} \\ar[d]^{f_{1}} " \ + "\\ar[r]^{f_{2}} \\ar[l]^{f_{9}} & A_{3} \\ar[d]_{f_{3}} " \ + "\\ar[u]^{f_{11}} \\\\\n" \ + "A_{6} \\ar[rrd]_{f_{7}} & A_{2} \\ar[r]^{f_{3}} \\ar[l]^{f_{10}} " \ + "& A_{4} \\ar[d]_{f_{11}} \\\\\n" \ + "& & A_{8} \n" \ + "}\n" + + +def test_XypicDiagramDrawer_curved_and_loops(): + # A simple diagram, with a curved arrow. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(D, A, "h") + k = NamedMorphism(D, B, "k") + d = Diagram([f, g, h, k]) + grid = DiagramGrid(d) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[r]_{f} & B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_3mm/[ll]_{h} \\\\\n" \ + "& C & \n" \ + "}\n" + + # The same diagram, transposed. + grid = DiagramGrid(d, transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[d]^{f} & \\\\\n" \ + "B \\ar[r]^{g} & C \\\\\n" \ + "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \ + "}\n" + + # The same diagram, larger and rotated. + assert drawer.draw(d, grid, diagram_format="@+1cm@dr") == \ + "\\xymatrix@+1cm@dr{\n" \ + "A \\ar[d]^{f} & \\\\\n" \ + "B \\ar[r]^{g} & C \\\\\n" \ + "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \ + "}\n" + + # A simple diagram with three curved arrows. + h1 = NamedMorphism(D, A, "h1") + h2 = NamedMorphism(A, D, "h2") + k = NamedMorphism(D, B, "k") + d = Diagram([f, g, h, k, h1, h2]) + grid = DiagramGrid(d) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \ + "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\\\\n" \ + "& C & \n" \ + "}\n" + + # The same diagram, transposed. + grid = DiagramGrid(d, transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} & \\\\\n" \ + "B \\ar[r]^{g} & C \\\\\n" \ + "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} & \n" \ + "}\n" + + # The same diagram, with "loop" morphisms. + l_A = NamedMorphism(A, A, "l_A") + l_D = NamedMorphism(D, D, "l_D") + l_C = NamedMorphism(C, C, "l_C") + d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C]) + grid = DiagramGrid(d) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \ + "& B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_7mm/[ll]_{h} " \ + "\\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} \\\\\n" \ + "& C \\ar@(l,d)[]^{l_{C}} & \n" \ + "}\n" + + # The same diagram with "loop" morphisms, transposed. + grid = DiagramGrid(d, transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} & \\\\\n" \ + "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\\\\n" \ + "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \ + "\\ar@(l,d)[]^{l_{D}} & \n" \ + "}\n" + + # The same diagram with two "loop" morphisms per object. + l_A_ = NamedMorphism(A, A, "n_A") + l_D_ = NamedMorphism(D, D, "n_D") + l_C_ = NamedMorphism(C, C, "n_C") + d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C, l_A_, l_D_, l_C_]) + grid = DiagramGrid(d) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \ + "\\ar@/^3mm/@(l,d)[]^{n_{A}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \ + "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} " \ + "\\ar@/^3mm/@(d,r)[]^{n_{D}} \\\\\n" \ + "& C \\ar@(l,d)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} & \n" \ + "}\n" + + # The same diagram with two "loop" morphisms per object, transposed. + grid = DiagramGrid(d, transpose=True) + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == "\\xymatrix{\n" \ + "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} " \ + "\\ar@/^3mm/@(u,l)[]^{n_{A}} & \\\\\n" \ + "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} \\\\\n" \ + "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \ + "\\ar@(l,d)[]^{l_{D}} \\ar@/^3mm/@(d,r)[]^{n_{D}} & \n" \ + "}\n" + + +def test_xypic_draw_diagram(): + # A linear diagram. + A = Object("A") + B = Object("B") + C = Object("C") + D = Object("D") + E = Object("E") + + f = NamedMorphism(A, B, "f") + g = NamedMorphism(B, C, "g") + h = NamedMorphism(C, D, "h") + i = NamedMorphism(D, E, "i") + d = Diagram([f, g, h, i]) + + grid = DiagramGrid(d, layout="sequential") + drawer = XypicDiagramDrawer() + assert drawer.draw(d, grid) == xypic_draw_diagram(d, layout="sequential") diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/__init__.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8846a99510601c9675103e21ef5a0a1e839fdd11 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/__init__.py @@ -0,0 +1,19 @@ +from .diffgeom import ( + BaseCovarDerivativeOp, BaseScalarField, BaseVectorField, Commutator, + contravariant_order, CoordSystem, CoordinateSymbol, + CovarDerivativeOp, covariant_order, Differential, intcurve_diffequ, + intcurve_series, LieDerivative, Manifold, metric_to_Christoffel_1st, + metric_to_Christoffel_2nd, metric_to_Ricci_components, + metric_to_Riemann_components, Patch, Point, TensorProduct, twoform_to_matrix, + vectors_in_basis, WedgeProduct, +) + +__all__ = [ + 'BaseCovarDerivativeOp', 'BaseScalarField', 'BaseVectorField', 'Commutator', + 'contravariant_order', 'CoordSystem', 'CoordinateSymbol', + 'CovarDerivativeOp', 'covariant_order', 'Differential', 'intcurve_diffequ', + 'intcurve_series', 'LieDerivative', 'Manifold', 'metric_to_Christoffel_1st', + 'metric_to_Christoffel_2nd', 'metric_to_Ricci_components', + 'metric_to_Riemann_components', 'Patch', 'Point', 'TensorProduct', + 'twoform_to_matrix', 'vectors_in_basis', 'WedgeProduct', +] diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/rn.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/rn.py new file mode 100644 index 0000000000000000000000000000000000000000..897c7e82bc804d260612f79c820af92632f3b281 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/rn.py @@ -0,0 +1,143 @@ +"""Predefined R^n manifolds together with common coord. systems. + +Coordinate systems are predefined as well as the transformation laws between +them. + +Coordinate functions can be accessed as attributes of the manifold (eg `R2.x`), +as attributes of the coordinate systems (eg `R2_r.x` and `R2_p.theta`), or by +using the usual `coord_sys.coord_function(index, name)` interface. +""" + +from typing import Any +import warnings + +from sympy.core.symbol import (Dummy, symbols) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin) +from .diffgeom import Manifold, Patch, CoordSystem + +__all__ = [ + 'R2', 'R2_origin', 'relations_2d', 'R2_r', 'R2_p', + 'R3', 'R3_origin', 'relations_3d', 'R3_r', 'R3_c', 'R3_s' +] + +############################################################################### +# R2 +############################################################################### +R2: Any = Manifold('R^2', 2) + +R2_origin: Any = Patch('origin', R2) + +x, y = symbols('x y', real=True) +r, theta = symbols('rho theta', nonnegative=True) + +relations_2d = { + ('rectangular', 'polar'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))], + ('polar', 'rectangular'): [(r, theta), (r*cos(theta), r*sin(theta))], +} + +R2_r: Any = CoordSystem('rectangular', R2_origin, (x, y), relations_2d) +R2_p: Any = CoordSystem('polar', R2_origin, (r, theta), relations_2d) + +# support deprecated feature +with warnings.catch_warnings(): + warnings.simplefilter("ignore") + x, y, r, theta = symbols('x y r theta', cls=Dummy) + R2_r.connect_to(R2_p, [x, y], + [sqrt(x**2 + y**2), atan2(y, x)], + inverse=False, fill_in_gaps=False) + R2_p.connect_to(R2_r, [r, theta], + [r*cos(theta), r*sin(theta)], + inverse=False, fill_in_gaps=False) + +# Defining the basis coordinate functions and adding shortcuts for them to the +# manifold and the patch. +R2.x, R2.y = R2_origin.x, R2_origin.y = R2_r.x, R2_r.y = R2_r.coord_functions() +R2.r, R2.theta = R2_origin.r, R2_origin.theta = R2_p.r, R2_p.theta = R2_p.coord_functions() + +# Defining the basis vector fields and adding shortcuts for them to the +# manifold and the patch. +R2.e_x, R2.e_y = R2_origin.e_x, R2_origin.e_y = R2_r.e_x, R2_r.e_y = R2_r.base_vectors() +R2.e_r, R2.e_theta = R2_origin.e_r, R2_origin.e_theta = R2_p.e_r, R2_p.e_theta = R2_p.base_vectors() + +# Defining the basis oneform fields and adding shortcuts for them to the +# manifold and the patch. +R2.dx, R2.dy = R2_origin.dx, R2_origin.dy = R2_r.dx, R2_r.dy = R2_r.base_oneforms() +R2.dr, R2.dtheta = R2_origin.dr, R2_origin.dtheta = R2_p.dr, R2_p.dtheta = R2_p.base_oneforms() + +############################################################################### +# R3 +############################################################################### +R3: Any = Manifold('R^3', 3) + +R3_origin: Any = Patch('origin', R3) + +x, y, z = symbols('x y z', real=True) +rho, psi, r, theta, phi = symbols('rho psi r theta phi', nonnegative=True) + +relations_3d = { + ('rectangular', 'cylindrical'): [(x, y, z), + (sqrt(x**2 + y**2), atan2(y, x), z)], + ('cylindrical', 'rectangular'): [(rho, psi, z), + (rho*cos(psi), rho*sin(psi), z)], + ('rectangular', 'spherical'): [(x, y, z), + (sqrt(x**2 + y**2 + z**2), + acos(z/sqrt(x**2 + y**2 + z**2)), + atan2(y, x))], + ('spherical', 'rectangular'): [(r, theta, phi), + (r*sin(theta)*cos(phi), + r*sin(theta)*sin(phi), + r*cos(theta))], + ('cylindrical', 'spherical'): [(rho, psi, z), + (sqrt(rho**2 + z**2), + acos(z/sqrt(rho**2 + z**2)), + psi)], + ('spherical', 'cylindrical'): [(r, theta, phi), + (r*sin(theta), phi, r*cos(theta))], +} + +R3_r: Any = CoordSystem('rectangular', R3_origin, (x, y, z), relations_3d) +R3_c: Any = CoordSystem('cylindrical', R3_origin, (rho, psi, z), relations_3d) +R3_s: Any = CoordSystem('spherical', R3_origin, (r, theta, phi), relations_3d) + +# support deprecated feature +with warnings.catch_warnings(): + warnings.simplefilter("ignore") + x, y, z, rho, psi, r, theta, phi = symbols('x y z rho psi r theta phi', cls=Dummy) + R3_r.connect_to(R3_c, [x, y, z], + [sqrt(x**2 + y**2), atan2(y, x), z], + inverse=False, fill_in_gaps=False) + R3_c.connect_to(R3_r, [rho, psi, z], + [rho*cos(psi), rho*sin(psi), z], + inverse=False, fill_in_gaps=False) + ## rectangular <-> spherical + R3_r.connect_to(R3_s, [x, y, z], + [sqrt(x**2 + y**2 + z**2), acos(z/ + sqrt(x**2 + y**2 + z**2)), atan2(y, x)], + inverse=False, fill_in_gaps=False) + R3_s.connect_to(R3_r, [r, theta, phi], + [r*sin(theta)*cos(phi), r*sin( + theta)*sin(phi), r*cos(theta)], + inverse=False, fill_in_gaps=False) + ## cylindrical <-> spherical + R3_c.connect_to(R3_s, [rho, psi, z], + [sqrt(rho**2 + z**2), acos(z/sqrt(rho**2 + z**2)), psi], + inverse=False, fill_in_gaps=False) + R3_s.connect_to(R3_c, [r, theta, phi], + [r*sin(theta), phi, r*cos(theta)], + inverse=False, fill_in_gaps=False) + +# Defining the basis coordinate functions. +R3_r.x, R3_r.y, R3_r.z = R3_r.coord_functions() +R3_c.rho, R3_c.psi, R3_c.z = R3_c.coord_functions() +R3_s.r, R3_s.theta, R3_s.phi = R3_s.coord_functions() + +# Defining the basis vector fields. +R3_r.e_x, R3_r.e_y, R3_r.e_z = R3_r.base_vectors() +R3_c.e_rho, R3_c.e_psi, R3_c.e_z = R3_c.base_vectors() +R3_s.e_r, R3_s.e_theta, R3_s.e_phi = R3_s.base_vectors() + +# Defining the basis oneform fields. +R3_r.dx, R3_r.dy, R3_r.dz = R3_r.base_oneforms() +R3_c.drho, R3_c.dpsi, R3_c.dz = R3_c.base_oneforms() +R3_s.dr, R3_s.dtheta, R3_s.dphi = R3_s.base_oneforms() diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72b98cbf611a1001c13938d697518357b58c8b24 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db857e162523df0e3943737aa42b1c52e15a4364 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..c649fd9fcb9acdf1f410a021966c6e0fee62cc2b --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/test_class_structure.py @@ -0,0 +1,33 @@ +from sympy.diffgeom import Manifold, Patch, CoordSystem, Point +from sympy.core.function import Function +from sympy.core.symbol import symbols +from sympy.testing.pytest import warns_deprecated_sympy + +m = Manifold('m', 2) +p = Patch('p', m) +a, b = symbols('a b') +cs = CoordSystem('cs', p, [a, b]) +x, y = symbols('x y') +f = Function('f') +s1, s2 = cs.coord_functions() +v1, v2 = cs.base_vectors() +f1, f2 = cs.base_oneforms() + +def test_point(): + point = Point(cs, [x, y]) + assert point != Point(cs, [2, y]) + #TODO assert point.subs(x, 2) == Point(cs, [2, y]) + #TODO assert point.free_symbols == set([x, y]) + +def test_subs(): + assert s1.subs(s1, s2) == s2 + assert v1.subs(v1, v2) == v2 + assert f1.subs(f1, f2) == f2 + assert (x*f(s1) + y).subs(s1, s2) == x*f(s2) + y + assert (f(s1)*v1).subs(v1, v2) == f(s1)*v2 + assert (y*f(s1)*f1).subs(f1, f2) == y*f(s1)*f2 + +def test_deprecated(): + with warns_deprecated_sympy(): + cs_wname = CoordSystem('cs', p, ['a', 'b']) + assert cs_wname == cs_wname.func(*cs_wname.args) diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3c9265785896b8f4ffa3a2b41816ca90579758 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/diffgeom/tests/test_diffgeom.py @@ -0,0 +1,342 @@ +from sympy.core import Lambda, Symbol, symbols +from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r, R3_c, R3_s, R2_origin +from sympy.diffgeom import (Manifold, Patch, CoordSystem, Commutator, Differential, TensorProduct, + WedgeProduct, BaseCovarDerivativeOp, CovarDerivativeOp, LieDerivative, + covariant_order, contravariant_order, twoform_to_matrix, metric_to_Christoffel_1st, + metric_to_Christoffel_2nd, metric_to_Riemann_components, + metric_to_Ricci_components, intcurve_diffequ, intcurve_series) +from sympy.simplify import trigsimp, simplify +from sympy.functions import sqrt, atan2, sin +from sympy.matrices import Matrix +from sympy.testing.pytest import raises, nocache_fail +from sympy.testing.pytest import warns_deprecated_sympy + +TP = TensorProduct + + +def test_coordsys_transform(): + # test inverse transforms + p, q, r, s = symbols('p q r s') + rel = {('first', 'second'): [(p, q), (q, -p)]} + R2_pq = CoordSystem('first', R2_origin, [p, q], rel) + R2_rs = CoordSystem('second', R2_origin, [r, s], rel) + r, s = R2_rs.symbols + assert R2_rs.transform(R2_pq) == Matrix([[-s], [r]]) + + # inverse transform impossible case + a, b = symbols('a b', positive=True) + rel = {('first', 'second'): [(a,), (-a,)]} + R2_a = CoordSystem('first', R2_origin, [a], rel) + R2_b = CoordSystem('second', R2_origin, [b], rel) + # This transformation is uninvertible because there is no positive a, b satisfying a = -b + with raises(NotImplementedError): + R2_b.transform(R2_a) + + # inverse transform ambiguous case + c, d = symbols('c d') + rel = {('first', 'second'): [(c,), (c**2,)]} + R2_c = CoordSystem('first', R2_origin, [c], rel) + R2_d = CoordSystem('second', R2_origin, [d], rel) + # The transform method should throw if it finds multiple inverses for a coordinate transformation. + with raises(ValueError): + R2_d.transform(R2_c) + + # test indirect transformation + a, b, c, d, e, f = symbols('a, b, c, d, e, f') + rel = {('C1', 'C2'): [(a, b), (2*a, 3*b)], + ('C2', 'C3'): [(c, d), (3*c, 2*d)]} + C1 = CoordSystem('C1', R2_origin, (a, b), rel) + C2 = CoordSystem('C2', R2_origin, (c, d), rel) + C3 = CoordSystem('C3', R2_origin, (e, f), rel) + a, b = C1.symbols + c, d = C2.symbols + e, f = C3.symbols + assert C2.transform(C1) == Matrix([c/2, d/3]) + assert C1.transform(C3) == Matrix([6*a, 6*b]) + assert C3.transform(C1) == Matrix([e/6, f/6]) + assert C3.transform(C2) == Matrix([e/3, f/2]) + + a, b, c, d, e, f = symbols('a, b, c, d, e, f') + rel = {('C1', 'C2'): [(a, b), (2*a, 3*b + 1)], + ('C3', 'C2'): [(e, f), (-e - 2, 2*f)]} + C1 = CoordSystem('C1', R2_origin, (a, b), rel) + C2 = CoordSystem('C2', R2_origin, (c, d), rel) + C3 = CoordSystem('C3', R2_origin, (e, f), rel) + a, b = C1.symbols + c, d = C2.symbols + e, f = C3.symbols + assert C2.transform(C1) == Matrix([c/2, (d - 1)/3]) + assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2]) + assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3]) + assert C3.transform(C2) == Matrix([-e - 2, 2*f]) + + # old signature uses Lambda + a, b, c, d, e, f = symbols('a, b, c, d, e, f') + rel = {('C1', 'C2'): Lambda((a, b), (2*a, 3*b + 1)), + ('C3', 'C2'): Lambda((e, f), (-e - 2, 2*f))} + C1 = CoordSystem('C1', R2_origin, (a, b), rel) + C2 = CoordSystem('C2', R2_origin, (c, d), rel) + C3 = CoordSystem('C3', R2_origin, (e, f), rel) + a, b = C1.symbols + c, d = C2.symbols + e, f = C3.symbols + assert C2.transform(C1) == Matrix([c/2, (d - 1)/3]) + assert C1.transform(C3) == Matrix([-2*a - 2, (3*b + 1)/2]) + assert C3.transform(C1) == Matrix([-e/2 - 1, (2*f - 1)/3]) + assert C3.transform(C2) == Matrix([-e - 2, 2*f]) + + +def test_R2(): + x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True) + point_r = R2_r.point([x0, y0]) + point_p = R2_p.point([r0, theta0]) + + # r**2 = x**2 + y**2 + assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0 + assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0 + assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0 + + # polar->rect->polar == Id + a, b = symbols('a b', positive=True) + m = Matrix([[a], [b]]) + + #TODO assert m == R2_r.transform(R2_p, R2_p.transform(R2_r, [a, b])).applyfunc(simplify) + assert m == R2_p.transform(R2_r, R2_r.transform(R2_p, m)).applyfunc(simplify) + + # deprecated method + with warns_deprecated_sympy(): + assert m == R2_p.coord_tuple_transform_to( + R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify) + + +def test_R3(): + a, b, c = symbols('a b c', positive=True) + m = Matrix([[a], [b], [c]]) + + assert m == R3_c.transform(R3_r, R3_r.transform(R3_c, m)).applyfunc(simplify) + #TODO assert m == R3_r.transform(R3_c, R3_c.transform(R3_r, m)).applyfunc(simplify) + assert m == R3_s.transform( + R3_r, R3_r.transform(R3_s, m)).applyfunc(simplify) + #TODO assert m == R3_r.transform(R3_s, R3_s.transform(R3_r, m)).applyfunc(simplify) + assert m == R3_s.transform( + R3_c, R3_c.transform(R3_s, m)).applyfunc(simplify) + #TODO assert m == R3_c.transform(R3_s, R3_s.transform(R3_c, m)).applyfunc(simplify) + + with warns_deprecated_sympy(): + assert m == R3_c.coord_tuple_transform_to( + R3_r, R3_r.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify) + #TODO assert m == R3_r.coord_tuple_transform_to(R3_c, R3_c.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify) + assert m == R3_s.coord_tuple_transform_to( + R3_r, R3_r.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify) + #TODO assert m == R3_r.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_r, m)).applyfunc(simplify) + assert m == R3_s.coord_tuple_transform_to( + R3_c, R3_c.coord_tuple_transform_to(R3_s, m)).applyfunc(simplify) + #TODO assert m == R3_c.coord_tuple_transform_to(R3_s, R3_s.coord_tuple_transform_to(R3_c, m)).applyfunc(simplify) + + +def test_CoordinateSymbol(): + x, y = R2_r.symbols + r, theta = R2_p.symbols + assert y.rewrite(R2_p) == r*sin(theta) + + +def test_point(): + x, y = symbols('x, y') + p = R2_r.point([x, y]) + assert p.free_symbols == {x, y} + assert p.coords(R2_r) == p.coords() == Matrix([x, y]) + assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)]) + + +def test_commutator(): + assert Commutator(R2.e_x, R2.e_y) == 0 + assert Commutator(R2.x*R2.e_x, R2.x*R2.e_x) == 0 + assert Commutator(R2.x*R2.e_x, R2.x*R2.e_y) == R2.x*R2.e_y + c = Commutator(R2.e_x, R2.e_r) + assert c(R2.x) == R2.y*(R2.x**2 + R2.y**2)**(-1)*sin(R2.theta) + + +def test_differential(): + xdy = R2.x*R2.dy + dxdy = Differential(xdy) + assert xdy.rcall(None) == xdy + assert dxdy(R2.e_x, R2.e_y) == 1 + assert dxdy(R2.e_x, R2.x*R2.e_y) == R2.x + assert Differential(dxdy) == 0 + + +def test_products(): + assert TensorProduct( + R2.dx, R2.dy)(R2.e_x, R2.e_y) == R2.dx(R2.e_x)*R2.dy(R2.e_y) == 1 + assert TensorProduct(R2.dx, R2.dy)(None, R2.e_y) == R2.dx + assert TensorProduct(R2.dx, R2.dy)(R2.e_x, None) == R2.dy + assert TensorProduct(R2.dx, R2.dy)(R2.e_x) == R2.dy + assert TensorProduct(R2.x, R2.dx) == R2.x*R2.dx + assert TensorProduct( + R2.e_x, R2.e_y)(R2.x, R2.y) == R2.e_x(R2.x) * R2.e_y(R2.y) == 1 + assert TensorProduct(R2.e_x, R2.e_y)(None, R2.y) == R2.e_x + assert TensorProduct(R2.e_x, R2.e_y)(R2.x, None) == R2.e_y + assert TensorProduct(R2.e_x, R2.e_y)(R2.x) == R2.e_y + assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x + assert TensorProduct( + R2.dx, R2.e_y)(R2.e_x, R2.y) == R2.dx(R2.e_x) * R2.e_y(R2.y) == 1 + assert TensorProduct(R2.dx, R2.e_y)(None, R2.y) == R2.dx + assert TensorProduct(R2.dx, R2.e_y)(R2.e_x, None) == R2.e_y + assert TensorProduct(R2.dx, R2.e_y)(R2.e_x) == R2.e_y + assert TensorProduct(R2.x, R2.e_x) == R2.x * R2.e_x + assert TensorProduct( + R2.e_x, R2.dy)(R2.x, R2.e_y) == R2.e_x(R2.x) * R2.dy(R2.e_y) == 1 + assert TensorProduct(R2.e_x, R2.dy)(None, R2.e_y) == R2.e_x + assert TensorProduct(R2.e_x, R2.dy)(R2.x, None) == R2.dy + assert TensorProduct(R2.e_x, R2.dy)(R2.x) == R2.dy + assert TensorProduct(R2.e_y,R2.e_x)(R2.x**2 + R2.y**2,R2.x**2 + R2.y**2) == 4*R2.x*R2.y + + assert WedgeProduct(R2.dx, R2.dy)(R2.e_x, R2.e_y) == 1 + assert WedgeProduct(R2.e_x, R2.e_y)(R2.x, R2.y) == 1 + + +def test_lie_derivative(): + assert LieDerivative(R2.e_x, R2.y) == R2.e_x(R2.y) == 0 + assert LieDerivative(R2.e_x, R2.x) == R2.e_x(R2.x) == 1 + assert LieDerivative(R2.e_x, R2.e_x) == Commutator(R2.e_x, R2.e_x) == 0 + assert LieDerivative(R2.e_x, R2.e_r) == Commutator(R2.e_x, R2.e_r) + assert LieDerivative(R2.e_x + R2.e_y, R2.x) == 1 + assert LieDerivative( + R2.e_x, TensorProduct(R2.dx, R2.dy))(R2.e_x, R2.e_y) == 0 + + +@nocache_fail +def test_covar_deriv(): + ch = metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) + cvd = BaseCovarDerivativeOp(R2_r, 0, ch) + assert cvd(R2.x) == 1 + # This line fails if the cache is disabled: + assert cvd(R2.x*R2.e_x) == R2.e_x + cvd = CovarDerivativeOp(R2.x*R2.e_x, ch) + assert cvd(R2.x) == R2.x + assert cvd(R2.x*R2.e_x) == R2.x*R2.e_x + + +def test_intcurve_diffequ(): + t = symbols('t') + start_point = R2_r.point([1, 0]) + vector_field = -R2.y*R2.e_x + R2.x*R2.e_y + equations, init_cond = intcurve_diffequ(vector_field, t, start_point) + assert str(equations) == '[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]' + assert str(init_cond) == '[f_0(0) - 1, f_1(0)]' + equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p) + assert str( + equations) == '[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]' + assert str(init_cond) == '[f_0(0) - 1, f_1(0)]' + + +def test_helpers_and_coordinate_dependent(): + one_form = R2.dr + R2.dx + two_form = Differential(R2.x*R2.dr + R2.r*R2.dx) + three_form = Differential( + R2.y*two_form) + Differential(R2.x*Differential(R2.r*R2.dr)) + metric = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dy, R2.dy) + metric_ambig = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dr, R2.dr) + misform_a = TensorProduct(R2.dr, R2.dr) + R2.dr + misform_b = R2.dr**4 + misform_c = R2.dx*R2.dy + twoform_not_sym = TensorProduct(R2.dx, R2.dx) + TensorProduct(R2.dx, R2.dy) + twoform_not_TP = WedgeProduct(R2.dx, R2.dy) + + one_vector = R2.e_x + R2.e_y + two_vector = TensorProduct(R2.e_x, R2.e_y) + three_vector = TensorProduct(R2.e_x, R2.e_y, R2.e_x) + two_wp = WedgeProduct(R2.e_x,R2.e_y) + + assert covariant_order(one_form) == 1 + assert covariant_order(two_form) == 2 + assert covariant_order(three_form) == 3 + assert covariant_order(two_form + metric) == 2 + assert covariant_order(two_form + metric_ambig) == 2 + assert covariant_order(two_form + twoform_not_sym) == 2 + assert covariant_order(two_form + twoform_not_TP) == 2 + + assert contravariant_order(one_vector) == 1 + assert contravariant_order(two_vector) == 2 + assert contravariant_order(three_vector) == 3 + assert contravariant_order(two_vector + two_wp) == 2 + + raises(ValueError, lambda: covariant_order(misform_a)) + raises(ValueError, lambda: covariant_order(misform_b)) + raises(ValueError, lambda: covariant_order(misform_c)) + + assert twoform_to_matrix(metric) == Matrix([[1, 0], [0, 1]]) + assert twoform_to_matrix(twoform_not_sym) == Matrix([[1, 0], [1, 0]]) + assert twoform_to_matrix(twoform_not_TP) == Matrix([[0, -1], [1, 0]]) + + raises(ValueError, lambda: twoform_to_matrix(one_form)) + raises(ValueError, lambda: twoform_to_matrix(three_form)) + raises(ValueError, lambda: twoform_to_matrix(metric_ambig)) + + raises(ValueError, lambda: metric_to_Christoffel_1st(twoform_not_sym)) + raises(ValueError, lambda: metric_to_Christoffel_2nd(twoform_not_sym)) + raises(ValueError, lambda: metric_to_Riemann_components(twoform_not_sym)) + raises(ValueError, lambda: metric_to_Ricci_components(twoform_not_sym)) + + +def test_correct_arguments(): + raises(ValueError, lambda: R2.e_x(R2.e_x)) + raises(ValueError, lambda: R2.e_x(R2.dx)) + + raises(ValueError, lambda: Commutator(R2.e_x, R2.x)) + raises(ValueError, lambda: Commutator(R2.dx, R2.e_x)) + + raises(ValueError, lambda: Differential(Differential(R2.e_x))) + + raises(ValueError, lambda: R2.dx(R2.x)) + + raises(ValueError, lambda: LieDerivative(R2.dx, R2.dx)) + raises(ValueError, lambda: LieDerivative(R2.x, R2.dx)) + + raises(ValueError, lambda: CovarDerivativeOp(R2.dx, [])) + raises(ValueError, lambda: CovarDerivativeOp(R2.x, [])) + + a = Symbol('a') + raises(ValueError, lambda: intcurve_series(R2.dx, a, R2_r.point([1, 2]))) + raises(ValueError, lambda: intcurve_series(R2.x, a, R2_r.point([1, 2]))) + + raises(ValueError, lambda: intcurve_diffequ(R2.dx, a, R2_r.point([1, 2]))) + raises(ValueError, lambda: intcurve_diffequ(R2.x, a, R2_r.point([1, 2]))) + + raises(ValueError, lambda: contravariant_order(R2.e_x + R2.dx)) + raises(ValueError, lambda: covariant_order(R2.e_x + R2.dx)) + + raises(ValueError, lambda: contravariant_order(R2.e_x*R2.e_y)) + raises(ValueError, lambda: covariant_order(R2.dx*R2.dy)) + +def test_simplify(): + x, y = R2_r.coord_functions() + dx, dy = R2_r.base_oneforms() + ex, ey = R2_r.base_vectors() + assert simplify(x) == x + assert simplify(x*y) == x*y + assert simplify(dx*dy) == dx*dy + assert simplify(ex*ey) == ex*ey + assert ((1-x)*dx)/(1-x)**2 == dx/(1-x) + + +def test_issue_17917(): + X = R2.x*R2.e_x - R2.y*R2.e_y + Y = (R2.x**2 + R2.y**2)*R2.e_x - R2.x*R2.y*R2.e_y + assert LieDerivative(X, Y).expand() == ( + R2.x**2*R2.e_x - 3*R2.y**2*R2.e_x - R2.x*R2.y*R2.e_y) + +def test_deprecations(): + m = Manifold('M', 2) + p = Patch('P', m) + with warns_deprecated_sympy(): + CoordSystem('Car2d', p, names=['x', 'y']) + + with warns_deprecated_sympy(): + c = CoordSystem('Car2d', p, ['x', 'y']) + + with warns_deprecated_sympy(): + list(m.patches) + + with warns_deprecated_sympy(): + list(c.transforms) diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..911cc78e9c08a40b260f25efc74fbd4482bc302a --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/polys/tests/__pycache__/test_polytools.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cb11feb0caa8cb49f79e512418295f25525a7d0026f85a3d08a7aac52eeff51 +size 141254 diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9892ef218461b853c5ba9687c566b3a2909d5a63 Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6096812d8589abf861d92bed60e6ba622995568b Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..138f8bd4581643d7b0972c6bb2a2ebf5fbb8520c Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-310.pyc b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02925d79613f155980d41aede7348a312cb509fc Binary files /dev/null and b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-310.pyc differ diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/__init__.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_autowrap.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_autowrap.py new file mode 100644 index 0000000000000000000000000000000000000000..acb0e9a5ef5926c4a14d4e91b92a20c2f98674aa --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_autowrap.py @@ -0,0 +1,469 @@ +# Tests that require installed backends go into +# sympy/test_external/test_autowrap + +import os +import tempfile +import shutil +from io import StringIO + +from sympy.core import symbols, Eq +from sympy.utilities.autowrap import (autowrap, binary_function, + CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper) +from sympy.utilities.codegen import ( + CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine +) +from sympy.testing.pytest import raises +from sympy.testing.tmpfiles import TmpFileManager + + +def get_string(dump_fn, routines, prefix="file", **kwargs): + """Wrapper for dump_fn. dump_fn writes its results to a stream object and + this wrapper returns the contents of that stream as a string. This + auxiliary function is used by many tests below. + + The header and the empty lines are not generator to facilitate the + testing of the output. + """ + output = StringIO() + dump_fn(routines, output, prefix, **kwargs) + source = output.getvalue() + output.close() + return source + + +def test_cython_wrapper_scalar_function(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + + expected = ( + "cdef extern from 'file.h':\n" + " double test(double x, double y, double z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " return test(x, y, z)") + assert source == expected + + +def test_cython_wrapper_outarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + + routine = make_routine("test", Equality(z, x + y)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y):\n" + "\n" + " cdef double z = 0\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_inoutarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + routine = make_routine("test", Equality(z, x + y + z)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_compile_flags(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + routine = make_routine("test", Equality(z, x + y)) + + code_gen = CythonCodeWrapper(CCodeGen()) + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'language_level': '3'}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=[], + library_dirs=[], + libraries=[], + extra_compile_args=['-std=c99'], + extra_link_args=[] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + temp_dir = tempfile.mkdtemp() + TmpFileManager.tmp_folder(temp_dir) + setup_file_path = os.path.join(temp_dir, 'setup.py') + + code_gen._prepare_files(routine, build_dir=temp_dir) + with open(setup_file_path) as f: + setup_text = f.read() + assert setup_text == expected + + code_gen = CythonCodeWrapper(CCodeGen(), + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math'], + extra_link_args=['-lswamp', '-ltrident'], + cythonize_options={'compiler_directives': {'boundscheck': False}} + ) + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._prepare_files(routine, build_dir=temp_dir) + with open(setup_file_path) as f: + setup_text = f.read() + assert setup_text == expected + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} +import numpy as np + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._need_numpy = True + code_gen._prepare_files(routine, build_dir=temp_dir) + with open(setup_file_path) as f: + setup_text = f.read() + assert setup_text == expected + + TmpFileManager.cleanup() + +def test_cython_wrapper_unique_dummyvars(): + from sympy.core.relational import Equality + from sympy.core.symbol import Dummy + x, y, z = Dummy('x'), Dummy('y'), Dummy('z') + x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]] + expr = Equality(z, x + y) + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + expected_template = ( + "cdef extern from 'file.h':\n" + " void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n" + "\n" + "def test_c(double x_{x_id}, double y_{y_id}):\n" + "\n" + " cdef double z_{z_id} = 0\n" + " test(x_{x_id}, y_{y_id}, &z_{z_id})\n" + " return z_{z_id}") + expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id) + assert source == expected + +def test_autowrap_dummy(): + x, y, z = symbols('x y z') + + # Uses DummyWrapper to test that codegen works as expected + + f = autowrap(x + y, backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "nameless" + f = autowrap(Eq(z, x + y), backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "z" + f = autowrap(Eq(z, x + y + z), backend='dummy') + assert f() == str(x + y + z) + assert f.args == "x, y, z" + assert f.returns == "z" + + +def test_autowrap_args(): + x, y, z = symbols('x y z') + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y), + backend='dummy', args=[x])) + f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x]) + assert f() == str(x + y) + assert f.args == "y, x" + assert f.returns == "z" + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z), + backend='dummy', args=[x, y])) + f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z]) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + + f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z)) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + +def test_autowrap_store_files(): + x, y = symbols('x y') + tmp = tempfile.mkdtemp() + TmpFileManager.tmp_folder(tmp) + + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + + TmpFileManager.cleanup() + +def test_autowrap_store_files_issue_gh12939(): + x, y = symbols('x y') + tmp = './tmp' + saved_cwd = os.getcwd() + temp_cwd = tempfile.mkdtemp() + try: + os.chdir(temp_cwd) + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + finally: + os.chdir(saved_cwd) + shutil.rmtree(temp_cwd) + + +def test_binary_function(): + x, y = symbols('x y') + f = binary_function('f', x + y, backend='dummy') + assert f._imp_() == str(x + y) + + +def test_ufuncify_source(): + x, y, z = symbols('x,y,z') + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routine = make_routine("test", x + y + z) + source = get_string(code_wrapper.dump_c, [routine]) + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +#ifdef NPY_1_19_API_VERSION +static void test_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) +#else +static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +#endif +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + for (i = 0; i < n; i++) { + *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + } +} +PyUFuncGenericFunction test_funcs[1] = {&test_ufunc}; +static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *test_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected + + +def test_ufuncify_source_multioutput(): + x, y, z = symbols('x,y,z') + var_symbols = (x, y, z) + expr = x + y**3 + 10*z**2 + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))] + source = get_string(code_wrapper.dump_c, routines, funcname='multitest') + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +#ifdef NPY_1_19_API_VERSION +static void multitest_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) +#else +static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +#endif +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + char *out1 = args[4]; + char *out2 = args[5]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + npy_intp out1_step = steps[4]; + npy_intp out2_step = steps[5]; + for (i = 0; i < n; i++) { + *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + out1 += out1_step; + out2 += out2_step; + } +} +PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc}; +static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *multitest_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_deprecated.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..dd4534ef1abc38ff368011b3ef9d11c497f3675b --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_deprecated.py @@ -0,0 +1,13 @@ +from sympy.testing.pytest import warns_deprecated_sympy + +# See https://github.com/sympy/sympy/pull/18095 + +def test_deprecated_utilities(): + with warns_deprecated_sympy(): + import sympy.utilities.pytest # noqa:F401 + with warns_deprecated_sympy(): + import sympy.utilities.runtests # noqa:F401 + with warns_deprecated_sympy(): + import sympy.utilities.randtest # noqa:F401 + with warns_deprecated_sympy(): + import sympy.utilities.tmpfiles # noqa:F401 diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_enumerative.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_enumerative.py new file mode 100644 index 0000000000000000000000000000000000000000..a29c6341dd6f3a19f145c94f6e996cc348428325 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_enumerative.py @@ -0,0 +1,178 @@ +from itertools import zip_longest + +from sympy.utilities.enumerative import ( + list_visitor, + MultisetPartitionTraverser, + multiset_partitions_taocp + ) +from sympy.utilities.iterables import _set_partitions + +# first some functions only useful as test scaffolding - these provide +# straightforward, but slow reference implementations against which to +# compare the real versions, and also a comparison to verify that +# different versions are giving identical results. + +def part_range_filter(partition_iterator, lb, ub): + """ + Filters (on the number of parts) a multiset partition enumeration + + Arguments + ========= + + lb, and ub are a range (in the Python slice sense) on the lpart + variable returned from a multiset partition enumeration. Recall + that lpart is 0-based (it points to the topmost part on the part + stack), so if you want to return parts of sizes 2,3,4,5 you would + use lb=1 and ub=5. + """ + for state in partition_iterator: + f, lpart, pstack = state + if lpart >= lb and lpart < ub: + yield state + +def multiset_partitions_baseline(multiplicities, components): + """Enumerates partitions of a multiset + + Parameters + ========== + + multiplicities + list of integer multiplicities of the components of the multiset. + + components + the components (elements) themselves + + Returns + ======= + + Set of partitions. Each partition is tuple of parts, and each + part is a tuple of components (with repeats to indicate + multiplicity) + + Notes + ===== + + Multiset partitions can be created as equivalence classes of set + partitions, and this function does just that. This approach is + slow and memory intensive compared to the more advanced algorithms + available, but the code is simple and easy to understand. Hence + this routine is strictly for testing -- to provide a + straightforward baseline against which to regress the production + versions. (This code is a simplified version of an earlier + production implementation.) + """ + + canon = [] # list of components with repeats + for ct, elem in zip(multiplicities, components): + canon.extend([elem]*ct) + + # accumulate the multiset partitions in a set to eliminate dups + cache = set() + n = len(canon) + for nc, q in _set_partitions(n): + rv = [[] for i in range(nc)] + for i in range(n): + rv[q[i]].append(canon[i]) + canonical = tuple( + sorted([tuple(p) for p in rv])) + cache.add(canonical) + return cache + + +def compare_multiset_w_baseline(multiplicities): + """ + Enumerates the partitions of multiset with AOCP algorithm and + baseline implementation, and compare the results. + + """ + letters = "abcdefghijklmnopqrstuvwxyz" + bl_partitions = multiset_partitions_baseline(multiplicities, letters) + + # The partitions returned by the different algorithms may have + # their parts in different orders. Also, they generate partitions + # in different orders. Hence the sorting, and set comparison. + + aocp_partitions = set() + for state in multiset_partitions_taocp(multiplicities): + p1 = tuple(sorted( + [tuple(p) for p in list_visitor(state, letters)])) + aocp_partitions.add(p1) + + assert bl_partitions == aocp_partitions + +def compare_multiset_states(s1, s2): + """compare for equality two instances of multiset partition states + + This is useful for comparing different versions of the algorithm + to verify correctness.""" + # Comparison is physical, the only use of semantics is to ignore + # trash off the top of the stack. + f1, lpart1, pstack1 = s1 + f2, lpart2, pstack2 = s2 + + if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]): + if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]: + return True + return False + +def test_multiset_partitions_taocp(): + """Compares the output of multiset_partitions_taocp with a baseline + (set partition based) implementation.""" + + # Test cases should not be too large, since the baseline + # implementation is fairly slow. + multiplicities = [2,2] + compare_multiset_w_baseline(multiplicities) + + multiplicities = [4,3,1] + compare_multiset_w_baseline(multiplicities) + +def test_multiset_partitions_versions(): + """Compares Knuth-based versions of multiset_partitions""" + multiplicities = [5,2,2,1] + m = MultisetPartitionTraverser() + for s1, s2 in zip_longest(m.enum_all(multiplicities), + multiset_partitions_taocp(multiplicities)): + assert compare_multiset_states(s1, s2) + +def subrange_exercise(mult, lb, ub): + """Compare filter-based and more optimized subrange implementations + + Helper for tests, called with both small and larger multisets. + """ + m = MultisetPartitionTraverser() + assert m.count_partitions(mult) == \ + m.count_partitions_slow(mult) + + # Note - multiple traversals from the same + # MultisetPartitionTraverser object cannot execute at the same + # time, hence make several instances here. + ma = MultisetPartitionTraverser() + mc = MultisetPartitionTraverser() + md = MultisetPartitionTraverser() + + # Several paths to compute just the size two partitions + a_it = ma.enum_range(mult, lb, ub) + b_it = part_range_filter(multiset_partitions_taocp(mult), lb, ub) + c_it = part_range_filter(mc.enum_small(mult, ub), lb, sum(mult)) + d_it = part_range_filter(md.enum_large(mult, lb), 0, ub) + + for sa, sb, sc, sd in zip_longest(a_it, b_it, c_it, d_it): + assert compare_multiset_states(sa, sb) + assert compare_multiset_states(sa, sc) + assert compare_multiset_states(sa, sd) + +def test_subrange(): + # Quick, but doesn't hit some of the corner cases + mult = [4,4,2,1] # mississippi + lb = 1 + ub = 2 + subrange_exercise(mult, lb, ub) + + +def test_subrange_large(): + # takes a second or so, depending on cpu, Python version, etc. + mult = [6,3,2,1] + lb = 4 + ub = 7 + subrange_exercise(mult, lb, ub) diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_exceptions.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d91e55e95d0ae4ac57cdd1989e0b3d39a55cd07d --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_exceptions.py @@ -0,0 +1,12 @@ +from sympy.testing.pytest import raises +from sympy.utilities.exceptions import sympy_deprecation_warning + +# Only test exceptions here because the other cases are tested in the +# warns_deprecated_sympy tests +def test_sympy_deprecation_warning(): + raises(TypeError, lambda: sympy_deprecation_warning('test', + deprecated_since_version=1.10, + active_deprecations_target='active-deprecations')) + + raises(ValueError, lambda: sympy_deprecation_warning('test', + deprecated_since_version="1.10", active_deprecations_target='(active-deprecations)=')) diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_iterables.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_iterables.py new file mode 100644 index 0000000000000000000000000000000000000000..1003522bcd556c6f63e04de7da57b43498575fee --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_iterables.py @@ -0,0 +1,945 @@ +from textwrap import dedent +from itertools import islice, product + +from sympy.core.basic import Basic +from sympy.core.numbers import Integer +from sympy.core.sorting import ordered +from sympy.core.symbol import (Dummy, symbols) +from sympy.functions.combinatorial.factorials import factorial +from sympy.matrices.dense import Matrix +from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation +from sympy.utilities.iterables import ( + _partition, _set_partitions, binary_partitions, bracelets, capture, + cartes, common_prefix, common_suffix, connected_components, dict_merge, + filter_symbols, flatten, generate_bell, generate_derangements, + generate_involutions, generate_oriented_forest, group, has_dups, ibin, + iproduct, kbins, minlex, multiset, multiset_combinations, + multiset_partitions, multiset_permutations, necklaces, numbered_symbols, + partitions, permutations, postfixes, + prefixes, reshape, rotate_left, rotate_right, runs, sift, + strongly_connected_components, subsets, take, topological_sort, unflatten, + uniq, variations, ordered_partitions, rotations, is_palindromic, iterable, + NotIterable, multiset_derangements, signed_permutations, + sequence_partitions, sequence_partitions_empty) +from sympy.utilities.enumerative import ( + factoring_visitor, multiset_partitions_taocp ) + +from sympy.core.singleton import S +from sympy.testing.pytest import raises, warns_deprecated_sympy + +w, x, y, z = symbols('w,x,y,z') + + +def test_deprecated_iterables(): + from sympy.utilities.iterables import default_sort_key, ordered + with warns_deprecated_sympy(): + assert list(ordered([y, x])) == [x, y] + with warns_deprecated_sympy(): + assert sorted([y, x], key=default_sort_key) == [x, y] + + +def test_is_palindromic(): + assert is_palindromic('') + assert is_palindromic('x') + assert is_palindromic('xx') + assert is_palindromic('xyx') + assert not is_palindromic('xy') + assert not is_palindromic('xyzx') + assert is_palindromic('xxyzzyx', 1) + assert not is_palindromic('xxyzzyx', 2) + assert is_palindromic('xxyzzyx', 2, -1) + assert is_palindromic('xxyzzyx', 2, 6) + assert is_palindromic('xxyzyx', 1) + assert not is_palindromic('xxyzyx', 2) + assert is_palindromic('xxyzyx', 2, 2 + 3) + + +def test_flatten(): + assert flatten((1, (1,))) == [1, 1] + assert flatten((x, (x,))) == [x, x] + + ls = [[(-2, -1), (1, 2)], [(0, 0)]] + + assert flatten(ls, levels=0) == ls + assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)] + assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0] + assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0] + + raises(ValueError, lambda: flatten(ls, levels=-1)) + + class MyOp(Basic): + pass + + assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z] + assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z] + + assert flatten({1, 11, 2}) == list({1, 11, 2}) + + +def test_iproduct(): + assert list(iproduct()) == [()] + assert list(iproduct([])) == [] + assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)] + assert sorted(iproduct([1, 2], [3, 4, 5])) == [ + (1,3),(1,4),(1,5),(2,3),(2,4),(2,5)] + assert sorted(iproduct([0,1],[0,1],[0,1])) == [ + (0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)] + assert iterable(iproduct(S.Integers)) is True + assert iterable(iproduct(S.Integers, S.Integers)) is True + assert (3,) in iproduct(S.Integers) + assert (4, 5) in iproduct(S.Integers, S.Integers) + assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers) + triples = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000)) + for n1, n2, n3 in triples: + assert isinstance(n1, Integer) + assert isinstance(n2, Integer) + assert isinstance(n3, Integer) + for t in set(product(*([range(-2, 3)]*3))): + assert t in iproduct(S.Integers, S.Integers, S.Integers) + + +def test_group(): + assert group([]) == [] + assert group([], multiple=False) == [] + + assert group([1]) == [[1]] + assert group([1], multiple=False) == [(1, 1)] + + assert group([1, 1]) == [[1, 1]] + assert group([1, 1], multiple=False) == [(1, 2)] + + assert group([1, 1, 1]) == [[1, 1, 1]] + assert group([1, 1, 1], multiple=False) == [(1, 3)] + + assert group([1, 2, 1]) == [[1], [2], [1]] + assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)] + + assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]] + assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2), + (2, 3), (1, 1), (3, 2)] + + +def test_subsets(): + # combinations + assert list(subsets([1, 2, 3], 0)) == [()] + assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)] + assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] + assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)] + l = list(range(4)) + assert list(subsets(l, 0, repetition=True)) == [()] + assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] + assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), + (0, 3), (1, 1), (1, 2), + (1, 3), (2, 2), (2, 3), + (3, 3)] + assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), + (0, 0, 2), (0, 0, 3), + (0, 1, 1), (0, 1, 2), + (0, 1, 3), (0, 2, 2), + (0, 2, 3), (0, 3, 3), + (1, 1, 1), (1, 1, 2), + (1, 1, 3), (1, 2, 2), + (1, 2, 3), (1, 3, 3), + (2, 2, 2), (2, 2, 3), + (2, 3, 3), (3, 3, 3)] + assert len(list(subsets(l, 4, repetition=True))) == 35 + + assert list(subsets(l[:2], 3, repetition=False)) == [] + assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0), + (0, 0, 1), + (0, 1, 1), + (1, 1, 1)] + assert list(subsets([1, 2], repetition=True)) == \ + [(), (1,), (2,), (1, 1), (1, 2), (2, 2)] + assert list(subsets([1, 2], repetition=False)) == \ + [(), (1,), (2,), (1, 2)] + assert list(subsets([1, 2, 3], 2)) == \ + [(1, 2), (1, 3), (2, 3)] + assert list(subsets([1, 2, 3], 2, repetition=True)) == \ + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + + +def test_variations(): + # permutations + l = list(range(4)) + assert list(variations(l, 0, repetition=False)) == [()] + assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)] + assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)] + assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)] + assert list(variations(l, 0, repetition=True)) == [()] + assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] + assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), + (0, 3), (1, 0), (1, 1), + (1, 2), (1, 3), (2, 0), + (2, 1), (2, 2), (2, 3), + (3, 0), (3, 1), (3, 2), + (3, 3)] + assert len(list(variations(l, 3, repetition=True))) == 64 + assert len(list(variations(l, 4, repetition=True))) == 256 + assert list(variations(l[:2], 3, repetition=False)) == [] + assert list(variations(l[:2], 3, repetition=True)) == [ + (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), + (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1) + ] + + +def test_cartes(): + assert list(cartes([1, 2], [3, 4, 5])) == \ + [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)] + assert list(cartes()) == [()] + assert list(cartes('a')) == [('a',)] + assert list(cartes('a', repeat=2)) == [('a', 'a')] + assert list(cartes(list(range(2)))) == [(0,), (1,)] + + +def test_filter_symbols(): + s = numbered_symbols() + filtered = filter_symbols(s, symbols("x0 x2 x3")) + assert take(filtered, 3) == list(symbols("x1 x4 x5")) + + +def test_numbered_symbols(): + s = numbered_symbols(cls=Dummy) + assert isinstance(next(s), Dummy) + assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \ + symbols('C2') + + +def test_sift(): + assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]} + assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]} + assert sift([S.One], lambda _: _.has(x)) == {False: [1]} + assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == ( + [1, 3], [0, 2]) + assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == ( + [1], [0, 2, 3]) + raises(ValueError, lambda: + sift([0, 1, 2, 3], lambda x: x % 3, binary=True)) + + +def test_take(): + X = numbered_symbols() + + assert take(X, 5) == list(symbols('x0:5')) + assert take(X, 5) == list(symbols('x5:10')) + + assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5] + + +def test_dict_merge(): + assert dict_merge({}, {1: x, y: z}) == {1: x, y: z} + assert dict_merge({1: x, y: z}, {}) == {1: x, y: z} + + assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} + assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z} + + assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} + assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z} + + +def test_prefixes(): + assert list(prefixes([])) == [] + assert list(prefixes([1])) == [[1]] + assert list(prefixes([1, 2])) == [[1], [1, 2]] + + assert list(prefixes([1, 2, 3, 4, 5])) == \ + [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] + + +def test_postfixes(): + assert list(postfixes([])) == [] + assert list(postfixes([1])) == [[1]] + assert list(postfixes([1, 2])) == [[2], [1, 2]] + + assert list(postfixes([1, 2, 3, 4, 5])) == \ + [[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]] + + +def test_topological_sort(): + V = [2, 3, 5, 7, 8, 9, 10, 11] + E = [(7, 11), (7, 8), (5, 11), + (3, 8), (3, 10), (11, 2), + (11, 9), (11, 10), (8, 9)] + + assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10] + assert topological_sort((V, E), key=lambda v: -v) == \ + [7, 5, 11, 3, 10, 8, 9, 2] + + raises(ValueError, lambda: topological_sort((V, E + [(10, 7)]))) + + +def test_strongly_connected_components(): + assert strongly_connected_components(([], [])) == [] + assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]] + + V = [1, 2, 3] + E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] + assert strongly_connected_components((V, E)) == [[1, 2, 3]] + + V = [1, 2, 3, 4] + E = [(1, 2), (2, 3), (3, 2), (3, 4)] + assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]] + + V = [1, 2, 3, 4] + E = [(1, 2), (2, 1), (3, 4), (4, 3)] + assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]] + + +def test_connected_components(): + assert connected_components(([], [])) == [] + assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]] + + V = [1, 2, 3] + E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] + assert connected_components((V, E)) == [[1, 2, 3]] + + V = [1, 2, 3, 4] + E = [(1, 2), (2, 3), (3, 2), (3, 4)] + assert connected_components((V, E)) == [[1, 2, 3, 4]] + + V = [1, 2, 3, 4] + E = [(1, 2), (3, 4)] + assert connected_components((V, E)) == [[1, 2], [3, 4]] + + +def test_rotate(): + A = [0, 1, 2, 3, 4] + + assert rotate_left(A, 2) == [2, 3, 4, 0, 1] + assert rotate_right(A, 1) == [4, 0, 1, 2, 3] + A = [] + B = rotate_right(A, 1) + assert B == [] + B.append(1) + assert A == [] + B = rotate_left(A, 1) + assert B == [] + B.append(1) + assert A == [] + + +def test_multiset_partitions(): + A = [0, 1, 2, 3, 4] + + assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]] + assert len(list(multiset_partitions(A, 4))) == 10 + assert len(list(multiset_partitions(A, 3))) == 25 + + assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [ + [[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]], + [[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]] + + assert list(multiset_partitions([1, 1, 2, 2], 2)) == [ + [[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]], + [[1, 2], [1, 2]]] + + assert list(multiset_partitions([1, 2, 3, 4], 2)) == [ + [[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], + [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], + [[1], [2, 3, 4]]] + + assert list(multiset_partitions([1, 2, 2], 2)) == [ + [[1, 2], [2]], [[1], [2, 2]]] + + assert list(multiset_partitions(3)) == [ + [[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], + [[0], [1], [2]]] + assert list(multiset_partitions(3, 2)) == [ + [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]] + assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]] + assert list(multiset_partitions([1] * 3)) == [ + [[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] + a = [3, 2, 1] + assert list(multiset_partitions(a)) == \ + list(multiset_partitions(sorted(a))) + assert list(multiset_partitions(a, 5)) == [] + assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]] + assert list(multiset_partitions(a + [4], 5)) == [] + assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]] + assert list(multiset_partitions(2, 5)) == [] + assert list(multiset_partitions(2, 1)) == [[[0, 1]]] + assert list(multiset_partitions('a')) == [[['a']]] + assert list(multiset_partitions('a', 2)) == [] + assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]] + assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]] + assert list(multiset_partitions('aaa', 1)) == [['aaa']] + assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]] + ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'), + ('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'), + ('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'), + ('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'), + ('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'), + ('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'), + ('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'), + ('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'), + ('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'), + ('m', 'py', 's', 'y'), ('m', 'p', 'syy'), + ('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'), + ('m', 'p', 's', 'y', 'y')] + assert [tuple("".join(part) for part in p) + for p in multiset_partitions('sympy')] == ans + factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], + [6, 2, 2], [2, 2, 2, 3]] + assert [factoring_visitor(p, [2,3]) for + p in multiset_partitions_taocp([3, 1])] == factorings + + +def test_multiset_combinations(): + ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips', + 'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss'] + assert [''.join(i) for i in + list(multiset_combinations('mississippi', 3))] == ans + M = multiset('mississippi') + assert [''.join(i) for i in + list(multiset_combinations(M, 3))] == ans + assert [''.join(i) for i in multiset_combinations(M, 30)] == [] + assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]] + assert len(list(multiset_combinations('a', 3))) == 0 + assert len(list(multiset_combinations('a', 0))) == 1 + assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']] + raises(ValueError, lambda: list(multiset_combinations({0: 3, 1: -1}, 2))) + + +def test_multiset_permutations(): + ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab', + 'byba', 'yabb', 'ybab', 'ybba'] + assert [''.join(i) for i in multiset_permutations('baby')] == ans + assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans + assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]] + assert list(multiset_permutations([0, 2, 1], 2)) == [ + [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]] + assert len(list(multiset_permutations('a', 0))) == 1 + assert len(list(multiset_permutations('a', 3))) == 0 + for nul in ([], {}, ''): + assert list(multiset_permutations(nul)) == [[]] + assert list(multiset_permutations(nul, 0)) == [[]] + # impossible requests give no result + assert list(multiset_permutations(nul, 1)) == [] + assert list(multiset_permutations(nul, -1)) == [] + + def test(): + for i in range(1, 7): + print(i) + for p in multiset_permutations([0, 0, 1, 0, 1], i): + print(p) + assert capture(lambda: test()) == dedent('''\ + 1 + [0] + [1] + 2 + [0, 0] + [0, 1] + [1, 0] + [1, 1] + 3 + [0, 0, 0] + [0, 0, 1] + [0, 1, 0] + [0, 1, 1] + [1, 0, 0] + [1, 0, 1] + [1, 1, 0] + 4 + [0, 0, 0, 1] + [0, 0, 1, 0] + [0, 0, 1, 1] + [0, 1, 0, 0] + [0, 1, 0, 1] + [0, 1, 1, 0] + [1, 0, 0, 0] + [1, 0, 0, 1] + [1, 0, 1, 0] + [1, 1, 0, 0] + 5 + [0, 0, 0, 1, 1] + [0, 0, 1, 0, 1] + [0, 0, 1, 1, 0] + [0, 1, 0, 0, 1] + [0, 1, 0, 1, 0] + [0, 1, 1, 0, 0] + [1, 0, 0, 0, 1] + [1, 0, 0, 1, 0] + [1, 0, 1, 0, 0] + [1, 1, 0, 0, 0] + 6\n''') + raises(ValueError, lambda: list(multiset_permutations({0: 3, 1: -1}))) + + +def test_partitions(): + ans = [[{}], [(0, {})]] + for i in range(2): + assert list(partitions(0, size=i)) == ans[i] + assert list(partitions(1, 0, size=i)) == ans[i] + assert list(partitions(6, 2, 2, size=i)) == ans[i] + assert list(partitions(6, 2, None, size=i)) != ans[i] + assert list(partitions(6, None, 2, size=i)) != ans[i] + assert list(partitions(6, 2, 0, size=i)) == ans[i] + + assert list(partitions(6, k=2)) == [ + {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] + + assert list(partitions(6, k=3)) == [ + {3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2}, + {1: 4, 2: 1}, {1: 6}] + + assert list(partitions(8, k=4, m=3)) == [ + {4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [ + i for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i) + and sum(i.values()) <=3] + + assert list(partitions(S(3), m=2)) == [ + {3: 1}, {1: 1, 2: 1}] + + assert list(partitions(4, k=3)) == [ + {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [ + i for i in partitions(4) if all(k <= 3 for k in i)] + + + # Consistency check on output of _partitions and RGS_unrank. + # This provides a sanity test on both routines. Also verifies that + # the total number of partitions is the same in each case. + # (from pkrathmann2) + + for n in range(2, 6): + i = 0 + for m, q in _set_partitions(n): + assert q == RGS_unrank(i, n) + i += 1 + assert i == RGS_enum(n) + + +def test_binary_partitions(): + assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1], + [4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1], + [4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2], + [2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1], + [2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] + + assert len([j[:] for j in binary_partitions(16)]) == 36 + + +def test_bell_perm(): + assert [len(set(generate_bell(i))) for i in range(1, 7)] == [ + factorial(i) for i in range(1, 7)] + assert list(generate_bell(3)) == [ + (0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] + # generate_bell and trotterjohnson are advertised to return the same + # permutations; this is not technically necessary so this test could + # be removed + for n in range(1, 5): + p = Permutation(range(n)) + b = generate_bell(n) + for bi in b: + assert bi == tuple(p.array_form) + p = p.next_trotterjohnson() + raises(ValueError, lambda: list(generate_bell(0))) # XXX is this consistent with other permutation algorithms? + + +def test_involutions(): + lengths = [1, 2, 4, 10, 26, 76] + for n, N in enumerate(lengths): + i = list(generate_involutions(n + 1)) + assert len(i) == N + assert len({Permutation(j)**2 for j in i}) == 1 + + +def test_derangements(): + assert len(list(generate_derangements(list(range(6))))) == 265 + assert ''.join(''.join(i) for i in generate_derangements('abcde')) == ( + 'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd' + 'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab' + 'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb' + 'edbacedbca') + assert list(generate_derangements([0, 1, 2, 3])) == [ + [1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], + [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]] + assert list(generate_derangements([0, 1, 2, 2])) == [ + [2, 2, 0, 1], [2, 2, 1, 0]] + assert list(generate_derangements('ba')) == [list('ab')] + # multiset_derangements + D = multiset_derangements + assert list(D('abb')) == [] + assert [''.join(i) for i in D('ab')] == ['ba'] + assert [''.join(i) for i in D('abc')] == ['bca', 'cab'] + assert [''.join(i) for i in D('aabb')] == ['bbaa'] + assert [''.join(i) for i in D('aabbcccc')] == [ + 'ccccaabb', 'ccccabab', 'ccccabba', 'ccccbaab', 'ccccbaba', + 'ccccbbaa'] + assert [''.join(i) for i in D('aabbccc')] == [ + 'cccabba', 'cccabab', 'cccaabb', 'ccacbba', 'ccacbab', + 'ccacabb', 'cbccbaa', 'cbccaba', 'cbccaab', 'bcccbaa', + 'bcccaba', 'bcccaab'] + assert [''.join(i) for i in D('books')] == ['kbsoo', 'ksboo', + 'sbkoo', 'skboo', 'oksbo', 'oskbo', 'okbso', 'obkso', 'oskob', + 'oksob', 'osbok', 'obsok'] + assert list(generate_derangements([[3], [2], [2], [1]])) == [ + [[2], [1], [3], [2]], [[2], [3], [1], [2]]] + + +def test_necklaces(): + def count(n, k, f): + return len(list(necklaces(n, k, f))) + m = [] + for i in range(1, 8): + m.append(( + i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1))) + assert Matrix(m) == Matrix([ + [1, 2, 2, 3], + [2, 3, 3, 6], + [3, 4, 4, 10], + [4, 6, 6, 21], + [5, 8, 8, 39], + [6, 14, 13, 92], + [7, 20, 18, 198]]) + + +def test_bracelets(): + bc = list(bracelets(2, 4)) + assert Matrix(bc) == Matrix([ + [0, 0], + [0, 1], + [0, 2], + [0, 3], + [1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3] + ]) + bc = list(bracelets(4, 2)) + assert Matrix(bc) == Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 1], + [0, 0, 1, 1], + [0, 1, 0, 1], + [0, 1, 1, 1], + [1, 1, 1, 1] + ]) + + +def test_generate_oriented_forest(): + assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4], + [0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0], + [0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2], + [0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0], + [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0], + [0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]] + assert len(list(generate_oriented_forest(10))) == 1842 + + +def test_unflatten(): + r = list(range(10)) + assert unflatten(r) == list(zip(r[::2], r[1::2])) + assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])] + raises(ValueError, lambda: unflatten(list(range(10)), 3)) + raises(ValueError, lambda: unflatten(list(range(10)), -2)) + + +def test_common_prefix_suffix(): + assert common_prefix([], [1]) == [] + assert common_prefix(list(range(3))) == [0, 1, 2] + assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2] + assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2] + assert common_prefix([1, 2, 3], [1, 3, 5]) == [1] + + assert common_suffix([], [1]) == [] + assert common_suffix(list(range(3))) == [0, 1, 2] + assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2] + assert common_suffix(list(range(3)), list(range(4))) == [] + assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3] + assert common_suffix([1, 2, 3], [9, 7, 3]) == [3] + + +def test_minlex(): + assert minlex([1, 2, 0]) == (0, 1, 2) + assert minlex((1, 2, 0)) == (0, 1, 2) + assert minlex((1, 0, 2)) == (0, 2, 1) + assert minlex((1, 0, 2), directed=False) == (0, 1, 2) + assert minlex('aba') == 'aab' + assert minlex(('bb', 'aaa', 'c', 'a'), key=len) == ('c', 'a', 'bb', 'aaa') + + +def test_ordered(): + assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]] + assert list(ordered((x, y), hash, default=False)) == \ + list(ordered((y, x), hash, default=False)) + assert list(ordered((x, y))) == [x, y] + + seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], + (lambda x: len(x), lambda x: sum(x))] + assert list(ordered(seq, keys, default=False, warn=False)) == \ + [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] + raises(ValueError, lambda: + list(ordered(seq, keys, default=False, warn=True))) + + +def test_runs(): + assert runs([]) == [] + assert runs([1]) == [[1]] + assert runs([1, 1]) == [[1], [1]] + assert runs([1, 1, 2]) == [[1], [1, 2]] + assert runs([1, 2, 1]) == [[1, 2], [1]] + assert runs([2, 1, 1]) == [[2], [1], [1]] + from operator import lt + assert runs([2, 1, 1], lt) == [[2, 1], [1]] + + +def test_reshape(): + seq = list(range(1, 9)) + assert reshape(seq, [4]) == \ + [[1, 2, 3, 4], [5, 6, 7, 8]] + assert reshape(seq, (4,)) == \ + [(1, 2, 3, 4), (5, 6, 7, 8)] + assert reshape(seq, (2, 2)) == \ + [(1, 2, 3, 4), (5, 6, 7, 8)] + assert reshape(seq, (2, [2])) == \ + [(1, 2, [3, 4]), (5, 6, [7, 8])] + assert reshape(seq, ((2,), [2])) == \ + [((1, 2), [3, 4]), ((5, 6), [7, 8])] + assert reshape(seq, (1, [2], 1)) == \ + [(1, [2, 3], 4), (5, [6, 7], 8)] + assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \ + (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) + assert reshape(tuple(seq), ([1], 1, (2,))) == \ + (([1], 2, (3, 4)), ([5], 6, (7, 8))) + assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \ + [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] + raises(ValueError, lambda: reshape([0, 1], [-1])) + raises(ValueError, lambda: reshape([0, 1], [3])) + + +def test_uniq(): + assert list(uniq(p for p in partitions(4))) == \ + [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] + assert list(uniq(x % 2 for x in range(5))) == [0, 1] + assert list(uniq('a')) == ['a'] + assert list(uniq('ababc')) == list('abc') + assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]] + assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \ + [([1], 2, 2), (2, [1], 2), (2, 2, [1])] + assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \ + [2, 3, 4, [2], [1], [3]] + f = [1] + raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) + f = [[1]] + raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) + + +def test_kbins(): + assert len(list(kbins('1123', 2, ordered=1))) == 24 + assert len(list(kbins('1123', 2, ordered=11))) == 36 + assert len(list(kbins('1123', 2, ordered=10))) == 10 + assert len(list(kbins('1123', 2, ordered=0))) == 5 + assert len(list(kbins('1123', 2, ordered=None))) == 3 + + def test1(): + for orderedval in [None, 0, 1, 10, 11]: + print('ordered =', orderedval) + for p in kbins([0, 0, 1], 2, ordered=orderedval): + print(' ', p) + assert capture(lambda : test1()) == dedent('''\ + ordered = None + [[0], [0, 1]] + [[0, 0], [1]] + ordered = 0 + [[0, 0], [1]] + [[0, 1], [0]] + ordered = 1 + [[0], [0, 1]] + [[0], [1, 0]] + [[1], [0, 0]] + ordered = 10 + [[0, 0], [1]] + [[1], [0, 0]] + [[0, 1], [0]] + [[0], [0, 1]] + ordered = 11 + [[0], [0, 1]] + [[0, 0], [1]] + [[0], [1, 0]] + [[0, 1], [0]] + [[1], [0, 0]] + [[1, 0], [0]]\n''') + + def test2(): + for orderedval in [None, 0, 1, 10, 11]: + print('ordered =', orderedval) + for p in kbins(list(range(3)), 2, ordered=orderedval): + print(' ', p) + assert capture(lambda : test2()) == dedent('''\ + ordered = None + [[0], [1, 2]] + [[0, 1], [2]] + ordered = 0 + [[0, 1], [2]] + [[0, 2], [1]] + [[0], [1, 2]] + ordered = 1 + [[0], [1, 2]] + [[0], [2, 1]] + [[1], [0, 2]] + [[1], [2, 0]] + [[2], [0, 1]] + [[2], [1, 0]] + ordered = 10 + [[0, 1], [2]] + [[2], [0, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[0], [1, 2]] + [[1, 2], [0]] + ordered = 11 + [[0], [1, 2]] + [[0, 1], [2]] + [[0], [2, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[1, 0], [2]] + [[1], [2, 0]] + [[1, 2], [0]] + [[2], [0, 1]] + [[2, 0], [1]] + [[2], [1, 0]] + [[2, 1], [0]]\n''') + + +def test_has_dups(): + assert has_dups(set()) is False + assert has_dups(list(range(3))) is False + assert has_dups([1, 2, 1]) is True + assert has_dups([[1], [1]]) is True + assert has_dups([[1], [2]]) is False + + +def test__partition(): + assert _partition('abcde', [1, 0, 1, 2, 0]) == [ + ['b', 'e'], ['a', 'c'], ['d']] + assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [ + ['b', 'e'], ['a', 'c'], ['d']] + output = (3, [1, 0, 1, 2, 0]) + assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']] + + +def test_ordered_partitions(): + from sympy.functions.combinatorial.numbers import nT + f = ordered_partitions + assert list(f(0, 1)) == [[]] + assert list(f(1, 0)) == [[]] + for i in range(1, 7): + for j in [None] + list(range(1, i)): + assert ( + sum(1 for p in f(i, j, 1)) == + sum(1 for p in f(i, j, 0)) == + nT(i, j)) + + +def test_rotations(): + assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']] + assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]] + assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]] + + +def test_ibin(): + assert ibin(3) == [1, 1] + assert ibin(3, 3) == [0, 1, 1] + assert ibin(3, str=True) == '11' + assert ibin(3, 3, str=True) == '011' + assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)] + assert list(ibin(2, '', str=True)) == ['00', '01', '10', '11'] + raises(ValueError, lambda: ibin(-.5)) + raises(ValueError, lambda: ibin(2, 1)) + + +def test_iterable(): + assert iterable(0) is False + assert iterable(1) is False + assert iterable(None) is False + + class Test1(NotIterable): + pass + + assert iterable(Test1()) is False + + class Test2(NotIterable): + _iterable = True + + assert iterable(Test2()) is True + + class Test3: + pass + + assert iterable(Test3()) is False + + class Test4: + _iterable = True + + assert iterable(Test4()) is True + + class Test5: + def __iter__(self): + yield 1 + + assert iterable(Test5()) is True + + class Test6(Test5): + _iterable = False + + assert iterable(Test6()) is False + + +def test_sequence_partitions(): + assert list(sequence_partitions([1], 1)) == [[[1]]] + assert list(sequence_partitions([1, 2], 1)) == [[[1, 2]]] + assert list(sequence_partitions([1, 2], 2)) == [[[1], [2]]] + assert list(sequence_partitions([1, 2, 3], 1)) == [[[1, 2, 3]]] + assert list(sequence_partitions([1, 2, 3], 2)) == \ + [[[1], [2, 3]], [[1, 2], [3]]] + assert list(sequence_partitions([1, 2, 3], 3)) == [[[1], [2], [3]]] + + # Exceptional cases + assert list(sequence_partitions([], 0)) == [] + assert list(sequence_partitions([], 1)) == [] + assert list(sequence_partitions([1, 2], 0)) == [] + assert list(sequence_partitions([1, 2], 3)) == [] + + +def test_sequence_partitions_empty(): + assert list(sequence_partitions_empty([], 1)) == [[[]]] + assert list(sequence_partitions_empty([], 2)) == [[[], []]] + assert list(sequence_partitions_empty([], 3)) == [[[], [], []]] + assert list(sequence_partitions_empty([1], 1)) == [[[1]]] + assert list(sequence_partitions_empty([1], 2)) == [[[], [1]], [[1], []]] + assert list(sequence_partitions_empty([1], 3)) == \ + [[[], [], [1]], [[], [1], []], [[1], [], []]] + assert list(sequence_partitions_empty([1, 2], 1)) == [[[1, 2]]] + assert list(sequence_partitions_empty([1, 2], 2)) == \ + [[[], [1, 2]], [[1], [2]], [[1, 2], []]] + assert list(sequence_partitions_empty([1, 2], 3)) == [ + [[], [], [1, 2]], [[], [1], [2]], [[], [1, 2], []], + [[1], [], [2]], [[1], [2], []], [[1, 2], [], []] + ] + assert list(sequence_partitions_empty([1, 2, 3], 1)) == [[[1, 2, 3]]] + assert list(sequence_partitions_empty([1, 2, 3], 2)) == \ + [[[], [1, 2, 3]], [[1], [2, 3]], [[1, 2], [3]], [[1, 2, 3], []]] + assert list(sequence_partitions_empty([1, 2, 3], 3)) == [ + [[], [], [1, 2, 3]], [[], [1], [2, 3]], + [[], [1, 2], [3]], [[], [1, 2, 3], []], + [[1], [], [2, 3]], [[1], [2], [3]], + [[1], [2, 3], []], [[1, 2], [], [3]], + [[1, 2], [3], []], [[1, 2, 3], [], []] + ] + + # Exceptional cases + assert list(sequence_partitions([], 0)) == [] + assert list(sequence_partitions([1], 0)) == [] + assert list(sequence_partitions([1, 2], 0)) == [] + + +def test_signed_permutations(): + ans = [(0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1), + (1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1), + (1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0)] + assert list(signed_permutations((0, 1, 1))) == ans + assert list(signed_permutations((1, 0, 1))) == ans + assert list(signed_permutations((1, 1, 0))) == ans diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_source.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_source.py new file mode 100644 index 0000000000000000000000000000000000000000..468185bc579fc325aee21024dfa15ebf14287b5f --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_source.py @@ -0,0 +1,11 @@ +from sympy.utilities.source import get_mod_func, get_class + + +def test_get_mod_func(): + assert get_mod_func( + 'sympy.core.basic.Basic') == ('sympy.core.basic', 'Basic') + + +def test_get_class(): + _basic = get_class('sympy.core.basic.Basic') + assert _basic.__name__ == 'Basic' diff --git a/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_wester.py b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_wester.py new file mode 100644 index 0000000000000000000000000000000000000000..c5699a4eb0824e507967ecd4ff8f7a5f32cc9a54 --- /dev/null +++ b/evalkit_tf437/lib/python3.10/site-packages/sympy/utilities/tests/test_wester.py @@ -0,0 +1,3104 @@ +""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical +capabilities". + +http://www.math.unm.edu/~wester/cas/book/Wester.pdf +See also http://math.unm.edu/~wester/cas_review.html for detailed output of +each tested system. +""" + +from sympy.assumptions.ask import Q, ask +from sympy.assumptions.refine import refine +from sympy.concrete.products import product +from sympy.core import EulerGamma +from sympy.core.evalf import N +from sympy.core.function import (Derivative, Function, Lambda, Subs, + diff, expand, expand_func) +from sympy.core.mul import Mul +from sympy.core.intfunc import igcd +from sympy.core.numbers import (AlgebraicNumber, E, I, Rational, + nan, oo, pi, zoo) +from sympy.core.relational import Eq, Lt +from sympy.core.singleton import S +from sympy.core.symbol import Dummy, Symbol, symbols +from sympy.functions.combinatorial.factorials import (rf, binomial, + factorial, factorial2) +from sympy.functions.combinatorial.numbers import bernoulli, fibonacci, totient, partition +from sympy.functions.elementary.complexes import (conjugate, im, re, + sign) +from sympy.functions.elementary.exponential import LambertW, exp, log +from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, + tanh) +from sympy.functions.elementary.integers import ceiling, floor +from sympy.functions.elementary.miscellaneous import Max, Min, sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (acos, acot, asin, + atan, cos, cot, csc, sec, sin, tan) +from sympy.functions.special.bessel import besselj +from sympy.functions.special.delta_functions import DiracDelta +from sympy.functions.special.elliptic_integrals import (elliptic_e, + elliptic_f) +from sympy.functions.special.gamma_functions import gamma, polygamma +from sympy.functions.special.hyper import hyper +from sympy.functions.special.polynomials import (assoc_legendre, + chebyshevt) +from sympy.functions.special.zeta_functions import polylog +from sympy.geometry.util import idiff +from sympy.logic.boolalg import And +from sympy.matrices.dense import hessian, wronskian +from sympy.matrices.expressions.matmul import MatMul +from sympy.ntheory.continued_fraction import ( + continued_fraction_convergents as cf_c, + continued_fraction_iterator as cf_i, continued_fraction_periodic as + cf_p, continued_fraction_reduce as cf_r) +from sympy.ntheory.factor_ import factorint +from sympy.ntheory.generate import primerange +from sympy.polys.domains.integerring import ZZ +from sympy.polys.orthopolys import legendre_poly +from sympy.polys.partfrac import apart +from sympy.polys.polytools import Poly, factor, gcd, resultant +from sympy.series.limits import limit +from sympy.series.order import O +from sympy.series.residues import residue +from sympy.series.series import series +from sympy.sets.fancysets import ImageSet +from sympy.sets.sets import FiniteSet, Intersection, Interval, Union +from sympy.simplify.combsimp import combsimp +from sympy.simplify.hyperexpand import hyperexpand +from sympy.simplify.powsimp import powdenest, powsimp +from sympy.simplify.radsimp import radsimp +from sympy.simplify.simplify import logcombine, simplify +from sympy.simplify.sqrtdenest import sqrtdenest +from sympy.simplify.trigsimp import trigsimp +from sympy.solvers.solvers import solve + +import mpmath +from sympy.functions.combinatorial.numbers import stirling +from sympy.functions.special.delta_functions import Heaviside +from sympy.functions.special.error_functions import Ci, Si, erf +from sympy.functions.special.zeta_functions import zeta +from sympy.testing.pytest import (XFAIL, slow, SKIP, tooslow, raises) +from sympy.utilities.iterables import partitions +from mpmath import mpi, mpc +from sympy.matrices import Matrix, GramSchmidt, eye +from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse +from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix +from sympy.physics.quantum import Commutator +from sympy.polys.rings import PolyRing +from sympy.polys.fields import FracField +from sympy.polys.solvers import solve_lin_sys +from sympy.concrete import Sum +from sympy.concrete.products import Product +from sympy.integrals import integrate +from sympy.integrals.transforms import laplace_transform,\ + inverse_laplace_transform, LaplaceTransform, fourier_transform,\ + mellin_transform, laplace_correspondence, laplace_initial_conds +from sympy.solvers.recurr import rsolve +from sympy.solvers.solveset import solveset, solveset_real, linsolve +from sympy.solvers.ode import dsolve +from sympy.core.relational import Equality +from itertools import islice, takewhile +from sympy.series.formal import fps +from sympy.series.fourier import fourier_series +from sympy.calculus.util import minimum + + +EmptySet = S.EmptySet +R = Rational +x, y, z = symbols('x y z') +i, j, k, l, m, n = symbols('i j k l m n', integer=True) +f = Function('f') +g = Function('g') + +# A. Boolean Logic and Quantifier Elimination +# Not implemented. + +# B. Set Theory + + +def test_B1(): + assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) | + FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m) + + +def test_B2(): + assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) & + FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l}) + # Previous output below. Not sure why that should be the expected output. + # There should probably be a way to rewrite Intersections that way but I + # don't see why an Intersection should evaluate like that: + # + # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l})))) + + +def test_B3(): + assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) == + FiniteSet(i, k, l, m)) + + +def test_B4(): + assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) == + FiniteSet((i, k), (i, l), (j, k), (j, l))) + + +# C. Numbers + + +def test_C1(): + assert (factorial(50) == + 30414093201713378043612608166064768844377641568960512000000000000) + + +def test_C2(): + assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8, + 11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1, + 41: 1, 43: 1, 47: 1}) + + +def test_C3(): + assert (factorial2(10), factorial2(9)) == (3840, 945) + + +# Base conversions; not really implemented by SymPy +# Whatever. Take credit! +def test_C4(): + assert 0xABC == 2748 + + +def test_C5(): + assert 123 == int('234', 7) + + +def test_C6(): + assert int('677', 8) == int('1BF', 16) == 447 + + +def test_C7(): + assert log(32768, 8) == 5 + + +def test_C8(): + # Modular multiplicative inverse. Would be nice if divmod could do this. + assert ZZ.invert(5, 7) == 3 + assert ZZ.invert(5, 6) == 5 + + +def test_C9(): + assert igcd(igcd(1776, 1554), 5698) == 74 + + +def test_C10(): + x = 0 + for n in range(2, 11): + x += R(1, n) + assert x == R(4861, 2520) + + +def test_C11(): + assert R(1, 7) == S('0.[142857]') + + +def test_C12(): + assert R(7, 11) * R(22, 7) == 2 + + +def test_C13(): + test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3) + good = 3 ** R(1, 3) + assert test == good + + +def test_C14(): + assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3) + + +def test_C15(): + test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2)))))) + good = sqrt(2) + 3 + assert test == good + + +def test_C16(): + test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15))) + good = sqrt(2) + sqrt(3) + sqrt(5) + assert test == good + + +def test_C17(): + test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2))) + good = 5 + 2*sqrt(6) + assert test == good + + +def test_C18(): + assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3 + + +@XFAIL +def test_C19(): + assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7) + + +def test_C20(): + inside = (135 + 78*sqrt(3)) + test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3)) + assert simplify(test) == AlgebraicNumber(12) + + +def test_C21(): + assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \ + AlgebraicNumber(1 + sqrt(2)) + + +@XFAIL +def test_C22(): + test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17 + - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72)) + good = sqrt(2)/3 - log(sqrt(2) - 1)/3 + assert test == good + + +def test_C23(): + assert 2 * oo - 3 is oo + + +@XFAIL +def test_C24(): + raise NotImplementedError("2**aleph_null == aleph_1") + +# D. Numerical Analysis + + +def test_D1(): + assert 0.0 / sqrt(2) == 0 + + +def test_D2(): + assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295' + + +def test_D3(): + assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744) + + +def test_D4(): + assert floor(R(-5, 3)) == -2 + assert ceiling(R(-5, 3)) == -1 + + +@XFAIL +def test_D5(): + raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8") + + +@XFAIL +def test_D6(): + raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN") + + +@XFAIL +def test_D7(): + raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C") + + +@XFAIL +def test_D8(): + # One way is to cheat by converting the sum to a string, + # and replacing the '[' and ']' with ''. + # E.g., horner(S(str(_).replace('[','').replace(']',''))) + raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))") + + +@XFAIL +def test_D9(): + raise NotImplementedError("translate D8 to FORTRAN") + + +@XFAIL +def test_D10(): + raise NotImplementedError("translate D8 to C") + + +@XFAIL +def test_D11(): + #Is there a way to use count_ops? + raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))") + + +@XFAIL +def test_D12(): + assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9) + + +@XFAIL +def test_D13(): + raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)") + +# E. Statistics +# See scipy; all of this is numerical. + +# F. Combinatorial Theory. + + +def test_F1(): + assert rf(x, 3) == x*(1 + x)*(2 + x) + + +def test_F2(): + assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6 + + +@XFAIL +def test_F3(): + assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n) + + +@XFAIL +def test_F4(): + assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n) + + +@XFAIL +def test_F5(): + assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2 + + +def test_F6(): + partTest = [p.copy() for p in partitions(4)] + partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}] + assert partTest == partDesired + + +def test_F7(): + assert partition(4) == 5 + + +def test_F8(): + assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1 + + +def test_F9(): + assert totient(1776) == 576 + +# G. Number Theory + + +def test_G1(): + assert list(primerange(999983, 1000004)) == [999983, 1000003] + + +@XFAIL +def test_G2(): + raise NotImplementedError("find the primitive root of 191 == 19") + + +@XFAIL +def test_G3(): + raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime") + +# ... G14 Modular equations are not implemented. + +def test_G15(): + assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15) + assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \ + R(26, 15) + + +def test_G16(): + assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1] + + +def test_G17(): + assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]] + + +def test_G18(): + assert cf_p(1, 2, 5) == [[1]] + assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2 + + +@XFAIL +def test_G19(): + s = symbols('s', integer=True, positive=True) + it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1)) + assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s] + + +def test_G20(): + s = symbols('s', integer=True, positive=True) + # Wester erroneously has this as -s + sqrt(s**2 + 1) + assert cf_r([[2*s]]) == s + sqrt(s**2 + 1) + + +@XFAIL +def test_G20b(): + s = symbols('s', integer=True, positive=True) + assert cf_p(s, 1, s**2 + 1) == [[2*s]] + + +# H. Algebra + + +def test_H1(): + assert simplify(2*2**n) == simplify(2**(n + 1)) + assert powdenest(2*2**n) == simplify(2**(n + 1)) + + +def test_H2(): + assert powsimp(4 * 2**n) == 2**(n + 2) + + +def test_H3(): + assert (-1)**(n*(n + 1)) == 1 + + +def test_H4(): + expr = factor(6*x - 10) + assert type(expr) is Mul + assert expr.args[0] == 2 + assert expr.args[1] == 3*x - 5 + +p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81 +p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81 +q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86 + + +def test_H5(): + assert gcd(p1, p2, x) == 1 + + +def test_H6(): + assert gcd(expand(p1 * q), expand(p2 * q)) == q + + +def test_H7(): + p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 + p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z + assert gcd(p1, p2, x, y, z) == 1 + + +def test_H8(): + p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 + p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z + q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8 + assert gcd(p1 * q, p2 * q, x, y, z) == q + + +def test_H9(): + x = Symbol('x', zero=False) + p1 = 2*x**(n + 4) - x**(n + 2) + p2 = 4*x**(n + 1) + 3*x**n + assert gcd(p1, p2) == x**n + + +def test_H10(): + p1 = 3*x**4 + 3*x**3 + x**2 - x - 2 + p2 = x**3 - 3*x**2 + x + 5 + assert resultant(p1, p2, x) == 0 + + +def test_H11(): + assert resultant(p1 * q, p2 * q, x) == 0 + + +def test_H12(): + num = x**2 - 4 + den = x**2 + 4*x + 4 + assert simplify(num/den) == (x - 2)/(x + 2) + + +@XFAIL +def test_H13(): + assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1 + + +def test_H14(): + p = (x + 1) ** 20 + ep = expand(p) + assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5 + + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10 + + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15 + + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20) + dep = diff(ep, x) + assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4 + + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9 + + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13 + + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18 + + 20*x**19) + assert factor(dep) == 20*(1 + x)**19 + + +def test_H15(): + assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7 + + +def test_H16(): + assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3 + + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4 + - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10 + + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1)) + + +def test_H17(): + assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0 + + +@XFAIL +def test_H18(): + # Factor over complex rationals. + test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153) + good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I) + assert test == good + + +def test_H19(): + a = symbols('a') + # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1") + assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1 + + +@XFAIL +def test_H20(): + raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - " + + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)") + + +@XFAIL +def test_H21(): + raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \ + Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9") + + +def test_H22(): + assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2 + + +def test_H23(): + f = x**11 + x + 1 + g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1) + assert factor(f, modulus=65537) == g + + +def test_H24(): + phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') + assert factor(x**4 - 3*x**2 + 1, extension=phi) == \ + (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi) + + +def test_H25(): + e = (x - 2*y**2 + 3*z**3) ** 20 + assert factor(expand(e)) == e + + +def test_H26(): + g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20) + assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20 + + +def test_H27(): + f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 + g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z + h = -2*z*y**7 \ + *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \ + *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5) + assert factor(expand(f*g)) == h + + +@XFAIL +def test_H28(): + raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * " + + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.") + + +@XFAIL +def test_H29(): + assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y) + + +def test_H30(): + test = factor(x**3 + y**3, extension=sqrt(-3)) + answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I)) + assert answer == test + + +def test_H31(): + f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) + g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) + assert apart(f) == g + + +@XFAIL +def test_H32(): # issue 6558 + raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \ + of a non-commuting product and its inverse)") + + +def test_H33(): + A, B, C = symbols('A, B, C', commutative=False) + assert (Commutator(A, Commutator(B, C)) + + Commutator(B, Commutator(C, A)) + + Commutator(C, Commutator(A, B))).doit().expand() == 0 + + +# I. Trigonometry + +def test_I1(): + assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5)) + + +@XFAIL +def test_I2(): + assert sqrt((1 + cos(6))/2) == -cos(3) + + +def test_I3(): + assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1 + + +def test_I4(): + assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1 + + +@XFAIL +def test_I5(): + assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0 + + +@XFAIL +def test_I6(): + raise NotImplementedError("assuming -3*pi pi**E) + + +@XFAIL +def test_N2(): + x = symbols('x', real=True) + assert ask(x**4 - x + 1 > 0) is True + assert ask(x**4 - x + 1 > 1) is False + + +@XFAIL +def test_N3(): + x = symbols('x', real=True) + assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 ) + +@XFAIL +def test_N4(): + x, y = symbols('x y', real=True) + assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True + + +@XFAIL +def test_N5(): + x, y, k = symbols('x y k', real=True) + assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True + + +@slow +@XFAIL +def test_N6(): + x, y, k, n = symbols('x y k n', real=True) + assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True + + +@XFAIL +def test_N7(): + x, y = symbols('x y', real=True) + assert ask(y > 0, (x > 1) & (y >= x - 1)) is True + + +@XFAIL +@slow +def test_N8(): + x, y, z = symbols('x y z', real=True) + assert ask(Eq(x, y) & Eq(y, z), + (x >= y) & (y >= z) & (z >= x)) + + +def test_N9(): + x = Symbol('x') + assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True), + Interval(3, oo, True)) + + +def test_N10(): + x = Symbol('x') + p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) + assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True), + Interval(2, 3, True, True), + Interval(4, 5, True, True)) + + +def test_N11(): + x = Symbol('x') + assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo)) + + +def test_N12(): + x = Symbol('x') + assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True) + + +def test_N13(): + x = Symbol('x') + assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals + + +@XFAIL +def test_N14(): + x = Symbol('x') + # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true), + # Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))' + # which is not the correct answer, but the provided also seems wrong. + assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True), + Interval(pi/2, oo, True, True)) + + +def test_N15(): + r, t = symbols('r t') + # raises NotImplementedError: only univariate inequalities are supported + solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals) + + +def test_N16(): + r, t = symbols('r t') + solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals) + + +@XFAIL +def test_N17(): + # currently only univariate inequalities are supported + assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y) + + +def test_O1(): + M = Matrix((1 + I, -2, 3*I)) + assert sqrt(expand(M.dot(M.H))) == sqrt(15) + + +def test_O2(): + assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11], + [-5], + [4]]) + +# The vector module has no way of representing vectors symbolically (without +# respect to a basis) +@XFAIL +def test_O3(): + # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc) + raise NotImplementedError("""The vector module has no way of representing + vectors symbolically (without respect to a basis)""") + +def test_O4(): + from sympy.vector import CoordSys3D, Del + N = CoordSys3D("N") + delop = Del() + i, j, k = N.base_vectors() + x, y, z = N.base_scalars() + F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3)) + assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k + +@XFAIL +def test_O5(): + #assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0 + raise NotImplementedError("""The vector module has no way of representing + vectors symbolically (without respect to a basis)""") + +#testO8-O9 MISSING!! + + +def test_O10(): + L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])] + assert GramSchmidt(L) == [Matrix([ + [2], + [3], + [5]]), + Matrix([ + [R(23, 19)], + [R(63, 19)], + [R(-47, 19)]]), + Matrix([ + [R(1692, 353)], + [R(-1551, 706)], + [R(-423, 706)]])] + + +def test_P1(): + assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix( + 1, 2, [-1, -1]) + + +def test_P2(): + M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + M.row_del(1) + M.col_del(2) + assert M == Matrix([[1, 2], + [7, 8]]) + + +def test_P3(): + A = Matrix([ + [11, 12, 13, 14], + [21, 22, 23, 24], + [31, 32, 33, 34], + [41, 42, 43, 44]]) + + A11 = A[0:3, 1:4] + A12 = A[(0, 1, 3), (2, 0, 3)] + A21 = A + A221 = -A[0:2, 2:4] + A222 = -A[(3, 0), (2, 1)] + A22 = BlockMatrix([[A221, A222]]).T + rows = [[-A11, A12], [A21, A22]] + raises(ValueError, lambda: BlockMatrix(rows)) + B = Matrix(rows) + assert B == Matrix([ + [-12, -13, -14, 13, 11, 14], + [-22, -23, -24, 23, 21, 24], + [-32, -33, -34, 43, 41, 44], + [11, 12, 13, 14, -13, -23], + [21, 22, 23, 24, -14, -24], + [31, 32, 33, 34, -43, -13], + [41, 42, 43, 44, -42, -12]]) + + +@XFAIL +def test_P4(): + raise NotImplementedError("Block matrix diagonalization not supported") + + +def test_P5(): + M = Matrix([[7, 11], + [3, 8]]) + assert M % 2 == Matrix([[1, 1], + [1, 0]]) + + +def test_P6(): + M = Matrix([[cos(x), sin(x)], + [-sin(x), cos(x)]]) + assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)], + [sin(x), -cos(x)]]) + + +def test_P7(): + M = Matrix([[x, y]])*( + z*Matrix([[1, 3, 5], + [2, 4, 6]]) + Matrix([[7, -9, 11], + [-8, 10, -12]])) + assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10), + x*(5*z + 11) + y*(6*z - 12)]]) + + +def test_P8(): + M = Matrix([[1, -2*I], + [-3*I, 4]]) + assert M.norm(ord=S.Infinity) == 7 + + +def test_P9(): + a, b, c = symbols('a b c', nonzero=True) + M = Matrix([[a/(b*c), 1/c, 1/b], + [1/c, b/(a*c), 1/a], + [1/b, 1/a, c/(a*b)]]) + assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c)) + + +@XFAIL +def test_P10(): + M = Matrix([[1, 2 + 3*I], + [f(4 - 5*I), 6]]) + # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I) + assert M.H == Matrix([[1, f(4 + 5*I)], + [2 + 3*I, 6]]) + + +@XFAIL +def test_P11(): + # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv() + # not simplifying to extract common factor") + assert Matrix([[x, y], + [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1], + [-1/y, x/y]]) + + +def test_P11_workaround(): + # This test was changed to inverse method ADJ because it depended on the + # specific form of inverse returned from the 'GE' method which has changed. + M = Matrix([[x, y], [1, x*y]]).inv('ADJ') + c = gcd(tuple(M)) + assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([ + [x*y, -y], + [ -1, x]]), evaluate=False) + + +def test_P12(): + A11 = MatrixSymbol('A11', n, n) + A12 = MatrixSymbol('A12', n, n) + A22 = MatrixSymbol('A22', n, n) + B = BlockMatrix([[A11, A12], + [ZeroMatrix(n, n), A22]]) + assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I], + [ZeroMatrix(n, n), A22.I]]) + + +def test_P13(): + M = Matrix([[1, x - 2, x - 3], + [x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2], + [x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]]) + L, U, _ = M.LUdecomposition() + assert simplify(L) == Matrix([[1, 0, 0], + [x - 1, 1, 0], + [x - 2, x - 3, 1]]) + assert simplify(U) == Matrix([[1, x - 2, x - 3], + [0, 4, x - 5], + [0, 0, x - 7]]) + + +def test_P14(): + M = Matrix([[1, 2, 3, 1, 3], + [3, 2, 1, 1, 7], + [0, 2, 4, 1, 1], + [1, 1, 1, 1, 4]]) + R, _ = M.rref() + assert R == Matrix([[1, 0, -1, 0, 2], + [0, 1, 2, 0, -1], + [0, 0, 0, 1, 3], + [0, 0, 0, 0, 0]]) + + +def test_P15(): + M = Matrix([[-1, 3, 7, -5], + [4, -2, 1, 3], + [2, 4, 15, -7]]) + assert M.rank() == 2 + + +def test_P16(): + M = Matrix([[2*sqrt(2), 8], + [6*sqrt(6), 24*sqrt(3)]]) + assert M.rank() == 1 + + +def test_P17(): + t = symbols('t', real=True) + M=Matrix([ + [sin(2*t), cos(2*t)], + [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]]) + assert M.rank() == 1 + + +def test_P18(): + M = Matrix([[1, 0, -2, 0], + [-2, 1, 0, 3], + [-1, 2, -6, 6]]) + assert M.nullspace() == [Matrix([[2], + [4], + [1], + [0]]), + Matrix([[0], + [-3], + [0], + [1]])] + + +def test_P19(): + w = symbols('w') + M = Matrix([[1, 1, 1, 1], + [w, x, y, z], + [w**2, x**2, y**2, z**2], + [w**3, x**3, y**3, z**3]]) + assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2 + + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z + + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3 + + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3 + + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2 + + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3 + ) + + +@XFAIL +def test_P20(): + raise NotImplementedError("Matrix minimal polynomial not supported") + + +def test_P21(): + M = Matrix([[5, -3, -7], + [-2, 1, 2], + [2, -3, -4]]) + assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6 + + +def test_P22(): + d = 100 + M = (2 - x)*eye(d) + assert M.eigenvals() == {-x + 2: d} + + +def test_P23(): + M = Matrix([ + [2, 1, 0, 0, 0], + [1, 2, 1, 0, 0], + [0, 1, 2, 1, 0], + [0, 0, 1, 2, 1], + [0, 0, 0, 1, 2]]) + assert M.eigenvals() == { + S('1'): 1, + S('2'): 1, + S('3'): 1, + S('sqrt(3) + 2'): 1, + S('-sqrt(3) + 2'): 1} + + +def test_P24(): + M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29], + [196, 899, 113, -192, -71, -43, -8, -44], + [-192, 113, 899, 196, 61, 49, 8, 52], + [ 407, -192, 196, 611, 8, 44, 59, -23], + [ -8, -71, 61, 8, 411, -599, 208, 208], + [ -52, -43, 49, 44, -599, 411, 208, 208], + [ -49, -8, 8, 59, 208, 208, 99, -911], + [ 29, -44, 52, -23, 208, 208, -911, 99]]) + assert M.eigenvals() == { + S('0'): 1, + S('10*sqrt(10405)'): 1, + S('100*sqrt(26) + 510'): 1, + S('1000'): 2, + S('-100*sqrt(26) + 510'): 1, + S('-10*sqrt(10405)'): 1, + S('1020'): 1} + + +def test_P25(): + MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29], + [ 196, 899, 113, -192, -71, -43, -8, -44], + [-192, 113, 899, 196, 61, 49, 8, 52], + [ 407, -192, 196, 611, 8, 44, 59, -23], + [ -8, -71, 61, 8, 411, -599, 208, 208], + [ -52, -43, 49, 44, -599, 411, 208, 208], + [ -49, -8, 8, 59, 208, 208, 99, -911], + [ 29, -44, 52, -23, 208, 208, -911, 99]])) + + ev_1 = sorted(MF.eigenvals(multiple=True)) + ev_2 = sorted( + [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0, + 1019.9019513592784, 1020.0, 1020.0490184299969]) + + for x, y in zip(ev_1, ev_2): + assert abs(x - y) < 1e-12 + + +def test_P26(): + a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4') + M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0], + [ 1, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 1, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 1, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 1, 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, -1, -1, 0, 0], + [ 0, 0, 0, 0, 0, 1, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 1, -1, -1], + [ 0, 0, 0, 0, 0, 0, 0, 1, 0]]) + assert M.eigenvals(error_when_incomplete=False) == { + S('-1/2 - sqrt(3)*I/2'): 2, + S('-1/2 + sqrt(3)*I/2'): 2} + + +def test_P27(): + a = symbols('a') + M = Matrix([[a, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 0, a, 0, 0], + [0, 0, 0, a, 0], + [0, -2, 0, 0, 2]]) + + assert M.eigenvects() == [ + (a, 3, [ + Matrix([1, 0, 0, 0, 0]), + Matrix([0, 0, 1, 0, 0]), + Matrix([0, 0, 0, 1, 0]) + ]), + (1 - I, 1, [ + Matrix([0, (1 + I)/2, 0, 0, 1]) + ]), + (1 + I, 1, [ + Matrix([0, (1 - I)/2, 0, 0, 1]) + ]), + ] + + +@XFAIL +def test_P28(): + raise NotImplementedError("Generalized eigenvectors not supported \ +https://github.com/sympy/sympy/issues/5293") + + +@XFAIL +def test_P29(): + raise NotImplementedError("Generalized eigenvectors not supported \ +https://github.com/sympy/sympy/issues/5293") + + +def test_P30(): + M = Matrix([[1, 0, 0, 1, -1], + [0, 1, -2, 3, -3], + [0, 0, -1, 2, -2], + [1, -1, 1, 0, 1], + [1, -1, 1, -1, 2]]) + _, J = M.jordan_form() + assert J == Matrix([[-1, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 1], + [0, 0, 0, 0, 1]]) + + +@XFAIL +def test_P31(): + raise NotImplementedError("Smith normal form not implemented") + + +def test_P32(): + M = Matrix([[1, -2], + [2, 1]]) + assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)], + [E*sin(2), E*cos(2)]]) + + +def test_P33(): + w, t = symbols('w t') + M = Matrix([[0, 1, 0, 0], + [0, 0, 0, 2*w], + [0, 0, 0, 1], + [0, -2*w, 3*w**2, 0]]) + assert exp(M*t).rewrite(cos).expand() == Matrix([ + [1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w], + [0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)], + [0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w], + [0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]]) + + +@XFAIL +def test_P34(): + a, b, c = symbols('a b c', real=True) + M = Matrix([[a, 1, 0, 0, 0, 0], + [0, a, 0, 0, 0, 0], + [0, 0, b, 0, 0, 0], + [0, 0, 0, c, 1, 0], + [0, 0, 0, 0, c, 1], + [0, 0, 0, 0, 0, c]]) + # raises exception, sin(M) not supported. exp(M*I) also not supported + # https://github.com/sympy/sympy/issues/6218 + assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0], + [0, sin(a), 0, 0, 0, 0], + [0, 0, sin(b), 0, 0, 0], + [0, 0, 0, sin(c), cos(c), -sin(c)/2], + [0, 0, 0, 0, sin(c), cos(c)], + [0, 0, 0, 0, 0, sin(c)]]) + + +@XFAIL +def test_P35(): + M = pi/2*Matrix([[2, 1, 1], + [2, 3, 2], + [1, 1, 2]]) + # raises exception, sin(M) not supported. exp(M*I) also not supported + # https://github.com/sympy/sympy/issues/6218 + assert sin(M) == eye(3) + + +@XFAIL +def test_P36(): + M = Matrix([[10, 7], + [7, 17]]) + assert sqrt(M) == Matrix([[3, 1], + [1, 4]]) + + +def test_P37(): + M = Matrix([[1, 1, 0], + [0, 1, 0], + [0, 0, 1]]) + assert M**S.Half == Matrix([[1, R(1, 2), 0], + [0, 1, 0], + [0, 0, 1]]) + + +@XFAIL +def test_P38(): + M=Matrix([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + + with raises(AssertionError): + # raises ValueError: Matrix det == 0; not invertible + M**S.Half + # if it doesn't raise then this assertion will be + # raised and the test will be flagged as not XFAILing + assert None + +@XFAIL +def test_P39(): + """ + M=Matrix([ + [1, 1], + [2, 2], + [3, 3]]) + M.SVD() + """ + raise NotImplementedError("Singular value decomposition not implemented") + + +def test_P40(): + r, t = symbols('r t', real=True) + M = Matrix([r*cos(t), r*sin(t)]) + assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)], + [sin(t), r*cos(t)]]) + + +def test_P41(): + r, t = symbols('r t', real=True) + assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)], + [2*r*cos(t), -r**2*sin(t)]]) + + +def test_P42(): + assert wronskian([cos(x), sin(x)], x).simplify() == 1 + + +def test_P43(): + def __my_jacobian(M, Y): + return Matrix([M.diff(v).T for v in Y]).T + r, t = symbols('r t', real=True) + M = Matrix([r*cos(t), r*sin(t)]) + assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)], + [sin(t), r*cos(t)]]) + + +def test_P44(): + def __my_hessian(f, Y): + V = Matrix([diff(f, v) for v in Y]) + return Matrix([V.T.diff(v) for v in Y]) + r, t = symbols('r t', real=True) + assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ + [ 2*sin(t), 2*r*cos(t)], + [2*r*cos(t), -r**2*sin(t)]]) + + +def test_P45(): + def __my_wronskian(Y, v): + M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) + return M.det() + assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 + +# Q1-Q6 Tensor tests missing + + +@XFAIL +def test_R1(): + i, j, n = symbols('i j n', integer=True, positive=True) + xn = MatrixSymbol('xn', n, 1) + Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1)) + # sum does not calculate + # Unknown result + Sm.doit() + raise NotImplementedError('Unknown result') + +@XFAIL +def test_R2(): + m, b = symbols('m b') + i, n = symbols('i n', integer=True, positive=True) + xn = MatrixSymbol('xn', n, 1) + yn = MatrixSymbol('yn', n, 1) + f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1)) + f1 = diff(f, m) + f2 = diff(f, b) + # raises TypeError: solveset() takes at most 2 arguments (3 given) + solveset((f1, f2), (m, b), domain=S.Reals) + + +@XFAIL +def test_R3(): + n, k = symbols('n k', integer=True, positive=True) + sk = ((-1)**k) * (binomial(2*n, k))**2 + Sm = Sum(sk, (k, 1, oo)) + T = Sm.doit() + T2 = T.combsimp() + # returns -((-1)**n*factorial(2*n) + # - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2 + assert T2 == (-1)**n*binomial(2*n, n) + + +@XFAIL +def test_R4(): +# Macsyma indefinite sum test case: +#(c15) /* Check whether the full Gosper algorithm is implemented +# => 1/2^(n + 1) binomial(n, k - 1) */ +#closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k)); +#Time= 2690 msecs +# (- n + k - 1) binomial(n + 1, k) +#(d15) - -------------------------------- +# n +# 2 2 (n + 1) +# +#(c16) factcomb(makefact(%)); +#Time= 220 msecs +# n! +#(d16) ---------------- +# n +# 2 k! 2 (n - k)! +# Might be possible after fixing https://github.com/sympy/sympy/pull/1879 + raise NotImplementedError("Indefinite sum not supported") + + +@XFAIL +def test_R5(): + a, b, c, n, k = symbols('a b c n k', integer=True, positive=True) + sk = ((-1)**k)*(binomial(a + b, a + k) + *binomial(b + c, b + k)*binomial(c + a, c + k)) + Sm = Sum(sk, (k, 1, oo)) + T = Sm.doit() # hypergeometric series not calculated + assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c)) + + +def test_R6(): + n, k = symbols('n k', integer=True, positive=True) + gn = MatrixSymbol('gn', n + 2, 1) + Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1)) + assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0] + + +def test_R7(): + n, k = symbols('n k', integer=True, positive=True) + T = Sum(k**3,(k,1,n)).doit() + assert T.factor() == n**2*(n + 1)**2/4 + +@XFAIL +def test_R8(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(k**2*binomial(n, k), (k, 1, n)) + T = Sm.doit() #returns Piecewise function + assert T.combsimp() == n*(n + 1)*2**(n - 2) + + +def test_R9(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1)) + assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1) + + +@XFAIL +def test_R10(): + n, m, r, k = symbols('n m r k', integer=True, positive=True) + Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r)) + T = Sm.doit() + T2 = T.combsimp().rewrite(factorial) + assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r)) + assert T2 == binomial(m + n, r).rewrite(factorial) + # rewrite(binomial) is not working. + # https://github.com/sympy/sympy/issues/7135 + T3 = T2.rewrite(binomial) + assert T3 == binomial(m + n, r) + + +@XFAIL +def test_R11(): + n, k = symbols('n k', integer=True, positive=True) + sk = binomial(n, k)*fibonacci(k) + Sm = Sum(sk, (k, 0, n)) + T = Sm.doit() + # Fibonacci simplification not implemented + # https://github.com/sympy/sympy/issues/7134 + assert T == fibonacci(2*n) + + +@XFAIL +def test_R12(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(fibonacci(k)**2, (k, 0, n)) + T = Sm.doit() + assert T == fibonacci(n)*fibonacci(n + 1) + + +@XFAIL +def test_R13(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(sin(k*x), (k, 1, n)) + T = Sm.doit() # Sum is not calculated + assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2)) + + +@XFAIL +def test_R14(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(sin((2*k - 1)*x), (k, 1, n)) + T = Sm.doit() # Sum is not calculated + assert T.simplify() == sin(n*x)**2/sin(x) + + +@XFAIL +def test_R15(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2))) + T = Sm.doit() # Sum is not calculated + assert T.simplify() == fibonacci(n + 1) + + +def test_R16(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo)) + assert Sm.doit() == zeta(3) + pi**2/6 + + +def test_R17(): + k = symbols('k', integer=True, positive=True) + assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo))) + - 2.8469909700078206) < 1e-15 + + +def test_R18(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/(2**k*k**2), (k, 1, oo)) + T = Sm.doit() + assert T.simplify() == -log(2)**2/2 + pi**2/12 + + +@slow +@XFAIL +def test_R19(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo)) + T = Sm.doit() + # assert fails, T not simplified + assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12 + + +@XFAIL +def test_R20(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(binomial(n, 4*k), (k, 0, oo)) + T = Sm.doit() + # assert fails, T not simplified + assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2 + + +@XFAIL +def test_R21(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo)) + T = Sm.doit() # Sum not calculated + assert T.simplify() == 1 + + +# test_R22 answer not available in Wester samples +# Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k), +# (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1? + + +@XFAIL +def test_R23(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))* + (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo)) + # Missing how to express constraint abs(x*y)<1? + T = Sm.doit() # Sum not calculated + assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1) + + +def test_R24(): + m, k = symbols('m k', integer=True, positive=True) + Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo)) + assert Sm.doit() == pi/2 + + +def test_S1(): + k = symbols('k', integer=True, positive=True) + Pr = Product(gamma(k/3), (k, 1, 8)) + assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561 + + +def test_S2(): + n, k = symbols('n k', integer=True, positive=True) + assert Product(k, (k, 1, n)).doit() == factorial(n) + + +def test_S3(): + n, k = symbols('n k', integer=True, positive=True) + assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2) + + +def test_S4(): + n, k = symbols('n k', integer=True, positive=True) + assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n + + +def test_S5(): + n, k = symbols('n k', integer=True, positive=True) + assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() == + gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) + + +@XFAIL +def test_S6(): + n, k = symbols('n k', integer=True, positive=True) + # Product does not evaluate + assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify() + == (x**(2*n) - 1)/(x**2 - 1)) + + +@XFAIL +def test_S7(): + k = symbols('k', integer=True, positive=True) + Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo)) + T = Pr.doit() # Product does not evaluate + assert T.simplify() == R(2, 3) + + +@XFAIL +def test_S8(): + k = symbols('k', integer=True, positive=True) + Pr = Product(1 - 1/(2*k)**2, (k, 1, oo)) + T = Pr.doit() + # Product does not evaluate + assert T.simplify() == 2/pi + + +@XFAIL +def test_S9(): + k = symbols('k', integer=True, positive=True) + Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo)) + T = Pr.doit() + # Product produces 0 + # https://github.com/sympy/sympy/issues/7133 + assert T.simplify() == sqrt(2) + + +@XFAIL +def test_S10(): + k = symbols('k', integer=True, positive=True) + Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo)) + T = Pr.doit() + # Product does not evaluate + assert T.simplify() == -1 + + +def test_T1(): + assert limit((1 + 1/n)**n, n, oo) == E + assert limit((1 - cos(x))/x**2, x, 0) == S.Half + + +def test_T2(): + assert limit((3**x + 5**x)**(1/x), x, oo) == 5 + + +def test_T3(): + assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1 + + +def test_T4(): + assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) + - exp(x))/x, x, oo) == -exp(2) + + +def test_T5(): + assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3) + + +def test_T6(): + assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1) + + +def test_T7(): + limit(1/n * gamma(n + 1)**(1/n), n, oo) + + +def test_T8(): + a, z = symbols('a z', positive=True) + assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1 + + +@XFAIL +def test_T9(): + z, k = symbols('z k', positive=True) + # raises NotImplementedError: + # Don't know how to calculate the mrv of '(1, k)' + assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z) + + +@XFAIL +def test_T10(): + # No longer raises PoleError, but should return euler-mascheroni constant + assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo)) + +@XFAIL +def test_T11(): + n, k = symbols('n k', integer=True, positive=True) + # evaluates to 0 + assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x) + + +def test_T12(): + x, t = symbols('x t', real=True) + # Does not evaluate the limit but returns an expression with erf + assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)), + x, 0) == 1 + + +def test_T13(): + x = symbols('x', real=True) + assert [limit(x/abs(x), x, 0, dir='-'), + limit(x/abs(x), x, 0, dir='+')] == [-1, 1] + + +def test_T14(): + x = symbols('x', real=True) + assert limit(atan(-log(x)), x, 0, dir='+') == pi/2 + + +def test_U1(): + x = symbols('x', real=True) + assert diff(abs(x), x) == sign(x) + + +def test_U2(): + f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0))) + assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0)) + + +def test_U3(): + f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1))) + f1 = Lambda(x, diff(f(x), x)) + assert f1(x) == 3*x**2 + assert f1(1) == 3 + + +@XFAIL +def test_U4(): + n = symbols('n', integer=True, positive=True) + x = symbols('x', real=True) + d = diff(x**n, x, n) + assert d.rewrite(factorial) == factorial(n) + + +def test_U5(): + # issue 6681 + t = symbols('t') + ans = ( + Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) + + Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2) + assert f(g(t)).diff(t, 2) == ans + assert ans.doit() == ans + + +def test_U6(): + h = Function('h') + T = integrate(f(y), (y, h(x), g(x))) + assert T.diff(x) == ( + f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x)) + + +@XFAIL +def test_U7(): + p, t = symbols('p t', real=True) + # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT + # raises ValueError: Since there is more than one variable in the + # expression, the variable(s) of differentiation must be supplied to + # differentiate f(p,t) + diff(f(p, t)) + + +def test_U8(): + x, y = symbols('x y', real=True) + eq = cos(x*y) + x + # If SymPy had implicit_diff() function this hack could be avoided + # TODO: Replace solve with solveset, current test fails for solveset + assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1) + + +def test_U9(): + # Wester sample case for Maple: + # O29 := diff(f(x, y), x) + diff(f(x, y), y); + # /d \ /d \ + # |-- f(x, y)| + |-- f(x, y)| + # \dx / \dy / + # + # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %)); + # 2 2 + # 2 D(g)(x + y ) (x + y) + x, y = symbols('x y', real=True) + su = diff(f(x, y), x) + diff(f(x, y), y) + s2 = su.subs(f(x, y), g(x**2 + y**2)) + s3 = s2.doit().factor() + # Subs not performed, s3 = 2*(x + y)*Subs(Derivative( + # g(_xi_1), _xi_1), _xi_1, x**2 + y**2) + # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy, + # and probably will remain that way. You can take derivatives with respect + # to other expressions only if they are atomic, like a symbol or a + # function. + # D operator should be added to SymPy + # See https://github.com/sympy/sympy/issues/4719. + assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2 + + +def test_U10(): + # see issue 2519: + assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4) + +@XFAIL +def test_U11(): + # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz + raise NotImplementedError + + +@XFAIL +def test_U12(): + # Wester sample case: + # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy) + # => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */ + # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy)); + # 4 + # (d41) (10 x y + 15 x + 8) dx dy dz + raise NotImplementedError( + "External diff of differential form not supported") + + +def test_U13(): + assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1 + + +@XFAIL +def test_U14(): + #f = 1/(x**2 + y**2 + 1) + #assert [minimize(f), maximize(f)] == [0,1] + raise NotImplementedError("minimize(), maximize() not supported") + + +@XFAIL +def test_U15(): + raise NotImplementedError("minimize() not supported and also solve does \ +not support multivariate inequalities") + + +@XFAIL +def test_U16(): + raise NotImplementedError("minimize() not supported in SymPy and also \ +solve does not support multivariate inequalities") + + +@XFAIL +def test_U17(): + raise NotImplementedError("Linear programming, symbolic simplex not \ +supported in SymPy") + + +def test_V1(): + x = symbols('x', real=True) + assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True)) + + +def test_V2(): + assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x + ) == Piecewise((-x**2/2, x < 0), (x**2/2, True)) + + +def test_V3(): + assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2) + + +def test_V4(): + assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2) + + +@XFAIL +def test_V5(): + # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1)) + assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() == + (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2))) + + +@XFAIL +def test_V6(): + # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m + assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*( + log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m)) + + +def test_V7(): + r1 = integrate(sinh(x)**4/cosh(x)**2) + assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2 + + +@XFAIL +def test_V8_V9(): +#Macsyma test case: +#(c27) /* This example involves several symbolic parameters +# => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/ +# [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2) +# [Gradshteyn and Ryzhik 2.553(3)] */ +#assume(b^2 > a^2)$ +#(c28) integrate(1/(a + b*cos(x)), x); +#(c29) trigsimp(ratsimp(diff(%, x))); +# 1 +#(d29) ------------ +# b cos(x) + a + raise NotImplementedError( + "Integrate with assumption not supported") + + +def test_V10(): + assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(4*tan(x/2) + 3)/4 + + +def test_V11(): + r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x) + r2 = factor(r1) + assert (logcombine(r2, force=True) == + log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3))) + + +def test_V12(): + r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x) + assert r1 == -1/(tan(x/2) + 2) + + +@XFAIL +def test_V13(): + r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x) + # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3 + # - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11 + assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11 + + +@slow +@XFAIL +def test_V14(): + r1 = integrate(log(abs(x**2 - y**2)), x) + # Piecewise result does not simplify to the desired result. + assert (r1.simplify() == x*log(abs(x**2 - y**2)) + + y*log(x + y) - y*log(x - y) - 2*x) + + +def test_V15(): + r1 = integrate(x*acot(x/y), x) + assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0 + + +@XFAIL +def test_V16(): + # Integral not calculated + assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10 + +@XFAIL +def test_V17(): + r1 = integrate((diff(f(x), x)*g(x) + - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x) + # integral not calculated + assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0 + + +@XFAIL +def test_W1(): + # The function has a pole at y. + # The integral has a Cauchy principal value of zero but SymPy returns -I*pi + # https://github.com/sympy/sympy/issues/7159 + assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0 + + +@XFAIL +def test_W2(): + # The function has a pole at y. + # The integral is divergent but SymPy returns -2 + # https://github.com/sympy/sympy/issues/7160 + # Test case in Macsyma: + # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1)); + # Integral is divergent + assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo + + +@XFAIL +@slow +def test_W3(): + # integral is not calculated + # https://github.com/sympy/sympy/issues/7161 + assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3) + + +@XFAIL +@slow +def test_W4(): + # integral is not calculated + assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3) + + +@XFAIL +@slow +def test_W5(): + # integral is not calculated + assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3) + + +@XFAIL +@slow +def test_W6(): + # integral is not calculated + assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2) + + +def test_W7(): + a = symbols('a', positive=True) + r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo)) + assert r1.simplify() == pi*exp(-a)/a + + +@XFAIL +def test_W8(): + # Test case in Mathematica: + # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity}, + # Assumptions -> 0 < a < 1] + # Out[19]= Pi Csc[a Pi] + raise NotImplementedError( + "Integrate with assumption 0 < a < 1 not supported") + + +@XFAIL +@slow +def test_W9(): + # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)] + # (principal value) [Levinson and Redheffer, p. 234] *) + r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo)) + r2 = r1.doit() + assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8)) + + +@XFAIL +def test_W10(): + # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) = + # 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1]) + # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */ + r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo)) + r2 = r1.doit() + assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5 + + +@XFAIL +def test_W11(): + # integral not calculated + assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) == + pi*(-1 + sqrt(2))) + + +def test_W12(): + p = symbols('p', positive=True) + q = symbols('q', real=True) + r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo)) + assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2) + + +@XFAIL +def test_W13(): + # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant) + r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1)) + assert r1 == 2*EulerGamma + + +def test_W14(): + assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0 + + +@XFAIL +def test_W15(): + # integral not calculated + assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12) + + +def test_W16(): + assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x), + (x, -1, 1)) == R(36, 35) + + +def test_W17(): + a, b = symbols('a b', positive=True) + assert integrate(exp(-a*x)*besselj(0, b*x), + (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1)) + + +def test_W18(): + assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi) + + +@XFAIL +def test_W19(): + # Integral not calculated + # Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)] + assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7 + + +@XFAIL +def test_W20(): + # integral not calculated + assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) == + -pi**2/36 - R(17, 108) + zeta(3)/4 + + (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9) + + +def test_W21(): + assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1))) + - 0.210882859565594) < 1e-15 + + +def test_W22(): + t, u = symbols('t u', real=True) + s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True))) + assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise( + (0, u < 0), + (-sin(Min(1, u)) + sin(Min(2, u)), True)) + + +@slow +def test_W23(): + a, b = symbols('a b', positive=True) + r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo)) + assert r1.collect(pi).cancel() == -pi*a + pi*b + + +def test_W23b(): + # like W23 but limits are reversed + a, b = symbols('a b', positive=True) + r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b)) + assert r2.collect(pi) == pi*(-a + b) + + +@XFAIL +@tooslow +def test_W24(): + # Not that slow, but does not fully evaluate so simplify is slow. + # Maybe also require doit() + x, y = symbols('x y', real=True) + r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1)) + assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0 + + +@XFAIL +@tooslow +def test_W25(): + a, x, y = symbols('a x y', real=True) + i1 = integrate( + sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2), + (x, 0, pi/2)) + i2 = integrate(i1, (y, 0, pi/2)) + assert (i2 - pi*a/2).simplify() == 0 + + +def test_W26(): + x, y = symbols('x y', real=True) + assert integrate(integrate(abs(y - x**2), (y, 0, 2)), + (x, -1, 1)) == R(46, 15) + + +def test_W27(): + a, b, c = symbols('a b c') + assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))), + (y, 0, b*(1 - x/a))), + (x, 0, a)) == a*b*c/6 + + +def test_X1(): + v, c = symbols('v c', real=True) + assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) == + 5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8)) + + +def test_X2(): + v, c = symbols('v c', real=True) + s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) + assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8) + + +def test_X3(): + s1 = (sin(x).series()/cos(x).series()).series() + s2 = tan(x).series() + assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6) + assert s1 == s2 + + +def test_X4(): + s1 = log(sin(x)/x).series() + assert s1 == -x**2/6 - x**4/180 + O(x**6) + assert log(series(sin(x)/x)).series() == s1 + + +@XFAIL +def test_X5(): + # test case in Mathematica syntax: + # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)] + # + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *) + # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}] + # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x] + # In[23]:= Series[%, {x, d, 1}] + # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) + + # 2 2 + # (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x] + h = Function('h') + a, b, c, d = symbols('a b c d', real=True) + # series() raises NotImplementedError: + # The _eval_nseries method should be added to to give terms up to O(x**n) at x=0 + series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)), + x, x0=d, n=2) + # assert missing, until exception is removed + + +def test_X6(): + # Taylor series of nonscalar objects (noncommutative multiplication) + # expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg] + a, b = symbols('a b', commutative=False, scalar=False) + assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) == + x**2*(-a*b/2 + b*a/2) + O(x**3)) + + +def test_X7(): + # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity ) + # = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6) + # [Levinson and Redheffer, p. 173] + assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) + + R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7)) + + +def test_X8(): + # Puiseux series (terms with fractional degree): + # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2)) + + # see issue 7167: + x = symbols('x', real=True) + assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == + 1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 + + (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2)))) + + +def test_X9(): + assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 + + x**3*log(x)**3/6 + O(x**4*log(x)**4)) + + +def test_X10(): + z, w = symbols('z w') + assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) == + log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) + + +def test_X11(): + z, w = symbols('z w') + assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) == + log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) + + +@XFAIL +def test_X12(): + # Look at the generalized Taylor series around x = 1 + # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)] + a, b, x = symbols('a b x', real=True) + # series returns O(log(x-1)**2) + # https://github.com/sympy/sympy/issues/7168 + assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) == + (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2))) + + +def test_X13(): + assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo)) + + +@XFAIL +def test_X14(): + # Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385] + assert series(1/2**(2*n)*binomial(2*n, n), + n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo)) + + +@SKIP("https://github.com/sympy/sympy/issues/7164") +def test_X15(): + # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544] + x, t = symbols('x t', real=True) + # raises RuntimeError: maximum recursion depth exceeded + # https://github.com/sympy/sympy/issues/7164 + # 2019-02-17: Raises + # PoleError: + # Asymptotic expansion of Ei around [-oo] is not implemented. + e1 = integrate(exp(-t)/t, (t, x, oo)) + assert (series(e1, x, x0=oo, n=5) == + 6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo))) + + +def test_X16(): + # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4) + assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 + + O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y)) + + +@XFAIL +def test_X17(): + # Power series (compute the general formula) + # (c41) powerseries(log(sin(x)/x), x, 0); + # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded. + # inf + # ==== i1 2 i1 2 i1 + # \ (- 1) 2 bern(2 i1) x + # (d41) > ------------------------------ + # / 2 i1 (2 i1)! + # ==== + # i1 = 1 + # fps does not calculate + assert fps(log(sin(x)/x)) == \ + Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo)) + + +@XFAIL +def test_X18(): + # Power series (compute the general formula). Maple FPS: + # > FormalPowerSeries(exp(-x)*sin(x), x = 0); + # infinity + # ----- (1/2 k) k + # \ 2 sin(3/4 k Pi) x + # ) ------------------------- + # / k! + # ----- + # + # Now, SymPy returns + # oo + # _____ + # \ ` + # \ / k k\ + # \ k |I*(-1 - I) I*(-1 + I) | + # \ x *|----------- - -----------| + # / \ 2 2 / + # / ------------------------------ + # / k! + # /____, + # k = 0 + k = Dummy('k') + assert fps(exp(-x)*sin(x)) == \ + Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo)) + + +@XFAIL +def test_X19(): + # (c45) /* Derive an explicit Taylor series solution of y as a function of + # x from the following implicit relation: + # y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 + + # 17/10 (x - 1)^5 + ... + # */ + # x = sin(y) + cos(y); + # Time= 0 msecs + # (d45) x = sin(y) + cos(y) + # + # (c46) taylor_revert(%, y, 7); + raise NotImplementedError("Solve using series not supported. \ +Inverse Taylor series expansion also not supported") + + +@XFAIL +def test_X20(): + # Pade (rational function) approximation => (2 - x)/(2 + x) + # > numapprox[pade](exp(-x), x = 0, [1, 1]); + # bytes used=9019816, alloc=3669344, time=13.12 + # 1 - 1/2 x + # --------- + # 1 + 1/2 x + # mpmath support numeric Pade approximant but there is + # no symbolic implementation in SymPy + # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant + raise NotImplementedError("Symbolic Pade approximant not supported") + + +def test_X21(): + """ + Test whether `fourier_series` of x periodical on the [-p, p] interval equals + `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`. + """ + p = symbols('p', positive=True) + n = symbols('n', positive=True, integer=True) + s = fourier_series(x, (x, -p, p)) + + # All cosine coefficients are equal to 0 + assert s.an.formula == 0 + + # Check for sine coefficients + assert s.bn.formula.subs(s.bn.variables[0], 0) == 0 + assert s.bn.formula.subs(s.bn.variables[0], n) == \ + -2*p/pi * (-1)**n / n * sin(n*pi*x/p) + + +@XFAIL +def test_X22(): + # (c52) /* => p / 2 + # - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2, + # n = 1..infinity ) */ + # fourier_series(abs(x), x, p); + # p + # (e52) a = - + # 0 2 + # + # %nn + # (2 (- 1) - 2) p + # (e53) a = ------------------ + # %nn 2 2 + # %pi %nn + # + # (e54) b = 0 + # %nn + # + # Time= 5290 msecs + # inf %nn %pi %nn x + # ==== (2 (- 1) - 2) cos(---------) + # \ p + # p > ------------------------------- + # / 2 + # ==== %nn + # %nn = 1 p + # (d54) ----------------------------------------- + - + # 2 2 + # %pi + raise NotImplementedError("Fourier series not supported") + + +def test_Y1(): + t = symbols('t', positive=True) + w = symbols('w', real=True) + s = symbols('s') + F, _, _ = laplace_transform(cos((w - 1)*t), t, s) + assert F == s/(s**2 + (w - 1)**2) + + +def test_Y2(): + t = symbols('t', positive=True) + w = symbols('w', real=True) + s = symbols('s') + f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t, simplify=True) + assert f == cos(t*(w - 1)) + + +def test_Y3(): + t = symbols('t', positive=True) + w = symbols('w', real=True) + s = symbols('s') + F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s, simplify=True) + assert F == w/(s**2 - 4*w**2) + + +def test_Y4(): + t = symbols('t', positive=True) + s = symbols('s') + F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s, simplify=True) + assert F == 1/s - exp(-6*sqrt(s))/s + + +def test_Y5_Y6(): +# Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the +# Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and +# duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T. +# Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing +# Company, 1983, p. 211. First, take the Laplace transform of the ODE +# => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)] +# where Y(s) is the Laplace transform of y(t) + t = symbols('t', real=True) + s = symbols('s') + y = Function('y') + Y = Function('Y') + F = laplace_correspondence(laplace_transform(diff(y(t), t, 2) + y(t) + - 4*(Heaviside(t - 1) - Heaviside(t - 2)), + t, s, noconds=True), {y: Y}) + D = ( + -F + s**2*Y(s) - s*y(0) + Y(s) - Subs(Derivative(y(t), t), t, 0) - + 4*exp(-s)/s + 4*exp(-2*s)/s) + assert D == 0 +# Now, solve for Y(s) and then take the inverse Laplace transform +# => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)] +# => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)} + Yf = solve(F, Y(s))[0] + Yf = laplace_initial_conds(Yf, t, {y: [1, 0]}) + assert Yf == (s**2*exp(2*s) + 4*exp(s) - 4)*exp(-2*s)/(s*(s**2 + 1)) + yf = inverse_laplace_transform(Yf, s, t) + yf = yf.collect(Heaviside(t-1)).collect(Heaviside(t-2)) + assert yf == ( + (4 - 4*cos(t - 1))*Heaviside(t - 1) + + (4*cos(t - 2) - 4)*Heaviside(t - 2) + + cos(t)*Heaviside(t)) + + +@XFAIL +def test_Y7(): + # What is the Laplace transform of an infinite square wave? + # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity ) + # [Sanchez, Allen and Kyner, p. 213] + t = symbols('t', positive=True) + a = symbols('a', real=True) + s = symbols('s') + F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a), + (n, 1, oo)), t, s) + # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t), + # (n, 1, oo)), t, s) + 1/s + # https://github.com/sympy/sympy/issues/7177 + assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s + + +@XFAIL +def test_Y8(): + assert fourier_transform(1, x, z) == DiracDelta(z) + + +def test_Y9(): + assert (fourier_transform(exp(-9*x**2), x, z) == + sqrt(pi)*exp(-pi**2*z**2/9)/3) + + +def test_Y10(): + assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() == + (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81)) + + +@SKIP("https://github.com/sympy/sympy/issues/7181") +@slow +def test_Y11(): + # => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)] + x, s = symbols('x s') + # raises RuntimeError: maximum recursion depth exceeded + # https://github.com/sympy/sympy/issues/7181 + # Update 2019-02-17 raises: + # TypeError: cannot unpack non-iterable MellinTransform object + F, _, _ = mellin_transform(1/(1 - x), x, s) + assert F == pi*cot(pi*s) + + +@XFAIL +def test_Y12(): + # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1) + # [Gradshteyn and Ryzhik 17.43(16)] + x, s = symbols('x s') + # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1) + # https://github.com/sympy/sympy/issues/7182 + F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s) + assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4) + + +@XFAIL +def test_Y13(): +# Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z + raise NotImplementedError("z-transform not supported") + + +@XFAIL +def test_Y14(): +# Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) + raise NotImplementedError("z-transform not supported") + + +def test_Z1(): + r = Function('r') + assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n), + {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1) + + +def test_Z2(): + r = Function('r') + assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1}) + == -2**n + 3**n) + + +def test_Z3(): + # => r(n) = Fibonacci[n + 1] [Cohen, p. 83] + r = Function('r') + # recurrence solution is correct, Wester expects it to be simplified to + # fibonacci(n+1), but that is quite hard + expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10) + + (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2)) + sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2}) + assert sol == expected + + +@XFAIL +def test_Z4(): +# => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)] +# [Joan Z. Yu and Robert Israel in sci.math.symbolic] + r = Function('r') + c = symbols('c') + # raises ValueError: Polynomial or rational function expected, + # got '(c**2 - c**n)/(c - c**n) + s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1) + - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1), + r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)}) + assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) + + (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0) + + +@XFAIL +def test_Z5(): + # Second order ODE with initial conditions---solve directly + # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 + C1, C2 = symbols('C1 C2') + # initial conditions not supported, this is a manual workaround + # https://github.com/sympy/sympy/issues/4720 + eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x) + sol = dsolve(eq, f(x)) + f0 = Lambda(x, sol.rhs) + assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x) + f1 = Lambda(x, diff(f0(x), x)) + # TODO: Replace solve with solveset, when it works for solveset + const_dict = solve((f0(0), f1(0))) + result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2]) + assert result == -x*cos(2*x)/4 + sin(2*x)/8 + # Result is OK, but ODE solving with initial conditions should be + # supported without all this manual work + raise NotImplementedError('ODE solving with initial conditions \ +not supported') + + +@XFAIL +def test_Z6(): + # Second order ODE with initial conditions---solve using Laplace + # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 + t = symbols('t', positive=True) + s = symbols('s') + eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t) + F, _, _ = laplace_transform(eq, t, s) + # Laplace transform for diff() not calculated + # https://github.com/sympy/sympy/issues/7176 + assert (F == s**2*LaplaceTransform(f(t), t, s) + + 4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4)) + # rest of test case not implemented diff --git a/falcon/lib/python3.10/site-packages/accelerate/__pycache__/accelerator.cpython-310.pyc b/falcon/lib/python3.10/site-packages/accelerate/__pycache__/accelerator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a6c12d6f9acc0815527f1be19698785992ed637 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/accelerate/__pycache__/accelerator.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dad53c48ca90c25740a9ae0aab6f20262e0886b5943db6cdeafcd77c71933a55 +size 116429 diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/__init__.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba72d341c3898d71fd155ec6772fd318d8d3494 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/__init__.py @@ -0,0 +1,54 @@ +""" +The :mod:`sklearn.cluster` module gathers popular unsupervised clustering +algorithms. +""" + +from ._spectral import spectral_clustering, SpectralClustering +from ._mean_shift import mean_shift, MeanShift, estimate_bandwidth, get_bin_seeds +from ._affinity_propagation import affinity_propagation, AffinityPropagation +from ._agglomerative import ( + ward_tree, + AgglomerativeClustering, + linkage_tree, + FeatureAgglomeration, +) +from ._kmeans import k_means, KMeans, MiniBatchKMeans, kmeans_plusplus +from ._bisect_k_means import BisectingKMeans +from ._dbscan import dbscan, DBSCAN +from ._optics import ( + OPTICS, + cluster_optics_dbscan, + compute_optics_graph, + cluster_optics_xi, +) +from ._bicluster import SpectralBiclustering, SpectralCoclustering +from ._birch import Birch + +__all__ = [ + "AffinityPropagation", + "AgglomerativeClustering", + "Birch", + "DBSCAN", + "OPTICS", + "cluster_optics_dbscan", + "cluster_optics_xi", + "compute_optics_graph", + "KMeans", + "BisectingKMeans", + "FeatureAgglomeration", + "MeanShift", + "MiniBatchKMeans", + "SpectralClustering", + "affinity_propagation", + "dbscan", + "estimate_bandwidth", + "get_bin_seeds", + "k_means", + "kmeans_plusplus", + "linkage_tree", + "mean_shift", + "spectral_clustering", + "ward_tree", + "SpectralBiclustering", + "SpectralCoclustering", +] diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/__pycache__/_dbscan.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/__pycache__/_dbscan.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95dad95cd931dcec2b1c1860ab0efb43156cd5b0 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/__pycache__/_dbscan.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_affinity_propagation.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_affinity_propagation.py new file mode 100644 index 0000000000000000000000000000000000000000..180e37996aa07e7da972ada4798abc905c33b9a2 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_affinity_propagation.py @@ -0,0 +1,582 @@ +"""Affinity Propagation clustering algorithm.""" + +# Author: Alexandre Gramfort alexandre.gramfort@inria.fr +# Gael Varoquaux gael.varoquaux@normalesup.org + +# License: BSD 3 clause + +from numbers import Integral, Real +import warnings + +import numpy as np + +from ..exceptions import ConvergenceWarning +from ..base import BaseEstimator, ClusterMixin +from ..utils import as_float_array, check_random_state +from ..utils._param_validation import Interval, StrOptions +from ..utils.validation import check_is_fitted +from ..metrics import euclidean_distances +from ..metrics import pairwise_distances_argmin +from .._config import config_context + + +def _equal_similarities_and_preferences(S, preference): + def all_equal_preferences(): + return np.all(preference == preference.flat[0]) + + def all_equal_similarities(): + # Create mask to ignore diagonal of S + mask = np.ones(S.shape, dtype=bool) + np.fill_diagonal(mask, 0) + + return np.all(S[mask].flat == S[mask].flat[0]) + + return all_equal_preferences() and all_equal_similarities() + + +def _affinity_propagation( + S, + *, + preference, + convergence_iter, + max_iter, + damping, + verbose, + return_n_iter, + random_state, +): + """Main affinity propagation algorithm.""" + n_samples = S.shape[0] + if n_samples == 1 or _equal_similarities_and_preferences(S, preference): + # It makes no sense to run the algorithm in this case, so return 1 or + # n_samples clusters, depending on preferences + warnings.warn( + "All samples have mutually equal similarities. " + "Returning arbitrary cluster center(s)." + ) + if preference.flat[0] >= S.flat[n_samples - 1]: + return ( + (np.arange(n_samples), np.arange(n_samples), 0) + if return_n_iter + else (np.arange(n_samples), np.arange(n_samples)) + ) + else: + return ( + (np.array([0]), np.array([0] * n_samples), 0) + if return_n_iter + else (np.array([0]), np.array([0] * n_samples)) + ) + + # Place preference on the diagonal of S + S.flat[:: (n_samples + 1)] = preference + + A = np.zeros((n_samples, n_samples)) + R = np.zeros((n_samples, n_samples)) # Initialize messages + # Intermediate results + tmp = np.zeros((n_samples, n_samples)) + + # Remove degeneracies + S += ( + np.finfo(S.dtype).eps * S + np.finfo(S.dtype).tiny * 100 + ) * random_state.standard_normal(size=(n_samples, n_samples)) + + # Execute parallel affinity propagation updates + e = np.zeros((n_samples, convergence_iter)) + + ind = np.arange(n_samples) + + for it in range(max_iter): + # tmp = A + S; compute responsibilities + np.add(A, S, tmp) + I = np.argmax(tmp, axis=1) + Y = tmp[ind, I] # np.max(A + S, axis=1) + tmp[ind, I] = -np.inf + Y2 = np.max(tmp, axis=1) + + # tmp = Rnew + np.subtract(S, Y[:, None], tmp) + tmp[ind, I] = S[ind, I] - Y2 + + # Damping + tmp *= 1 - damping + R *= damping + R += tmp + + # tmp = Rp; compute availabilities + np.maximum(R, 0, tmp) + tmp.flat[:: n_samples + 1] = R.flat[:: n_samples + 1] + + # tmp = -Anew + tmp -= np.sum(tmp, axis=0) + dA = np.diag(tmp).copy() + tmp.clip(0, np.inf, tmp) + tmp.flat[:: n_samples + 1] = dA + + # Damping + tmp *= 1 - damping + A *= damping + A -= tmp + + # Check for convergence + E = (np.diag(A) + np.diag(R)) > 0 + e[:, it % convergence_iter] = E + K = np.sum(E, axis=0) + + if it >= convergence_iter: + se = np.sum(e, axis=1) + unconverged = np.sum((se == convergence_iter) + (se == 0)) != n_samples + if (not unconverged and (K > 0)) or (it == max_iter): + never_converged = False + if verbose: + print("Converged after %d iterations." % it) + break + else: + never_converged = True + if verbose: + print("Did not converge") + + I = np.flatnonzero(E) + K = I.size # Identify exemplars + + if K > 0: + if never_converged: + warnings.warn( + "Affinity propagation did not converge, this model " + "may return degenerate cluster centers and labels.", + ConvergenceWarning, + ) + c = np.argmax(S[:, I], axis=1) + c[I] = np.arange(K) # Identify clusters + # Refine the final set of exemplars and clusters and return results + for k in range(K): + ii = np.where(c == k)[0] + j = np.argmax(np.sum(S[ii[:, np.newaxis], ii], axis=0)) + I[k] = ii[j] + + c = np.argmax(S[:, I], axis=1) + c[I] = np.arange(K) + labels = I[c] + # Reduce labels to a sorted, gapless, list + cluster_centers_indices = np.unique(labels) + labels = np.searchsorted(cluster_centers_indices, labels) + else: + warnings.warn( + "Affinity propagation did not converge and this model " + "will not have any cluster centers.", + ConvergenceWarning, + ) + labels = np.array([-1] * n_samples) + cluster_centers_indices = [] + + if return_n_iter: + return cluster_centers_indices, labels, it + 1 + else: + return cluster_centers_indices, labels + + +############################################################################### +# Public API + + +def affinity_propagation( + S, + *, + preference=None, + convergence_iter=15, + max_iter=200, + damping=0.5, + copy=True, + verbose=False, + return_n_iter=False, + random_state=None, +): + """Perform Affinity Propagation Clustering of data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + S : array-like of shape (n_samples, n_samples) + Matrix of similarities between points. + + preference : array-like of shape (n_samples,) or float, default=None + Preferences for each point - points with larger values of + preferences are more likely to be chosen as exemplars. The number of + exemplars, i.e. of clusters, is influenced by the input preferences + value. If the preferences are not passed as arguments, they will be + set to the median of the input similarities (resulting in a moderate + number of clusters). For a smaller amount of clusters, this can be set + to the minimum value of the similarities. + + convergence_iter : int, default=15 + Number of iterations with no change in the number + of estimated clusters that stops the convergence. + + max_iter : int, default=200 + Maximum number of iterations. + + damping : float, default=0.5 + Damping factor between 0.5 and 1. + + copy : bool, default=True + If copy is False, the affinity matrix is modified inplace by the + algorithm, for memory efficiency. + + verbose : bool, default=False + The verbosity level. + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the starting state. + Use an int for reproducible results across function calls. + See the :term:`Glossary `. + + .. versionadded:: 0.23 + this parameter was previously hardcoded as 0. + + Returns + ------- + cluster_centers_indices : ndarray of shape (n_clusters,) + Index of clusters centers. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. + + n_iter : int + Number of iterations run. Returned only if `return_n_iter` is + set to True. + + Notes + ----- + For an example, see :ref:`examples/cluster/plot_affinity_propagation.py + `. + + When the algorithm does not converge, it will still return a arrays of + ``cluster_center_indices`` and labels if there are any exemplars/clusters, + however they may be degenerate and should be used with caution. + + When all training samples have equal similarities and equal preferences, + the assignment of cluster centers and labels depends on the preference. + If the preference is smaller than the similarities, a single cluster center + and label ``0`` for every sample will be returned. Otherwise, every + training sample becomes its own cluster center and is assigned a unique + label. + + References + ---------- + Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages + Between Data Points", Science Feb. 2007 + """ + S = as_float_array(S, copy=copy) + + estimator = AffinityPropagation( + damping=damping, + max_iter=max_iter, + convergence_iter=convergence_iter, + copy=False, + preference=preference, + affinity="precomputed", + verbose=verbose, + random_state=random_state, + ).fit(S) + + if return_n_iter: + return estimator.cluster_centers_indices_, estimator.labels_, estimator.n_iter_ + return estimator.cluster_centers_indices_, estimator.labels_ + + +class AffinityPropagation(ClusterMixin, BaseEstimator): + """Perform Affinity Propagation Clustering of data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + damping : float, default=0.5 + Damping factor in the range `[0.5, 1.0)` is the extent to + which the current value is maintained relative to + incoming values (weighted 1 - damping). This in order + to avoid numerical oscillations when updating these + values (messages). + + max_iter : int, default=200 + Maximum number of iterations. + + convergence_iter : int, default=15 + Number of iterations with no change in the number + of estimated clusters that stops the convergence. + + copy : bool, default=True + Make a copy of input data. + + preference : array-like of shape (n_samples,) or float, default=None + Preferences for each point - points with larger values of + preferences are more likely to be chosen as exemplars. The number + of exemplars, ie of clusters, is influenced by the input + preferences value. If the preferences are not passed as arguments, + they will be set to the median of the input similarities. + + affinity : {'euclidean', 'precomputed'}, default='euclidean' + Which affinity to use. At the moment 'precomputed' and + ``euclidean`` are supported. 'euclidean' uses the + negative squared euclidean distance between points. + + verbose : bool, default=False + Whether to be verbose. + + random_state : int, RandomState instance or None, default=None + Pseudo-random number generator to control the starting state. + Use an int for reproducible results across function calls. + See the :term:`Glossary `. + + .. versionadded:: 0.23 + this parameter was previously hardcoded as 0. + + Attributes + ---------- + cluster_centers_indices_ : ndarray of shape (n_clusters,) + Indices of cluster centers. + + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Cluster centers (if affinity != ``precomputed``). + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + affinity_matrix_ : ndarray of shape (n_samples, n_samples) + Stores the affinity matrix used in ``fit``. + + n_iter_ : int + Number of iterations taken to converge. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + AgglomerativeClustering : Recursively merges the pair of + clusters that minimally increases a given linkage distance. + FeatureAgglomeration : Similar to AgglomerativeClustering, + but recursively merges features instead of samples. + KMeans : K-Means clustering. + MiniBatchKMeans : Mini-Batch K-Means clustering. + MeanShift : Mean shift clustering using a flat kernel. + SpectralClustering : Apply clustering to a projection + of the normalized Laplacian. + + Notes + ----- + For an example, see :ref:`examples/cluster/plot_affinity_propagation.py + `. + + The algorithmic complexity of affinity propagation is quadratic + in the number of points. + + When the algorithm does not converge, it will still return a arrays of + ``cluster_center_indices`` and labels if there are any exemplars/clusters, + however they may be degenerate and should be used with caution. + + When ``fit`` does not converge, ``cluster_centers_`` is still populated + however it may be degenerate. In such a case, proceed with caution. + If ``fit`` does not converge and fails to produce any ``cluster_centers_`` + then ``predict`` will label every sample as ``-1``. + + When all training samples have equal similarities and equal preferences, + the assignment of cluster centers and labels depends on the preference. + If the preference is smaller than the similarities, ``fit`` will result in + a single cluster center and label ``0`` for every sample. Otherwise, every + training sample becomes its own cluster center and is assigned a unique + label. + + References + ---------- + + Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages + Between Data Points", Science Feb. 2007 + + Examples + -------- + >>> from sklearn.cluster import AffinityPropagation + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> clustering = AffinityPropagation(random_state=5).fit(X) + >>> clustering + AffinityPropagation(random_state=5) + >>> clustering.labels_ + array([0, 0, 0, 1, 1, 1]) + >>> clustering.predict([[0, 0], [4, 4]]) + array([0, 1]) + >>> clustering.cluster_centers_ + array([[1, 2], + [4, 2]]) + """ + + _parameter_constraints: dict = { + "damping": [Interval(Real, 0.5, 1.0, closed="left")], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "convergence_iter": [Interval(Integral, 1, None, closed="left")], + "copy": ["boolean"], + "preference": [ + "array-like", + Interval(Real, None, None, closed="neither"), + None, + ], + "affinity": [StrOptions({"euclidean", "precomputed"})], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + *, + damping=0.5, + max_iter=200, + convergence_iter=15, + copy=True, + preference=None, + affinity="euclidean", + verbose=False, + random_state=None, + ): + + self.damping = damping + self.max_iter = max_iter + self.convergence_iter = convergence_iter + self.copy = copy + self.verbose = verbose + self.preference = preference + self.affinity = affinity + self.random_state = random_state + + def _more_tags(self): + return {"pairwise": self.affinity == "precomputed"} + + def fit(self, X, y=None): + """Fit the clustering from features, or affinity matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + array-like of shape (n_samples, n_samples) + Training instances to cluster, or similarities / affinities between + instances if ``affinity='precomputed'``. If a sparse feature matrix + is provided, it will be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self + Returns the instance itself. + """ + self._validate_params() + + if self.affinity == "precomputed": + accept_sparse = False + else: + accept_sparse = "csr" + X = self._validate_data(X, accept_sparse=accept_sparse) + if self.affinity == "precomputed": + self.affinity_matrix_ = X.copy() if self.copy else X + else: # self.affinity == "euclidean" + self.affinity_matrix_ = -euclidean_distances(X, squared=True) + + if self.affinity_matrix_.shape[0] != self.affinity_matrix_.shape[1]: + raise ValueError( + "The matrix of similarities must be a square array. " + f"Got {self.affinity_matrix_.shape} instead." + ) + + if self.preference is None: + preference = np.median(self.affinity_matrix_) + else: + preference = self.preference + preference = np.array(preference, copy=False) + + random_state = check_random_state(self.random_state) + + ( + self.cluster_centers_indices_, + self.labels_, + self.n_iter_, + ) = _affinity_propagation( + self.affinity_matrix_, + max_iter=self.max_iter, + convergence_iter=self.convergence_iter, + preference=preference, + damping=self.damping, + verbose=self.verbose, + return_n_iter=True, + random_state=random_state, + ) + + if self.affinity != "precomputed": + self.cluster_centers_ = X[self.cluster_centers_indices_].copy() + + return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to predict. If a sparse matrix is provided, it will be + converted into a sparse ``csr_matrix``. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + check_is_fitted(self) + X = self._validate_data(X, reset=False, accept_sparse="csr") + if not hasattr(self, "cluster_centers_"): + raise ValueError( + "Predict method is not supported when affinity='precomputed'." + ) + + if self.cluster_centers_.shape[0] > 0: + with config_context(assume_finite=True): + return pairwise_distances_argmin(X, self.cluster_centers_) + else: + warnings.warn( + "This model does not have any cluster centers " + "because affinity propagation did not converge. " + "Labeling every sample as '-1'.", + ConvergenceWarning, + ) + return np.array([-1] * X.shape[0]) + + def fit_predict(self, X, y=None): + """Fit clustering from features/affinity matrix; return cluster labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + array-like of shape (n_samples, n_samples) + Training instances to cluster, or similarities / affinities between + instances if ``affinity='precomputed'``. If a sparse feature matrix + is provided, it will be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py new file mode 100644 index 0000000000000000000000000000000000000000..ec54a915cc17a0cdfbdbd9fc71de8759624b4094 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py @@ -0,0 +1,1333 @@ +"""Hierarchical Agglomerative Clustering + +These routines perform some hierarchical agglomerative clustering of some +input data. + +Authors : Vincent Michel, Bertrand Thirion, Alexandre Gramfort, + Gael Varoquaux +License: BSD 3 clause +""" +import warnings +from heapq import heapify, heappop, heappush, heappushpop +from numbers import Integral, Real + +import numpy as np +from scipy import sparse +from scipy.sparse.csgraph import connected_components + +from ..base import BaseEstimator, ClusterMixin, ClassNamePrefixFeaturesOutMixin +from ..metrics.pairwise import paired_distances +from ..metrics.pairwise import _VALID_METRICS +from ..metrics import DistanceMetric +from ..metrics._dist_metrics import METRIC_MAPPING +from ..utils import check_array +from ..utils._fast_dict import IntFloatDict +from ..utils.graph import _fix_connected_components +from ..utils._param_validation import Hidden, Interval, StrOptions, HasMethods +from ..utils.validation import check_memory + +# mypy error: Module 'sklearn.cluster' has no attribute '_hierarchical_fast' +from . import _hierarchical_fast as _hierarchical # type: ignore +from ._feature_agglomeration import AgglomerationTransform + +############################################################################### +# For non fully-connected graphs + + +def _fix_connectivity(X, connectivity, affinity): + """ + Fixes the connectivity matrix. + + The different steps are: + + - copies it + - makes it symmetric + - converts it to LIL if necessary + - completes it if necessary. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is `None`, i.e, the Ward algorithm is unstructured. + + affinity : {"euclidean", "precomputed"}, default="euclidean" + Which affinity to use. At the moment `precomputed` and + ``euclidean`` are supported. `euclidean` uses the + negative squared Euclidean distance between points. + + Returns + ------- + connectivity : sparse matrix + The fixed connectivity matrix. + + n_connected_components : int + The number of connected components in the graph. + """ + n_samples = X.shape[0] + if connectivity.shape[0] != n_samples or connectivity.shape[1] != n_samples: + raise ValueError( + "Wrong shape for connectivity matrix: %s when X is %s" + % (connectivity.shape, X.shape) + ) + + # Make the connectivity matrix symmetric: + connectivity = connectivity + connectivity.T + + # Convert connectivity matrix to LIL + if not sparse.isspmatrix_lil(connectivity): + if not sparse.isspmatrix(connectivity): + connectivity = sparse.lil_matrix(connectivity) + else: + connectivity = connectivity.tolil() + + # Compute the number of nodes + n_connected_components, labels = connected_components(connectivity) + + if n_connected_components > 1: + warnings.warn( + "the number of connected components of the " + "connectivity matrix is %d > 1. Completing it to avoid " + "stopping the tree early." % n_connected_components, + stacklevel=2, + ) + # XXX: Can we do without completing the matrix? + connectivity = _fix_connected_components( + X=X, + graph=connectivity, + n_connected_components=n_connected_components, + component_labels=labels, + metric=affinity, + mode="connectivity", + ) + + return connectivity, n_connected_components + + +def _single_linkage_tree( + connectivity, + n_samples, + n_nodes, + n_clusters, + n_connected_components, + return_distance, +): + """ + Perform single linkage clustering on sparse data via the minimum + spanning tree from scipy.sparse.csgraph, then using union-find to label. + The parent array is then generated by walking through the tree. + """ + from scipy.sparse.csgraph import minimum_spanning_tree + + # explicitly cast connectivity to ensure safety + connectivity = connectivity.astype(np.float64, copy=False) + + # Ensure zero distances aren't ignored by setting them to "epsilon" + epsilon_value = np.finfo(dtype=connectivity.data.dtype).eps + connectivity.data[connectivity.data == 0] = epsilon_value + + # Use scipy.sparse.csgraph to generate a minimum spanning tree + mst = minimum_spanning_tree(connectivity.tocsr()) + + # Convert the graph to scipy.cluster.hierarchy array format + mst = mst.tocoo() + + # Undo the epsilon values + mst.data[mst.data == epsilon_value] = 0 + + mst_array = np.vstack([mst.row, mst.col, mst.data]).T + + # Sort edges of the min_spanning_tree by weight + mst_array = mst_array[np.argsort(mst_array.T[2], kind="mergesort"), :] + + # Convert edge list into standard hierarchical clustering format + single_linkage_tree = _hierarchical._single_linkage_label(mst_array) + children_ = single_linkage_tree[:, :2].astype(int) + + # Compute parents + parent = np.arange(n_nodes, dtype=np.intp) + for i, (left, right) in enumerate(children_, n_samples): + if n_clusters is not None and i >= n_nodes: + break + if left < n_nodes: + parent[left] = i + if right < n_nodes: + parent[right] = i + + if return_distance: + distances = single_linkage_tree[:, 2] + return children_, n_connected_components, n_samples, parent, distances + return children_, n_connected_components, n_samples, parent + + +############################################################################### +# Hierarchical tree building functions + + +def ward_tree(X, *, connectivity=None, n_clusters=None, return_distance=False): + """Ward clustering based on a Feature matrix. + + Recursively merges the pair of clusters that minimally increases + within-cluster variance. + + The inertia matrix uses a Heapq-based representation. + + This is the structured version, that takes into account some topological + structure between samples. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is None, i.e, the Ward algorithm is unstructured. + + n_clusters : int, default=None + `n_clusters` should be less than `n_samples`. Stop early the + construction of the tree at `n_clusters.` This is useful to decrease + computation time if the number of clusters is not small compared to the + number of samples. In this case, the complete tree is not computed, thus + the 'children' output is of limited use, and the 'parents' output should + rather be used. This option is valid only when specifying a connectivity + matrix. + + return_distance : bool, default=False + If `True`, return the distance between the clusters. + + Returns + ------- + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_connected_components : int + The number of connected components in the graph. + + n_leaves : int + The number of leaves in the tree. + + parents : ndarray of shape (n_nodes,) or None + The parent of each node. Only returned when a connectivity matrix + is specified, elsewhere 'None' is returned. + + distances : ndarray of shape (n_nodes-1,) + Only returned if `return_distance` is set to `True` (for compatibility). + The distances between the centers of the nodes. `distances[i]` + corresponds to a weighted Euclidean distance between + the nodes `children[i, 1]` and `children[i, 2]`. If the nodes refer to + leaves of the tree, then `distances[i]` is their unweighted Euclidean + distance. Distances are updated in the following way + (from scipy.hierarchy.linkage): + + The new entry :math:`d(u,v)` is computed as follows, + + .. math:: + + d(u,v) = \\sqrt{\\frac{|v|+|s|} + {T}d(v,s)^2 + + \\frac{|v|+|t|} + {T}d(v,t)^2 + - \\frac{|v|} + {T}d(s,t)^2} + + where :math:`u` is the newly joined cluster consisting of + clusters :math:`s` and :math:`t`, :math:`v` is an unused + cluster in the forest, :math:`T=|v|+|s|+|t|`, and + :math:`|*|` is the cardinality of its argument. This is also + known as the incremental algorithm. + """ + X = np.asarray(X) + if X.ndim == 1: + X = np.reshape(X, (-1, 1)) + n_samples, n_features = X.shape + + if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + + if n_clusters is not None: + warnings.warn( + "Partial build of the tree is implemented " + "only for structured clustering (i.e. with " + "explicit connectivity). The algorithm " + "will build the full tree and only " + "retain the lower branches required " + "for the specified number of clusters", + stacklevel=2, + ) + X = np.require(X, requirements="W") + out = hierarchy.ward(X) + children_ = out[:, :2].astype(np.intp) + + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + else: + return children_, 1, n_samples, None + + connectivity, n_connected_components = _fix_connectivity( + X, connectivity, affinity="euclidean" + ) + if n_clusters is None: + n_nodes = 2 * n_samples - 1 + else: + if n_clusters > n_samples: + raise ValueError( + "Cannot provide more clusters than samples. " + "%i n_clusters was asked, and there are %i " + "samples." % (n_clusters, n_samples) + ) + n_nodes = 2 * n_samples - n_clusters + + # create inertia matrix + coord_row = [] + coord_col = [] + A = [] + for ind, row in enumerate(connectivity.rows): + A.append(row) + # We keep only the upper triangular for the moments + # Generator expressions are faster than arrays on the following + row = [i for i in row if i < ind] + coord_row.extend( + len(row) + * [ + ind, + ] + ) + coord_col.extend(row) + + coord_row = np.array(coord_row, dtype=np.intp, order="C") + coord_col = np.array(coord_col, dtype=np.intp, order="C") + + # build moments as a list + moments_1 = np.zeros(n_nodes, order="C") + moments_1[:n_samples] = 1 + moments_2 = np.zeros((n_nodes, n_features), order="C") + moments_2[:n_samples] = X + inertia = np.empty(len(coord_row), dtype=np.float64, order="C") + _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, inertia) + inertia = list(zip(inertia, coord_row, coord_col)) + heapify(inertia) + + # prepare the main fields + parent = np.arange(n_nodes, dtype=np.intp) + used_node = np.ones(n_nodes, dtype=bool) + children = [] + if return_distance: + distances = np.empty(n_nodes - n_samples) + + not_visited = np.empty(n_nodes, dtype=np.int8, order="C") + + # recursive merge loop + for k in range(n_samples, n_nodes): + # identify the merge + while True: + inert, i, j = heappop(inertia) + if used_node[i] and used_node[j]: + break + parent[i], parent[j] = k, k + children.append((i, j)) + used_node[i] = used_node[j] = False + if return_distance: # store inertia value + distances[k - n_samples] = inert + + # update the moments + moments_1[k] = moments_1[i] + moments_1[j] + moments_2[k] = moments_2[i] + moments_2[j] + + # update the structure matrix A and the inertia matrix + coord_col = [] + not_visited.fill(1) + not_visited[k] = 0 + _hierarchical._get_parents(A[i], coord_col, parent, not_visited) + _hierarchical._get_parents(A[j], coord_col, parent, not_visited) + # List comprehension is faster than a for loop + [A[col].append(k) for col in coord_col] + A.append(coord_col) + coord_col = np.array(coord_col, dtype=np.intp, order="C") + coord_row = np.empty(coord_col.shape, dtype=np.intp, order="C") + coord_row.fill(k) + n_additions = len(coord_row) + ini = np.empty(n_additions, dtype=np.float64, order="C") + + _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, ini) + + # List comprehension is faster than a for loop + [heappush(inertia, (ini[idx], k, coord_col[idx])) for idx in range(n_additions)] + + # Separate leaves in children (empty lists up to now) + n_leaves = n_samples + # sort children to get consistent output with unstructured version + children = [c[::-1] for c in children] + children = np.array(children) # return numpy array for efficient caching + + if return_distance: + # 2 is scaling factor to compare w/ unstructured version + distances = np.sqrt(2.0 * distances) + return children, n_connected_components, n_leaves, parent, distances + else: + return children, n_connected_components, n_leaves, parent + + +# single average and complete linkage +def linkage_tree( + X, + connectivity=None, + n_clusters=None, + linkage="complete", + affinity="euclidean", + return_distance=False, +): + """Linkage agglomerative clustering based on a Feature matrix. + + The inertia matrix uses a Heapq-based representation. + + This is the structured version, that takes into account some topological + structure between samples. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is `None`, i.e, the Ward algorithm is unstructured. + + n_clusters : int, default=None + Stop early the construction of the tree at `n_clusters`. This is + useful to decrease computation time if the number of clusters is + not small compared to the number of samples. In this case, the + complete tree is not computed, thus the 'children' output is of + limited use, and the 'parents' output should rather be used. + This option is valid only when specifying a connectivity matrix. + + linkage : {"average", "complete", "single"}, default="complete" + Which linkage criteria to use. The linkage criterion determines which + distance to use between sets of observation. + - "average" uses the average of the distances of each observation of + the two sets. + - "complete" or maximum linkage uses the maximum distances between + all observations of the two sets. + - "single" uses the minimum of the distances between all + observations of the two sets. + + affinity : str or callable, default='euclidean' + Which metric to use. Can be 'euclidean', 'manhattan', or any + distance known to paired distance (see metric.pairwise). + + return_distance : bool, default=False + Whether or not to return the distances between the clusters. + + Returns + ------- + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_connected_components : int + The number of connected components in the graph. + + n_leaves : int + The number of leaves in the tree. + + parents : ndarray of shape (n_nodes, ) or None + The parent of each node. Only returned when a connectivity matrix + is specified, elsewhere 'None' is returned. + + distances : ndarray of shape (n_nodes-1,) + Returned when `return_distance` is set to `True`. + + distances[i] refers to the distance between children[i][0] and + children[i][1] when they are merged. + + See Also + -------- + ward_tree : Hierarchical clustering with ward linkage. + """ + X = np.asarray(X) + if X.ndim == 1: + X = np.reshape(X, (-1, 1)) + n_samples, n_features = X.shape + + linkage_choices = { + "complete": _hierarchical.max_merge, + "average": _hierarchical.average_merge, + "single": None, + } # Single linkage is handled differently + try: + join_func = linkage_choices[linkage] + except KeyError as e: + raise ValueError( + "Unknown linkage option, linkage should be one of %s, but %s was given" + % (linkage_choices.keys(), linkage) + ) from e + + if affinity == "cosine" and np.any(~np.any(X, axis=1)): + raise ValueError("Cosine affinity cannot be used when X contains zero vectors") + + if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + + if n_clusters is not None: + warnings.warn( + "Partial build of the tree is implemented " + "only for structured clustering (i.e. with " + "explicit connectivity). The algorithm " + "will build the full tree and only " + "retain the lower branches required " + "for the specified number of clusters", + stacklevel=2, + ) + + if affinity == "precomputed": + # for the linkage function of hierarchy to work on precomputed + # data, provide as first argument an ndarray of the shape returned + # by sklearn.metrics.pairwise_distances. + if X.shape[0] != X.shape[1]: + raise ValueError( + f"Distance matrix should be square, got matrix of shape {X.shape}" + ) + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + elif affinity == "l2": + # Translate to something understood by scipy + affinity = "euclidean" + elif affinity in ("l1", "manhattan"): + affinity = "cityblock" + elif callable(affinity): + X = affinity(X) + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + if ( + linkage == "single" + and affinity != "precomputed" + and not callable(affinity) + and affinity in METRIC_MAPPING + ): + + # We need the fast cythonized metric from neighbors + dist_metric = DistanceMetric.get_metric(affinity) + + # The Cython routines used require contiguous arrays + X = np.ascontiguousarray(X, dtype=np.double) + + mst = _hierarchical.mst_linkage_core(X, dist_metric) + # Sort edges of the min_spanning_tree by weight + mst = mst[np.argsort(mst.T[2], kind="mergesort"), :] + + # Convert edge list into standard hierarchical clustering format + out = _hierarchical.single_linkage_label(mst) + else: + out = hierarchy.linkage(X, method=linkage, metric=affinity) + children_ = out[:, :2].astype(int, copy=False) + + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + return children_, 1, n_samples, None + + connectivity, n_connected_components = _fix_connectivity( + X, connectivity, affinity=affinity + ) + connectivity = connectivity.tocoo() + # Put the diagonal to zero + diag_mask = connectivity.row != connectivity.col + connectivity.row = connectivity.row[diag_mask] + connectivity.col = connectivity.col[diag_mask] + connectivity.data = connectivity.data[diag_mask] + del diag_mask + + if affinity == "precomputed": + distances = X[connectivity.row, connectivity.col].astype(np.float64, copy=False) + else: + # FIXME We compute all the distances, while we could have only computed + # the "interesting" distances + distances = paired_distances( + X[connectivity.row], X[connectivity.col], metric=affinity + ) + connectivity.data = distances + + if n_clusters is None: + n_nodes = 2 * n_samples - 1 + else: + assert n_clusters <= n_samples + n_nodes = 2 * n_samples - n_clusters + + if linkage == "single": + return _single_linkage_tree( + connectivity, + n_samples, + n_nodes, + n_clusters, + n_connected_components, + return_distance, + ) + + if return_distance: + distances = np.empty(n_nodes - n_samples) + # create inertia heap and connection matrix + A = np.empty(n_nodes, dtype=object) + inertia = list() + + # LIL seems to the best format to access the rows quickly, + # without the numpy overhead of slicing CSR indices and data. + connectivity = connectivity.tolil() + # We are storing the graph in a list of IntFloatDict + for ind, (data, row) in enumerate(zip(connectivity.data, connectivity.rows)): + A[ind] = IntFloatDict( + np.asarray(row, dtype=np.intp), np.asarray(data, dtype=np.float64) + ) + # We keep only the upper triangular for the heap + # Generator expressions are faster than arrays on the following + inertia.extend( + _hierarchical.WeightedEdge(d, ind, r) for r, d in zip(row, data) if r < ind + ) + del connectivity + + heapify(inertia) + + # prepare the main fields + parent = np.arange(n_nodes, dtype=np.intp) + used_node = np.ones(n_nodes, dtype=np.intp) + children = [] + + # recursive merge loop + for k in range(n_samples, n_nodes): + # identify the merge + while True: + edge = heappop(inertia) + if used_node[edge.a] and used_node[edge.b]: + break + i = edge.a + j = edge.b + + if return_distance: + # store distances + distances[k - n_samples] = edge.weight + + parent[i] = parent[j] = k + children.append((i, j)) + # Keep track of the number of elements per cluster + n_i = used_node[i] + n_j = used_node[j] + used_node[k] = n_i + n_j + used_node[i] = used_node[j] = False + + # update the structure matrix A and the inertia matrix + # a clever 'min', or 'max' operation between A[i] and A[j] + coord_col = join_func(A[i], A[j], used_node, n_i, n_j) + for col, d in coord_col: + A[col].append(k, d) + # Here we use the information from coord_col (containing the + # distances) to update the heap + heappush(inertia, _hierarchical.WeightedEdge(d, k, col)) + A[k] = coord_col + # Clear A[i] and A[j] to save memory + A[i] = A[j] = 0 + + # Separate leaves in children (empty lists up to now) + n_leaves = n_samples + + # # return numpy array for efficient caching + children = np.array(children)[:, ::-1] + + if return_distance: + return children, n_connected_components, n_leaves, parent, distances + return children, n_connected_components, n_leaves, parent + + +# Matching names to tree-building strategies +def _complete_linkage(*args, **kwargs): + kwargs["linkage"] = "complete" + return linkage_tree(*args, **kwargs) + + +def _average_linkage(*args, **kwargs): + kwargs["linkage"] = "average" + return linkage_tree(*args, **kwargs) + + +def _single_linkage(*args, **kwargs): + kwargs["linkage"] = "single" + return linkage_tree(*args, **kwargs) + + +_TREE_BUILDERS = dict( + ward=ward_tree, + complete=_complete_linkage, + average=_average_linkage, + single=_single_linkage, +) + +############################################################################### +# Functions for cutting hierarchical clustering tree + + +def _hc_cut(n_clusters, children, n_leaves): + """Function cutting the ward tree for a given number of clusters. + + Parameters + ---------- + n_clusters : int or ndarray + The number of clusters to form. + + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_leaves : int + Number of leaves of the tree. + + Returns + ------- + labels : array [n_samples] + Cluster labels for each point. + """ + if n_clusters > n_leaves: + raise ValueError( + "Cannot extract more clusters than samples: " + "%s clusters where given for a tree with %s leaves." + % (n_clusters, n_leaves) + ) + # In this function, we store nodes as a heap to avoid recomputing + # the max of the nodes: the first element is always the smallest + # We use negated indices as heaps work on smallest elements, and we + # are interested in largest elements + # children[-1] is the root of the tree + nodes = [-(max(children[-1]) + 1)] + for _ in range(n_clusters - 1): + # As we have a heap, nodes[0] is the smallest element + these_children = children[-nodes[0] - n_leaves] + # Insert the 2 children and remove the largest node + heappush(nodes, -these_children[0]) + heappushpop(nodes, -these_children[1]) + label = np.zeros(n_leaves, dtype=np.intp) + for i, node in enumerate(nodes): + label[_hierarchical._hc_get_descendent(-node, children, n_leaves)] = i + return label + + +############################################################################### + + +class AgglomerativeClustering(ClusterMixin, BaseEstimator): + """ + Agglomerative Clustering. + + Recursively merges pair of clusters of sample data; uses linkage distance. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or None, default=2 + The number of clusters to find. It must be ``None`` if + ``distance_threshold`` is not ``None``. + + affinity : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If linkage is "ward", only "euclidean" is accepted. + If "precomputed", a distance matrix (instead of a similarity matrix) + is needed as input for the fit method. + + .. deprecated:: 1.2 + `affinity` was deprecated in version 1.2 and will be renamed to + `metric` in 1.4. + + metric : str or callable, default=None + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or "precomputed". If set to `None` then + "euclidean" is used. If linkage is "ward", only "euclidean" is + accepted. If "precomputed", a distance matrix is needed as input for + the fit method. + + .. versionadded:: 1.2 + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + connectivity : array-like or callable, default=None + Connectivity matrix. Defines for each sample the neighboring + samples following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + `kneighbors_graph`. Default is ``None``, i.e, the + hierarchical clustering algorithm is unstructured. + + compute_full_tree : 'auto' or bool, default='auto' + Stop early the construction of the tree at ``n_clusters``. This is + useful to decrease computation time if the number of clusters is not + small compared to the number of samples. This option is useful only + when specifying a connectivity matrix. Note also that when varying the + number of clusters and using caching, it may be advantageous to compute + the full tree. It must be ``True`` if ``distance_threshold`` is not + ``None``. By default `compute_full_tree` is "auto", which is equivalent + to `True` when `distance_threshold` is not `None` or that `n_clusters` + is inferior to the maximum between 100 or `0.02 * n_samples`. + Otherwise, "auto" is equivalent to `False`. + + linkage : {'ward', 'complete', 'average', 'single'}, default='ward' + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of observation. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - 'ward' minimizes the variance of the clusters being merged. + - 'average' uses the average of the distances of each observation of + the two sets. + - 'complete' or 'maximum' linkage uses the maximum distances between + all observations of the two sets. + - 'single' uses the minimum of the distances between all observations + of the two sets. + + .. versionadded:: 0.20 + Added the 'single' option + + distance_threshold : float, default=None + The linkage distance threshold at or above which clusters will not be + merged. If not ``None``, ``n_clusters`` must be ``None`` and + ``compute_full_tree`` must be ``True``. + + .. versionadded:: 0.21 + + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + + Attributes + ---------- + n_clusters_ : int + The number of clusters found by the algorithm. If + ``distance_threshold=None``, it will be equal to the given + ``n_clusters``. + + labels_ : ndarray of shape (n_samples) + Cluster labels for each point. + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_connected_components_ : int + The estimated number of connected components in the graph. + + .. versionadded:: 0.21 + ``n_connected_components_`` was added to replace ``n_components_``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + children_ : array-like of shape (n_samples-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + distances_ : array-like of shape (n_nodes-1,) + Distances between nodes in the corresponding place in `children_`. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. + + See Also + -------- + FeatureAgglomeration : Agglomerative clustering but for features instead of + samples. + ward_tree : Hierarchical clustering with ward linkage. + + Examples + -------- + >>> from sklearn.cluster import AgglomerativeClustering + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> clustering = AgglomerativeClustering().fit(X) + >>> clustering + AgglomerativeClustering() + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left"), None], + "affinity": [ + Hidden(StrOptions({"deprecated"})), + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + None, + ], + "memory": [str, HasMethods("cache"), None], + "connectivity": ["array-like", callable, None], + "compute_full_tree": [StrOptions({"auto"}), "boolean"], + "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))], + "distance_threshold": [Interval(Real, 0, None, closed="left"), None], + "compute_distances": ["boolean"], + } + + def __init__( + self, + n_clusters=2, + *, + affinity="deprecated", # TODO(1.4): Remove + metric=None, # TODO(1.4): Set to "euclidean" + memory=None, + connectivity=None, + compute_full_tree="auto", + linkage="ward", + distance_threshold=None, + compute_distances=False, + ): + self.n_clusters = n_clusters + self.distance_threshold = distance_threshold + self.memory = memory + self.connectivity = connectivity + self.compute_full_tree = compute_full_tree + self.linkage = linkage + self.affinity = affinity + self.metric = metric + self.compute_distances = compute_distances + + def fit(self, X, y=None): + """Fit the hierarchical clustering from features, or distance matrix. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Returns the fitted instance. + """ + self._validate_params() + X = self._validate_data(X, ensure_min_samples=2) + return self._fit(X) + + def _fit(self, X): + """Fit without validation + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``affinity='precomputed'``. + + Returns + ------- + self : object + Returns the fitted instance. + """ + memory = check_memory(self.memory) + + self._metric = self.metric + # TODO(1.4): Remove + if self.affinity != "deprecated": + if self.metric is not None: + raise ValueError( + "Both `affinity` and `metric` attributes were set. Attribute" + " `affinity` was deprecated in version 1.2 and will be removed in" + " 1.4. To avoid this error, only set the `metric` attribute." + ) + warnings.warn( + "Attribute `affinity` was deprecated in version 1.2 and will be removed" + " in 1.4. Use `metric` instead", + FutureWarning, + ) + self._metric = self.affinity + elif self.metric is None: + self._metric = "euclidean" + + if not ((self.n_clusters is None) ^ (self.distance_threshold is None)): + raise ValueError( + "Exactly one of n_clusters and " + "distance_threshold has to be set, and the other " + "needs to be None." + ) + + if self.distance_threshold is not None and not self.compute_full_tree: + raise ValueError( + "compute_full_tree must be True if distance_threshold is set." + ) + + if self.linkage == "ward" and self._metric != "euclidean": + raise ValueError( + f"{self._metric} was provided as metric. Ward can only " + "work with euclidean distances." + ) + + tree_builder = _TREE_BUILDERS[self.linkage] + + connectivity = self.connectivity + if self.connectivity is not None: + if callable(self.connectivity): + connectivity = self.connectivity(X) + connectivity = check_array( + connectivity, accept_sparse=["csr", "coo", "lil"] + ) + + n_samples = len(X) + compute_full_tree = self.compute_full_tree + if self.connectivity is None: + compute_full_tree = True + if compute_full_tree == "auto": + if self.distance_threshold is not None: + compute_full_tree = True + else: + # Early stopping is likely to give a speed up only for + # a large number of clusters. The actual threshold + # implemented here is heuristic + compute_full_tree = self.n_clusters < max(100, 0.02 * n_samples) + n_clusters = self.n_clusters + if compute_full_tree: + n_clusters = None + + # Construct the tree + kwargs = {} + if self.linkage != "ward": + kwargs["linkage"] = self.linkage + kwargs["affinity"] = self._metric + + distance_threshold = self.distance_threshold + + return_distance = (distance_threshold is not None) or self.compute_distances + + out = memory.cache(tree_builder)( + X, + connectivity=connectivity, + n_clusters=n_clusters, + return_distance=return_distance, + **kwargs, + ) + (self.children_, self.n_connected_components_, self.n_leaves_, parents) = out[ + :4 + ] + + if return_distance: + self.distances_ = out[-1] + + if self.distance_threshold is not None: # distance_threshold is used + self.n_clusters_ = ( + np.count_nonzero(self.distances_ >= distance_threshold) + 1 + ) + else: # n_clusters is used + self.n_clusters_ = self.n_clusters + + # Cut the tree + if compute_full_tree: + self.labels_ = _hc_cut(self.n_clusters_, self.children_, self.n_leaves_) + else: + labels = _hierarchical.hc_get_heads(parents, copy=False) + # copy to avoid holding a reference on the original array + labels = np.copy(labels[:n_samples]) + # Reassign cluster numbers + self.labels_ = np.searchsorted(np.unique(labels), labels) + return self + + def fit_predict(self, X, y=None): + """Fit and return the result of each sample's clustering assignment. + + In addition to fitting, this method also return the result of the + clustering assignment for each sample in the training set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``affinity='precomputed'``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) + + +class FeatureAgglomeration( + ClassNamePrefixFeaturesOutMixin, AgglomerativeClustering, AgglomerationTransform +): + """Agglomerate features. + + Recursively merges pair of clusters of features. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or None, default=2 + The number of clusters to find. It must be ``None`` if + ``distance_threshold`` is not ``None``. + + affinity : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If linkage is "ward", only "euclidean" is accepted. + If "precomputed", a distance matrix (instead of a similarity matrix) + is needed as input for the fit method. + + .. deprecated:: 1.2 + `affinity` was deprecated in version 1.2 and will be renamed to + `metric` in 1.4. + + metric : str or callable, default=None + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or "precomputed". If set to `None` then + "euclidean" is used. If linkage is "ward", only "euclidean" is + accepted. If "precomputed", a distance matrix is needed as input for + the fit method. + + .. versionadded:: 1.2 + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + connectivity : array-like or callable, default=None + Connectivity matrix. Defines for each feature the neighboring + features following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + `kneighbors_graph`. Default is `None`, i.e, the + hierarchical clustering algorithm is unstructured. + + compute_full_tree : 'auto' or bool, default='auto' + Stop early the construction of the tree at `n_clusters`. This is useful + to decrease computation time if the number of clusters is not small + compared to the number of features. This option is useful only when + specifying a connectivity matrix. Note also that when varying the + number of clusters and using caching, it may be advantageous to compute + the full tree. It must be ``True`` if ``distance_threshold`` is not + ``None``. By default `compute_full_tree` is "auto", which is equivalent + to `True` when `distance_threshold` is not `None` or that `n_clusters` + is inferior to the maximum between 100 or `0.02 * n_samples`. + Otherwise, "auto" is equivalent to `False`. + + linkage : {"ward", "complete", "average", "single"}, default="ward" + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of features. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - "ward" minimizes the variance of the clusters being merged. + - "complete" or maximum linkage uses the maximum distances between + all features of the two sets. + - "average" uses the average of the distances of each feature of + the two sets. + - "single" uses the minimum of the distances between all features + of the two sets. + + pooling_func : callable, default=np.mean + This combines the values of agglomerated features into a single + value, and should accept an array of shape [M, N] and the keyword + argument `axis=1`, and reduce it to an array of size [M]. + + distance_threshold : float, default=None + The linkage distance threshold at or above which clusters will not be + merged. If not ``None``, ``n_clusters`` must be ``None`` and + ``compute_full_tree`` must be ``True``. + + .. versionadded:: 0.21 + + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + + Attributes + ---------- + n_clusters_ : int + The number of clusters found by the algorithm. If + ``distance_threshold=None``, it will be equal to the given + ``n_clusters``. + + labels_ : array-like of (n_features,) + Cluster labels for each feature. + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_connected_components_ : int + The estimated number of connected components in the graph. + + .. versionadded:: 0.21 + ``n_connected_components_`` was added to replace ``n_components_``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + children_ : array-like of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_features` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_features` is a non-leaf + node and has children `children_[i - n_features]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_features + i`. + + distances_ : array-like of shape (n_nodes-1,) + Distances between nodes in the corresponding place in `children_`. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. + + See Also + -------- + AgglomerativeClustering : Agglomerative clustering samples instead of + features. + ward_tree : Hierarchical clustering with ward linkage. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import datasets, cluster + >>> digits = datasets.load_digits() + >>> images = digits.images + >>> X = np.reshape(images, (len(images), -1)) + >>> agglo = cluster.FeatureAgglomeration(n_clusters=32) + >>> agglo.fit(X) + FeatureAgglomeration(n_clusters=32) + >>> X_reduced = agglo.transform(X) + >>> X_reduced.shape + (1797, 32) + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left"), None], + "affinity": [ + Hidden(StrOptions({"deprecated"})), + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + None, + ], + "memory": [str, HasMethods("cache"), None], + "connectivity": ["array-like", callable, None], + "compute_full_tree": [StrOptions({"auto"}), "boolean"], + "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))], + "pooling_func": [callable], + "distance_threshold": [Interval(Real, 0, None, closed="left"), None], + "compute_distances": ["boolean"], + } + + def __init__( + self, + n_clusters=2, + *, + affinity="deprecated", # TODO(1.4): Remove + metric=None, # TODO(1.4): Set to "euclidean" + memory=None, + connectivity=None, + compute_full_tree="auto", + linkage="ward", + pooling_func=np.mean, + distance_threshold=None, + compute_distances=False, + ): + super().__init__( + n_clusters=n_clusters, + memory=memory, + connectivity=connectivity, + compute_full_tree=compute_full_tree, + linkage=linkage, + affinity=affinity, + metric=metric, + distance_threshold=distance_threshold, + compute_distances=compute_distances, + ) + self.pooling_func = pooling_func + + def fit(self, X, y=None): + """Fit the hierarchical clustering on the data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Returns the transformer. + """ + self._validate_params() + X = self._validate_data(X, ensure_min_features=2) + super()._fit(X.T) + self._n_features_out = self.n_clusters_ + return self + + @property + def fit_predict(self): + """Fit and return the result of each sample's clustering assignment.""" + raise AttributeError diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..73cb1c35290167ad5188b4ddd835da0dab4d1689 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py @@ -0,0 +1,628 @@ +"""Spectral biclustering algorithms.""" +# Authors : Kemal Eren +# License: BSD 3 clause + +from abc import ABCMeta, abstractmethod + +import numpy as np +from numbers import Integral + +from scipy.linalg import norm +from scipy.sparse import dia_matrix, issparse +from scipy.sparse.linalg import eigsh, svds + +from . import KMeans, MiniBatchKMeans +from ..base import BaseEstimator, BiclusterMixin +from ..utils import check_random_state +from ..utils import check_scalar + +from ..utils.extmath import make_nonnegative, randomized_svd, safe_sparse_dot + +from ..utils.validation import assert_all_finite +from ..utils._param_validation import Interval, StrOptions + + +__all__ = ["SpectralCoclustering", "SpectralBiclustering"] + + +def _scale_normalize(X): + """Normalize ``X`` by scaling rows and columns independently. + + Returns the normalized matrix and the row and column scaling + factors. + """ + X = make_nonnegative(X) + row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze() + col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze() + row_diag = np.where(np.isnan(row_diag), 0, row_diag) + col_diag = np.where(np.isnan(col_diag), 0, col_diag) + if issparse(X): + n_rows, n_cols = X.shape + r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows)) + c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols)) + an = r * X * c + else: + an = row_diag[:, np.newaxis] * X * col_diag + return an, row_diag, col_diag + + +def _bistochastic_normalize(X, max_iter=1000, tol=1e-5): + """Normalize rows and columns of ``X`` simultaneously so that all + rows sum to one constant and all columns sum to a different + constant. + """ + # According to paper, this can also be done more efficiently with + # deviation reduction and balancing algorithms. + X = make_nonnegative(X) + X_scaled = X + for _ in range(max_iter): + X_new, _, _ = _scale_normalize(X_scaled) + if issparse(X): + dist = norm(X_scaled.data - X.data) + else: + dist = norm(X_scaled - X_new) + X_scaled = X_new + if dist is not None and dist < tol: + break + return X_scaled + + +def _log_normalize(X): + """Normalize ``X`` according to Kluger's log-interactions scheme.""" + X = make_nonnegative(X, min_value=1) + if issparse(X): + raise ValueError( + "Cannot compute log of a sparse matrix," + " because log(x) diverges to -infinity as x" + " goes to 0." + ) + L = np.log(X) + row_avg = L.mean(axis=1)[:, np.newaxis] + col_avg = L.mean(axis=0) + avg = L.mean() + return L - row_avg - col_avg + avg + + +class BaseSpectral(BiclusterMixin, BaseEstimator, metaclass=ABCMeta): + """Base class for spectral biclustering.""" + + _parameter_constraints: dict = { + "svd_method": [StrOptions({"randomized", "arpack"})], + "n_svd_vecs": [Interval(Integral, 0, None, closed="left"), None], + "mini_batch": ["boolean"], + "init": [StrOptions({"k-means++", "random"}), np.ndarray], + "n_init": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + } + + @abstractmethod + def __init__( + self, + n_clusters=3, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + self.n_clusters = n_clusters + self.svd_method = svd_method + self.n_svd_vecs = n_svd_vecs + self.mini_batch = mini_batch + self.init = init + self.n_init = n_init + self.random_state = random_state + + @abstractmethod + def _check_parameters(self, n_samples): + """Validate parameters depending on the input data.""" + + def fit(self, X, y=None): + """Create a biclustering for X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + SpectralBiclustering instance. + """ + self._validate_params() + + X = self._validate_data(X, accept_sparse="csr", dtype=np.float64) + self._check_parameters(X.shape[0]) + self._fit(X) + return self + + def _svd(self, array, n_components, n_discard): + """Returns first `n_components` left and right singular + vectors u and v, discarding the first `n_discard`. + """ + if self.svd_method == "randomized": + kwargs = {} + if self.n_svd_vecs is not None: + kwargs["n_oversamples"] = self.n_svd_vecs + u, _, vt = randomized_svd( + array, n_components, random_state=self.random_state, **kwargs + ) + + elif self.svd_method == "arpack": + u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs) + if np.any(np.isnan(vt)): + # some eigenvalues of A * A.T are negative, causing + # sqrt() to be np.nan. This causes some vectors in vt + # to be np.nan. + A = safe_sparse_dot(array.T, array) + random_state = check_random_state(self.random_state) + # initialize with [-1,1] as in ARPACK + v0 = random_state.uniform(-1, 1, A.shape[0]) + _, v = eigsh(A, ncv=self.n_svd_vecs, v0=v0) + vt = v.T + if np.any(np.isnan(u)): + A = safe_sparse_dot(array, array.T) + random_state = check_random_state(self.random_state) + # initialize with [-1,1] as in ARPACK + v0 = random_state.uniform(-1, 1, A.shape[0]) + _, u = eigsh(A, ncv=self.n_svd_vecs, v0=v0) + + assert_all_finite(u) + assert_all_finite(vt) + u = u[:, n_discard:] + vt = vt[n_discard:] + return u, vt.T + + def _k_means(self, data, n_clusters): + if self.mini_batch: + model = MiniBatchKMeans( + n_clusters, + init=self.init, + n_init=self.n_init, + random_state=self.random_state, + ) + else: + model = KMeans( + n_clusters, + init=self.init, + n_init=self.n_init, + random_state=self.random_state, + ) + model.fit(data) + centroid = model.cluster_centers_ + labels = model.labels_ + return centroid, labels + + def _more_tags(self): + return { + "_xfail_checks": { + "check_estimators_dtypes": "raises nan error", + "check_fit2d_1sample": "_scale_normalize fails", + "check_fit2d_1feature": "raises apply_along_axis error", + "check_estimator_sparse_data": "does not fail gracefully", + "check_methods_subset_invariance": "empty array passed inside", + "check_dont_overwrite_parameters": "empty array passed inside", + "check_fit2d_predict1d": "empty array passed inside", + } + } + + +class SpectralCoclustering(BaseSpectral): + """Spectral Co-Clustering algorithm (Dhillon, 2001). + + Clusters rows and columns of an array `X` to solve the relaxed + normalized cut of the bipartite graph created from `X` as follows: + the edge between row vertex `i` and column vertex `j` has weight + `X[i, j]`. + + The resulting bicluster structure is block-diagonal, since each + row and each column belongs to exactly one bicluster. + + Supports sparse matrices, as long as they are nonnegative. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int, default=3 + The number of biclusters to find. + + svd_method : {'randomized', 'arpack'}, default='randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', use + :func:`sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', use + :func:`scipy.sparse.linalg.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, default=None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, default=False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random'}, or ndarray of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, default=10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + random_state : int, RandomState instance, default=None + Used for randomizing the singular value decomposition and the k-means + initialization. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Attributes + ---------- + rows_ : array-like of shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like of shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like of shape (n_rows,) + The bicluster label of each row. + + column_labels_ : array-like of shape (n_cols,) + The bicluster label of each column. + + biclusters_ : tuple of two ndarrays + The tuple contains the `rows_` and `columns_` arrays. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SpectralBiclustering : Partitions rows and columns under the assumption + that the data has an underlying checkerboard structure. + + References + ---------- + * :doi:`Dhillon, Inderjit S, 2001. Co-clustering documents and words using + bipartite spectral graph partitioning. + <10.1145/502512.502550>` + + Examples + -------- + >>> from sklearn.cluster import SpectralCoclustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X) + >>> clustering.row_labels_ #doctest: +SKIP + array([0, 1, 1, 0, 0, 0], dtype=int32) + >>> clustering.column_labels_ #doctest: +SKIP + array([0, 0], dtype=int32) + >>> clustering + SpectralCoclustering(n_clusters=2, random_state=0) + """ + + _parameter_constraints: dict = { + **BaseSpectral._parameter_constraints, + "n_clusters": [Interval(Integral, 1, None, closed="left")], + } + + def __init__( + self, + n_clusters=3, + *, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + super().__init__( + n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state + ) + + def _check_parameters(self, n_samples): + if self.n_clusters > n_samples: + raise ValueError( + f"n_clusters should be <= n_samples={n_samples}. Got" + f" {self.n_clusters} instead." + ) + + def _fit(self, X): + normalized_data, row_diag, col_diag = _scale_normalize(X) + n_sv = 1 + int(np.ceil(np.log2(self.n_clusters))) + u, v = self._svd(normalized_data, n_sv, n_discard=1) + z = np.vstack((row_diag[:, np.newaxis] * u, col_diag[:, np.newaxis] * v)) + + _, labels = self._k_means(z, self.n_clusters) + + n_rows = X.shape[0] + self.row_labels_ = labels[:n_rows] + self.column_labels_ = labels[n_rows:] + + self.rows_ = np.vstack([self.row_labels_ == c for c in range(self.n_clusters)]) + self.columns_ = np.vstack( + [self.column_labels_ == c for c in range(self.n_clusters)] + ) + + +class SpectralBiclustering(BaseSpectral): + """Spectral biclustering (Kluger, 2003). + + Partitions rows and columns under the assumption that the data has + an underlying checkerboard structure. For instance, if there are + two row partitions and three column partitions, each row will + belong to three biclusters, and each column will belong to two + biclusters. The outer product of the corresponding row and column + label vectors gives this checkerboard structure. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or tuple (n_row_clusters, n_column_clusters), default=3 + The number of row and column clusters in the checkerboard + structure. + + method : {'bistochastic', 'scale', 'log'}, default='bistochastic' + Method of normalizing and converting singular vectors into + biclusters. May be one of 'scale', 'bistochastic', or 'log'. + The authors recommend using 'log'. If the data is sparse, + however, log normalization will not work, which is why the + default is 'bistochastic'. + + .. warning:: + if `method='log'`, the data must not be sparse. + + n_components : int, default=6 + Number of singular vectors to check. + + n_best : int, default=3 + Number of best singular vectors to which to project the data + for clustering. + + svd_method : {'randomized', 'arpack'}, default='randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', uses + :func:`~sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', uses + `scipy.sparse.linalg.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, default=None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, default=False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random'} or ndarray of shape (n_clusters, n_features), \ + default='k-means++' + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, default=10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + random_state : int, RandomState instance, default=None + Used for randomizing the singular value decomposition and the k-means + initialization. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Attributes + ---------- + rows_ : array-like of shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like of shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like of shape (n_rows,) + Row partition labels. + + column_labels_ : array-like of shape (n_cols,) + Column partition labels. + + biclusters_ : tuple of two ndarrays + The tuple contains the `rows_` and `columns_` arrays. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SpectralCoclustering : Spectral Co-Clustering algorithm (Dhillon, 2001). + + References + ---------- + + * :doi:`Kluger, Yuval, et. al., 2003. Spectral biclustering of microarray + data: coclustering genes and conditions. + <10.1101/gr.648603>` + + Examples + -------- + >>> from sklearn.cluster import SpectralBiclustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X) + >>> clustering.row_labels_ + array([1, 1, 1, 0, 0, 0], dtype=int32) + >>> clustering.column_labels_ + array([0, 1], dtype=int32) + >>> clustering + SpectralBiclustering(n_clusters=2, random_state=0) + """ + + _parameter_constraints: dict = { + **BaseSpectral._parameter_constraints, + "n_clusters": [Interval(Integral, 1, None, closed="left"), tuple], + "method": [StrOptions({"bistochastic", "scale", "log"})], + "n_components": [Interval(Integral, 1, None, closed="left")], + "n_best": [Interval(Integral, 1, None, closed="left")], + } + + def __init__( + self, + n_clusters=3, + *, + method="bistochastic", + n_components=6, + n_best=3, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + super().__init__( + n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state + ) + self.method = method + self.n_components = n_components + self.n_best = n_best + + def _check_parameters(self, n_samples): + if isinstance(self.n_clusters, Integral): + if self.n_clusters > n_samples: + raise ValueError( + f"n_clusters should be <= n_samples={n_samples}. Got" + f" {self.n_clusters} instead." + ) + else: # tuple + try: + n_row_clusters, n_column_clusters = self.n_clusters + check_scalar( + n_row_clusters, + "n_row_clusters", + target_type=Integral, + min_val=1, + max_val=n_samples, + ) + check_scalar( + n_column_clusters, + "n_column_clusters", + target_type=Integral, + min_val=1, + max_val=n_samples, + ) + except (ValueError, TypeError) as e: + raise ValueError( + "Incorrect parameter n_clusters has value:" + f" {self.n_clusters}. It should either be a single integer" + " or an iterable with two integers:" + " (n_row_clusters, n_column_clusters)" + " And the values are should be in the" + " range: (1, n_samples)" + ) from e + + if self.n_best > self.n_components: + raise ValueError( + f"n_best={self.n_best} must be <= n_components={self.n_components}." + ) + + def _fit(self, X): + n_sv = self.n_components + if self.method == "bistochastic": + normalized_data = _bistochastic_normalize(X) + n_sv += 1 + elif self.method == "scale": + normalized_data, _, _ = _scale_normalize(X) + n_sv += 1 + elif self.method == "log": + normalized_data = _log_normalize(X) + n_discard = 0 if self.method == "log" else 1 + u, v = self._svd(normalized_data, n_sv, n_discard) + ut = u.T + vt = v.T + + try: + n_row_clusters, n_col_clusters = self.n_clusters + except TypeError: + n_row_clusters = n_col_clusters = self.n_clusters + + best_ut = self._fit_best_piecewise(ut, self.n_best, n_row_clusters) + + best_vt = self._fit_best_piecewise(vt, self.n_best, n_col_clusters) + + self.row_labels_ = self._project_and_cluster(X, best_vt.T, n_row_clusters) + + self.column_labels_ = self._project_and_cluster(X.T, best_ut.T, n_col_clusters) + + self.rows_ = np.vstack( + [ + self.row_labels_ == label + for label in range(n_row_clusters) + for _ in range(n_col_clusters) + ] + ) + self.columns_ = np.vstack( + [ + self.column_labels_ == label + for _ in range(n_row_clusters) + for label in range(n_col_clusters) + ] + ) + + def _fit_best_piecewise(self, vectors, n_best, n_clusters): + """Find the ``n_best`` vectors that are best approximated by piecewise + constant vectors. + + The piecewise vectors are found by k-means; the best is chosen + according to Euclidean distance. + + """ + + def make_piecewise(v): + centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters) + return centroid[labels].ravel() + + piecewise_vectors = np.apply_along_axis(make_piecewise, axis=1, arr=vectors) + dists = np.apply_along_axis(norm, axis=1, arr=(vectors - piecewise_vectors)) + result = vectors[np.argsort(dists)[:n_best]] + return result + + def _project_and_cluster(self, data, vectors, n_clusters): + """Project ``data`` to ``vectors`` and cluster the result.""" + projected = safe_sparse_dot(data, vectors) + _, labels = self._k_means(projected, n_clusters) + return labels diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_birch.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_birch.py new file mode 100644 index 0000000000000000000000000000000000000000..4c9d7921fdc704fc95496fd683c2eaab1deb0b70 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_birch.py @@ -0,0 +1,742 @@ +# Authors: Manoj Kumar +# Alexandre Gramfort +# Joel Nothman +# License: BSD 3 clause + +import warnings +import numpy as np +from numbers import Integral, Real +from scipy import sparse +from math import sqrt + +from ..metrics import pairwise_distances_argmin +from ..metrics.pairwise import euclidean_distances +from ..base import ( + TransformerMixin, + ClusterMixin, + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, +) +from ..utils.extmath import row_norms +from ..utils._param_validation import Interval +from ..utils.validation import check_is_fitted +from ..exceptions import ConvergenceWarning +from . import AgglomerativeClustering +from .._config import config_context + + +def _iterate_sparse_X(X): + """This little hack returns a densified row when iterating over a sparse + matrix, instead of constructing a sparse matrix for every row that is + expensive. + """ + n_samples = X.shape[0] + X_indices = X.indices + X_data = X.data + X_indptr = X.indptr + + for i in range(n_samples): + row = np.zeros(X.shape[1]) + startptr, endptr = X_indptr[i], X_indptr[i + 1] + nonzero_indices = X_indices[startptr:endptr] + row[nonzero_indices] = X_data[startptr:endptr] + yield row + + +def _split_node(node, threshold, branching_factor): + """The node has to be split if there is no place for a new subcluster + in the node. + 1. Two empty nodes and two empty subclusters are initialized. + 2. The pair of distant subclusters are found. + 3. The properties of the empty subclusters and nodes are updated + according to the nearest distance between the subclusters to the + pair of distant subclusters. + 4. The two nodes are set as children to the two subclusters. + """ + new_subcluster1 = _CFSubcluster() + new_subcluster2 = _CFSubcluster() + new_node1 = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=node.is_leaf, + n_features=node.n_features, + dtype=node.init_centroids_.dtype, + ) + new_node2 = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=node.is_leaf, + n_features=node.n_features, + dtype=node.init_centroids_.dtype, + ) + new_subcluster1.child_ = new_node1 + new_subcluster2.child_ = new_node2 + + if node.is_leaf: + if node.prev_leaf_ is not None: + node.prev_leaf_.next_leaf_ = new_node1 + new_node1.prev_leaf_ = node.prev_leaf_ + new_node1.next_leaf_ = new_node2 + new_node2.prev_leaf_ = new_node1 + new_node2.next_leaf_ = node.next_leaf_ + if node.next_leaf_ is not None: + node.next_leaf_.prev_leaf_ = new_node2 + + dist = euclidean_distances( + node.centroids_, Y_norm_squared=node.squared_norm_, squared=True + ) + n_clusters = dist.shape[0] + + farthest_idx = np.unravel_index(dist.argmax(), (n_clusters, n_clusters)) + node1_dist, node2_dist = dist[(farthest_idx,)] + + node1_closer = node1_dist < node2_dist + # make sure node1 is closest to itself even if all distances are equal. + # This can only happen when all node.centroids_ are duplicates leading to all + # distances between centroids being zero. + node1_closer[farthest_idx[0]] = True + + for idx, subcluster in enumerate(node.subclusters_): + if node1_closer[idx]: + new_node1.append_subcluster(subcluster) + new_subcluster1.update(subcluster) + else: + new_node2.append_subcluster(subcluster) + new_subcluster2.update(subcluster) + return new_subcluster1, new_subcluster2 + + +class _CFNode: + """Each node in a CFTree is called a CFNode. + + The CFNode can have a maximum of branching_factor + number of CFSubclusters. + + Parameters + ---------- + threshold : float + Threshold needed for a new subcluster to enter a CFSubcluster. + + branching_factor : int + Maximum number of CF subclusters in each node. + + is_leaf : bool + We need to know if the CFNode is a leaf or not, in order to + retrieve the final subclusters. + + n_features : int + The number of features. + + Attributes + ---------- + subclusters_ : list + List of subclusters for a particular CFNode. + + prev_leaf_ : _CFNode + Useful only if is_leaf is True. + + next_leaf_ : _CFNode + next_leaf. Useful only if is_leaf is True. + the final subclusters. + + init_centroids_ : ndarray of shape (branching_factor + 1, n_features) + Manipulate ``init_centroids_`` throughout rather than centroids_ since + the centroids are just a view of the ``init_centroids_`` . + + init_sq_norm_ : ndarray of shape (branching_factor + 1,) + manipulate init_sq_norm_ throughout. similar to ``init_centroids_``. + + centroids_ : ndarray of shape (branching_factor + 1, n_features) + View of ``init_centroids_``. + + squared_norm_ : ndarray of shape (branching_factor + 1,) + View of ``init_sq_norm_``. + + """ + + def __init__(self, *, threshold, branching_factor, is_leaf, n_features, dtype): + self.threshold = threshold + self.branching_factor = branching_factor + self.is_leaf = is_leaf + self.n_features = n_features + + # The list of subclusters, centroids and squared norms + # to manipulate throughout. + self.subclusters_ = [] + self.init_centroids_ = np.zeros((branching_factor + 1, n_features), dtype=dtype) + self.init_sq_norm_ = np.zeros((branching_factor + 1), dtype) + self.squared_norm_ = [] + self.prev_leaf_ = None + self.next_leaf_ = None + + def append_subcluster(self, subcluster): + n_samples = len(self.subclusters_) + self.subclusters_.append(subcluster) + self.init_centroids_[n_samples] = subcluster.centroid_ + self.init_sq_norm_[n_samples] = subcluster.sq_norm_ + + # Keep centroids and squared norm as views. In this way + # if we change init_centroids and init_sq_norm_, it is + # sufficient, + self.centroids_ = self.init_centroids_[: n_samples + 1, :] + self.squared_norm_ = self.init_sq_norm_[: n_samples + 1] + + def update_split_subclusters(self, subcluster, new_subcluster1, new_subcluster2): + """Remove a subcluster from a node and update it with the + split subclusters. + """ + ind = self.subclusters_.index(subcluster) + self.subclusters_[ind] = new_subcluster1 + self.init_centroids_[ind] = new_subcluster1.centroid_ + self.init_sq_norm_[ind] = new_subcluster1.sq_norm_ + self.append_subcluster(new_subcluster2) + + def insert_cf_subcluster(self, subcluster): + """Insert a new subcluster into the node.""" + if not self.subclusters_: + self.append_subcluster(subcluster) + return False + + threshold = self.threshold + branching_factor = self.branching_factor + # We need to find the closest subcluster among all the + # subclusters so that we can insert our new subcluster. + dist_matrix = np.dot(self.centroids_, subcluster.centroid_) + dist_matrix *= -2.0 + dist_matrix += self.squared_norm_ + closest_index = np.argmin(dist_matrix) + closest_subcluster = self.subclusters_[closest_index] + + # If the subcluster has a child, we need a recursive strategy. + if closest_subcluster.child_ is not None: + split_child = closest_subcluster.child_.insert_cf_subcluster(subcluster) + + if not split_child: + # If it is determined that the child need not be split, we + # can just update the closest_subcluster + closest_subcluster.update(subcluster) + self.init_centroids_[closest_index] = self.subclusters_[ + closest_index + ].centroid_ + self.init_sq_norm_[closest_index] = self.subclusters_[ + closest_index + ].sq_norm_ + return False + + # things not too good. we need to redistribute the subclusters in + # our child node, and add a new subcluster in the parent + # subcluster to accommodate the new child. + else: + new_subcluster1, new_subcluster2 = _split_node( + closest_subcluster.child_, + threshold, + branching_factor, + ) + self.update_split_subclusters( + closest_subcluster, new_subcluster1, new_subcluster2 + ) + + if len(self.subclusters_) > self.branching_factor: + return True + return False + + # good to go! + else: + merged = closest_subcluster.merge_subcluster(subcluster, self.threshold) + if merged: + self.init_centroids_[closest_index] = closest_subcluster.centroid_ + self.init_sq_norm_[closest_index] = closest_subcluster.sq_norm_ + return False + + # not close to any other subclusters, and we still + # have space, so add. + elif len(self.subclusters_) < self.branching_factor: + self.append_subcluster(subcluster) + return False + + # We do not have enough space nor is it closer to an + # other subcluster. We need to split. + else: + self.append_subcluster(subcluster) + return True + + +class _CFSubcluster: + """Each subcluster in a CFNode is called a CFSubcluster. + + A CFSubcluster can have a CFNode has its child. + + Parameters + ---------- + linear_sum : ndarray of shape (n_features,), default=None + Sample. This is kept optional to allow initialization of empty + subclusters. + + Attributes + ---------- + n_samples_ : int + Number of samples that belong to each subcluster. + + linear_sum_ : ndarray + Linear sum of all the samples in a subcluster. Prevents holding + all sample data in memory. + + squared_sum_ : float + Sum of the squared l2 norms of all samples belonging to a subcluster. + + centroid_ : ndarray of shape (branching_factor + 1, n_features) + Centroid of the subcluster. Prevent recomputing of centroids when + ``CFNode.centroids_`` is called. + + child_ : _CFNode + Child Node of the subcluster. Once a given _CFNode is set as the child + of the _CFNode, it is set to ``self.child_``. + + sq_norm_ : ndarray of shape (branching_factor + 1,) + Squared norm of the subcluster. Used to prevent recomputing when + pairwise minimum distances are computed. + """ + + def __init__(self, *, linear_sum=None): + if linear_sum is None: + self.n_samples_ = 0 + self.squared_sum_ = 0.0 + self.centroid_ = self.linear_sum_ = 0 + else: + self.n_samples_ = 1 + self.centroid_ = self.linear_sum_ = linear_sum + self.squared_sum_ = self.sq_norm_ = np.dot( + self.linear_sum_, self.linear_sum_ + ) + self.child_ = None + + def update(self, subcluster): + self.n_samples_ += subcluster.n_samples_ + self.linear_sum_ += subcluster.linear_sum_ + self.squared_sum_ += subcluster.squared_sum_ + self.centroid_ = self.linear_sum_ / self.n_samples_ + self.sq_norm_ = np.dot(self.centroid_, self.centroid_) + + def merge_subcluster(self, nominee_cluster, threshold): + """Check if a cluster is worthy enough to be merged. If + yes then merge. + """ + new_ss = self.squared_sum_ + nominee_cluster.squared_sum_ + new_ls = self.linear_sum_ + nominee_cluster.linear_sum_ + new_n = self.n_samples_ + nominee_cluster.n_samples_ + new_centroid = (1 / new_n) * new_ls + new_sq_norm = np.dot(new_centroid, new_centroid) + + # The squared radius of the cluster is defined: + # r^2 = sum_i ||x_i - c||^2 / n + # with x_i the n points assigned to the cluster and c its centroid: + # c = sum_i x_i / n + # This can be expanded to: + # r^2 = sum_i ||x_i||^2 / n - 2 < sum_i x_i / n, c> + n ||c||^2 / n + # and therefore simplifies to: + # r^2 = sum_i ||x_i||^2 / n - ||c||^2 + sq_radius = new_ss / new_n - new_sq_norm + + if sq_radius <= threshold**2: + ( + self.n_samples_, + self.linear_sum_, + self.squared_sum_, + self.centroid_, + self.sq_norm_, + ) = (new_n, new_ls, new_ss, new_centroid, new_sq_norm) + return True + return False + + @property + def radius(self): + """Return radius of the subcluster""" + # Because of numerical issues, this could become negative + sq_radius = self.squared_sum_ / self.n_samples_ - self.sq_norm_ + return sqrt(max(0, sq_radius)) + + +class Birch( + ClassNamePrefixFeaturesOutMixin, ClusterMixin, TransformerMixin, BaseEstimator +): + """Implements the BIRCH clustering algorithm. + + It is a memory-efficient, online-learning algorithm provided as an + alternative to :class:`MiniBatchKMeans`. It constructs a tree + data structure with the cluster centroids being read off the leaf. + These can be either the final cluster centroids or can be provided as input + to another clustering algorithm such as :class:`AgglomerativeClustering`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.16 + + Parameters + ---------- + threshold : float, default=0.5 + The radius of the subcluster obtained by merging a new sample and the + closest subcluster should be lesser than the threshold. Otherwise a new + subcluster is started. Setting this value to be very low promotes + splitting and vice-versa. + + branching_factor : int, default=50 + Maximum number of CF subclusters in each node. If a new samples enters + such that the number of subclusters exceed the branching_factor then + that node is split into two nodes with the subclusters redistributed + in each. The parent subcluster of that node is removed and two new + subclusters are added as parents of the 2 split nodes. + + n_clusters : int, instance of sklearn.cluster model or None, default=3 + Number of clusters after the final clustering step, which treats the + subclusters from the leaves as new samples. + + - `None` : the final clustering step is not performed and the + subclusters are returned as they are. + + - :mod:`sklearn.cluster` Estimator : If a model is provided, the model + is fit treating the subclusters as new samples and the initial data + is mapped to the label of the closest subcluster. + + - `int` : the model fit is :class:`AgglomerativeClustering` with + `n_clusters` set to be equal to the int. + + compute_labels : bool, default=True + Whether or not to compute labels for each fit. + + copy : bool, default=True + Whether or not to make a copy of the given data. If set to False, + the initial data will be overwritten. + + Attributes + ---------- + root_ : _CFNode + Root of the CFTree. + + dummy_leaf_ : _CFNode + Start pointer to all the leaves. + + subcluster_centers_ : ndarray + Centroids of all subclusters read directly from the leaves. + + subcluster_labels_ : ndarray + Labels assigned to the centroids of the subclusters after + they are clustered globally. + + labels_ : ndarray of shape (n_samples,) + Array of labels assigned to the input data. + if partial_fit is used instead of fit, they are assigned to the + last batch of data. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MiniBatchKMeans : Alternative implementation that does incremental updates + of the centers' positions using mini-batches. + + Notes + ----- + The tree data structure consists of nodes with each node consisting of + a number of subclusters. The maximum number of subclusters in a node + is determined by the branching factor. Each subcluster maintains a + linear sum, squared sum and the number of samples in that subcluster. + In addition, each subcluster can also have a node as its child, if the + subcluster is not a member of a leaf node. + + For a new point entering the root, it is merged with the subcluster closest + to it and the linear sum, squared sum and the number of samples of that + subcluster are updated. This is done recursively till the properties of + the leaf node are updated. + + References + ---------- + * Tian Zhang, Raghu Ramakrishnan, Maron Livny + BIRCH: An efficient data clustering method for large databases. + https://www.cs.sfu.ca/CourseCentral/459/han/papers/zhang96.pdf + + * Roberto Perdisci + JBirch - Java implementation of BIRCH clustering algorithm + https://code.google.com/archive/p/jbirch + + Examples + -------- + >>> from sklearn.cluster import Birch + >>> X = [[0, 1], [0.3, 1], [-0.3, 1], [0, -1], [0.3, -1], [-0.3, -1]] + >>> brc = Birch(n_clusters=None) + >>> brc.fit(X) + Birch(n_clusters=None) + >>> brc.predict(X) + array([0, 0, 0, 1, 1, 1]) + """ + + _parameter_constraints: dict = { + "threshold": [Interval(Real, 0.0, None, closed="neither")], + "branching_factor": [Interval(Integral, 1, None, closed="neither")], + "n_clusters": [None, ClusterMixin, Interval(Integral, 1, None, closed="left")], + "compute_labels": ["boolean"], + "copy": ["boolean"], + } + + def __init__( + self, + *, + threshold=0.5, + branching_factor=50, + n_clusters=3, + compute_labels=True, + copy=True, + ): + self.threshold = threshold + self.branching_factor = branching_factor + self.n_clusters = n_clusters + self.compute_labels = compute_labels + self.copy = copy + + def fit(self, X, y=None): + """ + Build a CF Tree for the input data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self + Fitted estimator. + """ + + self._validate_params() + + return self._fit(X, partial=False) + + def _fit(self, X, partial): + has_root = getattr(self, "root_", None) + first_call = not (partial and has_root) + + X = self._validate_data( + X, + accept_sparse="csr", + copy=self.copy, + reset=first_call, + dtype=[np.float64, np.float32], + ) + threshold = self.threshold + branching_factor = self.branching_factor + + n_samples, n_features = X.shape + + # If partial_fit is called for the first time or fit is called, we + # start a new tree. + if first_call: + # The first root is the leaf. Manipulate this object throughout. + self.root_ = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=True, + n_features=n_features, + dtype=X.dtype, + ) + + # To enable getting back subclusters. + self.dummy_leaf_ = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=True, + n_features=n_features, + dtype=X.dtype, + ) + self.dummy_leaf_.next_leaf_ = self.root_ + self.root_.prev_leaf_ = self.dummy_leaf_ + + # Cannot vectorize. Enough to convince to use cython. + if not sparse.issparse(X): + iter_func = iter + else: + iter_func = _iterate_sparse_X + + for sample in iter_func(X): + subcluster = _CFSubcluster(linear_sum=sample) + split = self.root_.insert_cf_subcluster(subcluster) + + if split: + new_subcluster1, new_subcluster2 = _split_node( + self.root_, threshold, branching_factor + ) + del self.root_ + self.root_ = _CFNode( + threshold=threshold, + branching_factor=branching_factor, + is_leaf=False, + n_features=n_features, + dtype=X.dtype, + ) + self.root_.append_subcluster(new_subcluster1) + self.root_.append_subcluster(new_subcluster2) + + centroids = np.concatenate([leaf.centroids_ for leaf in self._get_leaves()]) + self.subcluster_centers_ = centroids + self._n_features_out = self.subcluster_centers_.shape[0] + + self._global_clustering(X) + return self + + def _get_leaves(self): + """ + Retrieve the leaves of the CF Node. + + Returns + ------- + leaves : list of shape (n_leaves,) + List of the leaf nodes. + """ + leaf_ptr = self.dummy_leaf_.next_leaf_ + leaves = [] + while leaf_ptr is not None: + leaves.append(leaf_ptr) + leaf_ptr = leaf_ptr.next_leaf_ + return leaves + + def partial_fit(self, X=None, y=None): + """ + Online learning. Prevents rebuilding of CFTree from scratch. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), \ + default=None + Input data. If X is not provided, only the global clustering + step is done. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self + Fitted estimator. + """ + self._validate_params() + + if X is None: + # Perform just the final global clustering step. + self._global_clustering() + return self + else: + return self._fit(X, partial=True) + + def _check_fit(self, X): + check_is_fitted(self) + + if ( + hasattr(self, "subcluster_centers_") + and X.shape[1] != self.subcluster_centers_.shape[1] + ): + raise ValueError( + "Training data and predicted data do not have same number of features." + ) + + def predict(self, X): + """ + Predict data using the ``centroids_`` of subclusters. + + Avoid computation of the row norms of X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + Returns + ------- + labels : ndarray of shape(n_samples,) + Labelled data. + """ + check_is_fitted(self) + X = self._validate_data(X, accept_sparse="csr", reset=False) + return self._predict(X) + + def _predict(self, X): + """Predict data using the ``centroids_`` of subclusters.""" + kwargs = {"Y_norm_squared": self._subcluster_norms} + + with config_context(assume_finite=True): + argmin = pairwise_distances_argmin( + X, self.subcluster_centers_, metric_kwargs=kwargs + ) + return self.subcluster_labels_[argmin] + + def transform(self, X): + """ + Transform X into subcluster centroids dimension. + + Each dimension represents the distance from the sample point to each + cluster centroid. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + Returns + ------- + X_trans : {array-like, sparse matrix} of shape (n_samples, n_clusters) + Transformed data. + """ + check_is_fitted(self) + X = self._validate_data(X, accept_sparse="csr", reset=False) + with config_context(assume_finite=True): + return euclidean_distances(X, self.subcluster_centers_) + + def _global_clustering(self, X=None): + """ + Global clustering for the subclusters obtained after fitting + """ + clusterer = self.n_clusters + centroids = self.subcluster_centers_ + compute_labels = (X is not None) and self.compute_labels + + # Preprocessing for the global clustering. + not_enough_centroids = False + if isinstance(clusterer, Integral): + clusterer = AgglomerativeClustering(n_clusters=self.n_clusters) + # There is no need to perform the global clustering step. + if len(centroids) < self.n_clusters: + not_enough_centroids = True + + # To use in predict to avoid recalculation. + self._subcluster_norms = row_norms(self.subcluster_centers_, squared=True) + + if clusterer is None or not_enough_centroids: + self.subcluster_labels_ = np.arange(len(centroids)) + if not_enough_centroids: + warnings.warn( + "Number of subclusters found (%d) by BIRCH is less " + "than (%d). Decrease the threshold." + % (len(centroids), self.n_clusters), + ConvergenceWarning, + ) + else: + # The global clustering step that clusters the subclusters of + # the leaves. It assumes the centroids of the subclusters as + # samples and finds the final centroids. + self.subcluster_labels_ = clusterer.fit_predict(self.subcluster_centers_) + + if compute_labels: + self.labels_ = self._predict(X) + + def _more_tags(self): + return {"preserves_dtype": [np.float64, np.float32]} diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_bisect_k_means.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_bisect_k_means.py new file mode 100644 index 0000000000000000000000000000000000000000..b860596c03540be27e5930bce79e6fabf369de53 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_bisect_k_means.py @@ -0,0 +1,523 @@ +"""Bisecting K-means clustering.""" +# Author: Michal Krawczyk + +import warnings + +import numpy as np +import scipy.sparse as sp + +from ._kmeans import _BaseKMeans +from ._kmeans import _kmeans_single_elkan +from ._kmeans import _kmeans_single_lloyd +from ._kmeans import _labels_inertia_threadpool_limit +from ._k_means_common import _inertia_dense +from ._k_means_common import _inertia_sparse +from ..utils.extmath import row_norms +from ..utils._openmp_helpers import _openmp_effective_n_threads +from ..utils.validation import check_is_fitted +from ..utils.validation import _check_sample_weight +from ..utils.validation import check_random_state +from ..utils._param_validation import StrOptions + + +class _BisectingTree: + """Tree structure representing the hierarchical clusters of BisectingKMeans.""" + + def __init__(self, center, indices, score): + """Create a new cluster node in the tree. + + The node holds the center of this cluster and the indices of the data points + that belong to it. + """ + self.center = center + self.indices = indices + self.score = score + + self.left = None + self.right = None + + def split(self, labels, centers, scores): + """Split the cluster node into two subclusters.""" + self.left = _BisectingTree( + indices=self.indices[labels == 0], center=centers[0], score=scores[0] + ) + self.right = _BisectingTree( + indices=self.indices[labels == 1], center=centers[1], score=scores[1] + ) + + # reset the indices attribute to save memory + self.indices = None + + def get_cluster_to_bisect(self): + """Return the cluster node to bisect next. + + It's based on the score of the cluster, which can be either the number of + data points assigned to that cluster or the inertia of that cluster + (see `bisecting_strategy` for details). + """ + max_score = None + + for cluster_leaf in self.iter_leaves(): + if max_score is None or cluster_leaf.score > max_score: + max_score = cluster_leaf.score + best_cluster_leaf = cluster_leaf + + return best_cluster_leaf + + def iter_leaves(self): + """Iterate over all the cluster leaves in the tree.""" + if self.left is None: + yield self + else: + yield from self.left.iter_leaves() + yield from self.right.iter_leaves() + + +class BisectingKMeans(_BaseKMeans): + """Bisecting K-Means clustering. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + n_clusters : int, default=8 + The number of clusters to form as well as the number of + centroids to generate. + + init : {'k-means++', 'random'} or callable, default='random' + Method for initialization: + + 'k-means++' : selects initial cluster centers for k-mean + clustering in a smart way to speed up convergence. See section + Notes in k_init for more details. + + 'random': choose `n_clusters` observations (rows) at random from data + for the initial centroids. + + If a callable is passed, it should take arguments X, n_clusters and a + random state and return an initialization. + + n_init : int, default=1 + Number of time the inner k-means algorithm will be run with different + centroid seeds in each bisection. + That will result producing for each bisection best output of n_init + consecutive runs in terms of inertia. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization + in inner K-Means. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + max_iter : int, default=300 + Maximum number of iterations of the inner k-means algorithm at each + bisection. + + verbose : int, default=0 + Verbosity mode. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. Used in inner k-means algorithm at each bisection to pick + best possible clusters. + + copy_x : bool, default=True + When pre-computing distances it is more numerically accurate to center + the data first. If copy_x is True (default), then the original data is + not modified. If False, the original data is modified, and put back + before the function returns, but small numerical differences may be + introduced by subtracting and then adding the data mean. Note that if + the original data is not C-contiguous, a copy will be made even if + copy_x is False. If the original data is sparse, but not in CSR format, + a copy will be made even if copy_x is False. + + algorithm : {"lloyd", "elkan"}, default="lloyd" + Inner K-means algorithm used in bisection. + The classical EM-style algorithm is `"lloyd"`. + The `"elkan"` variation can be more efficient on some datasets with + well-defined clusters, by using the triangle inequality. However it's + more memory intensive due to the allocation of an extra array of shape + `(n_samples, n_clusters)`. + + bisecting_strategy : {"biggest_inertia", "largest_cluster"},\ + default="biggest_inertia" + Defines how bisection should be performed: + + - "biggest_inertia" means that BisectingKMeans will always check + all calculated cluster for cluster with biggest SSE + (Sum of squared errors) and bisect it. This approach concentrates on + precision, but may be costly in terms of execution time (especially for + larger amount of data points). + + - "largest_cluster" - BisectingKMeans will always split cluster with + largest amount of points assigned to it from all clusters + previously calculated. That should work faster than picking by SSE + ('biggest_inertia') and may produce similar results in most cases. + + Attributes + ---------- + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. If the algorithm stops before fully + converging (see ``tol`` and ``max_iter``), these will not be + consistent with ``labels_``. + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + inertia_ : float + Sum of squared distances of samples to their closest cluster center, + weighted by the sample weights if provided. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + See Also + -------- + KMeans : Original implementation of K-Means algorithm. + + Notes + ----- + It might be inefficient when n_cluster is less than 3, due to unnecessary + calculations for that case. + + Examples + -------- + >>> from sklearn.cluster import BisectingKMeans + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [10, 2], [10, 4], [10, 0], + ... [10, 6], [10, 8], [10, 10]]) + >>> bisect_means = BisectingKMeans(n_clusters=3, random_state=0).fit(X) + >>> bisect_means.labels_ + array([2, 2, 2, 0, 0, 0, 1, 1, 1], dtype=int32) + >>> bisect_means.predict([[0, 0], [12, 3]]) + array([2, 0], dtype=int32) + >>> bisect_means.cluster_centers_ + array([[10., 2.], + [10., 8.], + [ 1., 2.]]) + """ + + _parameter_constraints: dict = { + **_BaseKMeans._parameter_constraints, + "init": [StrOptions({"k-means++", "random"}), callable], + "copy_x": ["boolean"], + "algorithm": [StrOptions({"lloyd", "elkan"})], + "bisecting_strategy": [StrOptions({"biggest_inertia", "largest_cluster"})], + } + + def __init__( + self, + n_clusters=8, + *, + init="random", + n_init=1, + random_state=None, + max_iter=300, + verbose=0, + tol=1e-4, + copy_x=True, + algorithm="lloyd", + bisecting_strategy="biggest_inertia", + ): + + super().__init__( + n_clusters=n_clusters, + init=init, + max_iter=max_iter, + verbose=verbose, + random_state=random_state, + tol=tol, + n_init=n_init, + ) + + self.copy_x = copy_x + self.algorithm = algorithm + self.bisecting_strategy = bisecting_strategy + + def _warn_mkl_vcomp(self, n_active_threads): + """Warn when vcomp and mkl are both present""" + warnings.warn( + "BisectingKMeans is known to have a memory leak on Windows " + "with MKL, when there are less chunks than available " + "threads. You can avoid it by setting the environment" + f" variable OMP_NUM_THREADS={n_active_threads}." + ) + + def _inertia_per_cluster(self, X, centers, labels, sample_weight): + """Calculate the sum of squared errors (inertia) per cluster. + + Parameters + ---------- + X : {ndarray, csr_matrix} of shape (n_samples, n_features) + The input samples. + + centers : ndarray of shape (n_clusters, n_features) + The cluster centers. + + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + Returns + ------- + inertia_per_cluster : ndarray of shape (n_clusters,) + Sum of squared errors (inertia) for each cluster. + """ + _inertia = _inertia_sparse if sp.issparse(X) else _inertia_dense + + inertia_per_cluster = np.empty(centers.shape[1]) + for label in range(centers.shape[0]): + inertia_per_cluster[label] = _inertia( + X, sample_weight, centers, labels, self._n_threads, single_label=label + ) + + return inertia_per_cluster + + def _bisect(self, X, x_squared_norms, sample_weight, cluster_to_bisect): + """Split a cluster into 2 subsclusters. + + Parameters + ---------- + X : {ndarray, csr_matrix} of shape (n_samples, n_features) + Training instances to cluster. + + x_squared_norms : ndarray of shape (n_samples,) + Squared euclidean norm of each data point. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + cluster_to_bisect : _BisectingTree node object + The cluster node to split. + """ + X = X[cluster_to_bisect.indices] + x_squared_norms = x_squared_norms[cluster_to_bisect.indices] + sample_weight = sample_weight[cluster_to_bisect.indices] + + best_inertia = None + + # Split samples in X into 2 clusters. + # Repeating `n_init` times to obtain best clusters + for _ in range(self.n_init): + centers_init = self._init_centroids( + X, x_squared_norms, self.init, self._random_state, n_centroids=2 + ) + + labels, inertia, centers, _ = self._kmeans_single( + X, + sample_weight, + centers_init, + max_iter=self.max_iter, + verbose=self.verbose, + tol=self.tol, + n_threads=self._n_threads, + ) + + # allow small tolerance on the inertia to accommodate for + # non-deterministic rounding errors due to parallel computation + if best_inertia is None or inertia < best_inertia * (1 - 1e-6): + best_labels = labels + best_centers = centers + best_inertia = inertia + + if self.verbose: + print(f"New centroids from bisection: {best_centers}") + + if self.bisecting_strategy == "biggest_inertia": + scores = self._inertia_per_cluster( + X, best_centers, best_labels, sample_weight + ) + else: # bisecting_strategy == "largest_cluster" + # Using minlength to make sure that we have the counts for both labels even + # if all samples are labelled 0. + scores = np.bincount(best_labels, minlength=2) + + cluster_to_bisect.split(best_labels, best_centers, scores) + + def fit(self, X, y=None, sample_weight=None): + """Compute bisecting k-means clustering. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + + Training instances to cluster. + + .. note:: The data will be converted to C ordering, + which will cause a memory copy + if the given data is not C-contiguous. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + self + Fitted estimator. + """ + self._validate_params() + + X = self._validate_data( + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + copy=self.copy_x, + accept_large_sparse=False, + ) + + self._check_params_vs_input(X) + + self._random_state = check_random_state(self.random_state) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self._n_threads = _openmp_effective_n_threads() + + if self.algorithm == "lloyd" or self.n_clusters == 1: + self._kmeans_single = _kmeans_single_lloyd + self._check_mkl_vcomp(X, X.shape[0]) + else: + self._kmeans_single = _kmeans_single_elkan + + # Subtract of mean of X for more accurate distance computations + if not sp.issparse(X): + self._X_mean = X.mean(axis=0) + X -= self._X_mean + + # Initialize the hierarchical clusters tree + self._bisecting_tree = _BisectingTree( + indices=np.arange(X.shape[0]), + center=X.mean(axis=0), + score=0, + ) + + x_squared_norms = row_norms(X, squared=True) + + for _ in range(self.n_clusters - 1): + # Chose cluster to bisect + cluster_to_bisect = self._bisecting_tree.get_cluster_to_bisect() + + # Split this cluster into 2 subclusters + self._bisect(X, x_squared_norms, sample_weight, cluster_to_bisect) + + # Aggregate final labels and centers from the bisecting tree + self.labels_ = np.full(X.shape[0], -1, dtype=np.int32) + self.cluster_centers_ = np.empty((self.n_clusters, X.shape[1]), dtype=X.dtype) + + for i, cluster_node in enumerate(self._bisecting_tree.iter_leaves()): + self.labels_[cluster_node.indices] = i + self.cluster_centers_[i] = cluster_node.center + cluster_node.label = i # label final clusters for future prediction + cluster_node.indices = None # release memory + + # Restore original data + if not sp.issparse(X): + X += self._X_mean + self.cluster_centers_ += self._X_mean + + _inertia = _inertia_sparse if sp.issparse(X) else _inertia_dense + self.inertia_ = _inertia( + X, sample_weight, self.cluster_centers_, self.labels_, self._n_threads + ) + + self._n_features_out = self.cluster_centers_.shape[0] + + return self + + def predict(self, X): + """Predict which cluster each sample in X belongs to. + + Prediction is made by going down the hierarchical tree + in searching of closest leaf cluster. + + In the vector quantization literature, `cluster_centers_` is called + the code book and each value returned by `predict` is the index of + the closest code in the code book. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to predict. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + x_squared_norms = row_norms(X, squared=True) + + # sample weights are unused but necessary in cython helpers + sample_weight = np.ones_like(x_squared_norms) + + labels = self._predict_recursive(X, sample_weight, self._bisecting_tree) + + return labels + + def _predict_recursive(self, X, sample_weight, cluster_node): + """Predict recursively by going down the hierarchical tree. + + Parameters + ---------- + X : {ndarray, csr_matrix} of shape (n_samples, n_features) + The data points, currently assigned to `cluster_node`, to predict between + the subclusters of this node. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + cluster_node : _BisectingTree node object + The cluster node of the hierarchical tree. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + if cluster_node.left is None: + # This cluster has no subcluster. Labels are just the label of the cluster. + return np.full(X.shape[0], cluster_node.label, dtype=np.int32) + + # Determine if data points belong to the left or right subcluster + centers = np.vstack((cluster_node.left.center, cluster_node.right.center)) + if hasattr(self, "_X_mean"): + centers += self._X_mean + + cluster_labels = _labels_inertia_threadpool_limit( + X, + sample_weight, + centers, + self._n_threads, + return_inertia=False, + ) + mask = cluster_labels == 0 + + # Compute the labels for each subset of the data points. + labels = np.full(X.shape[0], -1, dtype=np.int32) + + labels[mask] = self._predict_recursive( + X[mask], sample_weight[mask], cluster_node.left + ) + + labels[~mask] = self._predict_recursive( + X[~mask], sample_weight[~mask], cluster_node.right + ) + + return labels + + def _more_tags(self): + return {"preserves_dtype": [np.float64, np.float32]} diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_dbscan.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_dbscan.py new file mode 100644 index 0000000000000000000000000000000000000000..a1cd96263e056790483f27490b95b1facfd0f3ba --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_dbscan.py @@ -0,0 +1,450 @@ +""" +DBSCAN: Density-Based Spatial Clustering of Applications with Noise +""" + +# Author: Robert Layton +# Joel Nothman +# Lars Buitinck +# +# License: BSD 3 clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy import sparse + +from ..metrics.pairwise import _VALID_METRICS +from ..base import BaseEstimator, ClusterMixin +from ..utils.validation import _check_sample_weight +from ..utils._param_validation import Interval, StrOptions +from ..neighbors import NearestNeighbors +from ._dbscan_inner import dbscan_inner + + +def dbscan( + X, + eps=0.5, + *, + min_samples=5, + metric="minkowski", + metric_params=None, + algorithm="auto", + leaf_size=30, + p=2, + sample_weight=None, + n_jobs=None, +): + """Perform DBSCAN clustering from vector array or distance matrix. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse (CSR) matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + A feature array, or array of distances between samples if + ``metric='precomputed'``. + + eps : float, default=0.5 + The maximum distance between two samples for one to be considered + as in the neighborhood of the other. This is not a maximum bound + on the distances of points within a cluster. This is the most + important DBSCAN parameter to choose appropriately for your data set + and distance function. + + min_samples : int, default=5 + The number of samples (or total weight) in a neighborhood for a point + to be considered as a core point. This includes the point itself. + + metric : str or callable, default='minkowski' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If metric is "precomputed", X is assumed to be a distance matrix and + must be square during fit. + X may be a :term:`sparse graph `, + in which case only "nonzero" elements may be considered neighbors. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + .. versionadded:: 0.19 + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + The algorithm to be used by the NearestNeighbors module + to compute pointwise distances and find nearest neighbors. + See NearestNeighbors module documentation for details. + + leaf_size : int, default=30 + Leaf size passed to BallTree or cKDTree. This can affect the speed + of the construction and query, as well as the memory required + to store the tree. The optimal value depends + on the nature of the problem. + + p : float, default=2 + The power of the Minkowski metric to be used to calculate distance + between points. + + sample_weight : array-like of shape (n_samples,), default=None + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with negative + weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. ``None`` means + 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means + using all processors. See :term:`Glossary ` for more details. + If precomputed distance are used, parallel execution is not available + and thus n_jobs will have no effect. + + Returns + ------- + core_samples : ndarray of shape (n_core_samples,) + Indices of core samples. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. Noisy samples are given the label -1. + + See Also + -------- + DBSCAN : An estimator interface for this clustering algorithm. + OPTICS : A similar estimator interface clustering at multiple values of + eps. Our implementation is optimized for memory usage. + + Notes + ----- + For an example, see :ref:`examples/cluster/plot_dbscan.py + `. + + This implementation bulk-computes all neighborhood queries, which increases + the memory complexity to O(n.d) where d is the average number of neighbors, + while original DBSCAN had memory complexity O(n). It may attract a higher + memory complexity when querying these nearest neighborhoods, depending + on the ``algorithm``. + + One way to avoid the query complexity is to pre-compute sparse + neighborhoods in chunks using + :func:`NearestNeighbors.radius_neighbors_graph + ` with + ``mode='distance'``, then using ``metric='precomputed'`` here. + + Another way to reduce memory and computation time is to remove + (near-)duplicate points and use ``sample_weight`` instead. + + :func:`cluster.optics ` provides a similar + clustering with lower memory usage. + + References + ---------- + Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based + Algorithm for Discovering Clusters in Large Spatial Databases with Noise" + `_. + In: Proceedings of the 2nd International Conference on Knowledge Discovery + and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 + + Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). + :doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN." + <10.1145/3068335>` + ACM Transactions on Database Systems (TODS), 42(3), 19. + """ + + est = DBSCAN( + eps=eps, + min_samples=min_samples, + metric=metric, + metric_params=metric_params, + algorithm=algorithm, + leaf_size=leaf_size, + p=p, + n_jobs=n_jobs, + ) + est.fit(X, sample_weight=sample_weight) + return est.core_sample_indices_, est.labels_ + + +class DBSCAN(ClusterMixin, BaseEstimator): + """Perform DBSCAN clustering from vector array or distance matrix. + + DBSCAN - Density-Based Spatial Clustering of Applications with Noise. + Finds core samples of high density and expands clusters from them. + Good for data which contains clusters of similar density. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + eps : float, default=0.5 + The maximum distance between two samples for one to be considered + as in the neighborhood of the other. This is not a maximum bound + on the distances of points within a cluster. This is the most + important DBSCAN parameter to choose appropriately for your data set + and distance function. + + min_samples : int, default=5 + The number of samples (or total weight) in a neighborhood for a point + to be considered as a core point. This includes the point itself. + + metric : str, or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If metric is "precomputed", X is assumed to be a distance matrix and + must be square. X may be a :term:`sparse graph`, in which + case only "nonzero" elements may be considered neighbors for DBSCAN. + + .. versionadded:: 0.17 + metric *precomputed* to accept precomputed sparse matrix. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + .. versionadded:: 0.19 + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + The algorithm to be used by the NearestNeighbors module + to compute pointwise distances and find nearest neighbors. + See NearestNeighbors module documentation for details. + + leaf_size : int, default=30 + Leaf size passed to BallTree or cKDTree. This can affect the speed + of the construction and query, as well as the memory required + to store the tree. The optimal value depends + on the nature of the problem. + + p : float, default=None + The power of the Minkowski metric to be used to calculate distance + between points. If None, then ``p=2`` (equivalent to the Euclidean + distance). + + n_jobs : int, default=None + The number of parallel jobs to run. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + core_sample_indices_ : ndarray of shape (n_core_samples,) + Indices of core samples. + + components_ : ndarray of shape (n_core_samples, n_features) + Copy of each core sample found by training. + + labels_ : ndarray of shape (n_samples) + Cluster labels for each point in the dataset given to fit(). + Noisy samples are given the label -1. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + OPTICS : A similar clustering at multiple values of eps. Our implementation + is optimized for memory usage. + + Notes + ----- + For an example, see :ref:`examples/cluster/plot_dbscan.py + `. + + This implementation bulk-computes all neighborhood queries, which increases + the memory complexity to O(n.d) where d is the average number of neighbors, + while original DBSCAN had memory complexity O(n). It may attract a higher + memory complexity when querying these nearest neighborhoods, depending + on the ``algorithm``. + + One way to avoid the query complexity is to pre-compute sparse + neighborhoods in chunks using + :func:`NearestNeighbors.radius_neighbors_graph + ` with + ``mode='distance'``, then using ``metric='precomputed'`` here. + + Another way to reduce memory and computation time is to remove + (near-)duplicate points and use ``sample_weight`` instead. + + :class:`cluster.OPTICS` provides a similar clustering with lower memory + usage. + + References + ---------- + Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based + Algorithm for Discovering Clusters in Large Spatial Databases with Noise" + `_. + In: Proceedings of the 2nd International Conference on Knowledge Discovery + and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996 + + Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017). + :doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN." + <10.1145/3068335>` + ACM Transactions on Database Systems (TODS), 42(3), 19. + + Examples + -------- + >>> from sklearn.cluster import DBSCAN + >>> import numpy as np + >>> X = np.array([[1, 2], [2, 2], [2, 3], + ... [8, 7], [8, 8], [25, 80]]) + >>> clustering = DBSCAN(eps=3, min_samples=2).fit(X) + >>> clustering.labels_ + array([ 0, 0, 0, 1, 1, -1]) + >>> clustering + DBSCAN(eps=3, min_samples=2) + """ + + _parameter_constraints: dict = { + "eps": [Interval(Real, 0.0, None, closed="neither")], + "min_samples": [Interval(Integral, 1, None, closed="left")], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "metric_params": [dict, None], + "algorithm": [StrOptions({"auto", "ball_tree", "kd_tree", "brute"})], + "leaf_size": [Interval(Integral, 1, None, closed="left")], + "p": [Interval(Real, 0.0, None, closed="left"), None], + "n_jobs": [Integral, None], + } + + def __init__( + self, + eps=0.5, + *, + min_samples=5, + metric="euclidean", + metric_params=None, + algorithm="auto", + leaf_size=30, + p=None, + n_jobs=None, + ): + self.eps = eps + self.min_samples = min_samples + self.metric = metric + self.metric_params = metric_params + self.algorithm = algorithm + self.leaf_size = leaf_size + self.p = p + self.n_jobs = n_jobs + + def fit(self, X, y=None, sample_weight=None): + """Perform DBSCAN clustering from features, or distance matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. If a sparse matrix is provided, it will + be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with a + negative weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + + Returns + ------- + self : object + Returns a fitted instance of self. + """ + self._validate_params() + + X = self._validate_data(X, accept_sparse="csr") + + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X) + + # Calculate neighborhood for all samples. This leaves the original + # point in, which needs to be considered later (i.e. point i is in the + # neighborhood of point i. While True, its useless information) + if self.metric == "precomputed" and sparse.issparse(X): + # set the diagonal to explicit values, as a point is its own + # neighbor + with warnings.catch_warnings(): + warnings.simplefilter("ignore", sparse.SparseEfficiencyWarning) + X.setdiag(X.diagonal()) # XXX: modifies X's internals in-place + + neighbors_model = NearestNeighbors( + radius=self.eps, + algorithm=self.algorithm, + leaf_size=self.leaf_size, + metric=self.metric, + metric_params=self.metric_params, + p=self.p, + n_jobs=self.n_jobs, + ) + neighbors_model.fit(X) + # This has worst case O(n^2) memory complexity + neighborhoods = neighbors_model.radius_neighbors(X, return_distance=False) + + if sample_weight is None: + n_neighbors = np.array([len(neighbors) for neighbors in neighborhoods]) + else: + n_neighbors = np.array( + [np.sum(sample_weight[neighbors]) for neighbors in neighborhoods] + ) + + # Initially, all samples are noise. + labels = np.full(X.shape[0], -1, dtype=np.intp) + + # A list of all core samples found. + core_samples = np.asarray(n_neighbors >= self.min_samples, dtype=np.uint8) + dbscan_inner(core_samples, neighborhoods, labels) + + self.core_sample_indices_ = np.where(core_samples)[0] + self.labels_ = labels + + if len(self.core_sample_indices_): + # fix for scipy sparse indexing issue + self.components_ = X[self.core_sample_indices_].copy() + else: + # no core samples + self.components_ = np.empty((0, X.shape[1])) + return self + + def fit_predict(self, X, y=None, sample_weight=None): + """Compute clusters from a data or distance matrix and predict labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. If a sparse matrix is provided, it will + be converted into a sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + Weight of each sample, such that a sample with a weight of at least + ``min_samples`` is by itself a core sample; a sample with a + negative weight may inhibit its eps-neighbor from being core. + Note that weights are absolute, and default to 1. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. Noisy samples are given the label -1. + """ + self.fit(X, sample_weight=sample_weight) + return self.labels_ + + def _more_tags(self): + return {"pairwise": self.metric == "precomputed"} diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py new file mode 100644 index 0000000000000000000000000000000000000000..457a83dd41e71076e53d1d2a296c99edb2acf9ff --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py @@ -0,0 +1,75 @@ +""" +Feature agglomeration. Base classes and functions for performing feature +agglomeration. +""" +# Author: V. Michel, A. Gramfort +# License: BSD 3 clause + +import numpy as np + +from ..base import TransformerMixin +from ..utils.validation import check_is_fitted +from scipy.sparse import issparse + +############################################################################### +# Mixin class for feature agglomeration. + + +class AgglomerationTransform(TransformerMixin): + """ + A class for feature agglomeration via the transform interface. + """ + + def transform(self, X): + """ + Transform a new matrix using the built clustering. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + A M by N array of M observations in N dimensions or a length + M array of M one-dimensional observations. + + Returns + ------- + Y : ndarray of shape (n_samples, n_clusters) or (n_clusters,) + The pooled values for each feature cluster. + """ + check_is_fitted(self) + + X = self._validate_data(X, reset=False) + if self.pooling_func == np.mean and not issparse(X): + size = np.bincount(self.labels_) + n_samples = X.shape[0] + # a fast way to compute the mean of grouped features + nX = np.array( + [np.bincount(self.labels_, X[i, :]) / size for i in range(n_samples)] + ) + else: + nX = [ + self.pooling_func(X[:, self.labels_ == l], axis=1) + for l in np.unique(self.labels_) + ] + nX = np.array(nX).T + return nX + + def inverse_transform(self, Xred): + """ + Inverse the transformation and return a vector of size `n_features`. + + Parameters + ---------- + Xred : array-like of shape (n_samples, n_clusters) or (n_clusters,) + The values to be assigned to each cluster of samples. + + Returns + ------- + X : ndarray of shape (n_samples, n_features) or (n_features,) + A vector of size `n_samples` with the values of `Xred` assigned to + each of the cluster of samples. + """ + check_is_fitted(self) + + unil, inverse = np.unique(self.labels_, return_inverse=True) + return Xred[..., inverse] diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..95b2771db5be5097aeeef2981ffb36a8eee27576 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbab2dfb377c76cc63b49b08c32f7f7c3848f951b42019bc08cd41b58f02d397 +size 327769 diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd new file mode 100644 index 0000000000000000000000000000000000000000..efbf4ed3246e36002a190ca6939eca6e8153e05d --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd @@ -0,0 +1,19 @@ +from cython cimport floating + + +cdef floating _euclidean_dense_dense(floating*, floating*, int, bint) nogil + +cdef floating _euclidean_sparse_dense(floating[::1], int[::1], floating[::1], + floating, bint) nogil + +cpdef void _relocate_empty_clusters_dense( + floating[:, ::1], floating[::1], floating[:, ::1], + floating[:, ::1], floating[::1], int[::1]) + +cpdef void _relocate_empty_clusters_sparse( + floating[::1], int[::1], int[::1], floating[::1], floating[:, ::1], + floating[:, ::1], floating[::1], int[::1]) + +cdef void _average_centers(floating[:, ::1], floating[::1]) + +cdef void _center_shift(floating[:, ::1], floating[:, ::1], floating[::1]) diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7754cecb168c9e41a311100ff4c8c33c57d5e90d --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edfd181e6be2fe2da302115e3d5729c53f06d0a7d66d42a19b5e21f87d37ea6d +size 431033 diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_lloyd.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_lloyd.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3f625a9b13122541b6e9c953dafccc6656113b0e --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_lloyd.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c62876b7992cf290309fa48abb64b2ac7c01eaa80426ac9075c96cd5499a2eb8 +size 344177 diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..24f8bf7e920e6ca0ca5a6ca17542369ca30ff216 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02427d73dd89676ee2cc95481e05e33b647a6aafeda54130d205c4560e762d5b +size 274121 diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_kmeans.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_kmeans.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0a161cc1e164d52022e53a3e56e6f7b8adb978 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_kmeans.py @@ -0,0 +1,2247 @@ +"""K-means clustering.""" + +# Authors: Gael Varoquaux +# Thomas Rueckstiess +# James Bergstra +# Jan Schlueter +# Nelle Varoquaux +# Peter Prettenhofer +# Olivier Grisel +# Mathieu Blondel +# Robert Layton +# License: BSD 3 clause + +from abc import ABC, abstractmethod +from numbers import Integral, Real +import warnings + +import numpy as np +import scipy.sparse as sp + +from ..base import ( + BaseEstimator, + ClusterMixin, + TransformerMixin, + ClassNamePrefixFeaturesOutMixin, +) +from ..metrics.pairwise import euclidean_distances +from ..metrics.pairwise import _euclidean_distances +from ..utils.extmath import row_norms, stable_cumsum +from ..utils.fixes import threadpool_limits +from ..utils.fixes import threadpool_info +from ..utils.sparsefuncs_fast import assign_rows_csr +from ..utils.sparsefuncs import mean_variance_axis +from ..utils import check_array +from ..utils import check_random_state +from ..utils.validation import check_is_fitted, _check_sample_weight +from ..utils.validation import _is_arraylike_not_scalar +from ..utils._param_validation import Hidden +from ..utils._param_validation import Interval +from ..utils._param_validation import StrOptions +from ..utils._param_validation import validate_params +from ..utils._openmp_helpers import _openmp_effective_n_threads +from ..utils._readonly_array_wrapper import ReadonlyArrayWrapper +from ..exceptions import ConvergenceWarning +from ._k_means_common import CHUNK_SIZE +from ._k_means_common import _inertia_dense +from ._k_means_common import _inertia_sparse +from ._k_means_common import _is_same_clustering +from ._k_means_minibatch import _minibatch_update_dense +from ._k_means_minibatch import _minibatch_update_sparse +from ._k_means_lloyd import lloyd_iter_chunked_dense +from ._k_means_lloyd import lloyd_iter_chunked_sparse +from ._k_means_elkan import init_bounds_dense +from ._k_means_elkan import init_bounds_sparse +from ._k_means_elkan import elkan_iter_chunked_dense +from ._k_means_elkan import elkan_iter_chunked_sparse + + +############################################################################### +# Initialization heuristic + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "x_squared_norms": ["array-like", None], + "random_state": ["random_state"], + "n_local_trials": [Interval(Integral, 1, None, closed="left"), None], + } +) +def kmeans_plusplus( + X, n_clusters, *, x_squared_norms=None, random_state=None, n_local_trials=None +): + """Init n_clusters seeds according to k-means++. + + .. versionadded:: 0.24 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to pick seeds from. + + n_clusters : int + The number of centroids to initialize. + + x_squared_norms : array-like of shape (n_samples,), default=None + Squared Euclidean norm of each data point. + + random_state : int or RandomState instance, default=None + Determines random number generation for centroid initialization. Pass + an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + n_local_trials : int, default=None + The number of seeding trials for each center (except the first), + of which the one reducing inertia the most is greedily chosen. + Set to None to make the number of trials depend logarithmically + on the number of seeds (2+log(k)) which is the recommended setting. + Setting to 1 disables the greedy cluster selection and recovers the + vanilla k-means++ algorithm which was empirically shown to work less + well than its greedy variant. + + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + The initial centers for k-means. + + indices : ndarray of shape (n_clusters,) + The index location of the chosen centers in the data array X. For a + given index and center, X[index] = center. + + Notes + ----- + Selects initial cluster centers for k-mean clustering in a smart way + to speed up convergence. see: Arthur, D. and Vassilvitskii, S. + "k-means++: the advantages of careful seeding". ACM-SIAM symposium + on Discrete algorithms. 2007 + + Examples + -------- + + >>> from sklearn.cluster import kmeans_plusplus + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [10, 2], [10, 4], [10, 0]]) + >>> centers, indices = kmeans_plusplus(X, n_clusters=2, random_state=0) + >>> centers + array([[10, 4], + [ 1, 0]]) + >>> indices + array([4, 2]) + """ + # Check data + check_array(X, accept_sparse="csr", dtype=[np.float64, np.float32]) + + if X.shape[0] < n_clusters: + raise ValueError( + f"n_samples={X.shape[0]} should be >= n_clusters={n_clusters}." + ) + + # Check parameters + if x_squared_norms is None: + x_squared_norms = row_norms(X, squared=True) + else: + x_squared_norms = check_array(x_squared_norms, dtype=X.dtype, ensure_2d=False) + + if x_squared_norms.shape[0] != X.shape[0]: + raise ValueError( + f"The length of x_squared_norms {x_squared_norms.shape[0]} should " + f"be equal to the length of n_samples {X.shape[0]}." + ) + + random_state = check_random_state(random_state) + + # Call private k-means++ + centers, indices = _kmeans_plusplus( + X, n_clusters, x_squared_norms, random_state, n_local_trials + ) + + return centers, indices + + +def _kmeans_plusplus(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): + """Computational component for initialization of n_clusters by + k-means++. Prior validation of data is assumed. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The data to pick seeds for. + + n_clusters : int + The number of seeds to choose. + + x_squared_norms : ndarray of shape (n_samples,) + Squared Euclidean norm of each data point. + + random_state : RandomState instance + The generator used to initialize the centers. + See :term:`Glossary `. + + n_local_trials : int, default=None + The number of seeding trials for each center (except the first), + of which the one reducing inertia the most is greedily chosen. + Set to None to make the number of trials depend logarithmically + on the number of seeds (2+log(k)); this is the default. + + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + The initial centers for k-means. + + indices : ndarray of shape (n_clusters,) + The index location of the chosen centers in the data array X. For a + given index and center, X[index] = center. + """ + n_samples, n_features = X.shape + + centers = np.empty((n_clusters, n_features), dtype=X.dtype) + + # Set the number of local seeding trials if none is given + if n_local_trials is None: + # This is what Arthur/Vassilvitskii tried, but did not report + # specific results for other than mentioning in the conclusion + # that it helped. + n_local_trials = 2 + int(np.log(n_clusters)) + + # Pick first center randomly and track index of point + center_id = random_state.randint(n_samples) + indices = np.full(n_clusters, -1, dtype=int) + if sp.issparse(X): + centers[0] = X[center_id].toarray() + else: + centers[0] = X[center_id] + indices[0] = center_id + + # Initialize list of closest distances and calculate current potential + closest_dist_sq = _euclidean_distances( + centers[0, np.newaxis], X, Y_norm_squared=x_squared_norms, squared=True + ) + current_pot = closest_dist_sq.sum() + + # Pick the remaining n_clusters-1 points + for c in range(1, n_clusters): + # Choose center candidates by sampling with probability proportional + # to the squared distance to the closest existing center + rand_vals = random_state.uniform(size=n_local_trials) * current_pot + candidate_ids = np.searchsorted(stable_cumsum(closest_dist_sq), rand_vals) + # XXX: numerical imprecision can result in a candidate_id out of range + np.clip(candidate_ids, None, closest_dist_sq.size - 1, out=candidate_ids) + + # Compute distances to center candidates + distance_to_candidates = _euclidean_distances( + X[candidate_ids], X, Y_norm_squared=x_squared_norms, squared=True + ) + + # update closest distances squared and potential for each candidate + np.minimum(closest_dist_sq, distance_to_candidates, out=distance_to_candidates) + candidates_pot = distance_to_candidates.sum(axis=1) + + # Decide which candidate is the best + best_candidate = np.argmin(candidates_pot) + current_pot = candidates_pot[best_candidate] + closest_dist_sq = distance_to_candidates[best_candidate] + best_candidate = candidate_ids[best_candidate] + + # Permanently add best center candidate found in local tries + if sp.issparse(X): + centers[c] = X[best_candidate].toarray() + else: + centers[c] = X[best_candidate] + indices[c] = best_candidate + + return centers, indices + + +############################################################################### +# K-means batch estimation by EM (expectation maximization) + + +def _tolerance(X, tol): + """Return a tolerance which is dependent on the dataset.""" + if tol == 0: + return 0 + if sp.issparse(X): + variances = mean_variance_axis(X, axis=0)[1] + else: + variances = np.var(X, axis=0) + return np.mean(variances) * tol + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "sample_weight": ["array-like", None], + "init": [StrOptions({"k-means++", "random"}), callable, "array-like"], + "n_init": [ + StrOptions({"auto"}), + Hidden(StrOptions({"warn"})), + Interval(Integral, 1, None, closed="left"), + ], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "verbose": [Interval(Integral, 0, None, closed="left"), bool], + "tol": [Interval(Real, 0, None, closed="left")], + "random_state": ["random_state"], + "copy_x": [bool], + "algorithm": [ + StrOptions({"lloyd", "elkan", "auto", "full"}, deprecated={"auto", "full"}) + ], + "return_n_iter": [bool], + } +) +def k_means( + X, + n_clusters, + *, + sample_weight=None, + init="k-means++", + n_init="warn", + max_iter=300, + verbose=False, + tol=1e-4, + random_state=None, + copy_x=True, + algorithm="lloyd", + return_n_iter=False, +): + """Perform K-means clustering algorithm. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The observations to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory copy + if the given data is not C-contiguous. + + n_clusters : int + The number of clusters to form as well as the number of + centroids to generate. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in `X`. If `None`, all observations + are assigned equal weight. + + init : {'k-means++', 'random'}, callable or array-like of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization: + + - `'k-means++'` : selects initial cluster centers for k-mean + clustering in a smart way to speed up convergence. See section + Notes in k_init for more details. + - `'random'`: choose `n_clusters` observations (rows) at random from data + for the initial centroids. + - If an array is passed, it should be of shape `(n_clusters, n_features)` + and gives the initial centers. + - If a callable is passed, it should take arguments `X`, `n_clusters` and a + random state and return an initialization. + + n_init : 'auto' or int, default=10 + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of + n_init consecutive runs in terms of inertia. + + When `n_init='auto'`, the number of runs depends on the value of init: + 10 if using `init='random'`, 1 if using `init='k-means++'`. + + .. versionadded:: 1.2 + Added 'auto' option for `n_init`. + + .. versionchanged:: 1.4 + Default value for `n_init` will change from 10 to `'auto'` in version 1.4. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm to run. + + verbose : bool, default=False + Verbosity mode. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization. Use + an int to make the randomness deterministic. + See :term:`Glossary `. + + copy_x : bool, default=True + When pre-computing distances it is more numerically accurate to center + the data first. If `copy_x` is True (default), then the original data is + not modified. If False, the original data is modified, and put back + before the function returns, but small numerical differences may be + introduced by subtracting and then adding the data mean. Note that if + the original data is not C-contiguous, a copy will be made even if + `copy_x` is False. If the original data is sparse, but not in CSR format, + a copy will be made even if `copy_x` is False. + + algorithm : {"lloyd", "elkan", "auto", "full"}, default="lloyd" + K-means algorithm to use. The classical EM-style algorithm is `"lloyd"`. + The `"elkan"` variation can be more efficient on some datasets with + well-defined clusters, by using the triangle inequality. However it's + more memory intensive due to the allocation of an extra array of shape + `(n_samples, n_clusters)`. + + `"auto"` and `"full"` are deprecated and they will be removed in + Scikit-Learn 1.3. They are both aliases for `"lloyd"`. + + .. versionchanged:: 0.18 + Added Elkan algorithm + + .. versionchanged:: 1.1 + Renamed "full" to "lloyd", and deprecated "auto" and "full". + Changed "auto" to use "lloyd" instead of "elkan". + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + Returns + ------- + centroid : ndarray of shape (n_clusters, n_features) + Centroids found at the last iteration of k-means. + + label : ndarray of shape (n_samples,) + The `label[i]` is the code or index of the centroid the + i'th observation is closest to. + + inertia : float + The final value of the inertia criterion (sum of squared distances to + the closest centroid for all observations in the training set). + + best_n_iter : int + Number of iterations corresponding to the best results. + Returned only if `return_n_iter` is set to True. + """ + est = KMeans( + n_clusters=n_clusters, + init=init, + n_init=n_init, + max_iter=max_iter, + verbose=verbose, + tol=tol, + random_state=random_state, + copy_x=copy_x, + algorithm=algorithm, + ).fit(X, sample_weight=sample_weight) + if return_n_iter: + return est.cluster_centers_, est.labels_, est.inertia_, est.n_iter_ + else: + return est.cluster_centers_, est.labels_, est.inertia_ + + +def _kmeans_single_elkan( + X, + sample_weight, + centers_init, + max_iter=300, + verbose=False, + tol=1e-4, + n_threads=1, +): + """A single run of k-means elkan, assumes preparation completed prior. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The observations to cluster. If sparse matrix, must be in CSR format. + + sample_weight : array-like of shape (n_samples,) + The weights for each observation in X. + + centers_init : ndarray of shape (n_clusters, n_features) + The initial centers. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm to run. + + verbose : bool, default=False + Verbosity mode. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + It's not advised to set `tol=0` since convergence might never be + declared due to rounding errors. Use a very small number instead. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. Parallelism is + sample-wise on the main cython loop which assigns each sample to its + closest center. + + Returns + ------- + centroid : ndarray of shape (n_clusters, n_features) + Centroids found at the last iteration of k-means. + + label : ndarray of shape (n_samples,) + label[i] is the code or index of the centroid the + i'th observation is closest to. + + inertia : float + The final value of the inertia criterion (sum of squared distances to + the closest centroid for all observations in the training set). + + n_iter : int + Number of iterations run. + """ + n_samples = X.shape[0] + n_clusters = centers_init.shape[0] + + # Buffers to avoid new allocations at each iteration. + centers = centers_init + centers_new = np.zeros_like(centers) + weight_in_clusters = np.zeros(n_clusters, dtype=X.dtype) + labels = np.full(n_samples, -1, dtype=np.int32) + labels_old = labels.copy() + center_half_distances = euclidean_distances(centers) / 2 + distance_next_center = np.partition( + np.asarray(center_half_distances), kth=1, axis=0 + )[1] + upper_bounds = np.zeros(n_samples, dtype=X.dtype) + lower_bounds = np.zeros((n_samples, n_clusters), dtype=X.dtype) + center_shift = np.zeros(n_clusters, dtype=X.dtype) + + if sp.issparse(X): + init_bounds = init_bounds_sparse + elkan_iter = elkan_iter_chunked_sparse + _inertia = _inertia_sparse + else: + init_bounds = init_bounds_dense + elkan_iter = elkan_iter_chunked_dense + _inertia = _inertia_dense + + init_bounds( + X, + centers, + center_half_distances, + labels, + upper_bounds, + lower_bounds, + n_threads=n_threads, + ) + + strict_convergence = False + + for i in range(max_iter): + elkan_iter( + X, + sample_weight, + centers, + centers_new, + weight_in_clusters, + center_half_distances, + distance_next_center, + upper_bounds, + lower_bounds, + labels, + center_shift, + n_threads, + ) + + # compute new pairwise distances between centers and closest other + # center of each center for next iterations + center_half_distances = euclidean_distances(centers_new) / 2 + distance_next_center = np.partition( + np.asarray(center_half_distances), kth=1, axis=0 + )[1] + + if verbose: + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + print(f"Iteration {i}, inertia {inertia}") + + centers, centers_new = centers_new, centers + + if np.array_equal(labels, labels_old): + # First check the labels for strict convergence. + if verbose: + print(f"Converged at iteration {i}: strict convergence.") + strict_convergence = True + break + else: + # No strict convergence, check for tol based convergence. + center_shift_tot = (center_shift**2).sum() + if center_shift_tot <= tol: + if verbose: + print( + f"Converged at iteration {i}: center shift " + f"{center_shift_tot} within tolerance {tol}." + ) + break + + labels_old[:] = labels + + if not strict_convergence: + # rerun E-step so that predicted labels match cluster centers + elkan_iter( + X, + sample_weight, + centers, + centers, + weight_in_clusters, + center_half_distances, + distance_next_center, + upper_bounds, + lower_bounds, + labels, + center_shift, + n_threads, + update_centers=False, + ) + + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + + return labels, inertia, centers, i + 1 + + +def _kmeans_single_lloyd( + X, + sample_weight, + centers_init, + max_iter=300, + verbose=False, + tol=1e-4, + n_threads=1, +): + """A single run of k-means lloyd, assumes preparation completed prior. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The observations to cluster. If sparse matrix, must be in CSR format. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + centers_init : ndarray of shape (n_clusters, n_features) + The initial centers. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm to run. + + verbose : bool, default=False + Verbosity mode + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + It's not advised to set `tol=0` since convergence might never be + declared due to rounding errors. Use a very small number instead. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. Parallelism is + sample-wise on the main cython loop which assigns each sample to its + closest center. + + Returns + ------- + centroid : ndarray of shape (n_clusters, n_features) + Centroids found at the last iteration of k-means. + + label : ndarray of shape (n_samples,) + label[i] is the code or index of the centroid the + i'th observation is closest to. + + inertia : float + The final value of the inertia criterion (sum of squared distances to + the closest centroid for all observations in the training set). + + n_iter : int + Number of iterations run. + """ + n_clusters = centers_init.shape[0] + + # Buffers to avoid new allocations at each iteration. + centers = centers_init + centers_new = np.zeros_like(centers) + labels = np.full(X.shape[0], -1, dtype=np.int32) + labels_old = labels.copy() + weight_in_clusters = np.zeros(n_clusters, dtype=X.dtype) + center_shift = np.zeros(n_clusters, dtype=X.dtype) + + if sp.issparse(X): + lloyd_iter = lloyd_iter_chunked_sparse + _inertia = _inertia_sparse + else: + lloyd_iter = lloyd_iter_chunked_dense + _inertia = _inertia_dense + + strict_convergence = False + + # Threadpoolctl context to limit the number of threads in second level of + # nested parallelism (i.e. BLAS) to avoid oversubscription. + with threadpool_limits(limits=1, user_api="blas"): + for i in range(max_iter): + lloyd_iter( + X, + sample_weight, + centers, + centers_new, + weight_in_clusters, + labels, + center_shift, + n_threads, + ) + + if verbose: + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + print(f"Iteration {i}, inertia {inertia}.") + + centers, centers_new = centers_new, centers + + if np.array_equal(labels, labels_old): + # First check the labels for strict convergence. + if verbose: + print(f"Converged at iteration {i}: strict convergence.") + strict_convergence = True + break + else: + # No strict convergence, check for tol based convergence. + center_shift_tot = (center_shift**2).sum() + if center_shift_tot <= tol: + if verbose: + print( + f"Converged at iteration {i}: center shift " + f"{center_shift_tot} within tolerance {tol}." + ) + break + + labels_old[:] = labels + + if not strict_convergence: + # rerun E-step so that predicted labels match cluster centers + lloyd_iter( + X, + sample_weight, + centers, + centers, + weight_in_clusters, + labels, + center_shift, + n_threads, + update_centers=False, + ) + + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + + return labels, inertia, centers, i + 1 + + +def _labels_inertia(X, sample_weight, centers, n_threads=1, return_inertia=True): + """E step of the K-means EM algorithm. + + Compute the labels and the inertia of the given samples and centers. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The input samples to assign to the labels. If sparse matrix, must + be in CSR format. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + x_squared_norms : ndarray of shape (n_samples,) + Precomputed squared euclidean norm of each data point, to speed up + computations. + + centers : ndarray of shape (n_clusters, n_features) + The cluster centers. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. Parallelism is + sample-wise on the main cython loop which assigns each sample to its + closest center. + + return_inertia : bool, default=True + Whether to compute and return the inertia. + + Returns + ------- + labels : ndarray of shape (n_samples,) + The resulting assignment. + + inertia : float + Sum of squared distances of samples to their closest cluster center. + Inertia is only returned if return_inertia is True. + """ + n_samples = X.shape[0] + n_clusters = centers.shape[0] + + labels = np.full(n_samples, -1, dtype=np.int32) + center_shift = np.zeros(n_clusters, dtype=centers.dtype) + + if sp.issparse(X): + _labels = lloyd_iter_chunked_sparse + _inertia = _inertia_sparse + else: + _labels = lloyd_iter_chunked_dense + _inertia = _inertia_dense + X = ReadonlyArrayWrapper(X) + + centers = ReadonlyArrayWrapper(centers) + _labels( + X, + sample_weight, + centers, + centers_new=None, + weight_in_clusters=None, + labels=labels, + center_shift=center_shift, + n_threads=n_threads, + update_centers=False, + ) + + if return_inertia: + inertia = _inertia(X, sample_weight, centers, labels, n_threads) + return labels, inertia + + return labels + + +def _labels_inertia_threadpool_limit( + X, sample_weight, centers, n_threads=1, return_inertia=True +): + """Same as _labels_inertia but in a threadpool_limits context.""" + with threadpool_limits(limits=1, user_api="blas"): + result = _labels_inertia(X, sample_weight, centers, n_threads, return_inertia) + + return result + + +class _BaseKMeans( + ClassNamePrefixFeaturesOutMixin, TransformerMixin, ClusterMixin, BaseEstimator, ABC +): + """Base class for KMeans and MiniBatchKMeans""" + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "init": [StrOptions({"k-means++", "random"}), callable, "array-like"], + "n_init": [ + StrOptions({"auto"}), + Hidden(StrOptions({"warn"})), + Interval(Integral, 1, None, closed="left"), + ], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="left")], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + n_clusters, + *, + init, + n_init, + max_iter, + tol, + verbose, + random_state, + ): + self.n_clusters = n_clusters + self.init = init + self.max_iter = max_iter + self.tol = tol + self.n_init = n_init + self.verbose = verbose + self.random_state = random_state + + def _check_params_vs_input(self, X, default_n_init=None): + # n_clusters + if X.shape[0] < self.n_clusters: + raise ValueError( + f"n_samples={X.shape[0]} should be >= n_clusters={self.n_clusters}." + ) + + # tol + self._tol = _tolerance(X, self.tol) + + # n-init + # TODO(1.4): Remove + self._n_init = self.n_init + if self._n_init == "warn": + warnings.warn( + "The default value of `n_init` will change from " + f"{default_n_init} to 'auto' in 1.4. Set the value of `n_init`" + " explicitly to suppress the warning", + FutureWarning, + ) + self._n_init = default_n_init + if self._n_init == "auto": + if self.init == "k-means++": + self._n_init = 1 + else: + self._n_init = default_n_init + + if _is_arraylike_not_scalar(self.init) and self._n_init != 1: + warnings.warn( + "Explicit initial center position passed: performing only" + f" one init in {self.__class__.__name__} instead of " + f"n_init={self._n_init}.", + RuntimeWarning, + stacklevel=2, + ) + self._n_init = 1 + + @abstractmethod + def _warn_mkl_vcomp(self, n_active_threads): + """Issue an estimator specific warning when vcomp and mkl are both present + + This method is called by `_check_mkl_vcomp`. + """ + + def _check_mkl_vcomp(self, X, n_samples): + """Check when vcomp and mkl are both present""" + # The BLAS call inside a prange in lloyd_iter_chunked_dense is known to + # cause a small memory leak when there are less chunks than the number + # of available threads. It only happens when the OpenMP library is + # vcomp (microsoft OpenMP) and the BLAS library is MKL. see #18653 + if sp.issparse(X): + return + + n_active_threads = int(np.ceil(n_samples / CHUNK_SIZE)) + if n_active_threads < self._n_threads: + modules = threadpool_info() + has_vcomp = "vcomp" in [module["prefix"] for module in modules] + has_mkl = ("mkl", "intel") in [ + (module["internal_api"], module.get("threading_layer", None)) + for module in modules + ] + if has_vcomp and has_mkl: + self._warn_mkl_vcomp(n_active_threads) + + def _validate_center_shape(self, X, centers): + """Check if centers is compatible with X and n_clusters.""" + if centers.shape[0] != self.n_clusters: + raise ValueError( + f"The shape of the initial centers {centers.shape} does not " + f"match the number of clusters {self.n_clusters}." + ) + if centers.shape[1] != X.shape[1]: + raise ValueError( + f"The shape of the initial centers {centers.shape} does not " + f"match the number of features of the data {X.shape[1]}." + ) + + def _check_test_data(self, X): + X = self._validate_data( + X, + accept_sparse="csr", + reset=False, + dtype=[np.float64, np.float32], + order="C", + accept_large_sparse=False, + ) + return X + + def _init_centroids( + self, X, x_squared_norms, init, random_state, init_size=None, n_centroids=None + ): + """Compute the initial centroids. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The input samples. + + x_squared_norms : ndarray of shape (n_samples,) + Squared euclidean norm of each data point. Pass it if you have it + at hands already to avoid it being recomputed here. + + init : {'k-means++', 'random'}, callable or ndarray of shape \ + (n_clusters, n_features) + Method for initialization. + + random_state : RandomState instance + Determines random number generation for centroid initialization. + See :term:`Glossary `. + + init_size : int, default=None + Number of samples to randomly sample for speeding up the + initialization (sometimes at the expense of accuracy). + + n_centroids : int, default=None + Number of centroids to initialize. + If left to 'None' the number of centroids will be equal to + number of clusters to form (self.n_clusters) + + Returns + ------- + centers : ndarray of shape (n_clusters, n_features) + """ + n_samples = X.shape[0] + n_clusters = self.n_clusters if n_centroids is None else n_centroids + + if init_size is not None and init_size < n_samples: + init_indices = random_state.randint(0, n_samples, init_size) + X = X[init_indices] + x_squared_norms = x_squared_norms[init_indices] + n_samples = X.shape[0] + + if isinstance(init, str) and init == "k-means++": + centers, _ = _kmeans_plusplus( + X, + n_clusters, + random_state=random_state, + x_squared_norms=x_squared_norms, + ) + elif isinstance(init, str) and init == "random": + seeds = random_state.permutation(n_samples)[:n_clusters] + centers = X[seeds] + elif _is_arraylike_not_scalar(self.init): + centers = init + elif callable(init): + centers = init(X, n_clusters, random_state=random_state) + centers = check_array(centers, dtype=X.dtype, copy=False, order="C") + self._validate_center_shape(X, centers) + + if sp.issparse(centers): + centers = centers.toarray() + + return centers + + def fit_predict(self, X, y=None, sample_weight=None): + """Compute cluster centers and predict cluster index for each sample. + + Convenience method; equivalent to calling fit(X) followed by + predict(X). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to transform. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + return self.fit(X, sample_weight=sample_weight).labels_ + + def predict(self, X, sample_weight=None): + """Predict the closest cluster each sample in X belongs to. + + In the vector quantization literature, `cluster_centers_` is called + the code book and each value returned by `predict` is the index of + the closest code in the code book. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to predict. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + labels = _labels_inertia_threadpool_limit( + X, + sample_weight, + self.cluster_centers_, + n_threads=self._n_threads, + return_inertia=False, + ) + + return labels + + def fit_transform(self, X, y=None, sample_weight=None): + """Compute clustering and transform X to cluster-distance space. + + Equivalent to fit(X).transform(X), but more efficiently implemented. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to transform. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_clusters) + X transformed in the new space. + """ + return self.fit(X, sample_weight=sample_weight)._transform(X) + + def transform(self, X): + """Transform X to a cluster-distance space. + + In the new space, each dimension is the distance to the cluster + centers. Note that even if X is sparse, the array returned by + `transform` will typically be dense. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data to transform. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_clusters) + X transformed in the new space. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + return self._transform(X) + + def _transform(self, X): + """Guts of transform method; no input validation.""" + return euclidean_distances(X, self.cluster_centers_) + + def score(self, X, y=None, sample_weight=None): + """Opposite of the value of X on the K-means objective. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + New data. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + score : float + Opposite of the value of X on the K-means objective. + """ + check_is_fitted(self) + + X = self._check_test_data(X) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + _, scores = _labels_inertia_threadpool_limit( + X, sample_weight, self.cluster_centers_, self._n_threads + ) + return -scores + + def _more_tags(self): + return { + "_xfail_checks": { + "check_sample_weights_invariance": ( + "zero sample_weight is not equivalent to removing samples" + ), + }, + } + + +class KMeans(_BaseKMeans): + """K-Means clustering. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + n_clusters : int, default=8 + The number of clusters to form as well as the number of + centroids to generate. + + init : {'k-means++', 'random'}, callable or array-like of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization: + + 'k-means++' : selects initial cluster centroids using sampling based on + an empirical probability distribution of the points' contribution to the + overall inertia. This technique speeds up convergence. The algorithm + implemented is "greedy k-means++". It differs from the vanilla k-means++ + by making several trials at each sampling step and choosing the best centroid + among them. + + 'random': choose `n_clusters` observations (rows) at random from data + for the initial centroids. + + If an array is passed, it should be of shape (n_clusters, n_features) + and gives the initial centers. + + If a callable is passed, it should take arguments X, n_clusters and a + random state and return an initialization. + + n_init : 'auto' or int, default=10 + Number of times the k-means algorithm is run with different centroid + seeds. The final results is the best output of `n_init` consecutive runs + in terms of inertia. Several runs are recommended for sparse + high-dimensional problems (see :ref:`kmeans_sparse_high_dim`). + + When `n_init='auto'`, the number of runs depends on the value of init: + 10 if using `init='random'`, 1 if using `init='k-means++'`. + + .. versionadded:: 1.2 + Added 'auto' option for `n_init`. + + .. versionchanged:: 1.4 + Default value for `n_init` will change from 10 to `'auto'` in version 1.4. + + max_iter : int, default=300 + Maximum number of iterations of the k-means algorithm for a + single run. + + tol : float, default=1e-4 + Relative tolerance with regards to Frobenius norm of the difference + in the cluster centers of two consecutive iterations to declare + convergence. + + verbose : int, default=0 + Verbosity mode. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization. Use + an int to make the randomness deterministic. + See :term:`Glossary `. + + copy_x : bool, default=True + When pre-computing distances it is more numerically accurate to center + the data first. If copy_x is True (default), then the original data is + not modified. If False, the original data is modified, and put back + before the function returns, but small numerical differences may be + introduced by subtracting and then adding the data mean. Note that if + the original data is not C-contiguous, a copy will be made even if + copy_x is False. If the original data is sparse, but not in CSR format, + a copy will be made even if copy_x is False. + + algorithm : {"lloyd", "elkan", "auto", "full"}, default="lloyd" + K-means algorithm to use. The classical EM-style algorithm is `"lloyd"`. + The `"elkan"` variation can be more efficient on some datasets with + well-defined clusters, by using the triangle inequality. However it's + more memory intensive due to the allocation of an extra array of shape + `(n_samples, n_clusters)`. + + `"auto"` and `"full"` are deprecated and they will be removed in + Scikit-Learn 1.3. They are both aliases for `"lloyd"`. + + .. versionchanged:: 0.18 + Added Elkan algorithm + + .. versionchanged:: 1.1 + Renamed "full" to "lloyd", and deprecated "auto" and "full". + Changed "auto" to use "lloyd" instead of "elkan". + + Attributes + ---------- + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. If the algorithm stops before fully + converging (see ``tol`` and ``max_iter``), these will not be + consistent with ``labels_``. + + labels_ : ndarray of shape (n_samples,) + Labels of each point + + inertia_ : float + Sum of squared distances of samples to their closest cluster center, + weighted by the sample weights if provided. + + n_iter_ : int + Number of iterations run. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MiniBatchKMeans : Alternative online implementation that does incremental + updates of the centers positions using mini-batches. + For large scale learning (say n_samples > 10k) MiniBatchKMeans is + probably much faster than the default batch implementation. + + Notes + ----- + The k-means problem is solved using either Lloyd's or Elkan's algorithm. + + The average complexity is given by O(k n T), where n is the number of + samples and T is the number of iteration. + + The worst case complexity is given by O(n^(k+2/p)) with + n = n_samples, p = n_features. + Refer to :doi:`"How slow is the k-means method?" D. Arthur and S. Vassilvitskii - + SoCG2006.<10.1145/1137856.1137880>` for more details. + + In practice, the k-means algorithm is very fast (one of the fastest + clustering algorithms available), but it falls in local minima. That's why + it can be useful to restart it several times. + + If the algorithm stops before fully converging (because of ``tol`` or + ``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent, + i.e. the ``cluster_centers_`` will not be the means of the points in each + cluster. Also, the estimator will reassign ``labels_`` after the last + iteration to make ``labels_`` consistent with ``predict`` on the training + set. + + Examples + -------- + + >>> from sklearn.cluster import KMeans + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [10, 2], [10, 4], [10, 0]]) + >>> kmeans = KMeans(n_clusters=2, random_state=0, n_init="auto").fit(X) + >>> kmeans.labels_ + array([1, 1, 1, 0, 0, 0], dtype=int32) + >>> kmeans.predict([[0, 0], [12, 3]]) + array([1, 0], dtype=int32) + >>> kmeans.cluster_centers_ + array([[10., 2.], + [ 1., 2.]]) + """ + + _parameter_constraints: dict = { + **_BaseKMeans._parameter_constraints, + "copy_x": ["boolean"], + "algorithm": [ + StrOptions({"lloyd", "elkan", "auto", "full"}, deprecated={"auto", "full"}) + ], + } + + def __init__( + self, + n_clusters=8, + *, + init="k-means++", + n_init="warn", + max_iter=300, + tol=1e-4, + verbose=0, + random_state=None, + copy_x=True, + algorithm="lloyd", + ): + super().__init__( + n_clusters=n_clusters, + init=init, + n_init=n_init, + max_iter=max_iter, + tol=tol, + verbose=verbose, + random_state=random_state, + ) + + self.copy_x = copy_x + self.algorithm = algorithm + + def _check_params_vs_input(self, X): + super()._check_params_vs_input(X, default_n_init=10) + + self._algorithm = self.algorithm + if self._algorithm in ("auto", "full"): + warnings.warn( + f"algorithm='{self._algorithm}' is deprecated, it will be " + "removed in 1.3. Using 'lloyd' instead.", + FutureWarning, + ) + self._algorithm = "lloyd" + if self._algorithm == "elkan" and self.n_clusters == 1: + warnings.warn( + "algorithm='elkan' doesn't make sense for a single " + "cluster. Using 'lloyd' instead.", + RuntimeWarning, + ) + self._algorithm = "lloyd" + + def _warn_mkl_vcomp(self, n_active_threads): + """Warn when vcomp and mkl are both present""" + warnings.warn( + "KMeans is known to have a memory leak on Windows " + "with MKL, when there are less chunks than available " + "threads. You can avoid it by setting the environment" + f" variable OMP_NUM_THREADS={n_active_threads}." + ) + + def fit(self, X, y=None, sample_weight=None): + """Compute k-means clustering. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training instances to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory + copy if the given data is not C-contiguous. + If a sparse matrix is passed, a copy will be made if it's not in + CSR format. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + .. versionadded:: 0.20 + + Returns + ------- + self : object + Fitted estimator. + """ + self._validate_params() + + X = self._validate_data( + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + copy=self.copy_x, + accept_large_sparse=False, + ) + + self._check_params_vs_input(X) + + random_state = check_random_state(self.random_state) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self._n_threads = _openmp_effective_n_threads() + + # Validate init array + init = self.init + init_is_array_like = _is_arraylike_not_scalar(init) + if init_is_array_like: + init = check_array(init, dtype=X.dtype, copy=True, order="C") + self._validate_center_shape(X, init) + + # subtract of mean of x for more accurate distance computations + if not sp.issparse(X): + X_mean = X.mean(axis=0) + # The copy was already done above + X -= X_mean + + if init_is_array_like: + init -= X_mean + + # precompute squared norms of data points + x_squared_norms = row_norms(X, squared=True) + + if self._algorithm == "elkan": + kmeans_single = _kmeans_single_elkan + else: + kmeans_single = _kmeans_single_lloyd + self._check_mkl_vcomp(X, X.shape[0]) + + best_inertia, best_labels = None, None + + for i in range(self._n_init): + # Initialize centers + centers_init = self._init_centroids( + X, x_squared_norms=x_squared_norms, init=init, random_state=random_state + ) + if self.verbose: + print("Initialization complete") + + # run a k-means once + labels, inertia, centers, n_iter_ = kmeans_single( + X, + sample_weight, + centers_init, + max_iter=self.max_iter, + verbose=self.verbose, + tol=self._tol, + n_threads=self._n_threads, + ) + + # determine if these results are the best so far + # we chose a new run if it has a better inertia and the clustering is + # different from the best so far (it's possible that the inertia is + # slightly better even if the clustering is the same with potentially + # permuted labels, due to rounding errors) + if best_inertia is None or ( + inertia < best_inertia + and not _is_same_clustering(labels, best_labels, self.n_clusters) + ): + best_labels = labels + best_centers = centers + best_inertia = inertia + best_n_iter = n_iter_ + + if not sp.issparse(X): + if not self.copy_x: + X += X_mean + best_centers += X_mean + + distinct_clusters = len(set(best_labels)) + if distinct_clusters < self.n_clusters: + warnings.warn( + "Number of distinct clusters ({}) found smaller than " + "n_clusters ({}). Possibly due to duplicate points " + "in X.".format(distinct_clusters, self.n_clusters), + ConvergenceWarning, + stacklevel=2, + ) + + self.cluster_centers_ = best_centers + self._n_features_out = self.cluster_centers_.shape[0] + self.labels_ = best_labels + self.inertia_ = best_inertia + self.n_iter_ = best_n_iter + return self + + +def _mini_batch_step( + X, + sample_weight, + centers, + centers_new, + weight_sums, + random_state, + random_reassign=False, + reassignment_ratio=0.01, + verbose=False, + n_threads=1, +): + """Incremental update of the centers for the Minibatch K-Means algorithm. + + Parameters + ---------- + + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The original data array. If sparse, must be in CSR format. + + x_squared_norms : ndarray of shape (n_samples,) + Squared euclidean norm of each data point. + + sample_weight : ndarray of shape (n_samples,) + The weights for each observation in X. + + centers : ndarray of shape (n_clusters, n_features) + The cluster centers before the current iteration + + centers_new : ndarray of shape (n_clusters, n_features) + The cluster centers after the current iteration. Modified in-place. + + weight_sums : ndarray of shape (n_clusters,) + The vector in which we keep track of the numbers of points in a + cluster. This array is modified in place. + + random_state : RandomState instance + Determines random number generation for low count centers reassignment. + See :term:`Glossary `. + + random_reassign : boolean, default=False + If True, centers with very low counts are randomly reassigned + to observations. + + reassignment_ratio : float, default=0.01 + Control the fraction of the maximum number of counts for a + center to be reassigned. A higher value means that low count + centers are more likely to be reassigned, which means that the + model will take longer to converge, but should converge in a + better clustering. + + verbose : bool, default=False + Controls the verbosity. + + n_threads : int, default=1 + The number of OpenMP threads to use for the computation. + + Returns + ------- + inertia : float + Sum of squared distances of samples to their closest cluster center. + The inertia is computed after finding the labels and before updating + the centers. + """ + # Perform label assignment to nearest centers + # For better efficiency, it's better to run _mini_batch_step in a + # threadpool_limit context than using _labels_inertia_threadpool_limit here + labels, inertia = _labels_inertia(X, sample_weight, centers, n_threads=n_threads) + + # Update centers according to the labels + if sp.issparse(X): + _minibatch_update_sparse( + X, sample_weight, centers, centers_new, weight_sums, labels, n_threads + ) + else: + _minibatch_update_dense( + ReadonlyArrayWrapper(X), + sample_weight, + centers, + centers_new, + weight_sums, + labels, + n_threads, + ) + + # Reassign clusters that have very low weight + if random_reassign and reassignment_ratio > 0: + to_reassign = weight_sums < reassignment_ratio * weight_sums.max() + + # pick at most .5 * batch_size samples as new centers + if to_reassign.sum() > 0.5 * X.shape[0]: + indices_dont_reassign = np.argsort(weight_sums)[int(0.5 * X.shape[0]) :] + to_reassign[indices_dont_reassign] = False + n_reassigns = to_reassign.sum() + + if n_reassigns: + # Pick new clusters amongst observations with uniform probability + new_centers = random_state.choice( + X.shape[0], replace=False, size=n_reassigns + ) + if verbose: + print(f"[MiniBatchKMeans] Reassigning {n_reassigns} cluster centers.") + + if sp.issparse(X): + assign_rows_csr( + X, + new_centers.astype(np.intp, copy=False), + np.where(to_reassign)[0].astype(np.intp, copy=False), + centers_new, + ) + else: + centers_new[to_reassign] = X[new_centers] + + # reset counts of reassigned centers, but don't reset them too small + # to avoid instant reassignment. This is a pretty dirty hack as it + # also modifies the learning rates. + weight_sums[to_reassign] = np.min(weight_sums[~to_reassign]) + + return inertia + + +class MiniBatchKMeans(_BaseKMeans): + """ + Mini-Batch K-Means clustering. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + n_clusters : int, default=8 + The number of clusters to form as well as the number of + centroids to generate. + + init : {'k-means++', 'random'}, callable or array-like of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization: + + 'k-means++' : selects initial cluster centroids using sampling based on + an empirical probability distribution of the points' contribution to the + overall inertia. This technique speeds up convergence. The algorithm + implemented is "greedy k-means++". It differs from the vanilla k-means++ + by making several trials at each sampling step and choosing the best centroid + among them. + + 'random': choose `n_clusters` observations (rows) at random from data + for the initial centroids. + + If an array is passed, it should be of shape (n_clusters, n_features) + and gives the initial centers. + + If a callable is passed, it should take arguments X, n_clusters and a + random state and return an initialization. + + max_iter : int, default=100 + Maximum number of iterations over the complete dataset before + stopping independently of any early stopping criterion heuristics. + + batch_size : int, default=1024 + Size of the mini batches. + For faster computations, you can set the ``batch_size`` greater than + 256 * number of cores to enable parallelism on all cores. + + .. versionchanged:: 1.0 + `batch_size` default changed from 100 to 1024. + + verbose : int, default=0 + Verbosity mode. + + compute_labels : bool, default=True + Compute label assignment and inertia for the complete dataset + once the minibatch optimization has converged in fit. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for centroid initialization and + random reassignment. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + tol : float, default=0.0 + Control early stopping based on the relative center changes as + measured by a smoothed, variance-normalized of the mean center + squared position changes. This early stopping heuristics is + closer to the one used for the batch variant of the algorithms + but induces a slight computational and memory overhead over the + inertia heuristic. + + To disable convergence detection based on normalized center + change, set tol to 0.0 (default). + + max_no_improvement : int, default=10 + Control early stopping based on the consecutive number of mini + batches that does not yield an improvement on the smoothed inertia. + + To disable convergence detection based on inertia, set + max_no_improvement to None. + + init_size : int, default=None + Number of samples to randomly sample for speeding up the + initialization (sometimes at the expense of accuracy): the + only algorithm is initialized by running a batch KMeans on a + random subset of the data. This needs to be larger than n_clusters. + + If `None`, the heuristic is `init_size = 3 * batch_size` if + `3 * batch_size < n_clusters`, else `init_size = 3 * n_clusters`. + + n_init : 'auto' or int, default=3 + Number of random initializations that are tried. + In contrast to KMeans, the algorithm is only run once, using the best of + the `n_init` initializations as measured by inertia. Several runs are + recommended for sparse high-dimensional problems (see + :ref:`kmeans_sparse_high_dim`). + + When `n_init='auto'`, the number of runs depends on the value of init: + 3 if using `init='random'`, 1 if using `init='k-means++'`. + + .. versionadded:: 1.2 + Added 'auto' option for `n_init`. + + .. versionchanged:: 1.4 + Default value for `n_init` will change from 3 to `'auto'` in version 1.4. + + reassignment_ratio : float, default=0.01 + Control the fraction of the maximum number of counts for a center to + be reassigned. A higher value means that low count centers are more + easily reassigned, which means that the model will take longer to + converge, but should converge in a better clustering. However, too high + a value may cause convergence issues, especially with a small batch + size. + + Attributes + ---------- + + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels_ : ndarray of shape (n_samples,) + Labels of each point (if compute_labels is set to True). + + inertia_ : float + The value of the inertia criterion associated with the chosen + partition if compute_labels is set to True. If compute_labels is set to + False, it's an approximation of the inertia based on an exponentially + weighted average of the batch inertiae. + The inertia is defined as the sum of square distances of samples to + their cluster center, weighted by the sample weights if provided. + + n_iter_ : int + Number of iterations over the full dataset. + + n_steps_ : int + Number of minibatches processed. + + .. versionadded:: 1.0 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + KMeans : The classic implementation of the clustering method based on the + Lloyd's algorithm. It consumes the whole set of input data at each + iteration. + + Notes + ----- + See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf + + When there are too few points in the dataset, some centers may be + duplicated, which means that a proper clustering in terms of the number + of requesting clusters and the number of returned clusters will not + always match. One solution is to set `reassignment_ratio=0`, which + prevents reassignments of clusters that are too small. + + Examples + -------- + >>> from sklearn.cluster import MiniBatchKMeans + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 0], [4, 4], + ... [4, 5], [0, 1], [2, 2], + ... [3, 2], [5, 5], [1, -1]]) + >>> # manually fit on batches + >>> kmeans = MiniBatchKMeans(n_clusters=2, + ... random_state=0, + ... batch_size=6, + ... n_init="auto") + >>> kmeans = kmeans.partial_fit(X[0:6,:]) + >>> kmeans = kmeans.partial_fit(X[6:12,:]) + >>> kmeans.cluster_centers_ + array([[2. , 1. ], + [3.5, 4.5]]) + >>> kmeans.predict([[0, 0], [4, 4]]) + array([0, 1], dtype=int32) + >>> # fit on the whole data + >>> kmeans = MiniBatchKMeans(n_clusters=2, + ... random_state=0, + ... batch_size=6, + ... max_iter=10, + ... n_init="auto").fit(X) + >>> kmeans.cluster_centers_ + array([[3.97727273, 2.43181818], + [1.125 , 1.6 ]]) + >>> kmeans.predict([[0, 0], [4, 4]]) + array([1, 0], dtype=int32) + """ + + _parameter_constraints: dict = { + **_BaseKMeans._parameter_constraints, + "batch_size": [Interval(Integral, 1, None, closed="left")], + "compute_labels": ["boolean"], + "max_no_improvement": [Interval(Integral, 0, None, closed="left"), None], + "init_size": [Interval(Integral, 1, None, closed="left"), None], + "reassignment_ratio": [Interval(Real, 0, None, closed="left")], + } + + def __init__( + self, + n_clusters=8, + *, + init="k-means++", + max_iter=100, + batch_size=1024, + verbose=0, + compute_labels=True, + random_state=None, + tol=0.0, + max_no_improvement=10, + init_size=None, + n_init="warn", + reassignment_ratio=0.01, + ): + + super().__init__( + n_clusters=n_clusters, + init=init, + max_iter=max_iter, + verbose=verbose, + random_state=random_state, + tol=tol, + n_init=n_init, + ) + + self.max_no_improvement = max_no_improvement + self.batch_size = batch_size + self.compute_labels = compute_labels + self.init_size = init_size + self.reassignment_ratio = reassignment_ratio + + def _check_params_vs_input(self, X): + super()._check_params_vs_input(X, default_n_init=3) + + self._batch_size = min(self.batch_size, X.shape[0]) + + # init_size + self._init_size = self.init_size + if self._init_size is None: + self._init_size = 3 * self._batch_size + if self._init_size < self.n_clusters: + self._init_size = 3 * self.n_clusters + elif self._init_size < self.n_clusters: + warnings.warn( + f"init_size={self._init_size} should be larger than " + f"n_clusters={self.n_clusters}. Setting it to " + "min(3*n_clusters, n_samples)", + RuntimeWarning, + stacklevel=2, + ) + self._init_size = 3 * self.n_clusters + self._init_size = min(self._init_size, X.shape[0]) + + # reassignment_ratio + if self.reassignment_ratio < 0: + raise ValueError( + "reassignment_ratio should be >= 0, got " + f"{self.reassignment_ratio} instead." + ) + + def _warn_mkl_vcomp(self, n_active_threads): + """Warn when vcomp and mkl are both present""" + warnings.warn( + "MiniBatchKMeans is known to have a memory leak on " + "Windows with MKL, when there are less chunks than " + "available threads. You can prevent it by setting " + f"batch_size >= {self._n_threads * CHUNK_SIZE} or by " + "setting the environment variable " + f"OMP_NUM_THREADS={n_active_threads}" + ) + + def _mini_batch_convergence( + self, step, n_steps, n_samples, centers_squared_diff, batch_inertia + ): + """Helper function to encapsulate the early stopping logic""" + # Normalize inertia to be able to compare values when + # batch_size changes + batch_inertia /= self._batch_size + + # count steps starting from 1 for user friendly verbose mode. + step = step + 1 + + # Ignore first iteration because it's inertia from initialization. + if step == 1: + if self.verbose: + print( + f"Minibatch step {step}/{n_steps}: mean batch " + f"inertia: {batch_inertia}" + ) + return False + + # Compute an Exponentially Weighted Average of the inertia to + # monitor the convergence while discarding minibatch-local stochastic + # variability: https://en.wikipedia.org/wiki/Moving_average + if self._ewa_inertia is None: + self._ewa_inertia = batch_inertia + else: + alpha = self._batch_size * 2.0 / (n_samples + 1) + alpha = min(alpha, 1) + self._ewa_inertia = self._ewa_inertia * (1 - alpha) + batch_inertia * alpha + + # Log progress to be able to monitor convergence + if self.verbose: + print( + f"Minibatch step {step}/{n_steps}: mean batch inertia: " + f"{batch_inertia}, ewa inertia: {self._ewa_inertia}" + ) + + # Early stopping based on absolute tolerance on squared change of + # centers position + if self._tol > 0.0 and centers_squared_diff <= self._tol: + if self.verbose: + print(f"Converged (small centers change) at step {step}/{n_steps}") + return True + + # Early stopping heuristic due to lack of improvement on smoothed + # inertia + if self._ewa_inertia_min is None or self._ewa_inertia < self._ewa_inertia_min: + self._no_improvement = 0 + self._ewa_inertia_min = self._ewa_inertia + else: + self._no_improvement += 1 + + if ( + self.max_no_improvement is not None + and self._no_improvement >= self.max_no_improvement + ): + if self.verbose: + print( + "Converged (lack of improvement in inertia) at step " + f"{step}/{n_steps}" + ) + return True + + return False + + def _random_reassign(self): + """Check if a random reassignment needs to be done. + + Do random reassignments each time 10 * n_clusters samples have been + processed. + + If there are empty clusters we always want to reassign. + """ + self._n_since_last_reassign += self._batch_size + if (self._counts == 0).any() or self._n_since_last_reassign >= ( + 10 * self.n_clusters + ): + self._n_since_last_reassign = 0 + return True + return False + + def fit(self, X, y=None, sample_weight=None): + """Compute the centroids on X by chunking it into mini-batches. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training instances to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory copy + if the given data is not C-contiguous. + If a sparse matrix is passed, a copy will be made if it's not in + CSR format. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + .. versionadded:: 0.20 + + Returns + ------- + self : object + Fitted estimator. + """ + self._validate_params() + + X = self._validate_data( + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + accept_large_sparse=False, + ) + + self._check_params_vs_input(X) + random_state = check_random_state(self.random_state) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self._n_threads = _openmp_effective_n_threads() + n_samples, n_features = X.shape + + # Validate init array + init = self.init + if _is_arraylike_not_scalar(init): + init = check_array(init, dtype=X.dtype, copy=True, order="C") + self._validate_center_shape(X, init) + + self._check_mkl_vcomp(X, self._batch_size) + + # precompute squared norms of data points + x_squared_norms = row_norms(X, squared=True) + + # Validation set for the init + validation_indices = random_state.randint(0, n_samples, self._init_size) + X_valid = X[validation_indices] + sample_weight_valid = sample_weight[validation_indices] + + # perform several inits with random subsets + best_inertia = None + for init_idx in range(self._n_init): + if self.verbose: + print(f"Init {init_idx + 1}/{self._n_init} with method {init}") + + # Initialize the centers using only a fraction of the data as we + # expect n_samples to be very large when using MiniBatchKMeans. + cluster_centers = self._init_centroids( + X, + x_squared_norms=x_squared_norms, + init=init, + random_state=random_state, + init_size=self._init_size, + ) + + # Compute inertia on a validation set. + _, inertia = _labels_inertia_threadpool_limit( + X_valid, + sample_weight_valid, + cluster_centers, + n_threads=self._n_threads, + ) + + if self.verbose: + print(f"Inertia for init {init_idx + 1}/{self._n_init}: {inertia}") + if best_inertia is None or inertia < best_inertia: + init_centers = cluster_centers + best_inertia = inertia + + centers = init_centers + centers_new = np.empty_like(centers) + + # Initialize counts + self._counts = np.zeros(self.n_clusters, dtype=X.dtype) + + # Attributes to monitor the convergence + self._ewa_inertia = None + self._ewa_inertia_min = None + self._no_improvement = 0 + + # Initialize number of samples seen since last reassignment + self._n_since_last_reassign = 0 + + n_steps = (self.max_iter * n_samples) // self._batch_size + + with threadpool_limits(limits=1, user_api="blas"): + # Perform the iterative optimization until convergence + for i in range(n_steps): + # Sample a minibatch from the full dataset + minibatch_indices = random_state.randint(0, n_samples, self._batch_size) + + # Perform the actual update step on the minibatch data + batch_inertia = _mini_batch_step( + X=X[minibatch_indices], + sample_weight=sample_weight[minibatch_indices], + centers=centers, + centers_new=centers_new, + weight_sums=self._counts, + random_state=random_state, + random_reassign=self._random_reassign(), + reassignment_ratio=self.reassignment_ratio, + verbose=self.verbose, + n_threads=self._n_threads, + ) + + if self._tol > 0.0: + centers_squared_diff = np.sum((centers_new - centers) ** 2) + else: + centers_squared_diff = 0 + + centers, centers_new = centers_new, centers + + # Monitor convergence and do early stopping if necessary + if self._mini_batch_convergence( + i, n_steps, n_samples, centers_squared_diff, batch_inertia + ): + break + + self.cluster_centers_ = centers + self._n_features_out = self.cluster_centers_.shape[0] + + self.n_steps_ = i + 1 + self.n_iter_ = int(np.ceil(((i + 1) * self._batch_size) / n_samples)) + + if self.compute_labels: + self.labels_, self.inertia_ = _labels_inertia_threadpool_limit( + X, + sample_weight, + self.cluster_centers_, + n_threads=self._n_threads, + ) + else: + self.inertia_ = self._ewa_inertia * n_samples + + return self + + def partial_fit(self, X, y=None, sample_weight=None): + """Update k means estimate on a single mini-batch X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training instances to cluster. It must be noted that the data + will be converted to C ordering, which will cause a memory copy + if the given data is not C-contiguous. + If a sparse matrix is passed, a copy will be made if it's not in + CSR format. + + y : Ignored + Not used, present here for API consistency by convention. + + sample_weight : array-like of shape (n_samples,), default=None + The weights for each observation in X. If None, all observations + are assigned equal weight. + + Returns + ------- + self : object + Return updated estimator. + """ + has_centers = hasattr(self, "cluster_centers_") + + if not has_centers: + self._validate_params() + + X = self._validate_data( + X, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + accept_large_sparse=False, + reset=not has_centers, + ) + + self._random_state = getattr( + self, "_random_state", check_random_state(self.random_state) + ) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + self.n_steps_ = getattr(self, "n_steps_", 0) + + # precompute squared norms of data points + x_squared_norms = row_norms(X, squared=True) + + if not has_centers: + # this instance has not been fitted yet (fit or partial_fit) + self._check_params_vs_input(X) + self._n_threads = _openmp_effective_n_threads() + + # Validate init array + init = self.init + if _is_arraylike_not_scalar(init): + init = check_array(init, dtype=X.dtype, copy=True, order="C") + self._validate_center_shape(X, init) + + self._check_mkl_vcomp(X, X.shape[0]) + + # initialize the cluster centers + self.cluster_centers_ = self._init_centroids( + X, + x_squared_norms=x_squared_norms, + init=init, + random_state=self._random_state, + init_size=self._init_size, + ) + + # Initialize counts + self._counts = np.zeros(self.n_clusters, dtype=X.dtype) + + # Initialize number of samples seen since last reassignment + self._n_since_last_reassign = 0 + + with threadpool_limits(limits=1, user_api="blas"): + _mini_batch_step( + X, + sample_weight=sample_weight, + centers=self.cluster_centers_, + centers_new=self.cluster_centers_, + weight_sums=self._counts, + random_state=self._random_state, + random_reassign=self._random_reassign(), + reassignment_ratio=self.reassignment_ratio, + verbose=self.verbose, + n_threads=self._n_threads, + ) + + if self.compute_labels: + self.labels_, self.inertia_ = _labels_inertia_threadpool_limit( + X, + sample_weight, + self.cluster_centers_, + n_threads=self._n_threads, + ) + + self.n_steps_ += 1 + self._n_features_out = self.cluster_centers_.shape[0] + + return self diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..4d1837ded92f9eee508999403d57e15c4394bd32 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py @@ -0,0 +1,536 @@ +"""Mean shift clustering algorithm. + +Mean shift clustering aims to discover *blobs* in a smooth density of +samples. It is a centroid based algorithm, which works by updating candidates +for centroids to be the mean of the points within a given region. These +candidates are then filtered in a post-processing stage to eliminate +near-duplicates to form the final set of centroids. + +Seeding is performed using a binning technique for scalability. +""" + +# Authors: Conrad Lee +# Alexandre Gramfort +# Gael Varoquaux +# Martino Sorbaro + +import numpy as np +import warnings +from numbers import Integral, Real + +from collections import defaultdict +from ..utils._param_validation import Interval +from ..utils.validation import check_is_fitted +from ..utils.parallel import delayed, Parallel +from ..utils import check_random_state, gen_batches, check_array +from ..base import BaseEstimator, ClusterMixin +from ..neighbors import NearestNeighbors +from ..metrics.pairwise import pairwise_distances_argmin +from .._config import config_context + + +def estimate_bandwidth(X, *, quantile=0.3, n_samples=None, random_state=0, n_jobs=None): + """Estimate the bandwidth to use with the mean-shift algorithm. + + That this function takes time at least quadratic in n_samples. For large + datasets, it's wise to set that parameter to a small value. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input points. + + quantile : float, default=0.3 + Should be between [0, 1] + 0.5 means that the median of all pairwise distances is used. + + n_samples : int, default=None + The number of samples to use. If not given, all samples are used. + + random_state : int, RandomState instance, default=None + The generator used to randomly select the samples from input points + for bandwidth estimation. Use an int to make the randomness + deterministic. + See :term:`Glossary `. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + bandwidth : float + The bandwidth parameter. + """ + X = check_array(X) + + random_state = check_random_state(random_state) + if n_samples is not None: + idx = random_state.permutation(X.shape[0])[:n_samples] + X = X[idx] + n_neighbors = int(X.shape[0] * quantile) + if n_neighbors < 1: # cannot fit NearestNeighbors with n_neighbors = 0 + n_neighbors = 1 + nbrs = NearestNeighbors(n_neighbors=n_neighbors, n_jobs=n_jobs) + nbrs.fit(X) + + bandwidth = 0.0 + for batch in gen_batches(len(X), 500): + d, _ = nbrs.kneighbors(X[batch, :], return_distance=True) + bandwidth += np.max(d, axis=1).sum() + + return bandwidth / X.shape[0] + + +# separate function for each seed's iterative loop +def _mean_shift_single_seed(my_mean, X, nbrs, max_iter): + # For each seed, climb gradient until convergence or max_iter + bandwidth = nbrs.get_params()["radius"] + stop_thresh = 1e-3 * bandwidth # when mean has converged + completed_iterations = 0 + while True: + # Find mean of points within bandwidth + i_nbrs = nbrs.radius_neighbors([my_mean], bandwidth, return_distance=False)[0] + points_within = X[i_nbrs] + if len(points_within) == 0: + break # Depending on seeding strategy this condition may occur + my_old_mean = my_mean # save the old mean + my_mean = np.mean(points_within, axis=0) + # If converged or at max_iter, adds the cluster + if ( + np.linalg.norm(my_mean - my_old_mean) < stop_thresh + or completed_iterations == max_iter + ): + break + completed_iterations += 1 + return tuple(my_mean), len(points_within), completed_iterations + + +def mean_shift( + X, + *, + bandwidth=None, + seeds=None, + bin_seeding=False, + min_bin_freq=1, + cluster_all=True, + max_iter=300, + n_jobs=None, +): + """Perform mean shift clustering of data using a flat kernel. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + X : array-like of shape (n_samples, n_features) + Input data. + + bandwidth : float, default=None + Kernel bandwidth. + + If bandwidth is not given, it is determined using a heuristic based on + the median of all pairwise distances. This will take quadratic time in + the number of samples. The sklearn.cluster.estimate_bandwidth function + can be used to do this more efficiently. + + seeds : array-like of shape (n_seeds, n_features) or None + Point used as initial kernel locations. If None and bin_seeding=False, + each data point is used as a seed. If None and bin_seeding=True, + see bin_seeding. + + bin_seeding : bool, default=False + If true, initial kernel locations are not locations of all + points, but rather the location of the discretized version of + points, where points are binned onto a grid whose coarseness + corresponds to the bandwidth. Setting this option to True will speed + up the algorithm because fewer seeds will be initialized. + Ignored if seeds argument is not None. + + min_bin_freq : int, default=1 + To speed up the algorithm, accept only those bins with at least + min_bin_freq points as seeds. + + cluster_all : bool, default=True + If true, then all points are clustered, even those orphans that are + not within any kernel. Orphans are assigned to the nearest kernel. + If false, then orphans are given cluster label -1. + + max_iter : int, default=300 + Maximum number of iterations, per seed point before the clustering + operation terminates (for that seed point), if has not converged yet. + + n_jobs : int, default=None + The number of jobs to use for the computation. The following tasks benefit + from the parallelization: + + - The search of nearest neighbors for bandwidth estimation and label + assignments. See the details in the docstring of the + ``NearestNeighbors`` class. + - Hill-climbing optimization for all seeds. + + See :term:`Glossary ` for more details. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 0.17 + Parallel Execution using *n_jobs*. + + Returns + ------- + + cluster_centers : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. + + Notes + ----- + For an example, see :ref:`examples/cluster/plot_mean_shift.py + `. + """ + model = MeanShift( + bandwidth=bandwidth, + seeds=seeds, + min_bin_freq=min_bin_freq, + bin_seeding=bin_seeding, + cluster_all=cluster_all, + n_jobs=n_jobs, + max_iter=max_iter, + ).fit(X) + return model.cluster_centers_, model.labels_ + + +def get_bin_seeds(X, bin_size, min_bin_freq=1): + """Find seeds for mean_shift. + + Finds seeds by first binning data onto a grid whose lines are + spaced bin_size apart, and then choosing those bins with at least + min_bin_freq points. + + Parameters + ---------- + + X : array-like of shape (n_samples, n_features) + Input points, the same points that will be used in mean_shift. + + bin_size : float + Controls the coarseness of the binning. Smaller values lead + to more seeding (which is computationally more expensive). If you're + not sure how to set this, set it to the value of the bandwidth used + in clustering.mean_shift. + + min_bin_freq : int, default=1 + Only bins with at least min_bin_freq will be selected as seeds. + Raising this value decreases the number of seeds found, which + makes mean_shift computationally cheaper. + + Returns + ------- + bin_seeds : array-like of shape (n_samples, n_features) + Points used as initial kernel positions in clustering.mean_shift. + """ + if bin_size == 0: + return X + + # Bin points + bin_sizes = defaultdict(int) + for point in X: + binned_point = np.round(point / bin_size) + bin_sizes[tuple(binned_point)] += 1 + + # Select only those bins as seeds which have enough members + bin_seeds = np.array( + [point for point, freq in bin_sizes.items() if freq >= min_bin_freq], + dtype=np.float32, + ) + if len(bin_seeds) == len(X): + warnings.warn( + "Binning data failed with provided bin_size=%f, using data points as seeds." + % bin_size + ) + return X + bin_seeds = bin_seeds * bin_size + return bin_seeds + + +class MeanShift(ClusterMixin, BaseEstimator): + """Mean shift clustering using a flat kernel. + + Mean shift clustering aims to discover "blobs" in a smooth density of + samples. It is a centroid-based algorithm, which works by updating + candidates for centroids to be the mean of the points within a given + region. These candidates are then filtered in a post-processing stage to + eliminate near-duplicates to form the final set of centroids. + + Seeding is performed using a binning technique for scalability. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + bandwidth : float, default=None + Bandwidth used in the flat kernel. + + If not given, the bandwidth is estimated using + sklearn.cluster.estimate_bandwidth; see the documentation for that + function for hints on scalability (see also the Notes, below). + + seeds : array-like of shape (n_samples, n_features), default=None + Seeds used to initialize kernels. If not set, + the seeds are calculated by clustering.get_bin_seeds + with bandwidth as the grid size and default values for + other parameters. + + bin_seeding : bool, default=False + If true, initial kernel locations are not locations of all + points, but rather the location of the discretized version of + points, where points are binned onto a grid whose coarseness + corresponds to the bandwidth. Setting this option to True will speed + up the algorithm because fewer seeds will be initialized. + The default value is False. + Ignored if seeds argument is not None. + + min_bin_freq : int, default=1 + To speed up the algorithm, accept only those bins with at least + min_bin_freq points as seeds. + + cluster_all : bool, default=True + If true, then all points are clustered, even those orphans that are + not within any kernel. Orphans are assigned to the nearest kernel. + If false, then orphans are given cluster label -1. + + n_jobs : int, default=None + The number of jobs to use for the computation. The following tasks benefit + from the parallelization: + + - The search of nearest neighbors for bandwidth estimation and label + assignments. See the details in the docstring of the + ``NearestNeighbors`` class. + - Hill-climbing optimization for all seeds. + + See :term:`Glossary ` for more details. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + max_iter : int, default=300 + Maximum number of iterations, per seed point before the clustering + operation terminates (for that seed point), if has not converged yet. + + .. versionadded:: 0.22 + + Attributes + ---------- + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + n_iter_ : int + Maximum number of iterations performed on each seed. + + .. versionadded:: 0.22 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + KMeans : K-Means clustering. + + Notes + ----- + + Scalability: + + Because this implementation uses a flat kernel and + a Ball Tree to look up members of each kernel, the complexity will tend + towards O(T*n*log(n)) in lower dimensions, with n the number of samples + and T the number of points. In higher dimensions the complexity will + tend towards O(T*n^2). + + Scalability can be boosted by using fewer seeds, for example by using + a higher value of min_bin_freq in the get_bin_seeds function. + + Note that the estimate_bandwidth function is much less scalable than the + mean shift algorithm and will be the bottleneck if it is used. + + References + ---------- + + Dorin Comaniciu and Peter Meer, "Mean Shift: A robust approach toward + feature space analysis". IEEE Transactions on Pattern Analysis and + Machine Intelligence. 2002. pp. 603-619. + + Examples + -------- + >>> from sklearn.cluster import MeanShift + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = MeanShift(bandwidth=2).fit(X) + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + >>> clustering.predict([[0, 0], [5, 5]]) + array([1, 0]) + >>> clustering + MeanShift(bandwidth=2) + """ + + _parameter_constraints: dict = { + "bandwidth": [Interval(Real, 0, None, closed="neither"), None], + "seeds": ["array-like", None], + "bin_seeding": ["boolean"], + "min_bin_freq": [Interval(Integral, 1, None, closed="left")], + "cluster_all": ["boolean"], + "n_jobs": [Integral, None], + "max_iter": [Interval(Integral, 0, None, closed="left")], + } + + def __init__( + self, + *, + bandwidth=None, + seeds=None, + bin_seeding=False, + min_bin_freq=1, + cluster_all=True, + n_jobs=None, + max_iter=300, + ): + self.bandwidth = bandwidth + self.seeds = seeds + self.bin_seeding = bin_seeding + self.cluster_all = cluster_all + self.min_bin_freq = min_bin_freq + self.n_jobs = n_jobs + self.max_iter = max_iter + + def fit(self, X, y=None): + """Perform clustering. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Samples to cluster. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Fitted instance. + """ + self._validate_params() + X = self._validate_data(X) + bandwidth = self.bandwidth + if bandwidth is None: + bandwidth = estimate_bandwidth(X, n_jobs=self.n_jobs) + + seeds = self.seeds + if seeds is None: + if self.bin_seeding: + seeds = get_bin_seeds(X, bandwidth, self.min_bin_freq) + else: + seeds = X + n_samples, n_features = X.shape + center_intensity_dict = {} + + # We use n_jobs=1 because this will be used in nested calls under + # parallel calls to _mean_shift_single_seed so there is no need for + # for further parallelism. + nbrs = NearestNeighbors(radius=bandwidth, n_jobs=1).fit(X) + + # execute iterations on all seeds in parallel + all_res = Parallel(n_jobs=self.n_jobs)( + delayed(_mean_shift_single_seed)(seed, X, nbrs, self.max_iter) + for seed in seeds + ) + # copy results in a dictionary + for i in range(len(seeds)): + if all_res[i][1]: # i.e. len(points_within) > 0 + center_intensity_dict[all_res[i][0]] = all_res[i][1] + + self.n_iter_ = max([x[2] for x in all_res]) + + if not center_intensity_dict: + # nothing near seeds + raise ValueError( + "No point was within bandwidth=%f of any seed. Try a different seeding" + " strategy or increase the bandwidth." + % bandwidth + ) + + # POST PROCESSING: remove near duplicate points + # If the distance between two kernels is less than the bandwidth, + # then we have to remove one because it is a duplicate. Remove the + # one with fewer points. + + sorted_by_intensity = sorted( + center_intensity_dict.items(), + key=lambda tup: (tup[1], tup[0]), + reverse=True, + ) + sorted_centers = np.array([tup[0] for tup in sorted_by_intensity]) + unique = np.ones(len(sorted_centers), dtype=bool) + nbrs = NearestNeighbors(radius=bandwidth, n_jobs=self.n_jobs).fit( + sorted_centers + ) + for i, center in enumerate(sorted_centers): + if unique[i]: + neighbor_idxs = nbrs.radius_neighbors([center], return_distance=False)[ + 0 + ] + unique[neighbor_idxs] = 0 + unique[i] = 1 # leave the current point as unique + cluster_centers = sorted_centers[unique] + + # ASSIGN LABELS: a point belongs to the cluster that it is closest to + nbrs = NearestNeighbors(n_neighbors=1, n_jobs=self.n_jobs).fit(cluster_centers) + labels = np.zeros(n_samples, dtype=int) + distances, idxs = nbrs.kneighbors(X) + if self.cluster_all: + labels = idxs.flatten() + else: + labels.fill(-1) + bool_selector = distances.flatten() <= bandwidth + labels[bool_selector] = idxs.flatten()[bool_selector] + + self.cluster_centers_, self.labels_ = cluster_centers, labels + return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + New data to predict. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self) + X = self._validate_data(X, reset=False) + with config_context(assume_finite=True): + return pairwise_distances_argmin(X, self.cluster_centers_) diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_optics.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_optics.py new file mode 100644 index 0000000000000000000000000000000000000000..07c22bbdff691e9d931022d0544dbb6f70aa901f --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_optics.py @@ -0,0 +1,1050 @@ +"""Ordering Points To Identify the Clustering Structure (OPTICS) + +These routines execute the OPTICS algorithm, and implement various +cluster extraction methods of the ordered list. + +Authors: Shane Grigsby + Adrin Jalali + Erich Schubert + Hanmin Qin +License: BSD 3 clause +""" + +from numbers import Integral, Real + +import warnings +import numpy as np + +from ..exceptions import DataConversionWarning +from ..metrics.pairwise import PAIRWISE_BOOLEAN_FUNCTIONS +from ..metrics.pairwise import _VALID_METRICS +from ..utils import gen_batches, get_chunk_n_rows +from ..utils._param_validation import Interval, HasMethods, StrOptions +from ..utils.validation import check_memory +from ..neighbors import NearestNeighbors +from ..base import BaseEstimator, ClusterMixin +from ..metrics import pairwise_distances +from scipy.sparse import issparse, SparseEfficiencyWarning + + +class OPTICS(ClusterMixin, BaseEstimator): + """Estimate clustering structure from vector array. + + OPTICS (Ordering Points To Identify the Clustering Structure), closely + related to DBSCAN, finds core sample of high density and expands clusters + from them [1]_. Unlike DBSCAN, keeps cluster hierarchy for a variable + neighborhood radius. Better suited for usage on large datasets than the + current sklearn implementation of DBSCAN. + + Clusters are then extracted using a DBSCAN-like method + (cluster_method = 'dbscan') or an automatic + technique proposed in [1]_ (cluster_method = 'xi'). + + This implementation deviates from the original OPTICS by first performing + k-nearest-neighborhood searches on all points to identify core sizes, then + computing only the distances to unprocessed points when constructing the + cluster order. Note that we do not employ a heap to manage the expansion + candidates, so the time complexity will be O(n^2). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + min_samples : int > 1 or float between 0 and 1, default=5 + The number of samples in a neighborhood for a point to be considered as + a core point. Also, up and down steep regions can't have more than + ``min_samples`` consecutive non-steep points. Expressed as an absolute + number or a fraction of the number of samples (rounded to be at least + 2). + + max_eps : float, default=np.inf + The maximum distance between two samples for one to be considered as + in the neighborhood of the other. Default value of ``np.inf`` will + identify clusters across all scales; reducing ``max_eps`` will result + in shorter run times. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. If metric is + "precomputed", `X` is assumed to be a distance matrix and must be + square. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + Sparse matrices are only supported by scikit-learn metrics. + See the documentation for scipy.spatial.distance for details on these + metrics. + + p : float, default=2 + Parameter for the Minkowski metric from + :class:`~sklearn.metrics.pairwise_distances`. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + cluster_method : str, default='xi' + The extraction method used to extract clusters using the calculated + reachability and ordering. Possible values are "xi" and "dbscan". + + eps : float, default=None + The maximum distance between two samples for one to be considered as + in the neighborhood of the other. By default it assumes the same value + as ``max_eps``. + Used only when ``cluster_method='dbscan'``. + + xi : float between 0 and 1, default=0.05 + Determines the minimum steepness on the reachability plot that + constitutes a cluster boundary. For example, an upwards point in the + reachability plot is defined by the ratio from one point to its + successor being at most 1-xi. + Used only when ``cluster_method='xi'``. + + predecessor_correction : bool, default=True + Correct clusters according to the predecessors calculated by OPTICS + [2]_. This parameter has minimal effect on most datasets. + Used only when ``cluster_method='xi'``. + + min_cluster_size : int > 1 or float between 0 and 1, default=None + Minimum number of samples in an OPTICS cluster, expressed as an + absolute number or a fraction of the number of samples (rounded to be + at least 2). If ``None``, the value of ``min_samples`` is used instead. + Used only when ``cluster_method='xi'``. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`BallTree`. + - 'kd_tree' will use :class:`KDTree`. + - 'brute' will use a brute-force search. + - 'auto' (default) will attempt to decide the most appropriate + algorithm based on the values passed to :meth:`fit` method. + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to :class:`BallTree` or :class:`KDTree`. This can + affect the speed of the construction and query, as well as the memory + required to store the tree. The optimal value depends on the + nature of the problem. + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + labels_ : ndarray of shape (n_samples,) + Cluster labels for each point in the dataset given to fit(). + Noisy samples and points which are not included in a leaf cluster + of ``cluster_hierarchy_`` are labeled as -1. + + reachability_ : ndarray of shape (n_samples,) + Reachability distances per sample, indexed by object order. Use + ``clust.reachability_[clust.ordering_]`` to access in cluster order. + + ordering_ : ndarray of shape (n_samples,) + The cluster ordered list of sample indices. + + core_distances_ : ndarray of shape (n_samples,) + Distance at which each sample becomes a core point, indexed by object + order. Points which will never be core have a distance of inf. Use + ``clust.core_distances_[clust.ordering_]`` to access in cluster order. + + predecessor_ : ndarray of shape (n_samples,) + Point that a sample was reached from, indexed by object order. + Seed points have a predecessor of -1. + + cluster_hierarchy_ : ndarray of shape (n_clusters, 2) + The list of clusters in the form of ``[start, end]`` in each row, with + all indices inclusive. The clusters are ordered according to + ``(end, -start)`` (ascending) so that larger clusters encompassing + smaller clusters come after those smaller ones. Since ``labels_`` does + not reflect the hierarchy, usually + ``len(cluster_hierarchy_) > np.unique(optics.labels_)``. Please also + note that these indices are of the ``ordering_``, i.e. + ``X[ordering_][start:end + 1]`` form a cluster. + Only available when ``cluster_method='xi'``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + DBSCAN : A similar clustering for a specified neighborhood radius (eps). + Our implementation is optimized for runtime. + + References + ---------- + .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, + and Jörg Sander. "OPTICS: ordering points to identify the clustering + structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60. + + .. [2] Schubert, Erich, Michael Gertz. + "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of + the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329. + + Examples + -------- + >>> from sklearn.cluster import OPTICS + >>> import numpy as np + >>> X = np.array([[1, 2], [2, 5], [3, 6], + ... [8, 7], [8, 8], [7, 3]]) + >>> clustering = OPTICS(min_samples=2).fit(X) + >>> clustering.labels_ + array([0, 0, 0, 1, 1, 1]) + """ + + _parameter_constraints: dict = { + "min_samples": [ + Interval(Integral, 2, None, closed="left"), + Interval(Real, 0, 1, closed="both"), + ], + "max_eps": [Interval(Real, 0, None, closed="both")], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + "p": [Interval(Real, 1, None, closed="left")], + "metric_params": [dict, None], + "cluster_method": [StrOptions({"dbscan", "xi"})], + "eps": [Interval(Real, 0, None, closed="both"), None], + "xi": [Interval(Real, 0, 1, closed="both")], + "predecessor_correction": ["boolean"], + "min_cluster_size": [ + Interval(Integral, 2, None, closed="left"), + Interval(Real, 0, 1, closed="right"), + None, + ], + "algorithm": [StrOptions({"auto", "brute", "ball_tree", "kd_tree"})], + "leaf_size": [Interval(Integral, 1, None, closed="left")], + "memory": [str, HasMethods("cache"), None], + "n_jobs": [Integral, None], + } + + def __init__( + self, + *, + min_samples=5, + max_eps=np.inf, + metric="minkowski", + p=2, + metric_params=None, + cluster_method="xi", + eps=None, + xi=0.05, + predecessor_correction=True, + min_cluster_size=None, + algorithm="auto", + leaf_size=30, + memory=None, + n_jobs=None, + ): + self.max_eps = max_eps + self.min_samples = min_samples + self.min_cluster_size = min_cluster_size + self.algorithm = algorithm + self.metric = metric + self.metric_params = metric_params + self.p = p + self.leaf_size = leaf_size + self.cluster_method = cluster_method + self.eps = eps + self.xi = xi + self.predecessor_correction = predecessor_correction + self.memory = memory + self.n_jobs = n_jobs + + def fit(self, X, y=None): + """Perform OPTICS clustering. + + Extracts an ordered list of points and reachability distances, and + performs initial clustering using ``max_eps`` distance specified at + OPTICS object instantiation. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features), or \ + (n_samples, n_samples) if metric='precomputed' + A feature array, or array of distances between samples if + metric='precomputed'. If a sparse matrix is provided, it will be + converted into CSR format. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Returns a fitted instance of self. + """ + self._validate_params() + + dtype = bool if self.metric in PAIRWISE_BOOLEAN_FUNCTIONS else float + if dtype == bool and X.dtype != bool: + msg = ( + "Data will be converted to boolean for" + f" metric {self.metric}, to avoid this warning," + " you may convert the data prior to calling fit." + ) + warnings.warn(msg, DataConversionWarning) + + X = self._validate_data(X, dtype=dtype, accept_sparse="csr") + if self.metric == "precomputed" and issparse(X): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SparseEfficiencyWarning) + # Set each diagonal to an explicit value so each point is its + # own neighbor + X.setdiag(X.diagonal()) + memory = check_memory(self.memory) + + ( + self.ordering_, + self.core_distances_, + self.reachability_, + self.predecessor_, + ) = memory.cache(compute_optics_graph)( + X=X, + min_samples=self.min_samples, + algorithm=self.algorithm, + leaf_size=self.leaf_size, + metric=self.metric, + metric_params=self.metric_params, + p=self.p, + n_jobs=self.n_jobs, + max_eps=self.max_eps, + ) + + # Extract clusters from the calculated orders and reachability + if self.cluster_method == "xi": + labels_, clusters_ = cluster_optics_xi( + reachability=self.reachability_, + predecessor=self.predecessor_, + ordering=self.ordering_, + min_samples=self.min_samples, + min_cluster_size=self.min_cluster_size, + xi=self.xi, + predecessor_correction=self.predecessor_correction, + ) + self.cluster_hierarchy_ = clusters_ + elif self.cluster_method == "dbscan": + if self.eps is None: + eps = self.max_eps + else: + eps = self.eps + + if eps > self.max_eps: + raise ValueError( + "Specify an epsilon smaller than %s. Got %s." % (self.max_eps, eps) + ) + + labels_ = cluster_optics_dbscan( + reachability=self.reachability_, + core_distances=self.core_distances_, + ordering=self.ordering_, + eps=eps, + ) + + self.labels_ = labels_ + return self + + +def _validate_size(size, n_samples, param_name): + if size > n_samples: + raise ValueError( + "%s must be no greater than the number of samples (%d). Got %d" + % (param_name, n_samples, size) + ) + + +# OPTICS helper functions +def _compute_core_distances_(X, neighbors, min_samples, working_memory): + """Compute the k-th nearest neighbor of each sample. + + Equivalent to neighbors.kneighbors(X, self.min_samples)[0][:, -1] + but with more memory efficiency. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + neighbors : NearestNeighbors instance + The fitted nearest neighbors estimator. + working_memory : int, default=None + The sought maximum memory for temporary distance matrix chunks. + When None (default), the value of + ``sklearn.get_config()['working_memory']`` is used. + + Returns + ------- + core_distances : ndarray of shape (n_samples,) + Distance at which each sample becomes a core point. + Points which will never be core have a distance of inf. + """ + n_samples = X.shape[0] + core_distances = np.empty(n_samples) + core_distances.fill(np.nan) + + chunk_n_rows = get_chunk_n_rows( + row_bytes=16 * min_samples, max_n_rows=n_samples, working_memory=working_memory + ) + slices = gen_batches(n_samples, chunk_n_rows) + for sl in slices: + core_distances[sl] = neighbors.kneighbors(X[sl], min_samples)[0][:, -1] + return core_distances + + +def compute_optics_graph( + X, *, min_samples, max_eps, metric, p, metric_params, algorithm, leaf_size, n_jobs +): + """Compute the OPTICS reachability graph. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features), or \ + (n_samples, n_samples) if metric='precomputed' + A feature array, or array of distances between samples if + metric='precomputed'. + + min_samples : int > 1 or float between 0 and 1 + The number of samples in a neighborhood for a point to be considered + as a core point. Expressed as an absolute number or a fraction of the + number of samples (rounded to be at least 2). + + max_eps : float, default=np.inf + The maximum distance between two samples for one to be considered as + in the neighborhood of the other. Default value of ``np.inf`` will + identify clusters across all scales; reducing ``max_eps`` will result + in shorter run times. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. If metric is + "precomputed", X is assumed to be a distance matrix and must be square. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + See the documentation for scipy.spatial.distance for details on these + metrics. + + p : int, default=2 + Parameter for the Minkowski metric from + :class:`~sklearn.metrics.pairwise_distances`. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`BallTree`. + - 'kd_tree' will use :class:`KDTree`. + - 'brute' will use a brute-force search. + - 'auto' will attempt to decide the most appropriate algorithm + based on the values passed to :meth:`fit` method. (default) + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to :class:`BallTree` or :class:`KDTree`. This can + affect the speed of the construction and query, as well as the memory + required to store the tree. The optimal value depends on the + nature of the problem. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + ordering_ : array of shape (n_samples,) + The cluster ordered list of sample indices. + + core_distances_ : array of shape (n_samples,) + Distance at which each sample becomes a core point, indexed by object + order. Points which will never be core have a distance of inf. Use + ``clust.core_distances_[clust.ordering_]`` to access in cluster order. + + reachability_ : array of shape (n_samples,) + Reachability distances per sample, indexed by object order. Use + ``clust.reachability_[clust.ordering_]`` to access in cluster order. + + predecessor_ : array of shape (n_samples,) + Point that a sample was reached from, indexed by object order. + Seed points have a predecessor of -1. + + References + ---------- + .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel, + and Jörg Sander. "OPTICS: ordering points to identify the clustering + structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60. + """ + n_samples = X.shape[0] + _validate_size(min_samples, n_samples, "min_samples") + if min_samples <= 1: + min_samples = max(2, int(min_samples * n_samples)) + + # Start all points as 'unprocessed' ## + reachability_ = np.empty(n_samples) + reachability_.fill(np.inf) + predecessor_ = np.empty(n_samples, dtype=int) + predecessor_.fill(-1) + + nbrs = NearestNeighbors( + n_neighbors=min_samples, + algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, + metric_params=metric_params, + p=p, + n_jobs=n_jobs, + ) + + nbrs.fit(X) + # Here we first do a kNN query for each point, this differs from + # the original OPTICS that only used epsilon range queries. + # TODO: handle working_memory somehow? + core_distances_ = _compute_core_distances_( + X=X, neighbors=nbrs, min_samples=min_samples, working_memory=None + ) + # OPTICS puts an upper limit on these, use inf for undefined. + core_distances_[core_distances_ > max_eps] = np.inf + np.around( + core_distances_, + decimals=np.finfo(core_distances_.dtype).precision, + out=core_distances_, + ) + + # Main OPTICS loop. Not parallelizable. The order that entries are + # written to the 'ordering_' list is important! + # Note that this implementation is O(n^2) theoretically, but + # supposedly with very low constant factors. + processed = np.zeros(X.shape[0], dtype=bool) + ordering = np.zeros(X.shape[0], dtype=int) + for ordering_idx in range(X.shape[0]): + # Choose next based on smallest reachability distance + # (And prefer smaller ids on ties, possibly np.inf!) + index = np.where(processed == 0)[0] + point = index[np.argmin(reachability_[index])] + + processed[point] = True + ordering[ordering_idx] = point + if core_distances_[point] != np.inf: + _set_reach_dist( + core_distances_=core_distances_, + reachability_=reachability_, + predecessor_=predecessor_, + point_index=point, + processed=processed, + X=X, + nbrs=nbrs, + metric=metric, + metric_params=metric_params, + p=p, + max_eps=max_eps, + ) + if np.all(np.isinf(reachability_)): + warnings.warn( + "All reachability values are inf. Set a larger" + " max_eps or all data will be considered outliers.", + UserWarning, + ) + return ordering, core_distances_, reachability_, predecessor_ + + +def _set_reach_dist( + core_distances_, + reachability_, + predecessor_, + point_index, + processed, + X, + nbrs, + metric, + metric_params, + p, + max_eps, +): + P = X[point_index : point_index + 1] + # Assume that radius_neighbors is faster without distances + # and we don't need all distances, nevertheless, this means + # we may be doing some work twice. + indices = nbrs.radius_neighbors(P, radius=max_eps, return_distance=False)[0] + + # Getting indices of neighbors that have not been processed + unproc = np.compress(~np.take(processed, indices), indices) + # Neighbors of current point are already processed. + if not unproc.size: + return + + # Only compute distances to unprocessed neighbors: + if metric == "precomputed": + dists = X[point_index, unproc] + if issparse(dists): + dists.sort_indices() + dists = dists.data + else: + _params = dict() if metric_params is None else metric_params.copy() + if metric == "minkowski" and "p" not in _params: + # the same logic as neighbors, p is ignored if explicitly set + # in the dict params + _params["p"] = p + dists = pairwise_distances(P, X[unproc], metric, n_jobs=None, **_params).ravel() + + rdists = np.maximum(dists, core_distances_[point_index]) + np.around(rdists, decimals=np.finfo(rdists.dtype).precision, out=rdists) + improved = np.where(rdists < np.take(reachability_, unproc)) + reachability_[unproc[improved]] = rdists[improved] + predecessor_[unproc[improved]] = point_index + + +def cluster_optics_dbscan(*, reachability, core_distances, ordering, eps): + """Perform DBSCAN extraction for an arbitrary epsilon. + + Extracting the clusters runs in linear time. Note that this results in + ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with + similar settings and ``eps``, only if ``eps`` is close to ``max_eps``. + + Parameters + ---------- + reachability : array of shape (n_samples,) + Reachability distances calculated by OPTICS (``reachability_``). + + core_distances : array of shape (n_samples,) + Distances at which points become core (``core_distances_``). + + ordering : array of shape (n_samples,) + OPTICS ordered point indices (``ordering_``). + + eps : float + DBSCAN ``eps`` parameter. Must be set to < ``max_eps``. Results + will be close to DBSCAN algorithm if ``eps`` and ``max_eps`` are close + to one another. + + Returns + ------- + labels_ : array of shape (n_samples,) + The estimated labels. + """ + n_samples = len(core_distances) + labels = np.zeros(n_samples, dtype=int) + + far_reach = reachability > eps + near_core = core_distances <= eps + labels[ordering] = np.cumsum(far_reach[ordering] & near_core[ordering]) - 1 + labels[far_reach & ~near_core] = -1 + return labels + + +def cluster_optics_xi( + *, + reachability, + predecessor, + ordering, + min_samples, + min_cluster_size=None, + xi=0.05, + predecessor_correction=True, +): + """Automatically extract clusters according to the Xi-steep method. + + Parameters + ---------- + reachability : ndarray of shape (n_samples,) + Reachability distances calculated by OPTICS (`reachability_`). + + predecessor : ndarray of shape (n_samples,) + Predecessors calculated by OPTICS. + + ordering : ndarray of shape (n_samples,) + OPTICS ordered point indices (`ordering_`). + + min_samples : int > 1 or float between 0 and 1 + The same as the min_samples given to OPTICS. Up and down steep regions + can't have more then ``min_samples`` consecutive non-steep points. + Expressed as an absolute number or a fraction of the number of samples + (rounded to be at least 2). + + min_cluster_size : int > 1 or float between 0 and 1, default=None + Minimum number of samples in an OPTICS cluster, expressed as an + absolute number or a fraction of the number of samples (rounded to be + at least 2). If ``None``, the value of ``min_samples`` is used instead. + + xi : float between 0 and 1, default=0.05 + Determines the minimum steepness on the reachability plot that + constitutes a cluster boundary. For example, an upwards point in the + reachability plot is defined by the ratio from one point to its + successor being at most 1-xi. + + predecessor_correction : bool, default=True + Correct clusters based on the calculated predecessors. + + Returns + ------- + labels : ndarray of shape (n_samples,) + The labels assigned to samples. Points which are not included + in any cluster are labeled as -1. + + clusters : ndarray of shape (n_clusters, 2) + The list of clusters in the form of ``[start, end]`` in each row, with + all indices inclusive. The clusters are ordered according to ``(end, + -start)`` (ascending) so that larger clusters encompassing smaller + clusters come after such nested smaller clusters. Since ``labels`` does + not reflect the hierarchy, usually ``len(clusters) > + np.unique(labels)``. + """ + n_samples = len(reachability) + _validate_size(min_samples, n_samples, "min_samples") + if min_samples <= 1: + min_samples = max(2, int(min_samples * n_samples)) + if min_cluster_size is None: + min_cluster_size = min_samples + _validate_size(min_cluster_size, n_samples, "min_cluster_size") + if min_cluster_size <= 1: + min_cluster_size = max(2, int(min_cluster_size * n_samples)) + + clusters = _xi_cluster( + reachability[ordering], + predecessor[ordering], + ordering, + xi, + min_samples, + min_cluster_size, + predecessor_correction, + ) + labels = _extract_xi_labels(ordering, clusters) + return labels, clusters + + +def _extend_region(steep_point, xward_point, start, min_samples): + """Extend the area until it's maximal. + + It's the same function for both upward and downward reagions, depending on + the given input parameters. Assuming: + + - steep_{upward/downward}: bool array indicating whether a point is a + steep {upward/downward}; + - upward/downward: bool array indicating whether a point is + upward/downward; + + To extend an upward reagion, ``steep_point=steep_upward`` and + ``xward_point=downward`` are expected, and to extend a downward region, + ``steep_point=steep_downward`` and ``xward_point=upward``. + + Parameters + ---------- + steep_point : ndarray of shape (n_samples,), dtype=bool + True if the point is steep downward (upward). + + xward_point : ndarray of shape (n_samples,), dtype=bool + True if the point is an upward (respectively downward) point. + + start : int + The start of the xward region. + + min_samples : int + The same as the min_samples given to OPTICS. Up and down steep + regions can't have more then ``min_samples`` consecutive non-steep + points. + + Returns + ------- + index : int + The current index iterating over all the samples, i.e. where we are up + to in our search. + + end : int + The end of the region, which can be behind the index. The region + includes the ``end`` index. + """ + n_samples = len(steep_point) + non_xward_points = 0 + index = start + end = start + # find a maximal area + while index < n_samples: + if steep_point[index]: + non_xward_points = 0 + end = index + elif not xward_point[index]: + # it's not a steep point, but still goes up. + non_xward_points += 1 + # region should include no more than min_samples consecutive + # non steep xward points. + if non_xward_points > min_samples: + break + else: + return end + index += 1 + return end + + +def _update_filter_sdas(sdas, mib, xi_complement, reachability_plot): + """Update steep down areas (SDAs) using the new maximum in between (mib) + value, and the given complement of xi, i.e. ``1 - xi``. + """ + if np.isinf(mib): + return [] + res = [ + sda for sda in sdas if mib <= reachability_plot[sda["start"]] * xi_complement + ] + for sda in res: + sda["mib"] = max(sda["mib"], mib) + return res + + +def _correct_predecessor(reachability_plot, predecessor_plot, ordering, s, e): + """Correct for predecessors. + + Applies Algorithm 2 of [1]_. + + Input parameters are ordered by the computer OPTICS ordering. + + .. [1] Schubert, Erich, Michael Gertz. + "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of + the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329. + """ + while s < e: + if reachability_plot[s] > reachability_plot[e]: + return s, e + p_e = ordering[predecessor_plot[e]] + for i in range(s, e): + if p_e == ordering[i]: + return s, e + e -= 1 + return None, None + + +def _xi_cluster( + reachability_plot, + predecessor_plot, + ordering, + xi, + min_samples, + min_cluster_size, + predecessor_correction, +): + """Automatically extract clusters according to the Xi-steep method. + + This is rouphly an implementation of Figure 19 of the OPTICS paper. + + Parameters + ---------- + reachability_plot : array-like of shape (n_samples,) + The reachability plot, i.e. reachability ordered according to + the calculated ordering, all computed by OPTICS. + + predecessor_plot : array-like of shape (n_samples,) + Predecessors ordered according to the calculated ordering. + + xi : float, between 0 and 1 + Determines the minimum steepness on the reachability plot that + constitutes a cluster boundary. For example, an upwards point in the + reachability plot is defined by the ratio from one point to its + successor being at most 1-xi. + + min_samples : int > 1 + The same as the min_samples given to OPTICS. Up and down steep regions + can't have more then ``min_samples`` consecutive non-steep points. + + min_cluster_size : int > 1 + Minimum number of samples in an OPTICS cluster. + + predecessor_correction : bool + Correct clusters based on the calculated predecessors. + + Returns + ------- + clusters : ndarray of shape (n_clusters, 2) + The list of clusters in the form of [start, end] in each row, with all + indices inclusive. The clusters are ordered in a way that larger + clusters encompassing smaller clusters come after those smaller + clusters. + """ + + # Our implementation adds an inf to the end of reachability plot + # this helps to find potential clusters at the end of the + # reachability plot even if there's no upward region at the end of it. + reachability_plot = np.hstack((reachability_plot, np.inf)) + + xi_complement = 1 - xi + sdas = [] # steep down areas, introduced in section 4.3.2 of the paper + clusters = [] + index = 0 + mib = 0.0 # maximum in between, section 4.3.2 + + # Our implementation corrects a mistake in the original + # paper, i.e., in Definition 9 steep downward point, + # r(p) * (1 - x1) <= r(p + 1) should be + # r(p) * (1 - x1) >= r(p + 1) + with np.errstate(invalid="ignore"): + ratio = reachability_plot[:-1] / reachability_plot[1:] + steep_upward = ratio <= xi_complement + steep_downward = ratio >= 1 / xi_complement + downward = ratio > 1 + upward = ratio < 1 + + # the following loop is almost exactly as Figure 19 of the paper. + # it jumps over the areas which are not either steep down or up areas + for steep_index in iter(np.flatnonzero(steep_upward | steep_downward)): + # just continue if steep_index has been a part of a discovered xward + # area. + if steep_index < index: + continue + + mib = max(mib, np.max(reachability_plot[index : steep_index + 1])) + + # steep downward areas + if steep_downward[steep_index]: + sdas = _update_filter_sdas(sdas, mib, xi_complement, reachability_plot) + D_start = steep_index + D_end = _extend_region(steep_downward, upward, D_start, min_samples) + D = {"start": D_start, "end": D_end, "mib": 0.0} + sdas.append(D) + index = D_end + 1 + mib = reachability_plot[index] + + # steep upward areas + else: + sdas = _update_filter_sdas(sdas, mib, xi_complement, reachability_plot) + U_start = steep_index + U_end = _extend_region(steep_upward, downward, U_start, min_samples) + index = U_end + 1 + mib = reachability_plot[index] + + U_clusters = [] + for D in sdas: + c_start = D["start"] + c_end = U_end + + # line (**), sc2* + if reachability_plot[c_end + 1] * xi_complement < D["mib"]: + continue + + # Definition 11: criterion 4 + D_max = reachability_plot[D["start"]] + if D_max * xi_complement >= reachability_plot[c_end + 1]: + # Find the first index from the left side which is almost + # at the same level as the end of the detected cluster. + while ( + reachability_plot[c_start + 1] > reachability_plot[c_end + 1] + and c_start < D["end"] + ): + c_start += 1 + elif reachability_plot[c_end + 1] * xi_complement >= D_max: + # Find the first index from the right side which is almost + # at the same level as the beginning of the detected + # cluster. + # Our implementation corrects a mistake in the original + # paper, i.e., in Definition 11 4c, r(x) < r(sD) should be + # r(x) > r(sD). + while reachability_plot[c_end - 1] > D_max and c_end > U_start: + c_end -= 1 + + # predecessor correction + if predecessor_correction: + c_start, c_end = _correct_predecessor( + reachability_plot, predecessor_plot, ordering, c_start, c_end + ) + if c_start is None: + continue + + # Definition 11: criterion 3.a + if c_end - c_start + 1 < min_cluster_size: + continue + + # Definition 11: criterion 1 + if c_start > D["end"]: + continue + + # Definition 11: criterion 2 + if c_end < U_start: + continue + + U_clusters.append((c_start, c_end)) + + # add smaller clusters first. + U_clusters.reverse() + clusters.extend(U_clusters) + + return np.array(clusters) + + +def _extract_xi_labels(ordering, clusters): + """Extracts the labels from the clusters returned by `_xi_cluster`. + We rely on the fact that clusters are stored + with the smaller clusters coming before the larger ones. + + Parameters + ---------- + ordering : array-like of shape (n_samples,) + The ordering of points calculated by OPTICS + + clusters : array-like of shape (n_clusters, 2) + List of clusters i.e. (start, end) tuples, + as returned by `_xi_cluster`. + + Returns + ------- + labels : ndarray of shape (n_samples,) + """ + + labels = np.full(len(ordering), -1, dtype=int) + label = 0 + for c in clusters: + if not np.any(labels[c[0] : (c[1] + 1)] != -1): + labels[c[0] : (c[1] + 1)] = label + label += 1 + labels[ordering] = labels.copy() + return labels diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/_spectral.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..25f5ee7f9453cf002eeb3e6df99ed627ebd8184b --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/_spectral.py @@ -0,0 +1,791 @@ +"""Algorithms for spectral clustering""" + +# Author: Gael Varoquaux +# Brian Cheung +# Wei LI +# Andrew Knyazev +# License: BSD 3 clause + +from numbers import Integral, Real +import warnings + +import numpy as np + +from scipy.linalg import LinAlgError, qr, svd +from scipy.sparse import csc_matrix + +from ..base import BaseEstimator, ClusterMixin +from ..utils._param_validation import Interval, StrOptions +from ..utils import check_random_state, as_float_array +from ..metrics.pairwise import pairwise_kernels, KERNEL_PARAMS +from ..neighbors import kneighbors_graph, NearestNeighbors +from ..manifold import spectral_embedding +from ._kmeans import k_means + + +def cluster_qr(vectors): + """Find the discrete partition closest to the eigenvector embedding. + + This implementation was proposed in [1]_. + + .. versionadded:: 1.1 + + Parameters + ---------- + vectors : array-like, shape: (n_samples, n_clusters) + The embedding space of the samples. + + Returns + ------- + labels : array of integers, shape: n_samples + The cluster labels of vectors. + + References + ---------- + .. [1] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + """ + + k = vectors.shape[1] + _, _, piv = qr(vectors.T, pivoting=True) + ut, _, v = svd(vectors[piv[:k], :].T) + vectors = abs(np.dot(vectors, np.dot(ut, v.conj()))) + return vectors.argmax(axis=1) + + +def discretize( + vectors, *, copy=True, max_svd_restarts=30, n_iter_max=20, random_state=None +): + """Search for a partition matrix which is closest to the eigenvector embedding. + + This implementation was proposed in [1]_. + + Parameters + ---------- + vectors : array-like of shape (n_samples, n_clusters) + The embedding space of the samples. + + copy : bool, default=True + Whether to copy vectors, or perform in-place normalization. + + max_svd_restarts : int, default=30 + Maximum number of attempts to restart SVD if convergence fails + + n_iter_max : int, default=30 + Maximum number of iterations to attempt in rotation and partition + matrix search if machine precision convergence is not reached + + random_state : int, RandomState instance, default=None + Determines random number generation for rotation matrix initialization. + Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Returns + ------- + labels : array of integers, shape: n_samples + The labels of the clusters. + + References + ---------- + + .. [1] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + Notes + ----- + + The eigenvector embedding is used to iteratively search for the + closest discrete partition. First, the eigenvector embedding is + normalized to the space of partition matrices. An optimal discrete + partition matrix closest to this normalized embedding multiplied by + an initial rotation is calculated. Fixing this discrete partition + matrix, an optimal rotation matrix is calculated. These two + calculations are performed until convergence. The discrete partition + matrix is returned as the clustering solution. Used in spectral + clustering, this method tends to be faster and more robust to random + initialization than k-means. + + """ + + random_state = check_random_state(random_state) + + vectors = as_float_array(vectors, copy=copy) + + eps = np.finfo(float).eps + n_samples, n_components = vectors.shape + + # Normalize the eigenvectors to an equal length of a vector of ones. + # Reorient the eigenvectors to point in the negative direction with respect + # to the first element. This may have to do with constraining the + # eigenvectors to lie in a specific quadrant to make the discretization + # search easier. + norm_ones = np.sqrt(n_samples) + for i in range(vectors.shape[1]): + vectors[:, i] = (vectors[:, i] / np.linalg.norm(vectors[:, i])) * norm_ones + if vectors[0, i] != 0: + vectors[:, i] = -1 * vectors[:, i] * np.sign(vectors[0, i]) + + # Normalize the rows of the eigenvectors. Samples should lie on the unit + # hypersphere centered at the origin. This transforms the samples in the + # embedding space to the space of partition matrices. + vectors = vectors / np.sqrt((vectors**2).sum(axis=1))[:, np.newaxis] + + svd_restarts = 0 + has_converged = False + + # If there is an exception we try to randomize and rerun SVD again + # do this max_svd_restarts times. + while (svd_restarts < max_svd_restarts) and not has_converged: + + # Initialize first column of rotation matrix with a row of the + # eigenvectors + rotation = np.zeros((n_components, n_components)) + rotation[:, 0] = vectors[random_state.randint(n_samples), :].T + + # To initialize the rest of the rotation matrix, find the rows + # of the eigenvectors that are as orthogonal to each other as + # possible + c = np.zeros(n_samples) + for j in range(1, n_components): + # Accumulate c to ensure row is as orthogonal as possible to + # previous picks as well as current one + c += np.abs(np.dot(vectors, rotation[:, j - 1])) + rotation[:, j] = vectors[c.argmin(), :].T + + last_objective_value = 0.0 + n_iter = 0 + + while not has_converged: + n_iter += 1 + + t_discrete = np.dot(vectors, rotation) + + labels = t_discrete.argmax(axis=1) + vectors_discrete = csc_matrix( + (np.ones(len(labels)), (np.arange(0, n_samples), labels)), + shape=(n_samples, n_components), + ) + + t_svd = vectors_discrete.T * vectors + + try: + U, S, Vh = np.linalg.svd(t_svd) + except LinAlgError: + svd_restarts += 1 + print("SVD did not converge, randomizing and trying again") + break + + ncut_value = 2.0 * (n_samples - S.sum()) + if (abs(ncut_value - last_objective_value) < eps) or (n_iter > n_iter_max): + has_converged = True + else: + # otherwise calculate rotation and continue + last_objective_value = ncut_value + rotation = np.dot(Vh.T, U.T) + + if not has_converged: + raise LinAlgError("SVD did not converge") + return labels + + +def spectral_clustering( + affinity, + *, + n_clusters=8, + n_components=None, + eigen_solver=None, + random_state=None, + n_init=10, + eigen_tol="auto", + assign_labels="kmeans", + verbose=False, +): + """Apply clustering to a projection of the normalized Laplacian. + + In practice Spectral Clustering is very useful when the structure of + the individual clusters is highly non-convex or more generally when + a measure of the center and spread of the cluster is not a suitable + description of the complete cluster. For instance, when clusters are + nested circles on the 2D plane. + + If affinity is the adjacency matrix of a graph, this method can be + used to find normalized graph cuts [1]_, [2]_. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + affinity : {array-like, sparse matrix} of shape (n_samples, n_samples) + The affinity matrix describing the relationship of the samples to + embed. **Must be symmetric**. + + Possible examples: + - adjacency matrix of a graph, + - heat kernel of the pairwise distance matrix of the samples, + - symmetric k-nearest neighbours connectivity matrix of the samples. + + n_clusters : int, default=None + Number of clusters to extract. + + n_components : int, default=n_clusters + Number of eigenvectors to use for the spectral embedding. + + eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} + The eigenvalue decomposition method. If None then ``'arpack'`` is used. + See [4]_ for more details regarding ``'lobpcg'``. + Eigensolver ``'amg'`` runs ``'lobpcg'`` with optional + Algebraic MultiGrid preconditioning and requires pyamg to be installed. + It can be faster on very large sparse problems [6]_ and [7]_. + + random_state : int, RandomState instance, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigenvectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + n_init : int, default=10 + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of n_init + consecutive runs in terms of inertia. Only used if + ``assign_labels='kmeans'``. + + eigen_tol : float, default="auto" + Stopping criterion for eigendecomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"` + values of `tol<1e-5` may lead to convergence issues and should be + avoided. + + .. versionadded:: 1.2 + Added 'auto' option. + + assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans' + The strategy to use to assign labels in the embedding + space. There are three ways to assign labels after the Laplacian + embedding. k-means can be applied and is a popular choice. But it can + also be sensitive to initialization. Discretization is another + approach which is less sensitive to random initialization [3]_. + The cluster_qr method [5]_ directly extracts clusters from eigenvectors + in spectral clustering. In contrast to k-means and discretization, cluster_qr + has no tuning parameters and is not an iterative method, yet may outperform + k-means and discretization in terms of both quality and speed. + + .. versionchanged:: 1.1 + Added new labeling method 'cluster_qr'. + + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + + Returns + ------- + labels : array of integers, shape: n_samples + The labels of the clusters. + + Notes + ----- + The graph should contain only one connected component, elsewhere + the results make little sense. + + This algorithm solves the normalized cut for `k=2`: it is a + normalized spectral clustering. + + References + ---------- + + .. [1] :doi:`Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + <10.1109/34.868688>` + + .. [2] :doi:`A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + <10.1007/s11222-007-9033-z>` + + .. [3] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver: + Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001 + A. V. Knyazev + SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541. + <10.1137/S1064827500366124>` + + .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + .. [6] :doi:`Multiscale Spectral Image Segmentation Multiscale preconditioning + for computing eigenvalues of graph Laplacians in image segmentation, 2006 + Andrew Knyazev + <10.13140/RG.2.2.35280.02565>` + + .. [7] :doi:`Preconditioned spectral clustering for stochastic block partition + streaming graph challenge (Preliminary version at arXiv.) + David Zhuzhunashvili, Andrew Knyazev + <10.1109/HPEC.2017.8091045>` + """ + if assign_labels not in ("kmeans", "discretize", "cluster_qr"): + raise ValueError( + "The 'assign_labels' parameter should be " + "'kmeans' or 'discretize', or 'cluster_qr', " + f"but {assign_labels!r} was given" + ) + if isinstance(affinity, np.matrix): + raise TypeError( + "spectral_clustering does not support passing in affinity as an " + "np.matrix. Please convert to a numpy array with np.asarray. For " + "more information see: " + "https://numpy.org/doc/stable/reference/generated/numpy.matrix.html", # noqa + ) + + random_state = check_random_state(random_state) + n_components = n_clusters if n_components is None else n_components + + # We now obtain the real valued solution matrix to the + # relaxed Ncut problem, solving the eigenvalue problem + # L_sym x = lambda x and recovering u = D^-1/2 x. + # The first eigenvector is constant only for fully connected graphs + # and should be kept for spectral clustering (drop_first = False) + # See spectral_embedding documentation. + maps = spectral_embedding( + affinity, + n_components=n_components, + eigen_solver=eigen_solver, + random_state=random_state, + eigen_tol=eigen_tol, + drop_first=False, + ) + if verbose: + print(f"Computing label assignment using {assign_labels}") + + if assign_labels == "kmeans": + _, labels, _ = k_means( + maps, n_clusters, random_state=random_state, n_init=n_init, verbose=verbose + ) + elif assign_labels == "cluster_qr": + labels = cluster_qr(maps) + else: + labels = discretize(maps, random_state=random_state) + + return labels + + +class SpectralClustering(ClusterMixin, BaseEstimator): + """Apply clustering to a projection of the normalized Laplacian. + + In practice Spectral Clustering is very useful when the structure of + the individual clusters is highly non-convex, or more generally when + a measure of the center and spread of the cluster is not a suitable + description of the complete cluster, such as when clusters are + nested circles on the 2D plane. + + If the affinity matrix is the adjacency matrix of a graph, this method + can be used to find normalized graph cuts [1]_, [2]_. + + When calling ``fit``, an affinity matrix is constructed using either + a kernel function such the Gaussian (aka RBF) kernel with Euclidean + distance ``d(X, X)``:: + + np.exp(-gamma * d(X,X) ** 2) + + or a k-nearest neighbors connectivity matrix. + + Alternatively, a user-provided affinity matrix can be specified by + setting ``affinity='precomputed'``. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int, default=8 + The dimension of the projection subspace. + + eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None + The eigenvalue decomposition strategy to use. AMG requires pyamg + to be installed. It can be faster on very large, sparse problems, + but may also lead to instabilities. If None, then ``'arpack'`` is + used. See [4]_ for more details regarding `'lobpcg'`. + + n_components : int, default=None + Number of eigenvectors to use for the spectral embedding. If None, + defaults to `n_clusters`. + + random_state : int, RandomState instance, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigenvectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + n_init : int, default=10 + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of n_init + consecutive runs in terms of inertia. Only used if + ``assign_labels='kmeans'``. + + gamma : float, default=1.0 + Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. + Ignored for ``affinity='nearest_neighbors'``. + + affinity : str or callable, default='rbf' + How to construct the affinity matrix. + - 'nearest_neighbors': construct the affinity matrix by computing a + graph of nearest neighbors. + - 'rbf': construct the affinity matrix using a radial basis function + (RBF) kernel. + - 'precomputed': interpret ``X`` as a precomputed affinity matrix, + where larger values indicate greater similarity between instances. + - 'precomputed_nearest_neighbors': interpret ``X`` as a sparse graph + of precomputed distances, and construct a binary affinity matrix + from the ``n_neighbors`` nearest neighbors of each instance. + - one of the kernels supported by + :func:`~sklearn.metrics.pairwise_kernels`. + + Only kernels that produce similarity scores (non-negative values that + increase with similarity) should be used. This property is not checked + by the clustering algorithm. + + n_neighbors : int, default=10 + Number of neighbors to use when constructing the affinity matrix using + the nearest neighbors method. Ignored for ``affinity='rbf'``. + + eigen_tol : float, default="auto" + Stopping criterion for eigendecomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"` + values of `tol<1e-5` may lead to convergence issues and should be + avoided. + + .. versionadded:: 1.2 + Added 'auto' option. + + assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans' + The strategy for assigning labels in the embedding space. There are two + ways to assign labels after the Laplacian embedding. k-means is a + popular choice, but it can be sensitive to initialization. + Discretization is another approach which is less sensitive to random + initialization [3]_. + The cluster_qr method [5]_ directly extract clusters from eigenvectors + in spectral clustering. In contrast to k-means and discretization, cluster_qr + has no tuning parameters and runs no iterations, yet may outperform + k-means and discretization in terms of both quality and speed. + + .. versionchanged:: 1.1 + Added new labeling method 'cluster_qr'. + + degree : float, default=3 + Degree of the polynomial kernel. Ignored by other kernels. + + coef0 : float, default=1 + Zero coefficient for polynomial and sigmoid kernels. + Ignored by other kernels. + + kernel_params : dict of str to any, default=None + Parameters (keyword arguments) and values for kernel passed as + callable object. Ignored by other kernels. + + n_jobs : int, default=None + The number of parallel jobs to run when `affinity='nearest_neighbors'` + or `affinity='precomputed_nearest_neighbors'`. The neighbors search + will be done in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + + Attributes + ---------- + affinity_matrix_ : array-like of shape (n_samples, n_samples) + Affinity matrix used for clustering. Available only after calling + ``fit``. + + labels_ : ndarray of shape (n_samples,) + Labels of each point + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.cluster.KMeans : K-Means clustering. + sklearn.cluster.DBSCAN : Density-Based Spatial Clustering of + Applications with Noise. + + Notes + ----- + A distance matrix for which 0 indicates identical elements and high values + indicate very dissimilar elements can be transformed into an affinity / + similarity matrix that is well-suited for the algorithm by + applying the Gaussian (aka RBF, heat) kernel:: + + np.exp(- dist_matrix ** 2 / (2. * delta ** 2)) + + where ``delta`` is a free parameter representing the width of the Gaussian + kernel. + + An alternative is to take a symmetric version of the k-nearest neighbors + connectivity matrix of the points. + + If the pyamg package is installed, it is used: this greatly + speeds up computation. + + References + ---------- + .. [1] :doi:`Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + <10.1109/34.868688>` + + .. [2] :doi:`A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + <10.1007/s11222-007-9033-z>` + + .. [3] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver: + Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001 + A. V. Knyazev + SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541. + <10.1137/S1064827500366124>` + + .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + Examples + -------- + >>> from sklearn.cluster import SpectralClustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralClustering(n_clusters=2, + ... assign_labels='discretize', + ... random_state=0).fit(X) + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + >>> clustering + SpectralClustering(assign_labels='discretize', n_clusters=2, + random_state=0) + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "eigen_solver": [StrOptions({"arpack", "lobpcg", "amg"}), None], + "n_components": [Interval(Integral, 1, None, closed="left"), None], + "random_state": ["random_state"], + "n_init": [Interval(Integral, 1, None, closed="left")], + "gamma": [Interval(Real, 0, None, closed="left")], + "affinity": [ + callable, + StrOptions( + set(KERNEL_PARAMS) + | {"nearest_neighbors", "precomputed", "precomputed_nearest_neighbors"} + ), + ], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "eigen_tol": [ + Interval(Real, 0.0, None, closed="left"), + StrOptions({"auto"}), + ], + "assign_labels": [StrOptions({"kmeans", "discretize", "cluster_qr"})], + "degree": [Interval(Integral, 0, None, closed="left")], + "coef0": [Interval(Real, None, None, closed="neither")], + "kernel_params": [dict, None], + "n_jobs": [Integral, None], + "verbose": ["verbose"], + } + + def __init__( + self, + n_clusters=8, + *, + eigen_solver=None, + n_components=None, + random_state=None, + n_init=10, + gamma=1.0, + affinity="rbf", + n_neighbors=10, + eigen_tol="auto", + assign_labels="kmeans", + degree=3, + coef0=1, + kernel_params=None, + n_jobs=None, + verbose=False, + ): + self.n_clusters = n_clusters + self.eigen_solver = eigen_solver + self.n_components = n_components + self.random_state = random_state + self.n_init = n_init + self.gamma = gamma + self.affinity = affinity + self.n_neighbors = n_neighbors + self.eigen_tol = eigen_tol + self.assign_labels = assign_labels + self.degree = degree + self.coef0 = coef0 + self.kernel_params = kernel_params + self.n_jobs = n_jobs + self.verbose = verbose + + def fit(self, X, y=None): + """Perform spectral clustering from features, or affinity matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, similarities / affinities between + instances if ``affinity='precomputed'``, or distances between + instances if ``affinity='precomputed_nearest_neighbors``. If a + sparse matrix is provided in a format other than ``csr_matrix``, + ``csc_matrix``, or ``coo_matrix``, it will be converted into a + sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + A fitted instance of the estimator. + """ + self._validate_params() + + X = self._validate_data( + X, + accept_sparse=["csr", "csc", "coo"], + dtype=np.float64, + ensure_min_samples=2, + ) + allow_squared = self.affinity in [ + "precomputed", + "precomputed_nearest_neighbors", + ] + if X.shape[0] == X.shape[1] and not allow_squared: + warnings.warn( + "The spectral clustering API has changed. ``fit``" + "now constructs an affinity matrix from data. To use" + " a custom affinity matrix, " + "set ``affinity=precomputed``." + ) + + if self.affinity == "nearest_neighbors": + connectivity = kneighbors_graph( + X, n_neighbors=self.n_neighbors, include_self=True, n_jobs=self.n_jobs + ) + self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) + elif self.affinity == "precomputed_nearest_neighbors": + estimator = NearestNeighbors( + n_neighbors=self.n_neighbors, n_jobs=self.n_jobs, metric="precomputed" + ).fit(X) + connectivity = estimator.kneighbors_graph(X=X, mode="connectivity") + self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) + elif self.affinity == "precomputed": + self.affinity_matrix_ = X + else: + params = self.kernel_params + if params is None: + params = {} + if not callable(self.affinity): + params["gamma"] = self.gamma + params["degree"] = self.degree + params["coef0"] = self.coef0 + self.affinity_matrix_ = pairwise_kernels( + X, metric=self.affinity, filter_params=True, **params + ) + + random_state = check_random_state(self.random_state) + self.labels_ = spectral_clustering( + self.affinity_matrix_, + n_clusters=self.n_clusters, + n_components=self.n_components, + eigen_solver=self.eigen_solver, + random_state=random_state, + n_init=self.n_init, + eigen_tol=self.eigen_tol, + assign_labels=self.assign_labels, + verbose=self.verbose, + ) + return self + + def fit_predict(self, X, y=None): + """Perform spectral clustering on `X` and return cluster labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, similarities / affinities between + instances if ``affinity='precomputed'``, or distances between + instances if ``affinity='precomputed_nearest_neighbors``. If a + sparse matrix is provided in a format other than ``csr_matrix``, + ``csc_matrix``, or ``coo_matrix``, it will be converted into a + sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) + + def _more_tags(self): + return { + "pairwise": self.affinity + in ["precomputed", "precomputed_nearest_neighbors"] + } diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__init__.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/common.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c8fd28af448d0dfd7b9dd5e2efc9e5ce3f75177 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/common.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_bicluster.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_bicluster.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc169ad2ece9afd6ff6fb99a6cf5b7454bab9302 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_bicluster.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_dbscan.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_dbscan.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc33da81dfbcc34a2243bc3ecf7e52f3dbd73865 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_dbscan.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_feature_agglomeration.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_feature_agglomeration.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e925ae394294d721c30e98d28e959eb6432b88e Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_feature_agglomeration.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_hierarchical.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_hierarchical.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..038856d23e576151293fe42660e5f9ab386991be Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_hierarchical.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_k_means.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_k_means.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ade0866c93d89ce8ba5a23a760978d18a12e3429 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_k_means.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_mean_shift.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_mean_shift.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daf5a7522f5650bc3de04b3e0dbe01c50547f49c Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_mean_shift.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_optics.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_optics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a49f5a7f5dd515597d9d8bb5847f56b9eefd66c2 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/__pycache__/test_optics.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_bicluster.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..d04e9dba4fade8fe9e32e5283c0a0d9a5518a0a8 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_bicluster.py @@ -0,0 +1,261 @@ +"""Testing for Spectral Biclustering methods""" + +import numpy as np +import pytest +from scipy.sparse import csr_matrix, issparse + +from sklearn.model_selection import ParameterGrid + +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_almost_equal + +from sklearn.base import BaseEstimator, BiclusterMixin + +from sklearn.cluster import SpectralCoclustering +from sklearn.cluster import SpectralBiclustering +from sklearn.cluster._bicluster import _scale_normalize +from sklearn.cluster._bicluster import _bistochastic_normalize +from sklearn.cluster._bicluster import _log_normalize + +from sklearn.metrics import consensus_score, v_measure_score + +from sklearn.datasets import make_biclusters, make_checkerboard + + +class MockBiclustering(BiclusterMixin, BaseEstimator): + # Mock object for testing get_submatrix. + def __init__(self): + pass + + def get_indices(self, i): + # Overridden to reproduce old get_submatrix test. + return ( + np.where([True, True, False, False, True])[0], + np.where([False, False, True, True])[0], + ) + + +def test_get_submatrix(): + data = np.arange(20).reshape(5, 4) + model = MockBiclustering() + + for X in (data, csr_matrix(data), data.tolist()): + submatrix = model.get_submatrix(0, X) + if issparse(submatrix): + submatrix = submatrix.toarray() + assert_array_equal(submatrix, [[2, 3], [6, 7], [18, 19]]) + submatrix[:] = -1 + if issparse(X): + X = X.toarray() + assert np.all(X != -1) + + +def _test_shape_indices(model): + # Test get_shape and get_indices on fitted model. + for i in range(model.n_clusters): + m, n = model.get_shape(i) + i_ind, j_ind = model.get_indices(i) + assert len(i_ind) == m + assert len(j_ind) == n + + +def test_spectral_coclustering(global_random_seed): + # Test Dhillon's Spectral CoClustering on a simple problem. + param_grid = { + "svd_method": ["randomized", "arpack"], + "n_svd_vecs": [None, 20], + "mini_batch": [False, True], + "init": ["k-means++"], + "n_init": [10], + } + S, rows, cols = make_biclusters( + (30, 30), 3, noise=0.1, random_state=global_random_seed + ) + S -= S.min() # needs to be nonnegative before making it sparse + S = np.where(S < 1, 0, S) # threshold some values + for mat in (S, csr_matrix(S)): + for kwargs in ParameterGrid(param_grid): + model = SpectralCoclustering( + n_clusters=3, random_state=global_random_seed, **kwargs + ) + model.fit(mat) + + assert model.rows_.shape == (3, 30) + assert_array_equal(model.rows_.sum(axis=0), np.ones(30)) + assert_array_equal(model.columns_.sum(axis=0), np.ones(30)) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + _test_shape_indices(model) + + +def test_spectral_biclustering(global_random_seed): + # Test Kluger methods on a checkerboard dataset. + S, rows, cols = make_checkerboard( + (30, 30), 3, noise=0.5, random_state=global_random_seed + ) + + non_default_params = { + "method": ["scale", "log"], + "svd_method": ["arpack"], + "n_svd_vecs": [20], + "mini_batch": [True], + } + + for mat in (S, csr_matrix(S)): + for param_name, param_values in non_default_params.items(): + for param_value in param_values: + + model = SpectralBiclustering( + n_clusters=3, + n_init=3, + init="k-means++", + random_state=global_random_seed, + ) + model.set_params(**dict([(param_name, param_value)])) + + if issparse(mat) and model.get_params().get("method") == "log": + # cannot take log of sparse matrix + with pytest.raises(ValueError): + model.fit(mat) + continue + else: + model.fit(mat) + + assert model.rows_.shape == (9, 30) + assert model.columns_.shape == (9, 30) + assert_array_equal(model.rows_.sum(axis=0), np.repeat(3, 30)) + assert_array_equal(model.columns_.sum(axis=0), np.repeat(3, 30)) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + _test_shape_indices(model) + + +def _do_scale_test(scaled): + """Check that rows sum to one constant, and columns to another.""" + row_sum = scaled.sum(axis=1) + col_sum = scaled.sum(axis=0) + if issparse(scaled): + row_sum = np.asarray(row_sum).squeeze() + col_sum = np.asarray(col_sum).squeeze() + assert_array_almost_equal(row_sum, np.tile(row_sum.mean(), 100), decimal=1) + assert_array_almost_equal(col_sum, np.tile(col_sum.mean(), 100), decimal=1) + + +def _do_bistochastic_test(scaled): + """Check that rows and columns sum to the same constant.""" + _do_scale_test(scaled) + assert_almost_equal(scaled.sum(axis=0).mean(), scaled.sum(axis=1).mean(), decimal=1) + + +def test_scale_normalize(global_random_seed): + generator = np.random.RandomState(global_random_seed) + X = generator.rand(100, 100) + for mat in (X, csr_matrix(X)): + scaled, _, _ = _scale_normalize(mat) + _do_scale_test(scaled) + if issparse(mat): + assert issparse(scaled) + + +def test_bistochastic_normalize(global_random_seed): + generator = np.random.RandomState(global_random_seed) + X = generator.rand(100, 100) + for mat in (X, csr_matrix(X)): + scaled = _bistochastic_normalize(mat) + _do_bistochastic_test(scaled) + if issparse(mat): + assert issparse(scaled) + + +def test_log_normalize(global_random_seed): + # adding any constant to a log-scaled matrix should make it + # bistochastic + generator = np.random.RandomState(global_random_seed) + mat = generator.rand(100, 100) + scaled = _log_normalize(mat) + 1 + _do_bistochastic_test(scaled) + + +def test_fit_best_piecewise(global_random_seed): + model = SpectralBiclustering(random_state=global_random_seed) + vectors = np.array([[0, 0, 0, 1, 1, 1], [2, 2, 2, 3, 3, 3], [0, 1, 2, 3, 4, 5]]) + best = model._fit_best_piecewise(vectors, n_best=2, n_clusters=2) + assert_array_equal(best, vectors[:2]) + + +def test_project_and_cluster(global_random_seed): + model = SpectralBiclustering(random_state=global_random_seed) + data = np.array([[1, 1, 1], [1, 1, 1], [3, 6, 3], [3, 6, 3]]) + vectors = np.array([[1, 0], [0, 1], [0, 0]]) + for mat in (data, csr_matrix(data)): + labels = model._project_and_cluster(mat, vectors, n_clusters=2) + assert_almost_equal(v_measure_score(labels, [0, 0, 1, 1]), 1.0) + + +def test_perfect_checkerboard(global_random_seed): + # XXX Previously failed on build bot (not reproducible) + model = SpectralBiclustering( + 3, svd_method="arpack", random_state=global_random_seed + ) + + S, rows, cols = make_checkerboard( + (30, 30), 3, noise=0, random_state=global_random_seed + ) + model.fit(S) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + S, rows, cols = make_checkerboard( + (40, 30), 3, noise=0, random_state=global_random_seed + ) + model.fit(S) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + S, rows, cols = make_checkerboard( + (30, 40), 3, noise=0, random_state=global_random_seed + ) + model.fit(S) + assert consensus_score(model.biclusters_, (rows, cols)) == 1 + + +@pytest.mark.parametrize( + "params, type_err, err_msg", + [ + ( + {"n_clusters": 6}, + ValueError, + "n_clusters should be <= n_samples=5", + ), + ( + {"n_clusters": (3, 3, 3)}, + ValueError, + "Incorrect parameter n_clusters", + ), + ( + {"n_clusters": (3, 6)}, + ValueError, + "Incorrect parameter n_clusters", + ), + ( + {"n_components": 3, "n_best": 4}, + ValueError, + "n_best=4 must be <= n_components=3", + ), + ], +) +def test_spectralbiclustering_parameter_validation(params, type_err, err_msg): + """Check parameters validation in `SpectralBiClustering`""" + data = np.arange(25).reshape((5, 5)) + model = SpectralBiclustering(**params) + with pytest.raises(type_err, match=err_msg): + model.fit(data) + + +@pytest.mark.parametrize("est", (SpectralBiclustering(), SpectralCoclustering())) +def test_n_features_in_(est): + + X, _, _ = make_biclusters((3, 3), 3, random_state=0) + + assert not hasattr(est, "n_features_in_") + est.fit(X) + assert est.n_features_in_ == 3 diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_hierarchical.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_hierarchical.py new file mode 100644 index 0000000000000000000000000000000000000000..510295ab8343b6f368555cde0a4ac139b6d20629 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_hierarchical.py @@ -0,0 +1,912 @@ +""" +Several basic tests for hierarchical clustering procedures + +""" +# Authors: Vincent Michel, 2010, Gael Varoquaux 2012, +# Matteo Visconti di Oleggio Castello 2014 +# License: BSD 3 clause +import itertools +from tempfile import mkdtemp +import shutil +import pytest +from functools import partial + +import numpy as np +from scipy import sparse +from scipy.cluster import hierarchy +from scipy.sparse.csgraph import connected_components + +from sklearn.metrics.cluster import adjusted_rand_score +from sklearn.metrics.tests.test_dist_metrics import METRICS_DEFAULT_PARAMS +from sklearn.utils._testing import assert_almost_equal, create_memmap_backed_data +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils._testing import ignore_warnings + +from sklearn.cluster import ward_tree +from sklearn.cluster import AgglomerativeClustering, FeatureAgglomeration +from sklearn.cluster._agglomerative import ( + _hc_cut, + _TREE_BUILDERS, + linkage_tree, + _fix_connectivity, +) +from sklearn.feature_extraction.image import grid_to_graph +from sklearn.metrics import DistanceMetric +from sklearn.metrics.pairwise import ( + PAIRED_DISTANCES, + cosine_distances, + manhattan_distances, + pairwise_distances, +) +from sklearn.metrics.cluster import normalized_mutual_info_score +from sklearn.neighbors import kneighbors_graph +from sklearn.cluster._hierarchical_fast import ( + average_merge, + max_merge, + mst_linkage_core, +) +from sklearn.utils._fast_dict import IntFloatDict +from sklearn.utils._testing import assert_array_equal +from sklearn.datasets import make_moons, make_circles + + +def test_linkage_misc(): + # Misc tests on linkage + rng = np.random.RandomState(42) + X = rng.normal(size=(5, 5)) + + with pytest.raises(ValueError): + linkage_tree(X, linkage="foo") + + with pytest.raises(ValueError): + linkage_tree(X, connectivity=np.ones((4, 4))) + + # Smoke test FeatureAgglomeration + FeatureAgglomeration().fit(X) + + # test hierarchical clustering on a precomputed distances matrix + dis = cosine_distances(X) + + res = linkage_tree(dis, affinity="precomputed") + assert_array_equal(res[0], linkage_tree(X, affinity="cosine")[0]) + + # test hierarchical clustering on a precomputed distances matrix + res = linkage_tree(X, affinity=manhattan_distances) + assert_array_equal(res[0], linkage_tree(X, affinity="manhattan")[0]) + + +def test_structured_linkage_tree(): + # Check that we obtain the correct solution for structured linkage trees. + rng = np.random.RandomState(0) + mask = np.ones([10, 10], dtype=bool) + # Avoiding a mask with only 'True' entries + mask[4:7, 4:7] = 0 + X = rng.randn(50, 100) + connectivity = grid_to_graph(*mask.shape) + for tree_builder in _TREE_BUILDERS.values(): + children, n_components, n_leaves, parent = tree_builder( + X.T, connectivity=connectivity + ) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + # Check that ward_tree raises a ValueError with a connectivity matrix + # of the wrong shape + with pytest.raises(ValueError): + tree_builder(X.T, connectivity=np.ones((4, 4))) + # Check that fitting with no samples raises an error + with pytest.raises(ValueError): + tree_builder(X.T[:0], connectivity=connectivity) + + +def test_unstructured_linkage_tree(): + # Check that we obtain the correct solution for unstructured linkage trees. + rng = np.random.RandomState(0) + X = rng.randn(50, 100) + for this_X in (X, X[0]): + # With specified a number of clusters just for the sake of + # raising a warning and testing the warning code + with ignore_warnings(): + with pytest.warns(UserWarning): + children, n_nodes, n_leaves, parent = ward_tree(this_X.T, n_clusters=10) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + + for tree_builder in _TREE_BUILDERS.values(): + for this_X in (X, X[0]): + with ignore_warnings(): + with pytest.warns(UserWarning): + children, n_nodes, n_leaves, parent = tree_builder( + this_X.T, n_clusters=10 + ) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + + +def test_height_linkage_tree(): + # Check that the height of the results of linkage tree is sorted. + rng = np.random.RandomState(0) + mask = np.ones([10, 10], dtype=bool) + X = rng.randn(50, 100) + connectivity = grid_to_graph(*mask.shape) + for linkage_func in _TREE_BUILDERS.values(): + children, n_nodes, n_leaves, parent = linkage_func( + X.T, connectivity=connectivity + ) + n_nodes = 2 * X.shape[1] - 1 + assert len(children) + n_leaves == n_nodes + + +def test_zero_cosine_linkage_tree(): + # Check that zero vectors in X produce an error when + # 'cosine' affinity is used + X = np.array([[0, 1], [0, 0]]) + msg = "Cosine affinity cannot be used when X contains zero vectors" + with pytest.raises(ValueError, match=msg): + linkage_tree(X, affinity="cosine") + + +@pytest.mark.parametrize("n_clusters, distance_threshold", [(None, 0.5), (10, None)]) +@pytest.mark.parametrize("compute_distances", [True, False]) +@pytest.mark.parametrize("linkage", ["ward", "complete", "average", "single"]) +def test_agglomerative_clustering_distances( + n_clusters, compute_distances, distance_threshold, linkage +): + # Check that when `compute_distances` is True or `distance_threshold` is + # given, the fitted model has an attribute `distances_`. + rng = np.random.RandomState(0) + mask = np.ones([10, 10], dtype=bool) + n_samples = 100 + X = rng.randn(n_samples, 50) + connectivity = grid_to_graph(*mask.shape) + + clustering = AgglomerativeClustering( + n_clusters=n_clusters, + connectivity=connectivity, + linkage=linkage, + distance_threshold=distance_threshold, + compute_distances=compute_distances, + ) + clustering.fit(X) + if compute_distances or (distance_threshold is not None): + assert hasattr(clustering, "distances_") + n_children = clustering.children_.shape[0] + n_nodes = n_children + 1 + assert clustering.distances_.shape == (n_nodes - 1,) + else: + assert not hasattr(clustering, "distances_") + + +def test_agglomerative_clustering(global_random_seed): + # Check that we obtain the correct number of clusters with + # agglomerative clustering. + rng = np.random.RandomState(global_random_seed) + mask = np.ones([10, 10], dtype=bool) + n_samples = 100 + X = rng.randn(n_samples, 50) + connectivity = grid_to_graph(*mask.shape) + for linkage in ("ward", "complete", "average", "single"): + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, linkage=linkage + ) + clustering.fit(X) + # test caching + try: + tempdir = mkdtemp() + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=connectivity, + memory=tempdir, + linkage=linkage, + ) + clustering.fit(X) + labels = clustering.labels_ + assert np.size(np.unique(labels)) == 10 + finally: + shutil.rmtree(tempdir) + # Turn caching off now + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, linkage=linkage + ) + # Check that we obtain the same solution with early-stopping of the + # tree building + clustering.compute_full_tree = False + clustering.fit(X) + assert_almost_equal(normalized_mutual_info_score(clustering.labels_, labels), 1) + clustering.connectivity = None + clustering.fit(X) + assert np.size(np.unique(clustering.labels_)) == 10 + # Check that we raise a TypeError on dense matrices + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=sparse.lil_matrix(connectivity.toarray()[:10, :10]), + linkage=linkage, + ) + with pytest.raises(ValueError): + clustering.fit(X) + + # Test that using ward with another metric than euclidean raises an + # exception + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=connectivity.toarray(), + metric="manhattan", + linkage="ward", + ) + with pytest.raises(ValueError): + clustering.fit(X) + + # Test using another metric than euclidean works with linkage complete + for metric in PAIRED_DISTANCES.keys(): + # Compare our (structured) implementation to scipy + clustering = AgglomerativeClustering( + n_clusters=10, + connectivity=np.ones((n_samples, n_samples)), + metric=metric, + linkage="complete", + ) + clustering.fit(X) + clustering2 = AgglomerativeClustering( + n_clusters=10, connectivity=None, metric=metric, linkage="complete" + ) + clustering2.fit(X) + assert_almost_equal( + normalized_mutual_info_score(clustering2.labels_, clustering.labels_), 1 + ) + + # Test that using a distance matrix (affinity = 'precomputed') has same + # results (with connectivity constraints) + clustering = AgglomerativeClustering( + n_clusters=10, connectivity=connectivity, linkage="complete" + ) + clustering.fit(X) + X_dist = pairwise_distances(X) + clustering2 = AgglomerativeClustering( + n_clusters=10, + connectivity=connectivity, + metric="precomputed", + linkage="complete", + ) + clustering2.fit(X_dist) + assert_array_equal(clustering.labels_, clustering2.labels_) + + +def test_agglomerative_clustering_memory_mapped(): + """AgglomerativeClustering must work on mem-mapped dataset. + + Non-regression test for issue #19875. + """ + rng = np.random.RandomState(0) + Xmm = create_memmap_backed_data(rng.randn(50, 100)) + AgglomerativeClustering(metric="euclidean", linkage="single").fit(Xmm) + + +def test_ward_agglomeration(global_random_seed): + # Check that we obtain the correct solution in a simplistic case + rng = np.random.RandomState(global_random_seed) + mask = np.ones([10, 10], dtype=bool) + X = rng.randn(50, 100) + connectivity = grid_to_graph(*mask.shape) + agglo = FeatureAgglomeration(n_clusters=5, connectivity=connectivity) + agglo.fit(X) + assert np.size(np.unique(agglo.labels_)) == 5 + + X_red = agglo.transform(X) + assert X_red.shape[1] == 5 + X_full = agglo.inverse_transform(X_red) + assert np.unique(X_full[0]).size == 5 + assert_array_almost_equal(agglo.transform(X_full), X_red) + + # Check that fitting with no samples raises a ValueError + with pytest.raises(ValueError): + agglo.fit(X[:0]) + + +def test_single_linkage_clustering(): + # Check that we get the correct result in two emblematic cases + moons, moon_labels = make_moons(noise=0.05, random_state=42) + clustering = AgglomerativeClustering(n_clusters=2, linkage="single") + clustering.fit(moons) + assert_almost_equal( + normalized_mutual_info_score(clustering.labels_, moon_labels), 1 + ) + + circles, circle_labels = make_circles(factor=0.5, noise=0.025, random_state=42) + clustering = AgglomerativeClustering(n_clusters=2, linkage="single") + clustering.fit(circles) + assert_almost_equal( + normalized_mutual_info_score(clustering.labels_, circle_labels), 1 + ) + + +def assess_same_labelling(cut1, cut2): + """Util for comparison with scipy""" + co_clust = [] + for cut in [cut1, cut2]: + n = len(cut) + k = cut.max() + 1 + ecut = np.zeros((n, k)) + ecut[np.arange(n), cut] = 1 + co_clust.append(np.dot(ecut, ecut.T)) + assert (co_clust[0] == co_clust[1]).all() + + +def test_sparse_scikit_vs_scipy(global_random_seed): + # Test scikit linkage with full connectivity (i.e. unstructured) vs scipy + n, p, k = 10, 5, 3 + rng = np.random.RandomState(global_random_seed) + + # Not using a lil_matrix here, just to check that non sparse + # matrices are well handled + connectivity = np.ones((n, n)) + for linkage in _TREE_BUILDERS.keys(): + for i in range(5): + X = 0.1 * rng.normal(size=(n, p)) + X -= 4.0 * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out = hierarchy.linkage(X, method=linkage) + + children_ = out[:, :2].astype(int, copy=False) + children, _, n_leaves, _ = _TREE_BUILDERS[linkage]( + X, connectivity=connectivity + ) + + # Sort the order of child nodes per row for consistency + children.sort(axis=1) + assert_array_equal( + children, + children_, + "linkage tree differs from scipy impl for linkage: " + linkage, + ) + + cut = _hc_cut(k, children, n_leaves) + cut_ = _hc_cut(k, children_, n_leaves) + assess_same_labelling(cut, cut_) + + # Test error management in _hc_cut + with pytest.raises(ValueError): + _hc_cut(n_leaves + 1, children, n_leaves) + + +# Make sure our custom mst_linkage_core gives +# the same results as scipy's builtin +def test_vector_scikit_single_vs_scipy_single(global_random_seed): + n_samples, n_features, n_clusters = 10, 5, 3 + rng = np.random.RandomState(global_random_seed) + X = 0.1 * rng.normal(size=(n_samples, n_features)) + X -= 4.0 * np.arange(n_samples)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out = hierarchy.linkage(X, method="single") + children_scipy = out[:, :2].astype(int) + + children, _, n_leaves, _ = _TREE_BUILDERS["single"](X) + + # Sort the order of child nodes per row for consistency + children.sort(axis=1) + assert_array_equal( + children, + children_scipy, + "linkage tree differs from scipy impl for single linkage.", + ) + + cut = _hc_cut(n_clusters, children, n_leaves) + cut_scipy = _hc_cut(n_clusters, children_scipy, n_leaves) + assess_same_labelling(cut, cut_scipy) + + +# TODO: Remove filterwarnings in 1.3 when wminkowski is removed +@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn") +@pytest.mark.parametrize("metric_param_grid", METRICS_DEFAULT_PARAMS) +def test_mst_linkage_core_memory_mapped(metric_param_grid): + """The MST-LINKAGE-CORE algorithm must work on mem-mapped dataset. + + Non-regression test for issue #19875. + """ + rng = np.random.RandomState(seed=1) + X = rng.normal(size=(20, 4)) + Xmm = create_memmap_backed_data(X) + metric, param_grid = metric_param_grid + keys = param_grid.keys() + for vals in itertools.product(*param_grid.values()): + kwargs = dict(zip(keys, vals)) + distance_metric = DistanceMetric.get_metric(metric, **kwargs) + mst = mst_linkage_core(X, distance_metric) + mst_mm = mst_linkage_core(Xmm, distance_metric) + np.testing.assert_equal(mst, mst_mm) + + +def test_identical_points(): + # Ensure identical points are handled correctly when using mst with + # a sparse connectivity matrix + X = np.array([[0, 0, 0], [0, 0, 0], [1, 1, 1], [1, 1, 1], [2, 2, 2], [2, 2, 2]]) + true_labels = np.array([0, 0, 1, 1, 2, 2]) + connectivity = kneighbors_graph(X, n_neighbors=3, include_self=False) + connectivity = 0.5 * (connectivity + connectivity.T) + connectivity, n_components = _fix_connectivity(X, connectivity, "euclidean") + + for linkage in ("single", "average", "average", "ward"): + clustering = AgglomerativeClustering( + n_clusters=3, linkage=linkage, connectivity=connectivity + ) + clustering.fit(X) + + assert_almost_equal( + normalized_mutual_info_score(clustering.labels_, true_labels), 1 + ) + + +def test_connectivity_propagation(): + # Check that connectivity in the ward tree is propagated correctly during + # merging. + X = np.array( + [ + (0.014, 0.120), + (0.014, 0.099), + (0.014, 0.097), + (0.017, 0.153), + (0.017, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.153), + (0.018, 0.152), + (0.018, 0.149), + (0.018, 0.144), + ] + ) + connectivity = kneighbors_graph(X, 10, include_self=False) + ward = AgglomerativeClustering( + n_clusters=4, connectivity=connectivity, linkage="ward" + ) + # If changes are not propagated correctly, fit crashes with an + # IndexError + ward.fit(X) + + +def test_ward_tree_children_order(global_random_seed): + # Check that children are ordered in the same way for both structured and + # unstructured versions of ward_tree. + + # test on five random datasets + n, p = 10, 5 + rng = np.random.RandomState(global_random_seed) + + connectivity = np.ones((n, n)) + for i in range(5): + X = 0.1 * rng.normal(size=(n, p)) + X -= 4.0 * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out_unstructured = ward_tree(X) + out_structured = ward_tree(X, connectivity=connectivity) + + assert_array_equal(out_unstructured[0], out_structured[0]) + + +def test_ward_linkage_tree_return_distance(global_random_seed): + # Test return_distance option on linkage and ward trees + + # test that return_distance when set true, gives same + # output on both structured and unstructured clustering. + n, p = 10, 5 + rng = np.random.RandomState(global_random_seed) + + connectivity = np.ones((n, n)) + for i in range(5): + X = 0.1 * rng.normal(size=(n, p)) + X -= 4.0 * np.arange(n)[:, np.newaxis] + X -= X.mean(axis=1)[:, np.newaxis] + + out_unstructured = ward_tree(X, return_distance=True) + out_structured = ward_tree(X, connectivity=connectivity, return_distance=True) + + # get children + children_unstructured = out_unstructured[0] + children_structured = out_structured[0] + + # check if we got the same clusters + assert_array_equal(children_unstructured, children_structured) + + # check if the distances are the same + dist_unstructured = out_unstructured[-1] + dist_structured = out_structured[-1] + + assert_array_almost_equal(dist_unstructured, dist_structured) + + for linkage in ["average", "complete", "single"]: + structured_items = linkage_tree( + X, connectivity=connectivity, linkage=linkage, return_distance=True + )[-1] + unstructured_items = linkage_tree(X, linkage=linkage, return_distance=True)[ + -1 + ] + structured_dist = structured_items[-1] + unstructured_dist = unstructured_items[-1] + structured_children = structured_items[0] + unstructured_children = unstructured_items[0] + assert_array_almost_equal(structured_dist, unstructured_dist) + assert_array_almost_equal(structured_children, unstructured_children) + + # test on the following dataset where we know the truth + # taken from scipy/cluster/tests/hierarchy_test_data.py + X = np.array( + [ + [1.43054825, -7.5693489], + [6.95887839, 6.82293382], + [2.87137846, -9.68248579], + [7.87974764, -6.05485803], + [8.24018364, -6.09495602], + [7.39020262, 8.54004355], + ] + ) + # truth + linkage_X_ward = np.array( + [ + [3.0, 4.0, 0.36265956, 2.0], + [1.0, 5.0, 1.77045373, 2.0], + [0.0, 2.0, 2.55760419, 2.0], + [6.0, 8.0, 9.10208346, 4.0], + [7.0, 9.0, 24.7784379, 6.0], + ] + ) + + linkage_X_complete = np.array( + [ + [3.0, 4.0, 0.36265956, 2.0], + [1.0, 5.0, 1.77045373, 2.0], + [0.0, 2.0, 2.55760419, 2.0], + [6.0, 8.0, 6.96742194, 4.0], + [7.0, 9.0, 18.77445997, 6.0], + ] + ) + + linkage_X_average = np.array( + [ + [3.0, 4.0, 0.36265956, 2.0], + [1.0, 5.0, 1.77045373, 2.0], + [0.0, 2.0, 2.55760419, 2.0], + [6.0, 8.0, 6.55832839, 4.0], + [7.0, 9.0, 15.44089605, 6.0], + ] + ) + + n_samples, n_features = np.shape(X) + connectivity_X = np.ones((n_samples, n_samples)) + + out_X_unstructured = ward_tree(X, return_distance=True) + out_X_structured = ward_tree(X, connectivity=connectivity_X, return_distance=True) + + # check that the labels are the same + assert_array_equal(linkage_X_ward[:, :2], out_X_unstructured[0]) + assert_array_equal(linkage_X_ward[:, :2], out_X_structured[0]) + + # check that the distances are correct + assert_array_almost_equal(linkage_X_ward[:, 2], out_X_unstructured[4]) + assert_array_almost_equal(linkage_X_ward[:, 2], out_X_structured[4]) + + linkage_options = ["complete", "average", "single"] + X_linkage_truth = [linkage_X_complete, linkage_X_average] + for linkage, X_truth in zip(linkage_options, X_linkage_truth): + out_X_unstructured = linkage_tree(X, return_distance=True, linkage=linkage) + out_X_structured = linkage_tree( + X, connectivity=connectivity_X, linkage=linkage, return_distance=True + ) + + # check that the labels are the same + assert_array_equal(X_truth[:, :2], out_X_unstructured[0]) + assert_array_equal(X_truth[:, :2], out_X_structured[0]) + + # check that the distances are correct + assert_array_almost_equal(X_truth[:, 2], out_X_unstructured[4]) + assert_array_almost_equal(X_truth[:, 2], out_X_structured[4]) + + +def test_connectivity_fixing_non_lil(): + # Check non regression of a bug if a non item assignable connectivity is + # provided with more than one component. + # create dummy data + x = np.array([[0, 0], [1, 1]]) + # create a mask with several components to force connectivity fixing + m = np.array([[True, False], [False, True]]) + c = grid_to_graph(n_x=2, n_y=2, mask=m) + w = AgglomerativeClustering(connectivity=c, linkage="ward") + with pytest.warns(UserWarning): + w.fit(x) + + +def test_int_float_dict(): + rng = np.random.RandomState(0) + keys = np.unique(rng.randint(100, size=10).astype(np.intp, copy=False)) + values = rng.rand(len(keys)) + + d = IntFloatDict(keys, values) + for key, value in zip(keys, values): + assert d[key] == value + + other_keys = np.arange(50, dtype=np.intp)[::2] + other_values = np.full(50, 0.5)[::2] + other = IntFloatDict(other_keys, other_values) + # Complete smoke test + max_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1) + average_merge(d, other, mask=np.ones(100, dtype=np.intp), n_a=1, n_b=1) + + +def test_connectivity_callable(): + rng = np.random.RandomState(0) + X = rng.rand(20, 5) + connectivity = kneighbors_graph(X, 3, include_self=False) + aglc1 = AgglomerativeClustering(connectivity=connectivity) + aglc2 = AgglomerativeClustering( + connectivity=partial(kneighbors_graph, n_neighbors=3, include_self=False) + ) + aglc1.fit(X) + aglc2.fit(X) + assert_array_equal(aglc1.labels_, aglc2.labels_) + + +def test_connectivity_ignores_diagonal(): + rng = np.random.RandomState(0) + X = rng.rand(20, 5) + connectivity = kneighbors_graph(X, 3, include_self=False) + connectivity_include_self = kneighbors_graph(X, 3, include_self=True) + aglc1 = AgglomerativeClustering(connectivity=connectivity) + aglc2 = AgglomerativeClustering(connectivity=connectivity_include_self) + aglc1.fit(X) + aglc2.fit(X) + assert_array_equal(aglc1.labels_, aglc2.labels_) + + +def test_compute_full_tree(): + # Test that the full tree is computed if n_clusters is small + rng = np.random.RandomState(0) + X = rng.randn(10, 2) + connectivity = kneighbors_graph(X, 5, include_self=False) + + # When n_clusters is less, the full tree should be built + # that is the number of merges should be n_samples - 1 + agc = AgglomerativeClustering(n_clusters=2, connectivity=connectivity) + agc.fit(X) + n_samples = X.shape[0] + n_nodes = agc.children_.shape[0] + assert n_nodes == n_samples - 1 + + # When n_clusters is large, greater than max of 100 and 0.02 * n_samples. + # we should stop when there are n_clusters. + n_clusters = 101 + X = rng.randn(200, 2) + connectivity = kneighbors_graph(X, 10, include_self=False) + agc = AgglomerativeClustering(n_clusters=n_clusters, connectivity=connectivity) + agc.fit(X) + n_samples = X.shape[0] + n_nodes = agc.children_.shape[0] + assert n_nodes == n_samples - n_clusters + + +def test_n_components(): + # Test n_components returned by linkage, average and ward tree + rng = np.random.RandomState(0) + X = rng.rand(5, 5) + + # Connectivity matrix having five components. + connectivity = np.eye(5) + + for linkage_func in _TREE_BUILDERS.values(): + assert ignore_warnings(linkage_func)(X, connectivity=connectivity)[1] == 5 + + +def test_affinity_passed_to_fix_connectivity(): + # Test that the affinity parameter is actually passed to the pairwise + # function + + size = 2 + rng = np.random.RandomState(0) + X = rng.randn(size, size) + mask = np.array([True, False, False, True]) + + connectivity = grid_to_graph(n_x=size, n_y=size, mask=mask, return_as=np.ndarray) + + class FakeAffinity: + def __init__(self): + self.counter = 0 + + def increment(self, *args, **kwargs): + self.counter += 1 + return self.counter + + fa = FakeAffinity() + + linkage_tree(X, connectivity=connectivity, affinity=fa.increment) + + assert fa.counter == 3 + + +@pytest.mark.parametrize("linkage", ["ward", "complete", "average"]) +def test_agglomerative_clustering_with_distance_threshold(linkage, global_random_seed): + # Check that we obtain the correct number of clusters with + # agglomerative clustering with distance_threshold. + rng = np.random.RandomState(global_random_seed) + mask = np.ones([10, 10], dtype=bool) + n_samples = 100 + X = rng.randn(n_samples, 50) + connectivity = grid_to_graph(*mask.shape) + # test when distance threshold is set to 10 + distance_threshold = 10 + for conn in [None, connectivity]: + clustering = AgglomerativeClustering( + n_clusters=None, + distance_threshold=distance_threshold, + connectivity=conn, + linkage=linkage, + ) + clustering.fit(X) + clusters_produced = clustering.labels_ + num_clusters_produced = len(np.unique(clustering.labels_)) + # test if the clusters produced match the point in the linkage tree + # where the distance exceeds the threshold + tree_builder = _TREE_BUILDERS[linkage] + children, n_components, n_leaves, parent, distances = tree_builder( + X, connectivity=conn, n_clusters=None, return_distance=True + ) + num_clusters_at_threshold = ( + np.count_nonzero(distances >= distance_threshold) + 1 + ) + # test number of clusters produced + assert num_clusters_at_threshold == num_clusters_produced + # test clusters produced + clusters_at_threshold = _hc_cut( + n_clusters=num_clusters_produced, children=children, n_leaves=n_leaves + ) + assert np.array_equiv(clusters_produced, clusters_at_threshold) + + +def test_small_distance_threshold(global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 10 + X = rng.randint(-300, 300, size=(n_samples, 3)) + # this should result in all data in their own clusters, given that + # their pairwise distances are bigger than .1 (which may not be the case + # with a different random seed). + clustering = AgglomerativeClustering( + n_clusters=None, distance_threshold=1.0, linkage="single" + ).fit(X) + # check that the pairwise distances are indeed all larger than .1 + all_distances = pairwise_distances(X, metric="minkowski", p=2) + np.fill_diagonal(all_distances, np.inf) + assert np.all(all_distances > 0.1) + assert clustering.n_clusters_ == n_samples + + +def test_cluster_distances_with_distance_threshold(global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 100 + X = rng.randint(-10, 10, size=(n_samples, 3)) + # check the distances within the clusters and with other clusters + distance_threshold = 4 + clustering = AgglomerativeClustering( + n_clusters=None, distance_threshold=distance_threshold, linkage="single" + ).fit(X) + labels = clustering.labels_ + D = pairwise_distances(X, metric="minkowski", p=2) + # to avoid taking the 0 diagonal in min() + np.fill_diagonal(D, np.inf) + for label in np.unique(labels): + in_cluster_mask = labels == label + max_in_cluster_distance = ( + D[in_cluster_mask][:, in_cluster_mask].min(axis=0).max() + ) + min_out_cluster_distance = ( + D[in_cluster_mask][:, ~in_cluster_mask].min(axis=0).min() + ) + # single data point clusters only have that inf diagonal here + if in_cluster_mask.sum() > 1: + assert max_in_cluster_distance < distance_threshold + assert min_out_cluster_distance >= distance_threshold + + +@pytest.mark.parametrize("linkage", ["ward", "complete", "average"]) +@pytest.mark.parametrize( + ("threshold", "y_true"), [(0.5, [1, 0]), (1.0, [1, 0]), (1.5, [0, 0])] +) +def test_agglomerative_clustering_with_distance_threshold_edge_case( + linkage, threshold, y_true +): + # test boundary case of distance_threshold matching the distance + X = [[0], [1]] + clusterer = AgglomerativeClustering( + n_clusters=None, distance_threshold=threshold, linkage=linkage + ) + y_pred = clusterer.fit_predict(X) + assert adjusted_rand_score(y_true, y_pred) == 1 + + +def test_dist_threshold_invalid_parameters(): + X = [[0], [1]] + with pytest.raises(ValueError, match="Exactly one of "): + AgglomerativeClustering(n_clusters=None, distance_threshold=None).fit(X) + + with pytest.raises(ValueError, match="Exactly one of "): + AgglomerativeClustering(n_clusters=2, distance_threshold=1).fit(X) + + X = [[0], [1]] + with pytest.raises(ValueError, match="compute_full_tree must be True if"): + AgglomerativeClustering( + n_clusters=None, distance_threshold=1, compute_full_tree=False + ).fit(X) + + +def test_invalid_shape_precomputed_dist_matrix(): + # Check that an error is raised when affinity='precomputed' + # and a non square matrix is passed (PR #16257). + rng = np.random.RandomState(0) + X = rng.rand(5, 3) + with pytest.raises( + ValueError, + match=r"Distance matrix should be square, got matrix of shape \(5, 3\)", + ): + AgglomerativeClustering(metric="precomputed", linkage="complete").fit(X) + + +def test_precomputed_connectivity_affinity_with_2_connected_components(): + """Check that connecting components works when connectivity and + affinity are both precomputed and the number of connected components is + greater than 1. Non-regression test for #16151. + """ + + connectivity_matrix = np.array( + [ + [0, 1, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 0, 0, 0, 0], + ] + ) + # ensure that connectivity_matrix has two connected components + assert connected_components(connectivity_matrix)[0] == 2 + + rng = np.random.RandomState(0) + X = rng.randn(5, 10) + + X_dist = pairwise_distances(X) + clusterer_precomputed = AgglomerativeClustering( + affinity="precomputed", connectivity=connectivity_matrix, linkage="complete" + ) + msg = "Completing it to avoid stopping the tree early" + with pytest.warns(UserWarning, match=msg): + clusterer_precomputed.fit(X_dist) + + clusterer = AgglomerativeClustering( + connectivity=connectivity_matrix, linkage="complete" + ) + with pytest.warns(UserWarning, match=msg): + clusterer.fit(X) + + assert_array_equal(clusterer.labels_, clusterer_precomputed.labels_) + assert_array_equal(clusterer.children_, clusterer_precomputed.children_) + + +# TODO(1.4): Remove +def test_deprecate_affinity(): + rng = np.random.RandomState(42) + X = rng.randn(50, 10) + + af = AgglomerativeClustering(affinity="euclidean") + msg = ( + "Attribute `affinity` was deprecated in version 1.2 and will be removed in 1.4." + " Use `metric` instead" + ) + with pytest.warns(FutureWarning, match=msg): + af.fit(X) + with pytest.warns(FutureWarning, match=msg): + af.fit_predict(X) + + af = AgglomerativeClustering(metric="euclidean", affinity="euclidean") + msg = "Both `affinity` and `metric` attributes were set. Attribute" + with pytest.raises(ValueError, match=msg): + af.fit(X) + with pytest.raises(ValueError, match=msg): + af.fit_predict(X) diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_k_means.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_k_means.py new file mode 100644 index 0000000000000000000000000000000000000000..257d1619a3f00940abe9bfb84209a1ffed9ddd0b --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_k_means.py @@ -0,0 +1,1265 @@ +"""Testing for K-means""" +import re +import sys +import warnings + +import numpy as np +from scipy import sparse as sp + +import pytest + +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_allclose +from sklearn.utils.fixes import threadpool_limits +from sklearn.base import clone +from sklearn.exceptions import ConvergenceWarning + +from sklearn.utils.extmath import row_norms +from sklearn.metrics import pairwise_distances +from sklearn.metrics import pairwise_distances_argmin +from sklearn.metrics.cluster import v_measure_score +from sklearn.cluster import KMeans, k_means, kmeans_plusplus +from sklearn.cluster import MiniBatchKMeans +from sklearn.cluster._kmeans import _labels_inertia +from sklearn.cluster._kmeans import _mini_batch_step +from sklearn.cluster._k_means_common import _relocate_empty_clusters_dense +from sklearn.cluster._k_means_common import _relocate_empty_clusters_sparse +from sklearn.cluster._k_means_common import _euclidean_dense_dense_wrapper +from sklearn.cluster._k_means_common import _euclidean_sparse_dense_wrapper +from sklearn.cluster._k_means_common import _inertia_dense +from sklearn.cluster._k_means_common import _inertia_sparse +from sklearn.cluster._k_means_common import _is_same_clustering +from sklearn.utils._testing import create_memmap_backed_data +from sklearn.datasets import make_blobs +from io import StringIO + +# TODO(1.4): Remove +msg = ( + r"The default value of `n_init` will change from \d* to 'auto' in 1.4. Set the" + r" value of `n_init` explicitly to suppress the warning:FutureWarning" +) +pytestmark = pytest.mark.filterwarnings("ignore:" + msg) + +# non centered, sparse centers to check the +centers = np.array( + [ + [0.0, 5.0, 0.0, 0.0, 0.0], + [1.0, 1.0, 4.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 5.0, 1.0], + ] +) +n_samples = 100 +n_clusters, n_features = centers.shape +X, true_labels = make_blobs( + n_samples=n_samples, centers=centers, cluster_std=1.0, random_state=42 +) +X_csr = sp.csr_matrix(X) + + +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +@pytest.mark.parametrize("algo", ["lloyd", "elkan"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_kmeans_results(array_constr, algo, dtype): + # Checks that KMeans works as intended on toy dataset by comparing with + # expected results computed by hand. + X = array_constr([[0, 0], [0.5, 0], [0.5, 1], [1, 1]], dtype=dtype) + sample_weight = [3, 1, 1, 3] + init_centers = np.array([[0, 0], [1, 1]], dtype=dtype) + + expected_labels = [0, 0, 1, 1] + expected_inertia = 0.375 + expected_centers = np.array([[0.125, 0], [0.875, 1]], dtype=dtype) + expected_n_iter = 2 + + kmeans = KMeans(n_clusters=2, n_init=1, init=init_centers, algorithm=algo) + kmeans.fit(X, sample_weight=sample_weight) + + assert_array_equal(kmeans.labels_, expected_labels) + assert_allclose(kmeans.inertia_, expected_inertia) + assert_allclose(kmeans.cluster_centers_, expected_centers) + assert kmeans.n_iter_ == expected_n_iter + + +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +@pytest.mark.parametrize("algo", ["lloyd", "elkan"]) +def test_kmeans_relocated_clusters(array_constr, algo): + # check that empty clusters are relocated as expected + X = array_constr([[0, 0], [0.5, 0], [0.5, 1], [1, 1]]) + + # second center too far from others points will be empty at first iter + init_centers = np.array([[0.5, 0.5], [3, 3]]) + + kmeans = KMeans(n_clusters=2, n_init=1, init=init_centers, algorithm=algo) + kmeans.fit(X) + + expected_n_iter = 3 + expected_inertia = 0.25 + assert_allclose(kmeans.inertia_, expected_inertia) + assert kmeans.n_iter_ == expected_n_iter + + # There are two acceptable ways of relocating clusters in this example, the output + # depends on how the argpartition strategy breaks ties. We accept both outputs. + try: + expected_labels = [0, 0, 1, 1] + expected_centers = [[0.25, 0], [0.75, 1]] + assert_array_equal(kmeans.labels_, expected_labels) + assert_allclose(kmeans.cluster_centers_, expected_centers) + except AssertionError: + expected_labels = [1, 1, 0, 0] + expected_centers = [[0.75, 1.0], [0.25, 0.0]] + assert_array_equal(kmeans.labels_, expected_labels) + assert_allclose(kmeans.cluster_centers_, expected_centers) + + +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +def test_relocate_empty_clusters(array_constr): + # test for the _relocate_empty_clusters_(dense/sparse) helpers + + # Synthetic dataset with 3 obvious clusters of different sizes + X = np.array([-10.0, -9.5, -9, -8.5, -8, -1, 1, 9, 9.5, 10]).reshape(-1, 1) + X = array_constr(X) + sample_weight = np.ones(10) + + # centers all initialized to the first point of X + centers_old = np.array([-10.0, -10, -10]).reshape(-1, 1) + + # With this initialization, all points will be assigned to the first center + # At this point a center in centers_new is the weighted sum of the points + # it contains if it's not empty, otherwise it is the same as before. + centers_new = np.array([-16.5, -10, -10]).reshape(-1, 1) + weight_in_clusters = np.array([10.0, 0, 0]) + labels = np.zeros(10, dtype=np.int32) + + if array_constr is np.array: + _relocate_empty_clusters_dense( + X, sample_weight, centers_old, centers_new, weight_in_clusters, labels + ) + else: + _relocate_empty_clusters_sparse( + X.data, + X.indices, + X.indptr, + sample_weight, + centers_old, + centers_new, + weight_in_clusters, + labels, + ) + + # The relocation scheme will take the 2 points farthest from the center and + # assign them to the 2 empty clusters, i.e. points at 10 and at 9.9. The + # first center will be updated to contain the other 8 points. + assert_array_equal(weight_in_clusters, [8, 1, 1]) + assert_allclose(centers_new, [[-36], [10], [9.5]]) + + +@pytest.mark.parametrize("distribution", ["normal", "blobs"]) +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +@pytest.mark.parametrize("tol", [1e-2, 1e-8, 1e-100, 0]) +def test_kmeans_elkan_results(distribution, array_constr, tol, global_random_seed): + # Check that results are identical between lloyd and elkan algorithms + rnd = np.random.RandomState(global_random_seed) + if distribution == "normal": + X = rnd.normal(size=(5000, 10)) + else: + X, _ = make_blobs(random_state=rnd) + X[X < 0] = 0 + X = array_constr(X) + + km_lloyd = KMeans(n_clusters=5, random_state=global_random_seed, n_init=1, tol=tol) + km_elkan = KMeans( + algorithm="elkan", + n_clusters=5, + random_state=global_random_seed, + n_init=1, + tol=tol, + ) + + km_lloyd.fit(X) + km_elkan.fit(X) + assert_allclose(km_elkan.cluster_centers_, km_lloyd.cluster_centers_) + assert_array_equal(km_elkan.labels_, km_lloyd.labels_) + assert km_elkan.n_iter_ == km_lloyd.n_iter_ + assert km_elkan.inertia_ == pytest.approx(km_lloyd.inertia_, rel=1e-6) + + +@pytest.mark.parametrize("algorithm", ["lloyd", "elkan"]) +def test_kmeans_convergence(algorithm, global_random_seed): + # Check that KMeans stops when convergence is reached when tol=0. (#16075) + rnd = np.random.RandomState(global_random_seed) + X = rnd.normal(size=(5000, 10)) + max_iter = 300 + + km = KMeans( + algorithm=algorithm, + n_clusters=5, + random_state=global_random_seed, + n_init=1, + tol=0, + max_iter=max_iter, + ).fit(X) + + assert km.n_iter_ < max_iter + + +@pytest.mark.parametrize("algorithm", ["auto", "full"]) +def test_algorithm_auto_full_deprecation_warning(algorithm): + X = np.random.rand(100, 2) + kmeans = KMeans(algorithm=algorithm) + with pytest.warns( + FutureWarning, + match=( + f"algorithm='{algorithm}' is deprecated, it will " + "be removed in 1.3. Using 'lloyd' instead." + ), + ): + kmeans.fit(X) + assert kmeans._algorithm == "lloyd" + + +def test_minibatch_update_consistency(global_random_seed): + # Check that dense and sparse minibatch update give the same results + rng = np.random.RandomState(global_random_seed) + + centers_old = centers + rng.normal(size=centers.shape) + centers_old_csr = centers_old.copy() + + centers_new = np.zeros_like(centers_old) + centers_new_csr = np.zeros_like(centers_old_csr) + + weight_sums = np.zeros(centers_old.shape[0], dtype=X.dtype) + weight_sums_csr = np.zeros(centers_old.shape[0], dtype=X.dtype) + + sample_weight = np.ones(X.shape[0], dtype=X.dtype) + + # extract a small minibatch + X_mb = X[:10] + X_mb_csr = X_csr[:10] + sample_weight_mb = sample_weight[:10] + + # step 1: compute the dense minibatch update + old_inertia = _mini_batch_step( + X_mb, + sample_weight_mb, + centers_old, + centers_new, + weight_sums, + np.random.RandomState(global_random_seed), + random_reassign=False, + ) + assert old_inertia > 0.0 + + # compute the new inertia on the same batch to check that it decreased + labels, new_inertia = _labels_inertia(X_mb, sample_weight_mb, centers_new) + assert new_inertia > 0.0 + assert new_inertia < old_inertia + + # step 2: compute the sparse minibatch update + old_inertia_csr = _mini_batch_step( + X_mb_csr, + sample_weight_mb, + centers_old_csr, + centers_new_csr, + weight_sums_csr, + np.random.RandomState(global_random_seed), + random_reassign=False, + ) + assert old_inertia_csr > 0.0 + + # compute the new inertia on the same batch to check that it decreased + labels_csr, new_inertia_csr = _labels_inertia( + X_mb_csr, sample_weight_mb, centers_new_csr + ) + assert new_inertia_csr > 0.0 + assert new_inertia_csr < old_inertia_csr + + # step 3: check that sparse and dense updates lead to the same results + assert_array_equal(labels, labels_csr) + assert_allclose(centers_new, centers_new_csr) + assert_allclose(old_inertia, old_inertia_csr) + assert_allclose(new_inertia, new_inertia_csr) + + +def _check_fitted_model(km): + # check that the number of clusters centers and distinct labels match + # the expectation + centers = km.cluster_centers_ + assert centers.shape == (n_clusters, n_features) + + labels = km.labels_ + assert np.unique(labels).shape[0] == n_clusters + + # check that the labels assignment are perfect (up to a permutation) + assert_allclose(v_measure_score(true_labels, labels), 1.0) + assert km.inertia_ > 0.0 + + +@pytest.mark.parametrize("data", [X, X_csr], ids=["dense", "sparse"]) +@pytest.mark.parametrize( + "init", + ["random", "k-means++", centers, lambda X, k, random_state: centers], + ids=["random", "k-means++", "ndarray", "callable"], +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_all_init(Estimator, data, init): + # Check KMeans and MiniBatchKMeans with all possible init. + n_init = 10 if isinstance(init, str) else 1 + km = Estimator( + init=init, n_clusters=n_clusters, random_state=42, n_init=n_init + ).fit(data) + _check_fitted_model(km) + + +@pytest.mark.parametrize( + "init", + ["random", "k-means++", centers, lambda X, k, random_state: centers], + ids=["random", "k-means++", "ndarray", "callable"], +) +def test_minibatch_kmeans_partial_fit_init(init): + # Check MiniBatchKMeans init with partial_fit + n_init = 10 if isinstance(init, str) else 1 + km = MiniBatchKMeans( + init=init, n_clusters=n_clusters, random_state=0, n_init=n_init + ) + for i in range(100): + # "random" init requires many batches to recover the true labels. + km.partial_fit(X) + _check_fitted_model(km) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_fortran_aligned_data(Estimator, global_random_seed): + # Check that KMeans works with fortran-aligned data. + X_fortran = np.asfortranarray(X) + centers_fortran = np.asfortranarray(centers) + + km_c = Estimator( + n_clusters=n_clusters, init=centers, n_init=1, random_state=global_random_seed + ).fit(X) + km_f = Estimator( + n_clusters=n_clusters, + init=centers_fortran, + n_init=1, + random_state=global_random_seed, + ).fit(X_fortran) + assert_allclose(km_c.cluster_centers_, km_f.cluster_centers_) + assert_array_equal(km_c.labels_, km_f.labels_) + + +def test_minibatch_kmeans_verbose(): + # Check verbose mode of MiniBatchKMeans for better coverage. + km = MiniBatchKMeans(n_clusters=n_clusters, random_state=42, verbose=1) + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + km.fit(X) + finally: + sys.stdout = old_stdout + + +@pytest.mark.parametrize("algorithm", ["lloyd", "elkan"]) +@pytest.mark.parametrize("tol", [1e-2, 0]) +def test_kmeans_verbose(algorithm, tol, capsys): + # Check verbose mode of KMeans for better coverage. + X = np.random.RandomState(0).normal(size=(5000, 10)) + + KMeans( + algorithm=algorithm, + n_clusters=n_clusters, + random_state=42, + init="random", + n_init=1, + tol=tol, + verbose=1, + ).fit(X) + + captured = capsys.readouterr() + + assert re.search(r"Initialization complete", captured.out) + assert re.search(r"Iteration [0-9]+, inertia", captured.out) + + if tol == 0: + assert re.search(r"strict convergence", captured.out) + else: + assert re.search(r"center shift .* within tolerance", captured.out) + + +def test_minibatch_kmeans_warning_init_size(): + # Check that a warning is raised when init_size is smaller than n_clusters + with pytest.warns( + RuntimeWarning, match=r"init_size.* should be larger than n_clusters" + ): + MiniBatchKMeans(init_size=10, n_clusters=20).fit(X) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_warning_n_init_precomputed_centers(Estimator): + # Check that a warning is raised when n_init > 1 and an array is passed for + # the init parameter. + with pytest.warns( + RuntimeWarning, + match="Explicit initial center position passed: performing only one init", + ): + Estimator(init=centers, n_clusters=n_clusters, n_init=10).fit(X) + + +def test_minibatch_sensible_reassign(global_random_seed): + # check that identical initial clusters are reassigned + # also a regression test for when there are more desired reassignments than + # samples. + zeroed_X, true_labels = make_blobs( + n_samples=100, centers=5, random_state=global_random_seed + ) + zeroed_X[::2, :] = 0 + + km = MiniBatchKMeans( + n_clusters=20, batch_size=10, random_state=global_random_seed, init="random" + ).fit(zeroed_X) + # there should not be too many exact zero cluster centers + assert km.cluster_centers_.any(axis=1).sum() > 10 + + # do the same with batch-size > X.shape[0] (regression test) + km = MiniBatchKMeans( + n_clusters=20, batch_size=200, random_state=global_random_seed, init="random" + ).fit(zeroed_X) + # there should not be too many exact zero cluster centers + assert km.cluster_centers_.any(axis=1).sum() > 10 + + # do the same with partial_fit API + km = MiniBatchKMeans(n_clusters=20, random_state=global_random_seed, init="random") + for i in range(100): + km.partial_fit(zeroed_X) + # there should not be too many exact zero cluster centers + assert km.cluster_centers_.any(axis=1).sum() > 10 + + +@pytest.mark.parametrize("data", [X, X_csr], ids=["dense", "sparse"]) +def test_minibatch_reassign(data, global_random_seed): + # Check the reassignment part of the minibatch step with very high or very + # low reassignment ratio. + perfect_centers = np.empty((n_clusters, n_features)) + for i in range(n_clusters): + perfect_centers[i] = X[true_labels == i].mean(axis=0) + + sample_weight = np.ones(n_samples) + centers_new = np.empty_like(perfect_centers) + + # Give a perfect initialization, but a large reassignment_ratio, as a + # result many centers should be reassigned and the model should no longer + # be good + score_before = -_labels_inertia(data, sample_weight, perfect_centers, 1)[1] + + _mini_batch_step( + data, + sample_weight, + perfect_centers, + centers_new, + np.zeros(n_clusters), + np.random.RandomState(global_random_seed), + random_reassign=True, + reassignment_ratio=1, + ) + + score_after = -_labels_inertia(data, sample_weight, centers_new, 1)[1] + + assert score_before > score_after + + # Give a perfect initialization, with a small reassignment_ratio, + # no center should be reassigned. + _mini_batch_step( + data, + sample_weight, + perfect_centers, + centers_new, + np.zeros(n_clusters), + np.random.RandomState(global_random_seed), + random_reassign=True, + reassignment_ratio=1e-15, + ) + + assert_allclose(centers_new, perfect_centers) + + +def test_minibatch_with_many_reassignments(): + # Test for the case that the number of clusters to reassign is bigger + # than the batch_size. Run the test with 100 clusters and a batch_size of + # 10 because it turned out that these values ensure that the number of + # clusters to reassign is always bigger than the batch_size. + MiniBatchKMeans( + n_clusters=100, + batch_size=10, + init_size=n_samples, + random_state=42, + verbose=True, + ).fit(X) + + +def test_minibatch_kmeans_init_size(): + # Check the internal _init_size attribute of MiniBatchKMeans + + # default init size should be 3 * batch_size + km = MiniBatchKMeans(n_clusters=10, batch_size=5, n_init=1).fit(X) + assert km._init_size == 15 + + # if 3 * batch size < n_clusters, it should then be 3 * n_clusters + km = MiniBatchKMeans(n_clusters=10, batch_size=1, n_init=1).fit(X) + assert km._init_size == 30 + + # it should not be larger than n_samples + km = MiniBatchKMeans( + n_clusters=10, batch_size=5, n_init=1, init_size=n_samples + 1 + ).fit(X) + assert km._init_size == n_samples + + +@pytest.mark.parametrize("tol, max_no_improvement", [(1e-4, None), (0, 10)]) +def test_minibatch_declared_convergence(capsys, tol, max_no_improvement): + # Check convergence detection based on ewa batch inertia or on + # small center change. + X, _, centers = make_blobs(centers=3, random_state=0, return_centers=True) + + km = MiniBatchKMeans( + n_clusters=3, + init=centers, + batch_size=20, + tol=tol, + random_state=0, + max_iter=10, + n_init=1, + verbose=1, + max_no_improvement=max_no_improvement, + ) + + km.fit(X) + assert 1 < km.n_iter_ < 10 + + captured = capsys.readouterr() + if max_no_improvement is None: + assert "Converged (small centers change)" in captured.out + if tol == 0: + assert "Converged (lack of improvement in inertia)" in captured.out + + +def test_minibatch_iter_steps(): + # Check consistency of n_iter_ and n_steps_ attributes. + batch_size = 30 + n_samples = X.shape[0] + km = MiniBatchKMeans(n_clusters=3, batch_size=batch_size, random_state=0).fit(X) + + # n_iter_ is the number of started epochs + assert km.n_iter_ == np.ceil((km.n_steps_ * batch_size) / n_samples) + assert isinstance(km.n_iter_, int) + + # without stopping condition, max_iter should be reached + km = MiniBatchKMeans( + n_clusters=3, + batch_size=batch_size, + random_state=0, + tol=0, + max_no_improvement=None, + max_iter=10, + ).fit(X) + + assert km.n_iter_ == 10 + assert km.n_steps_ == (10 * n_samples) // batch_size + assert isinstance(km.n_steps_, int) + + +def test_kmeans_copyx(): + # Check that copy_x=False returns nearly equal X after de-centering. + my_X = X.copy() + km = KMeans(copy_x=False, n_clusters=n_clusters, random_state=42) + km.fit(my_X) + _check_fitted_model(km) + + # check that my_X is de-centered + assert_allclose(my_X, X) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_score_max_iter(Estimator, global_random_seed): + # Check that fitting KMeans or MiniBatchKMeans with more iterations gives + # better score + X = np.random.RandomState(global_random_seed).randn(100, 10) + + km1 = Estimator(n_init=1, random_state=global_random_seed, max_iter=1) + s1 = km1.fit(X).score(X) + km2 = Estimator(n_init=1, random_state=global_random_seed, max_iter=10) + s2 = km2.fit(X).score(X) + assert s2 > s1 + + +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +@pytest.mark.parametrize( + "Estimator, algorithm", + [(KMeans, "lloyd"), (KMeans, "elkan"), (MiniBatchKMeans, None)], +) +@pytest.mark.parametrize("max_iter", [2, 100]) +def test_kmeans_predict( + Estimator, algorithm, array_constr, max_iter, global_dtype, global_random_seed +): + # Check the predict method and the equivalence between fit.predict and + # fit_predict. + X, _ = make_blobs( + n_samples=200, n_features=10, centers=10, random_state=global_random_seed + ) + X = array_constr(X, dtype=global_dtype) + + km = Estimator( + n_clusters=10, + init="random", + n_init=10, + max_iter=max_iter, + random_state=global_random_seed, + ) + if algorithm is not None: + km.set_params(algorithm=algorithm) + km.fit(X) + labels = km.labels_ + + # re-predict labels for training set using predict + pred = km.predict(X) + assert_array_equal(pred, labels) + + # re-predict labels for training set using fit_predict + pred = km.fit_predict(X) + assert_array_equal(pred, labels) + + # predict centroid labels + pred = km.predict(km.cluster_centers_) + assert_array_equal(pred, np.arange(10)) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_dense_sparse(Estimator, global_random_seed): + # Check that the results are the same for dense and sparse input. + sample_weight = np.random.RandomState(global_random_seed).random_sample( + (n_samples,) + ) + km_dense = Estimator( + n_clusters=n_clusters, random_state=global_random_seed, n_init=1 + ) + km_dense.fit(X, sample_weight=sample_weight) + km_sparse = Estimator( + n_clusters=n_clusters, random_state=global_random_seed, n_init=1 + ) + km_sparse.fit(X_csr, sample_weight=sample_weight) + + assert_array_equal(km_dense.labels_, km_sparse.labels_) + assert_allclose(km_dense.cluster_centers_, km_sparse.cluster_centers_) + + +@pytest.mark.parametrize( + "init", ["random", "k-means++", centers], ids=["random", "k-means++", "ndarray"] +) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_predict_dense_sparse(Estimator, init): + # check that models trained on sparse input also works for dense input at + # predict time and vice versa. + n_init = 10 if isinstance(init, str) else 1 + km = Estimator(n_clusters=n_clusters, init=init, n_init=n_init, random_state=0) + + km.fit(X_csr) + assert_array_equal(km.predict(X), km.labels_) + + km.fit(X) + assert_array_equal(km.predict(X_csr), km.labels_) + + +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +@pytest.mark.parametrize("dtype", [np.int32, np.int64]) +@pytest.mark.parametrize("init", ["k-means++", "ndarray"]) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_integer_input(Estimator, array_constr, dtype, init, global_random_seed): + # Check that KMeans and MiniBatchKMeans work with integer input. + X_dense = np.array([[0, 0], [10, 10], [12, 9], [-1, 1], [2, 0], [8, 10]]) + X = array_constr(X_dense, dtype=dtype) + + n_init = 1 if init == "ndarray" else 10 + init = X_dense[:2] if init == "ndarray" else init + + km = Estimator( + n_clusters=2, init=init, n_init=n_init, random_state=global_random_seed + ) + if Estimator is MiniBatchKMeans: + km.set_params(batch_size=2) + + km.fit(X) + + # Internally integer input should be converted to float64 + assert km.cluster_centers_.dtype == np.float64 + + expected_labels = [0, 1, 1, 0, 0, 1] + assert_allclose(v_measure_score(km.labels_, expected_labels), 1.0) + + # Same with partial_fit (#14314) + if Estimator is MiniBatchKMeans: + km = clone(km).partial_fit(X) + assert km.cluster_centers_.dtype == np.float64 + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_transform(Estimator, global_random_seed): + # Check the transform method + km = Estimator(n_clusters=n_clusters, random_state=global_random_seed).fit(X) + + # Transorfming cluster_centers_ should return the pairwise distances + # between centers + Xt = km.transform(km.cluster_centers_) + assert_allclose(Xt, pairwise_distances(km.cluster_centers_)) + # In particular, diagonal must be 0 + assert_array_equal(Xt.diagonal(), np.zeros(n_clusters)) + + # Transorfming X should return the pairwise distances between X and the + # centers + Xt = km.transform(X) + assert_allclose(Xt, pairwise_distances(X, km.cluster_centers_)) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_fit_transform(Estimator, global_random_seed): + # Check equivalence between fit.transform and fit_transform + X1 = Estimator(random_state=global_random_seed, n_init=1).fit(X).transform(X) + X2 = Estimator(random_state=global_random_seed, n_init=1).fit_transform(X) + assert_allclose(X1, X2) + + +def test_n_init(global_random_seed): + # Check that increasing the number of init increases the quality + previous_inertia = np.inf + for n_init in [1, 5, 10]: + # set max_iter=1 to avoid finding the global minimum and get the same + # inertia each time + km = KMeans( + n_clusters=n_clusters, + init="random", + n_init=n_init, + random_state=global_random_seed, + max_iter=1, + ).fit(X) + assert km.inertia_ <= previous_inertia + + +def test_k_means_function(global_random_seed): + # test calling the k_means function directly + cluster_centers, labels, inertia = k_means( + X, n_clusters=n_clusters, sample_weight=None, random_state=global_random_seed + ) + + assert cluster_centers.shape == (n_clusters, n_features) + assert np.unique(labels).shape[0] == n_clusters + + # check that the labels assignment are perfect (up to a permutation) + assert_allclose(v_measure_score(true_labels, labels), 1.0) + assert inertia > 0.0 + + +@pytest.mark.parametrize("data", [X, X_csr], ids=["dense", "sparse"]) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_float_precision(Estimator, data, global_random_seed): + # Check that the results are the same for single and double precision. + km = Estimator(n_init=1, random_state=global_random_seed) + + inertia = {} + Xt = {} + centers = {} + labels = {} + + for dtype in [np.float64, np.float32]: + X = data.astype(dtype, copy=False) + km.fit(X) + + inertia[dtype] = km.inertia_ + Xt[dtype] = km.transform(X) + centers[dtype] = km.cluster_centers_ + labels[dtype] = km.labels_ + + # dtype of cluster centers has to be the dtype of the input data + assert km.cluster_centers_.dtype == dtype + + # same with partial_fit + if Estimator is MiniBatchKMeans: + km.partial_fit(X[0:3]) + assert km.cluster_centers_.dtype == dtype + + # compare arrays with low precision since the difference between 32 and + # 64 bit comes from an accumulation of rounding errors. + assert_allclose(inertia[np.float32], inertia[np.float64], rtol=1e-4) + assert_allclose(Xt[np.float32], Xt[np.float64], atol=Xt[np.float64].max() * 1e-4) + assert_allclose( + centers[np.float32], centers[np.float64], atol=centers[np.float64].max() * 1e-4 + ) + assert_array_equal(labels[np.float32], labels[np.float64]) + + +@pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64]) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_centers_not_mutated(Estimator, dtype): + # Check that KMeans and MiniBatchKMeans won't mutate the user provided + # init centers silently even if input data and init centers have the same + # type. + X_new_type = X.astype(dtype, copy=False) + centers_new_type = centers.astype(dtype, copy=False) + + km = Estimator(init=centers_new_type, n_clusters=n_clusters, n_init=1) + km.fit(X_new_type) + + assert not np.may_share_memory(km.cluster_centers_, centers_new_type) + + +@pytest.mark.parametrize("data", [X, X_csr], ids=["dense", "sparse"]) +def test_kmeans_init_fitted_centers(data): + # Check that starting fitting from a local optimum shouldn't change the + # solution + km1 = KMeans(n_clusters=n_clusters).fit(data) + km2 = KMeans(n_clusters=n_clusters, init=km1.cluster_centers_, n_init=1).fit(data) + + assert_allclose(km1.cluster_centers_, km2.cluster_centers_) + + +def test_kmeans_warns_less_centers_than_unique_points(global_random_seed): + # Check KMeans when the number of found clusters is smaller than expected + X = np.asarray([[0, 0], [0, 1], [1, 0], [1, 0]]) # last point is duplicated + km = KMeans(n_clusters=4, random_state=global_random_seed) + + # KMeans should warn that fewer labels than cluster centers have been used + msg = ( + r"Number of distinct clusters \(3\) found smaller than " + r"n_clusters \(4\). Possibly due to duplicate points in X." + ) + with pytest.warns(ConvergenceWarning, match=msg): + km.fit(X) + # only three distinct points, so only three clusters + # can have points assigned to them + assert set(km.labels_) == set(range(3)) + + +def _sort_centers(centers): + return np.sort(centers, axis=0) + + +def test_weighted_vs_repeated(global_random_seed): + # Check that a sample weight of N should yield the same result as an N-fold + # repetition of the sample. Valid only if init is precomputed, otherwise + # rng produces different results. Not valid for MinibatchKMeans due to rng + # to extract minibatches. + sample_weight = np.random.RandomState(global_random_seed).randint( + 1, 5, size=n_samples + ) + X_repeat = np.repeat(X, sample_weight, axis=0) + + km = KMeans( + init=centers, n_init=1, n_clusters=n_clusters, random_state=global_random_seed + ) + + km_weighted = clone(km).fit(X, sample_weight=sample_weight) + repeated_labels = np.repeat(km_weighted.labels_, sample_weight) + km_repeated = clone(km).fit(X_repeat) + + assert_array_equal(km_repeated.labels_, repeated_labels) + assert_allclose(km_weighted.inertia_, km_repeated.inertia_) + assert_allclose( + _sort_centers(km_weighted.cluster_centers_), + _sort_centers(km_repeated.cluster_centers_), + ) + + +@pytest.mark.parametrize("data", [X, X_csr], ids=["dense", "sparse"]) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_unit_weights_vs_no_weights(Estimator, data, global_random_seed): + # Check that not passing sample weights should be equivalent to passing + # sample weights all equal to one. + sample_weight = np.ones(n_samples) + + km = Estimator(n_clusters=n_clusters, random_state=global_random_seed, n_init=1) + km_none = clone(km).fit(data, sample_weight=None) + km_ones = clone(km).fit(data, sample_weight=sample_weight) + + assert_array_equal(km_none.labels_, km_ones.labels_) + assert_allclose(km_none.cluster_centers_, km_ones.cluster_centers_) + + +@pytest.mark.parametrize("data", [X, X_csr], ids=["dense", "sparse"]) +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_scaled_weights(Estimator, data, global_random_seed): + # Check that scaling all sample weights by a common factor + # shouldn't change the result + sample_weight = np.random.RandomState(global_random_seed).uniform(size=n_samples) + + km = Estimator(n_clusters=n_clusters, random_state=global_random_seed, n_init=1) + km_orig = clone(km).fit(data, sample_weight=sample_weight) + km_scaled = clone(km).fit(data, sample_weight=0.5 * sample_weight) + + assert_array_equal(km_orig.labels_, km_scaled.labels_) + assert_allclose(km_orig.cluster_centers_, km_scaled.cluster_centers_) + + +def test_kmeans_elkan_iter_attribute(): + # Regression test on bad n_iter_ value. Previous bug n_iter_ was one off + # it's right value (#11340). + km = KMeans(algorithm="elkan", max_iter=1).fit(X) + assert km.n_iter_ == 1 + + +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +def test_kmeans_empty_cluster_relocated(array_constr): + # check that empty clusters are correctly relocated when using sample + # weights (#13486) + X = array_constr([[-1], [1]]) + sample_weight = [1.9, 0.1] + init = np.array([[-1], [10]]) + + km = KMeans(n_clusters=2, init=init, n_init=1) + km.fit(X, sample_weight=sample_weight) + + assert len(set(km.labels_)) == 2 + assert_allclose(km.cluster_centers_, [[-1], [1]]) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_result_equal_in_diff_n_threads(Estimator, global_random_seed): + # Check that KMeans/MiniBatchKMeans give the same results in parallel mode + # than in sequential mode. + rnd = np.random.RandomState(global_random_seed) + X = rnd.normal(size=(50, 10)) + + with threadpool_limits(limits=1, user_api="openmp"): + result_1 = ( + Estimator(n_clusters=n_clusters, random_state=global_random_seed) + .fit(X) + .labels_ + ) + with threadpool_limits(limits=2, user_api="openmp"): + result_2 = ( + Estimator(n_clusters=n_clusters, random_state=global_random_seed) + .fit(X) + .labels_ + ) + assert_array_equal(result_1, result_2) + + +def test_warning_elkan_1_cluster(): + # Check warning messages specific to KMeans + with pytest.warns( + RuntimeWarning, + match="algorithm='elkan' doesn't make sense for a single cluster", + ): + KMeans(n_clusters=1, algorithm="elkan").fit(X) + + +@pytest.mark.parametrize( + "array_constr", [np.array, sp.csr_matrix], ids=["dense", "sparse"] +) +@pytest.mark.parametrize("algo", ["lloyd", "elkan"]) +def test_k_means_1_iteration(array_constr, algo, global_random_seed): + # check the results after a single iteration (E-step M-step E-step) by + # comparing against a pure python implementation. + X = np.random.RandomState(global_random_seed).uniform(size=(100, 5)) + init_centers = X[:5] + X = array_constr(X) + + def py_kmeans(X, init): + new_centers = init.copy() + labels = pairwise_distances_argmin(X, init) + for label in range(init.shape[0]): + new_centers[label] = X[labels == label].mean(axis=0) + labels = pairwise_distances_argmin(X, new_centers) + return labels, new_centers + + py_labels, py_centers = py_kmeans(X, init_centers) + + cy_kmeans = KMeans( + n_clusters=5, n_init=1, init=init_centers, algorithm=algo, max_iter=1 + ).fit(X) + cy_labels = cy_kmeans.labels_ + cy_centers = cy_kmeans.cluster_centers_ + + assert_array_equal(py_labels, cy_labels) + assert_allclose(py_centers, cy_centers) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("squared", [True, False]) +def test_euclidean_distance(dtype, squared, global_random_seed): + # Check that the _euclidean_(dense/sparse)_dense helpers produce correct + # results + rng = np.random.RandomState(global_random_seed) + a_sparse = sp.random( + 1, 100, density=0.5, format="csr", random_state=rng, dtype=dtype + ) + a_dense = a_sparse.toarray().reshape(-1) + b = rng.randn(100).astype(dtype, copy=False) + b_squared_norm = (b**2).sum() + + expected = ((a_dense - b) ** 2).sum() + expected = expected if squared else np.sqrt(expected) + + distance_dense_dense = _euclidean_dense_dense_wrapper(a_dense, b, squared) + distance_sparse_dense = _euclidean_sparse_dense_wrapper( + a_sparse.data, a_sparse.indices, b, b_squared_norm, squared + ) + + rtol = 1e-4 if dtype == np.float32 else 1e-7 + assert_allclose(distance_dense_dense, distance_sparse_dense, rtol=rtol) + assert_allclose(distance_dense_dense, expected, rtol=rtol) + assert_allclose(distance_sparse_dense, expected, rtol=rtol) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_inertia(dtype, global_random_seed): + # Check that the _inertia_(dense/sparse) helpers produce correct results. + rng = np.random.RandomState(global_random_seed) + X_sparse = sp.random( + 100, 10, density=0.5, format="csr", random_state=rng, dtype=dtype + ) + X_dense = X_sparse.toarray() + sample_weight = rng.randn(100).astype(dtype, copy=False) + centers = rng.randn(5, 10).astype(dtype, copy=False) + labels = rng.randint(5, size=100, dtype=np.int32) + + distances = ((X_dense - centers[labels]) ** 2).sum(axis=1) + expected = np.sum(distances * sample_weight) + + inertia_dense = _inertia_dense(X_dense, sample_weight, centers, labels, n_threads=1) + inertia_sparse = _inertia_sparse( + X_sparse, sample_weight, centers, labels, n_threads=1 + ) + + rtol = 1e-4 if dtype == np.float32 else 1e-6 + assert_allclose(inertia_dense, inertia_sparse, rtol=rtol) + assert_allclose(inertia_dense, expected, rtol=rtol) + assert_allclose(inertia_sparse, expected, rtol=rtol) + + # Check the single_label parameter. + label = 1 + mask = labels == label + distances = ((X_dense[mask] - centers[label]) ** 2).sum(axis=1) + expected = np.sum(distances * sample_weight[mask]) + + inertia_dense = _inertia_dense( + X_dense, sample_weight, centers, labels, n_threads=1, single_label=label + ) + inertia_sparse = _inertia_sparse( + X_sparse, sample_weight, centers, labels, n_threads=1, single_label=label + ) + + assert_allclose(inertia_dense, inertia_sparse, rtol=rtol) + assert_allclose(inertia_dense, expected, rtol=rtol) + assert_allclose(inertia_sparse, expected, rtol=rtol) + + +# TODO(1.4): Remove +@pytest.mark.parametrize("Klass, default_n_init", [(KMeans, 10), (MiniBatchKMeans, 3)]) +def test_change_n_init_future_warning(Klass, default_n_init): + est = Klass(n_init=1) + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + est.fit(X) + + default_n_init = 10 if Klass.__name__ == "KMeans" else 3 + msg = ( + f"The default value of `n_init` will change from {default_n_init} to 'auto'" + " in 1.4" + ) + est = Klass() + with pytest.warns(FutureWarning, match=msg): + est.fit(X) + + +@pytest.mark.parametrize("Klass, default_n_init", [(KMeans, 10), (MiniBatchKMeans, 3)]) +def test_n_init_auto(Klass, default_n_init): + est = Klass(n_init="auto", init="k-means++") + est.fit(X) + assert est._n_init == 1 + + est = Klass(n_init="auto", init="random") + est.fit(X) + assert est._n_init == 10 if Klass.__name__ == "KMeans" else 3 + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +def test_sample_weight_unchanged(Estimator): + # Check that sample_weight is not modified in place by KMeans (#17204) + X = np.array([[1], [2], [4]]) + sample_weight = np.array([0.5, 0.2, 0.3]) + Estimator(n_clusters=2, random_state=0).fit(X, sample_weight=sample_weight) + + assert_array_equal(sample_weight, np.array([0.5, 0.2, 0.3])) + + +@pytest.mark.parametrize("Estimator", [KMeans, MiniBatchKMeans]) +@pytest.mark.parametrize( + "param, match", + [ + ({"n_clusters": n_samples + 1}, r"n_samples.* should be >= n_clusters"), + ( + {"init": X[:2]}, + r"The shape of the initial centers .* does not match " + r"the number of clusters", + ), + ( + {"init": lambda X_, k, random_state: X_[:2]}, + r"The shape of the initial centers .* does not match " + r"the number of clusters", + ), + ( + {"init": X[:8, :2]}, + r"The shape of the initial centers .* does not match " + r"the number of features of the data", + ), + ( + {"init": lambda X_, k, random_state: X_[:8, :2]}, + r"The shape of the initial centers .* does not match " + r"the number of features of the data", + ), + ], +) +def test_wrong_params(Estimator, param, match): + # Check that error are raised with clear error message when wrong values + # are passed for the parameters + # Set n_init=1 by default to avoid warning with precomputed init + km = Estimator(n_init=1) + with pytest.raises(ValueError, match=match): + km.set_params(**param).fit(X) + + +@pytest.mark.parametrize( + "param, match", + [ + ( + {"x_squared_norms": X[:2]}, + r"The length of x_squared_norms .* should " + r"be equal to the length of n_samples", + ), + ], +) +def test_kmeans_plusplus_wrong_params(param, match): + with pytest.raises(ValueError, match=match): + kmeans_plusplus(X, n_clusters, **param) + + +@pytest.mark.parametrize("data", [X, X_csr]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_kmeans_plusplus_output(data, dtype, global_random_seed): + # Check for the correct number of seeds and all positive values + data = data.astype(dtype) + centers, indices = kmeans_plusplus( + data, n_clusters, random_state=global_random_seed + ) + + # Check there are the correct number of indices and that all indices are + # positive and within the number of samples + assert indices.shape[0] == n_clusters + assert (indices >= 0).all() + assert (indices <= data.shape[0]).all() + + # Check for the correct number of seeds and that they are bound by the data + assert centers.shape[0] == n_clusters + assert (centers.max(axis=0) <= data.max(axis=0)).all() + assert (centers.min(axis=0) >= data.min(axis=0)).all() + + # Check that indices correspond to reported centers + # Use X for comparison rather than data, test still works against centers + # calculated with sparse data. + assert_allclose(X[indices].astype(dtype), centers) + + +@pytest.mark.parametrize("x_squared_norms", [row_norms(X, squared=True), None]) +def test_kmeans_plusplus_norms(x_squared_norms): + # Check that defining x_squared_norms returns the same as default=None. + centers, indices = kmeans_plusplus(X, n_clusters, x_squared_norms=x_squared_norms) + + assert_allclose(X[indices], centers) + + +def test_kmeans_plusplus_dataorder(global_random_seed): + # Check that memory layout does not effect result + centers_c, _ = kmeans_plusplus(X, n_clusters, random_state=global_random_seed) + + X_fortran = np.asfortranarray(X) + + centers_fortran, _ = kmeans_plusplus( + X_fortran, n_clusters, random_state=global_random_seed + ) + + assert_allclose(centers_c, centers_fortran) + + +def test_is_same_clustering(): + # Sanity check for the _is_same_clustering utility function + labels1 = np.array([1, 0, 0, 1, 2, 0, 2, 1], dtype=np.int32) + assert _is_same_clustering(labels1, labels1, 3) + + # these other labels represent the same clustering since we can retrieve the first + # labels by simply renaming the labels: 0 -> 1, 1 -> 2, 2 -> 0. + labels2 = np.array([0, 2, 2, 0, 1, 2, 1, 0], dtype=np.int32) + assert _is_same_clustering(labels1, labels2, 3) + + # these other labels do not represent the same clustering since not all ones are + # mapped to a same value + labels3 = np.array([1, 0, 0, 2, 2, 0, 2, 1], dtype=np.int32) + assert not _is_same_clustering(labels1, labels3, 3) + + +@pytest.mark.parametrize( + "kwargs", ({"init": np.str_("k-means++")}, {"init": [[0, 0], [1, 1]], "n_init": 1}) +) +def test_kmeans_with_array_like_or_np_scalar_init(kwargs): + """Check that init works with numpy scalar strings. + + Non-regression test for #21964. + """ + X = np.asarray([[0, 0], [0.5, 0], [0.5, 1], [1, 1]], dtype=np.float64) + + clustering = KMeans(n_clusters=2, **kwargs) + # Does not raise + clustering.fit(X) + + +@pytest.mark.parametrize( + "Klass, method", + [(KMeans, "fit"), (MiniBatchKMeans, "fit"), (MiniBatchKMeans, "partial_fit")], +) +def test_feature_names_out(Klass, method): + """Check `feature_names_out` for `KMeans` and `MiniBatchKMeans`.""" + class_name = Klass.__name__.lower() + kmeans = Klass() + getattr(kmeans, method)(X) + n_clusters = kmeans.cluster_centers_.shape[0] + + names_out = kmeans.get_feature_names_out() + assert_array_equal([f"{class_name}{i}" for i in range(n_clusters)], names_out) + + +@pytest.mark.parametrize("is_sparse", [True, False]) +def test_predict_does_not_change_cluster_centers(is_sparse): + """Check that predict does not change cluster centers. + + Non-regression test for gh-24253. + """ + X, _ = make_blobs(n_samples=200, n_features=10, centers=10, random_state=0) + if is_sparse: + X = sp.csr_matrix(X) + + kmeans = KMeans() + y_pred1 = kmeans.fit_predict(X) + # Make cluster_centers readonly + kmeans.cluster_centers_ = create_memmap_backed_data(kmeans.cluster_centers_) + kmeans.labels_ = create_memmap_backed_data(kmeans.labels_) + + y_pred2 = kmeans.predict(X) + assert_array_equal(y_pred1, y_pred2) diff --git a/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_mean_shift.py b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_mean_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4d1c68d2f6e1007fe3c33ced07011139d62c24 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/cluster/tests/test_mean_shift.py @@ -0,0 +1,221 @@ +""" +Testing for mean shift clustering methods + +""" + +import numpy as np +import warnings +import pytest + +from scipy import sparse + +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_allclose + +from sklearn.cluster import MeanShift +from sklearn.cluster import mean_shift +from sklearn.cluster import estimate_bandwidth +from sklearn.cluster import get_bin_seeds +from sklearn.datasets import make_blobs +from sklearn.metrics import v_measure_score + + +n_clusters = 3 +centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 +X, _ = make_blobs( + n_samples=300, + n_features=2, + centers=centers, + cluster_std=0.4, + shuffle=True, + random_state=11, +) + + +def test_estimate_bandwidth(): + # Test estimate_bandwidth + bandwidth = estimate_bandwidth(X, n_samples=200) + assert 0.9 <= bandwidth <= 1.5 + + +def test_estimate_bandwidth_1sample(global_dtype): + # Test estimate_bandwidth when n_samples=1 and quantile<1, so that + # n_neighbors is set to 1. + bandwidth = estimate_bandwidth( + X.astype(global_dtype, copy=False), n_samples=1, quantile=0.3 + ) + + assert bandwidth.dtype == X.dtype + assert bandwidth == pytest.approx(0.0, abs=1e-5) + + +@pytest.mark.parametrize( + "bandwidth, cluster_all, expected, first_cluster_label", + [(1.2, True, 3, 0), (1.2, False, 4, -1)], +) +def test_mean_shift( + global_dtype, bandwidth, cluster_all, expected, first_cluster_label +): + # Test MeanShift algorithm + X_with_global_dtype = X.astype(global_dtype, copy=False) + ms = MeanShift(bandwidth=bandwidth, cluster_all=cluster_all) + labels = ms.fit(X_with_global_dtype).labels_ + labels_unique = np.unique(labels) + n_clusters_ = len(labels_unique) + assert n_clusters_ == expected + assert labels_unique[0] == first_cluster_label + assert ms.cluster_centers_.dtype == global_dtype + + cluster_centers, labels_mean_shift = mean_shift( + X_with_global_dtype, cluster_all=cluster_all + ) + labels_mean_shift_unique = np.unique(labels_mean_shift) + n_clusters_mean_shift = len(labels_mean_shift_unique) + assert n_clusters_mean_shift == expected + assert labels_mean_shift_unique[0] == first_cluster_label + assert cluster_centers.dtype == global_dtype + + +def test_estimate_bandwidth_with_sparse_matrix(): + # Test estimate_bandwidth with sparse matrix + X = sparse.lil_matrix((1000, 1000)) + msg = "A sparse matrix was passed, but dense data is required." + with pytest.raises(TypeError, match=msg): + estimate_bandwidth(X) + + +def test_parallel(global_dtype): + centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10 + X, _ = make_blobs( + n_samples=50, + n_features=2, + centers=centers, + cluster_std=0.4, + shuffle=True, + random_state=11, + ) + + X = X.astype(global_dtype, copy=False) + + ms1 = MeanShift(n_jobs=2) + ms1.fit(X) + + ms2 = MeanShift() + ms2.fit(X) + + assert_allclose(ms1.cluster_centers_, ms2.cluster_centers_) + assert ms1.cluster_centers_.dtype == ms2.cluster_centers_.dtype + assert_array_equal(ms1.labels_, ms2.labels_) + + +def test_meanshift_predict(global_dtype): + # Test MeanShift.predict + ms = MeanShift(bandwidth=1.2) + X_with_global_dtype = X.astype(global_dtype, copy=False) + labels = ms.fit_predict(X_with_global_dtype) + labels2 = ms.predict(X_with_global_dtype) + assert_array_equal(labels, labels2) + + +def test_meanshift_all_orphans(): + # init away from the data, crash with a sensible warning + ms = MeanShift(bandwidth=0.1, seeds=[[-9, -9], [-10, -10]]) + msg = "No point was within bandwidth=0.1" + with pytest.raises(ValueError, match=msg): + ms.fit( + X, + ) + + +def test_unfitted(): + # Non-regression: before fit, there should be not fitted attributes. + ms = MeanShift() + assert not hasattr(ms, "cluster_centers_") + assert not hasattr(ms, "labels_") + + +def test_cluster_intensity_tie(global_dtype): + X = np.array([[1, 1], [2, 1], [1, 0], [4, 7], [3, 5], [3, 6]], dtype=global_dtype) + c1 = MeanShift(bandwidth=2).fit(X) + + X = np.array([[4, 7], [3, 5], [3, 6], [1, 1], [2, 1], [1, 0]], dtype=global_dtype) + c2 = MeanShift(bandwidth=2).fit(X) + assert_array_equal(c1.labels_, [1, 1, 1, 0, 0, 0]) + assert_array_equal(c2.labels_, [0, 0, 0, 1, 1, 1]) + + +def test_bin_seeds(global_dtype): + # Test the bin seeding technique which can be used in the mean shift + # algorithm + # Data is just 6 points in the plane + X = np.array( + [[1.0, 1.0], [1.4, 1.4], [1.8, 1.2], [2.0, 1.0], [2.1, 1.1], [0.0, 0.0]], + dtype=global_dtype, + ) + + # With a bin coarseness of 1.0 and min_bin_freq of 1, 3 bins should be + # found + ground_truth = {(1.0, 1.0), (2.0, 1.0), (0.0, 0.0)} + test_bins = get_bin_seeds(X, 1, 1) + test_result = set(tuple(p) for p in test_bins) + assert len(ground_truth.symmetric_difference(test_result)) == 0 + + # With a bin coarseness of 1.0 and min_bin_freq of 2, 2 bins should be + # found + ground_truth = {(1.0, 1.0), (2.0, 1.0)} + test_bins = get_bin_seeds(X, 1, 2) + test_result = set(tuple(p) for p in test_bins) + assert len(ground_truth.symmetric_difference(test_result)) == 0 + + # With a bin size of 0.01 and min_bin_freq of 1, 6 bins should be found + # we bail and use the whole data here. + with warnings.catch_warnings(record=True): + test_bins = get_bin_seeds(X, 0.01, 1) + assert_allclose(test_bins, X) + + # tight clusters around [0, 0] and [1, 1], only get two bins + X, _ = make_blobs( + n_samples=100, + n_features=2, + centers=[[0, 0], [1, 1]], + cluster_std=0.1, + random_state=0, + ) + X = X.astype(global_dtype, copy=False) + test_bins = get_bin_seeds(X, 1) + assert_array_equal(test_bins, [[0, 0], [1, 1]]) + + +@pytest.mark.parametrize("max_iter", [1, 100]) +def test_max_iter(max_iter): + clusters1, _ = mean_shift(X, max_iter=max_iter) + ms = MeanShift(max_iter=max_iter).fit(X) + clusters2 = ms.cluster_centers_ + + assert ms.n_iter_ <= ms.max_iter + assert len(clusters1) == len(clusters2) + + for c1, c2 in zip(clusters1, clusters2): + assert np.allclose(c1, c2) + + +def test_mean_shift_zero_bandwidth(global_dtype): + # Check that mean shift works when the estimated bandwidth is 0. + X = np.array([1, 1, 1, 2, 2, 2, 3, 3], dtype=global_dtype).reshape(-1, 1) + + # estimate_bandwidth with default args returns 0 on this dataset + bandwidth = estimate_bandwidth(X) + assert bandwidth == 0 + + # get_bin_seeds with a 0 bin_size should return the dataset itself + assert get_bin_seeds(X, bin_size=bandwidth) is X + + # MeanShift with binning and a 0 estimated bandwidth should be equivalent + # to no binning. + ms_binning = MeanShift(bin_seeding=True, bandwidth=None).fit(X) + ms_nobinning = MeanShift(bin_seeding=False).fit(X) + expected_labels = np.array([0, 0, 0, 1, 1, 1, 2, 2]) + + assert v_measure_score(ms_binning.labels_, expected_labels) == pytest.approx(1) + assert v_measure_score(ms_nobinning.labels_, expected_labels) == pytest.approx(1) + assert_allclose(ms_binning.cluster_centers_, ms_nobinning.cluster_centers_) diff --git a/falcon/lib/python3.10/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..139a800524f4e9ad57e5e943edecd75a6e0c1fed --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44052fd3053ae64240dce9c5d800ba0ca662c5fc35a441f85a2a66f59196f975 +size 339729 diff --git a/falcon/lib/python3.10/site-packages/sklearn/experimental/enable_halving_search_cv.py b/falcon/lib/python3.10/site-packages/sklearn/experimental/enable_halving_search_cv.py new file mode 100644 index 0000000000000000000000000000000000000000..f6937b0d14c016b56e9f6646ca738c6f7580e10a --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/experimental/enable_halving_search_cv.py @@ -0,0 +1,33 @@ +"""Enables Successive Halving search-estimators + +The API and results of these estimators might change without any deprecation +cycle. + +Importing this file dynamically sets the +:class:`~sklearn.model_selection.HalvingRandomSearchCV` and +:class:`~sklearn.model_selection.HalvingGridSearchCV` as attributes of the +`model_selection` module:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_halving_search_cv # noqa + >>> # now you can import normally from model_selection + >>> from sklearn.model_selection import HalvingRandomSearchCV + >>> from sklearn.model_selection import HalvingGridSearchCV + + +The ``# noqa`` comment comment can be removed: it just tells linters like +flake8 to ignore the import, which appears as unused. +""" + +from ..model_selection._search_successive_halving import ( + HalvingRandomSearchCV, + HalvingGridSearchCV, +) + +from .. import model_selection + +# use settattr to avoid mypy errors when monkeypatching +setattr(model_selection, "HalvingRandomSearchCV", HalvingRandomSearchCV) +setattr(model_selection, "HalvingGridSearchCV", HalvingGridSearchCV) + +model_selection.__all__ += ["HalvingRandomSearchCV", "HalvingGridSearchCV"] diff --git a/falcon/lib/python3.10/site-packages/sklearn/experimental/enable_hist_gradient_boosting.py b/falcon/lib/python3.10/site-packages/sklearn/experimental/enable_hist_gradient_boosting.py new file mode 100644 index 0000000000000000000000000000000000000000..f0416ac013e96e8d74f8aac18c17a4b114885538 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/experimental/enable_hist_gradient_boosting.py @@ -0,0 +1,21 @@ +"""This is now a no-op and can be safely removed from your code. + +It used to enable the use of +:class:`~sklearn.ensemble.HistGradientBoostingClassifier` and +:class:`~sklearn.ensemble.HistGradientBoostingRegressor` when they were still +:term:`experimental`, but these estimators are now stable and can be imported +normally from `sklearn.ensemble`. +""" +# Don't remove this file, we don't want to break users code just because the +# feature isn't experimental anymore. + + +import warnings + + +warnings.warn( + "Since version 1.0, " + "it is not needed to import enable_hist_gradient_boosting anymore. " + "HistGradientBoostingClassifier and HistGradientBoostingRegressor are now " + "stable and can be normally imported from sklearn.ensemble." +) diff --git a/falcon/lib/python3.10/site-packages/sklearn/experimental/tests/__init__.py b/falcon/lib/python3.10/site-packages/sklearn/experimental/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_search.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3660a53d1cdd40e4a0698670532188fb0bbb4765 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_search.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_search_successive_halving.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_search_successive_halving.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e7d56425c4b14961600a9b8a0252c3a8ed4790d Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_search_successive_halving.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_split.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_split.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7e97285f949e62c87181670247ac38cf4ea4546 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/model_selection/__pycache__/_split.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/__init__.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b80dcd3188e342fc7657817f8768f23657a8f3 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/test_search.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/test_search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91681c29f7423b4f0861ff72e4f419149e112024 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/test_search.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/test_split.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/test_split.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11e550ac360afbd9403c28d1d072ea088b6f02d5 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/__pycache__/test_split.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/test_successive_halving.py b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/test_successive_halving.py new file mode 100644 index 0000000000000000000000000000000000000000..61193ba0c4e3bd5965139114fe8a4cd66c18a20c --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/model_selection/tests/test_successive_halving.py @@ -0,0 +1,783 @@ +from math import ceil + +import pytest +from scipy.stats import norm, randint +import numpy as np + +from sklearn.datasets import make_classification +from sklearn.dummy import DummyClassifier +from sklearn.experimental import enable_halving_search_cv # noqa +from sklearn.model_selection import StratifiedKFold +from sklearn.model_selection import StratifiedShuffleSplit +from sklearn.model_selection import LeaveOneGroupOut +from sklearn.model_selection import LeavePGroupsOut +from sklearn.model_selection import GroupKFold +from sklearn.model_selection import GroupShuffleSplit +from sklearn.model_selection import HalvingGridSearchCV +from sklearn.model_selection import HalvingRandomSearchCV +from sklearn.model_selection import KFold, ShuffleSplit +from sklearn.svm import LinearSVC +from sklearn.model_selection._search_successive_halving import ( + _SubsampleMetaSplitter, + _top_k, +) + + +class FastClassifier(DummyClassifier): + """Dummy classifier that accepts parameters a, b, ... z. + + These parameter don't affect the predictions and are useful for fast + grid searching.""" + + # update the constraints such that we accept all parameters from a to z + _parameter_constraints: dict = { + **DummyClassifier._parameter_constraints, + **{ + chr(key): "no_validation" # type: ignore + for key in range(ord("a"), ord("z") + 1) + }, + } + + def __init__( + self, strategy="stratified", random_state=None, constant=None, **kwargs + ): + super().__init__( + strategy=strategy, random_state=random_state, constant=constant + ) + + def get_params(self, deep=False): + params = super().get_params(deep=deep) + for char in range(ord("a"), ord("z") + 1): + params[chr(char)] = "whatever" + return params + + +class SometimesFailClassifier(DummyClassifier): + def __init__( + self, + strategy="stratified", + random_state=None, + constant=None, + n_estimators=10, + fail_fit=False, + fail_predict=False, + a=0, + ): + self.fail_fit = fail_fit + self.fail_predict = fail_predict + self.n_estimators = n_estimators + self.a = a + + super().__init__( + strategy=strategy, random_state=random_state, constant=constant + ) + + def fit(self, X, y): + if self.fail_fit: + raise Exception("fitting failed") + return super().fit(X, y) + + def predict(self, X): + if self.fail_predict: + raise Exception("predict failed") + return super().predict(X) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.FitFailedWarning") +@pytest.mark.filterwarnings("ignore:Scoring failed:UserWarning") +@pytest.mark.filterwarnings("ignore:One or more of the:UserWarning") +@pytest.mark.parametrize("HalvingSearch", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize("fail_at", ("fit", "predict")) +def test_nan_handling(HalvingSearch, fail_at): + """Check the selection of the best scores in presence of failure represented by + NaN values.""" + n_samples = 1_000 + X, y = make_classification(n_samples=n_samples, random_state=0) + + search = HalvingSearch( + SometimesFailClassifier(), + {f"fail_{fail_at}": [False, True], "a": range(3)}, + resource="n_estimators", + max_resources=6, + min_resources=1, + factor=2, + ) + + search.fit(X, y) + + # estimators that failed during fit/predict should always rank lower + # than ones where the fit/predict succeeded + assert not search.best_params_[f"fail_{fail_at}"] + scores = search.cv_results_["mean_test_score"] + ranks = search.cv_results_["rank_test_score"] + + # some scores should be NaN + assert np.isnan(scores).any() + + unique_nan_ranks = np.unique(ranks[np.isnan(scores)]) + # all NaN scores should have the same rank + assert unique_nan_ranks.shape[0] == 1 + # NaNs should have the lowest rank + assert (unique_nan_ranks[0] >= ranks).all() + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize( + "aggressive_elimination," + "max_resources," + "expected_n_iterations," + "expected_n_required_iterations," + "expected_n_possible_iterations," + "expected_n_remaining_candidates," + "expected_n_candidates," + "expected_n_resources,", + [ + # notice how it loops at the beginning + # also, the number of candidates evaluated at the last iteration is + # <= factor + (True, "limited", 4, 4, 3, 1, [60, 20, 7, 3], [20, 20, 60, 180]), + # no aggressive elimination: we end up with less iterations, and + # the number of candidates at the last iter is > factor, which isn't + # ideal + (False, "limited", 3, 4, 3, 3, [60, 20, 7], [20, 60, 180]), + # # When the amount of resource isn't limited, aggressive_elimination + # # has no effect. Here the default min_resources='exhaust' will take + # # over. + (True, "unlimited", 4, 4, 4, 1, [60, 20, 7, 3], [37, 111, 333, 999]), + (False, "unlimited", 4, 4, 4, 1, [60, 20, 7, 3], [37, 111, 333, 999]), + ], +) +def test_aggressive_elimination( + Est, + aggressive_elimination, + max_resources, + expected_n_iterations, + expected_n_required_iterations, + expected_n_possible_iterations, + expected_n_remaining_candidates, + expected_n_candidates, + expected_n_resources, +): + # Test the aggressive_elimination parameter. + + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {"a": ("l1", "l2"), "b": list(range(30))} + base_estimator = FastClassifier() + + if max_resources == "limited": + max_resources = 180 + else: + max_resources = n_samples + + sh = Est( + base_estimator, + param_grid, + aggressive_elimination=aggressive_elimination, + max_resources=max_resources, + factor=3, + ) + sh.set_params(verbose=True) # just for test coverage + + if Est is HalvingRandomSearchCV: + # same number of candidates as with the grid + sh.set_params(n_candidates=2 * 30, min_resources="exhaust") + + sh.fit(X, y) + + assert sh.n_iterations_ == expected_n_iterations + assert sh.n_required_iterations_ == expected_n_required_iterations + assert sh.n_possible_iterations_ == expected_n_possible_iterations + assert sh.n_resources_ == expected_n_resources + assert sh.n_candidates_ == expected_n_candidates + assert sh.n_remaining_candidates_ == expected_n_remaining_candidates + assert ceil(sh.n_candidates_[-1] / sh.factor) == sh.n_remaining_candidates_ + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize( + "min_resources," + "max_resources," + "expected_n_iterations," + "expected_n_possible_iterations," + "expected_n_resources,", + [ + # with enough resources + ("smallest", "auto", 2, 4, [20, 60]), + # with enough resources but min_resources set manually + (50, "auto", 2, 3, [50, 150]), + # without enough resources, only one iteration can be done + ("smallest", 30, 1, 1, [20]), + # with exhaust: use as much resources as possible at the last iter + ("exhaust", "auto", 2, 2, [333, 999]), + ("exhaust", 1000, 2, 2, [333, 999]), + ("exhaust", 999, 2, 2, [333, 999]), + ("exhaust", 600, 2, 2, [200, 600]), + ("exhaust", 599, 2, 2, [199, 597]), + ("exhaust", 300, 2, 2, [100, 300]), + ("exhaust", 60, 2, 2, [20, 60]), + ("exhaust", 50, 1, 1, [20]), + ("exhaust", 20, 1, 1, [20]), + ], +) +def test_min_max_resources( + Est, + min_resources, + max_resources, + expected_n_iterations, + expected_n_possible_iterations, + expected_n_resources, +): + # Test the min_resources and max_resources parameters, and how they affect + # the number of resources used at each iteration + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {"a": [1, 2], "b": [1, 2, 3]} + base_estimator = FastClassifier() + + sh = Est( + base_estimator, + param_grid, + factor=3, + min_resources=min_resources, + max_resources=max_resources, + ) + if Est is HalvingRandomSearchCV: + sh.set_params(n_candidates=6) # same number as with the grid + + sh.fit(X, y) + + expected_n_required_iterations = 2 # given 6 combinations and factor = 3 + assert sh.n_iterations_ == expected_n_iterations + assert sh.n_required_iterations_ == expected_n_required_iterations + assert sh.n_possible_iterations_ == expected_n_possible_iterations + assert sh.n_resources_ == expected_n_resources + if min_resources == "exhaust": + assert sh.n_possible_iterations_ == sh.n_iterations_ == len(sh.n_resources_) + + +@pytest.mark.parametrize("Est", (HalvingRandomSearchCV, HalvingGridSearchCV)) +@pytest.mark.parametrize( + "max_resources, n_iterations, n_possible_iterations", + [ + ("auto", 5, 9), # all resources are used + (1024, 5, 9), + (700, 5, 8), + (512, 5, 8), + (511, 5, 7), + (32, 4, 4), + (31, 3, 3), + (16, 3, 3), + (4, 1, 1), # max_resources == min_resources, only one iteration is + # possible + ], +) +def test_n_iterations(Est, max_resources, n_iterations, n_possible_iterations): + # test the number of actual iterations that were run depending on + # max_resources + + n_samples = 1024 + X, y = make_classification(n_samples=n_samples, random_state=1) + param_grid = {"a": [1, 2], "b": list(range(10))} + base_estimator = FastClassifier() + factor = 2 + + sh = Est( + base_estimator, + param_grid, + cv=2, + factor=factor, + max_resources=max_resources, + min_resources=4, + ) + if Est is HalvingRandomSearchCV: + sh.set_params(n_candidates=20) # same as for HalvingGridSearchCV + sh.fit(X, y) + assert sh.n_required_iterations_ == 5 + assert sh.n_iterations_ == n_iterations + assert sh.n_possible_iterations_ == n_possible_iterations + + +@pytest.mark.parametrize("Est", (HalvingRandomSearchCV, HalvingGridSearchCV)) +def test_resource_parameter(Est): + # Test the resource parameter + + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {"a": [1, 2], "b": list(range(10))} + base_estimator = FastClassifier() + sh = Est(base_estimator, param_grid, cv=2, resource="c", max_resources=10, factor=3) + sh.fit(X, y) + assert set(sh.n_resources_) == set([1, 3, 9]) + for r_i, params, param_c in zip( + sh.cv_results_["n_resources"], + sh.cv_results_["params"], + sh.cv_results_["param_c"], + ): + assert r_i == params["c"] == param_c + + with pytest.raises( + ValueError, match="Cannot use resource=1234 which is not supported " + ): + sh = HalvingGridSearchCV( + base_estimator, param_grid, cv=2, resource="1234", max_resources=10 + ) + sh.fit(X, y) + + with pytest.raises( + ValueError, + match=( + "Cannot use parameter c as the resource since it is part " + "of the searched parameters." + ), + ): + param_grid = {"a": [1, 2], "b": [1, 2], "c": [1, 3]} + sh = HalvingGridSearchCV( + base_estimator, param_grid, cv=2, resource="c", max_resources=10 + ) + sh.fit(X, y) + + +@pytest.mark.parametrize( + "max_resources, n_candidates, expected_n_candidates", + [ + (512, "exhaust", 128), # generate exactly as much as needed + (32, "exhaust", 8), + (32, 8, 8), + (32, 7, 7), # ask for less than what we could + (32, 9, 9), # ask for more than 'reasonable' + ], +) +def test_random_search(max_resources, n_candidates, expected_n_candidates): + # Test random search and make sure the number of generated candidates is + # as expected + + n_samples = 1024 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {"a": norm, "b": norm} + base_estimator = FastClassifier() + sh = HalvingRandomSearchCV( + base_estimator, + param_grid, + n_candidates=n_candidates, + cv=2, + max_resources=max_resources, + factor=2, + min_resources=4, + ) + sh.fit(X, y) + assert sh.n_candidates_[0] == expected_n_candidates + if n_candidates == "exhaust": + # Make sure 'exhaust' makes the last iteration use as much resources as + # we can + assert sh.n_resources_[-1] == max_resources + + +@pytest.mark.parametrize( + "param_distributions, expected_n_candidates", + [ + ({"a": [1, 2]}, 2), # all lists, sample less than n_candidates + ({"a": randint(1, 3)}, 10), # not all list, respect n_candidates + ], +) +def test_random_search_discrete_distributions( + param_distributions, expected_n_candidates +): + # Make sure random search samples the appropriate number of candidates when + # we ask for more than what's possible. How many parameters are sampled + # depends whether the distributions are 'all lists' or not (see + # ParameterSampler for details). This is somewhat redundant with the checks + # in ParameterSampler but interaction bugs were discovered during + # development of SH + + n_samples = 1024 + X, y = make_classification(n_samples=n_samples, random_state=0) + base_estimator = FastClassifier() + sh = HalvingRandomSearchCV(base_estimator, param_distributions, n_candidates=10) + sh.fit(X, y) + assert sh.n_candidates_[0] == expected_n_candidates + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize( + "params, expected_error_message", + [ + ({"scoring": {"accuracy", "accuracy"}}, "Multimetric scoring is not supported"), + ( + {"resource": "not_a_parameter"}, + "Cannot use resource=not_a_parameter which is not supported", + ), + ( + {"resource": "a", "max_resources": 100}, + "Cannot use parameter a as the resource since it is part of", + ), + ({"max_resources": "not_auto"}, "max_resources must be either"), + ({"max_resources": 100.5}, "max_resources must be either"), + ({"max_resources": -10}, "max_resources must be either"), + ({"min_resources": "bad str"}, "min_resources must be either"), + ({"min_resources": 0.5}, "min_resources must be either"), + ({"min_resources": -10}, "min_resources must be either"), + ( + {"max_resources": "auto", "resource": "b"}, + "resource can only be 'n_samples' when max_resources='auto'", + ), + ( + {"min_resources": 15, "max_resources": 14}, + "min_resources_=15 is greater than max_resources_=14", + ), + ({"cv": KFold(shuffle=True)}, "must yield consistent folds"), + ({"cv": ShuffleSplit()}, "must yield consistent folds"), + ({"refit": "whatever"}, "refit is expected to be a boolean"), + ], +) +def test_input_errors(Est, params, expected_error_message): + base_estimator = FastClassifier() + param_grid = {"a": [1]} + X, y = make_classification(100) + + sh = Est(base_estimator, param_grid, **params) + + with pytest.raises(ValueError, match=expected_error_message): + sh.fit(X, y) + + +@pytest.mark.parametrize( + "params, expected_error_message", + [ + ( + {"n_candidates": "exhaust", "min_resources": "exhaust"}, + "cannot be both set to 'exhaust'", + ), + ({"n_candidates": "bad"}, "either 'exhaust' or a positive integer"), + ({"n_candidates": 0}, "either 'exhaust' or a positive integer"), + ], +) +def test_input_errors_randomized(params, expected_error_message): + # tests specific to HalvingRandomSearchCV + + base_estimator = FastClassifier() + param_grid = {"a": [1]} + X, y = make_classification(100) + + sh = HalvingRandomSearchCV(base_estimator, param_grid, **params) + + with pytest.raises(ValueError, match=expected_error_message): + sh.fit(X, y) + + +@pytest.mark.parametrize( + "fraction, subsample_test, expected_train_size, expected_test_size", + [ + (0.5, True, 40, 10), + (0.5, False, 40, 20), + (0.2, True, 16, 4), + (0.2, False, 16, 20), + ], +) +def test_subsample_splitter_shapes( + fraction, subsample_test, expected_train_size, expected_test_size +): + # Make sure splits returned by SubsampleMetaSplitter are of appropriate + # size + + n_samples = 100 + X, y = make_classification(n_samples) + cv = _SubsampleMetaSplitter( + base_cv=KFold(5), + fraction=fraction, + subsample_test=subsample_test, + random_state=None, + ) + + for train, test in cv.split(X, y): + assert train.shape[0] == expected_train_size + assert test.shape[0] == expected_test_size + if subsample_test: + assert train.shape[0] + test.shape[0] == int(n_samples * fraction) + else: + assert test.shape[0] == n_samples // cv.base_cv.get_n_splits() + + +@pytest.mark.parametrize("subsample_test", (True, False)) +def test_subsample_splitter_determinism(subsample_test): + # Make sure _SubsampleMetaSplitter is consistent across calls to split(): + # - we're OK having training sets differ (they're always sampled with a + # different fraction anyway) + # - when we don't subsample the test set, we want it to be always the same. + # This check is the most important. This is ensured by the determinism + # of the base_cv. + + # Note: we could force both train and test splits to be always the same if + # we drew an int seed in _SubsampleMetaSplitter.__init__ + + n_samples = 100 + X, y = make_classification(n_samples) + cv = _SubsampleMetaSplitter( + base_cv=KFold(5), fraction=0.5, subsample_test=subsample_test, random_state=None + ) + + folds_a = list(cv.split(X, y, groups=None)) + folds_b = list(cv.split(X, y, groups=None)) + + for (train_a, test_a), (train_b, test_b) in zip(folds_a, folds_b): + assert not np.all(train_a == train_b) + + if subsample_test: + assert not np.all(test_a == test_b) + else: + assert np.all(test_a == test_b) + assert np.all(X[test_a] == X[test_b]) + + +@pytest.mark.parametrize( + "k, itr, expected", + [ + (1, 0, ["c"]), + (2, 0, ["a", "c"]), + (4, 0, ["d", "b", "a", "c"]), + (10, 0, ["d", "b", "a", "c"]), + (1, 1, ["e"]), + (2, 1, ["f", "e"]), + (10, 1, ["f", "e"]), + (1, 2, ["i"]), + (10, 2, ["g", "h", "i"]), + ], +) +def test_top_k(k, itr, expected): + + results = { # this isn't a 'real world' result dict + "iter": [0, 0, 0, 0, 1, 1, 2, 2, 2], + "mean_test_score": [4, 3, 5, 1, 11, 10, 5, 6, 9], + "params": ["a", "b", "c", "d", "e", "f", "g", "h", "i"], + } + got = _top_k(results, k=k, itr=itr) + assert np.all(got == expected) + + +@pytest.mark.parametrize("Est", (HalvingRandomSearchCV, HalvingGridSearchCV)) +def test_cv_results(Est): + # test that the cv_results_ matches correctly the logic of the + # tournament: in particular that the candidates continued in each + # successive iteration are those that were best in the previous iteration + pd = pytest.importorskip("pandas") + + rng = np.random.RandomState(0) + + n_samples = 1000 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {"a": ("l1", "l2"), "b": list(range(30))} + base_estimator = FastClassifier() + + # generate random scores: we want to avoid ties, which would otherwise + # mess with the ordering and make testing harder + def scorer(est, X, y): + return rng.rand() + + sh = Est(base_estimator, param_grid, factor=2, scoring=scorer) + if Est is HalvingRandomSearchCV: + # same number of candidates as with the grid + sh.set_params(n_candidates=2 * 30, min_resources="exhaust") + + sh.fit(X, y) + + # non-regression check for + # https://github.com/scikit-learn/scikit-learn/issues/19203 + assert isinstance(sh.cv_results_["iter"], np.ndarray) + assert isinstance(sh.cv_results_["n_resources"], np.ndarray) + + cv_results_df = pd.DataFrame(sh.cv_results_) + + # just make sure we don't have ties + assert len(cv_results_df["mean_test_score"].unique()) == len(cv_results_df) + + cv_results_df["params_str"] = cv_results_df["params"].apply(str) + table = cv_results_df.pivot( + index="params_str", columns="iter", values="mean_test_score" + ) + + # table looks like something like this: + # iter 0 1 2 3 4 5 + # params_str + # {'a': 'l2', 'b': 23} 0.75 NaN NaN NaN NaN NaN + # {'a': 'l1', 'b': 30} 0.90 0.875 NaN NaN NaN NaN + # {'a': 'l1', 'b': 0} 0.75 NaN NaN NaN NaN NaN + # {'a': 'l2', 'b': 3} 0.85 0.925 0.9125 0.90625 NaN NaN + # {'a': 'l1', 'b': 5} 0.80 NaN NaN NaN NaN NaN + # ... + + # where a NaN indicates that the candidate wasn't evaluated at a given + # iteration, because it wasn't part of the top-K at some previous + # iteration. We here make sure that candidates that aren't in the top-k at + # any given iteration are indeed not evaluated at the subsequent + # iterations. + nan_mask = pd.isna(table) + n_iter = sh.n_iterations_ + for it in range(n_iter - 1): + already_discarded_mask = nan_mask[it] + + # make sure that if a candidate is already discarded, we don't evaluate + # it later + assert ( + already_discarded_mask & nan_mask[it + 1] == already_discarded_mask + ).all() + + # make sure that the number of discarded candidate is correct + discarded_now_mask = ~already_discarded_mask & nan_mask[it + 1] + kept_mask = ~already_discarded_mask & ~discarded_now_mask + assert kept_mask.sum() == sh.n_candidates_[it + 1] + + # make sure that all discarded candidates have a lower score than the + # kept candidates + discarded_max_score = table[it].where(discarded_now_mask).max() + kept_min_score = table[it].where(kept_mask).min() + assert discarded_max_score < kept_min_score + + # We now make sure that the best candidate is chosen only from the last + # iteration. + # We also make sure this is true even if there were higher scores in + # earlier rounds (this isn't generally the case, but worth ensuring it's + # possible). + + last_iter = cv_results_df["iter"].max() + idx_best_last_iter = cv_results_df[cv_results_df["iter"] == last_iter][ + "mean_test_score" + ].idxmax() + idx_best_all_iters = cv_results_df["mean_test_score"].idxmax() + + assert sh.best_params_ == cv_results_df.iloc[idx_best_last_iter]["params"] + assert ( + cv_results_df.iloc[idx_best_last_iter]["mean_test_score"] + < cv_results_df.iloc[idx_best_all_iters]["mean_test_score"] + ) + assert ( + cv_results_df.iloc[idx_best_last_iter]["params"] + != cv_results_df.iloc[idx_best_all_iters]["params"] + ) + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +def test_base_estimator_inputs(Est): + # make sure that the base estimators are passed the correct parameters and + # number of samples at each iteration. + pd = pytest.importorskip("pandas") + + passed_n_samples_fit = [] + passed_n_samples_predict = [] + passed_params = [] + + class FastClassifierBookKeeping(FastClassifier): + def fit(self, X, y): + passed_n_samples_fit.append(X.shape[0]) + return super().fit(X, y) + + def predict(self, X): + passed_n_samples_predict.append(X.shape[0]) + return super().predict(X) + + def set_params(self, **params): + passed_params.append(params) + return super().set_params(**params) + + n_samples = 1024 + n_splits = 2 + X, y = make_classification(n_samples=n_samples, random_state=0) + param_grid = {"a": ("l1", "l2"), "b": list(range(30))} + base_estimator = FastClassifierBookKeeping() + + sh = Est( + base_estimator, + param_grid, + factor=2, + cv=n_splits, + return_train_score=False, + refit=False, + ) + if Est is HalvingRandomSearchCV: + # same number of candidates as with the grid + sh.set_params(n_candidates=2 * 30, min_resources="exhaust") + + sh.fit(X, y) + + assert len(passed_n_samples_fit) == len(passed_n_samples_predict) + passed_n_samples = [ + x + y for (x, y) in zip(passed_n_samples_fit, passed_n_samples_predict) + ] + + # Lists are of length n_splits * n_iter * n_candidates_at_i. + # Each chunk of size n_splits corresponds to the n_splits folds for the + # same candidate at the same iteration, so they contain equal values. We + # subsample such that the lists are of length n_iter * n_candidates_at_it + passed_n_samples = passed_n_samples[::n_splits] + passed_params = passed_params[::n_splits] + + cv_results_df = pd.DataFrame(sh.cv_results_) + + assert len(passed_params) == len(passed_n_samples) == len(cv_results_df) + + uniques, counts = np.unique(passed_n_samples, return_counts=True) + assert (sh.n_resources_ == uniques).all() + assert (sh.n_candidates_ == counts).all() + + assert (cv_results_df["params"] == passed_params).all() + assert (cv_results_df["n_resources"] == passed_n_samples).all() + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +def test_groups_support(Est): + # Check if ValueError (when groups is None) propagates to + # HalvingGridSearchCV and HalvingRandomSearchCV + # And also check if groups is correctly passed to the cv object + rng = np.random.RandomState(0) + + X, y = make_classification(n_samples=50, n_classes=2, random_state=0) + groups = rng.randint(0, 3, 50) + + clf = LinearSVC(random_state=0) + grid = {"C": [1]} + + group_cvs = [ + LeaveOneGroupOut(), + LeavePGroupsOut(2), + GroupKFold(n_splits=3), + GroupShuffleSplit(random_state=0), + ] + error_msg = "The 'groups' parameter should not be None." + for cv in group_cvs: + gs = Est(clf, grid, cv=cv, random_state=0) + with pytest.raises(ValueError, match=error_msg): + gs.fit(X, y) + gs.fit(X, y, groups=groups) + + non_group_cvs = [StratifiedKFold(), StratifiedShuffleSplit(random_state=0)] + for cv in non_group_cvs: + gs = Est(clf, grid, cv=cv) + # Should not raise an error + gs.fit(X, y) + + +@pytest.mark.parametrize("SearchCV", [HalvingRandomSearchCV, HalvingGridSearchCV]) +def test_min_resources_null(SearchCV): + """Check that we raise an error if the minimum resources is set to 0.""" + base_estimator = FastClassifier() + param_grid = {"a": [1]} + X = np.empty(0).reshape(0, 3) + + search = SearchCV(base_estimator, param_grid, min_resources="smallest") + + err_msg = "min_resources_=0: you might have passed an empty dataset X." + with pytest.raises(ValueError, match=err_msg): + search.fit(X, []) + + +@pytest.mark.parametrize("SearchCV", [HalvingGridSearchCV, HalvingRandomSearchCV]) +def test_select_best_index(SearchCV): + """Check the selection strategy of the halving search.""" + results = { # this isn't a 'real world' result dict + "iter": np.array([0, 0, 0, 0, 1, 1, 2, 2, 2]), + "mean_test_score": np.array([4, 3, 5, 1, 11, 10, 5, 6, 9]), + "params": np.array(["a", "b", "c", "d", "e", "f", "g", "h", "i"]), + } + + # we expect the index of 'i' + best_index = SearchCV._select_best_index(None, None, results) + assert best_index == 8 diff --git a/falcon/lib/python3.10/site-packages/sklearn/svm/_libsvm_sparse.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/svm/_libsvm_sparse.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1b2b5afedbd851086c84e73e06ea43c229d4bb56 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/svm/_libsvm_sparse.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:006a80b7058dcaf167df2ef6a29212f59d605d18f53f150bc4d1d9b22c5a65ea +size 725817 diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/__init__.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..515877a550b6a7a1464bc4fe92f197760b54f506 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/__init__.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_classes.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_classes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc770641f301c2e94c9e43f7d771ccb23b1bbf30 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_classes.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_export.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_export.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9544353297c56a870a4c63fb6a160bf39c719e11 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_export.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_reingold_tilford.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_reingold_tilford.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3311d3c9da6978833ed36b687413fb781b13938 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/tree/__pycache__/_reingold_tilford.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/_criterion.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/tree/_criterion.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e25132ca405786c8433ef0819e54be7865f6e947 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/tree/_criterion.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbc932ad7614087f3496359287e83dff24716c547922acb6c65094bce3a5a842 +size 302545 diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/_splitter.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/tree/_splitter.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..018a5f6217a60d79dcd34f366a9a4bb2950080d8 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/tree/_splitter.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a7a2549d04cb0b090ebaebb4bdc56101c237221d65089aa5cf27ed7cdc4256a +size 290273 diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/_tree.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/tree/_tree.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..00834ebada3c0ede27fa5678d82e53e592b9c113 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/tree/_tree.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34bc522f51131a8c59011338c951880845d395e26e3f2bcd37052cac388feb8c +size 608473 diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so b/falcon/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6e1d27b1773cd0bf1852bd8d033e2020558ce087 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f61b3136021cc79f20389c80b3c58dc74558c0604ae25ee04ebbe6bdd3db52b0 +size 241201 diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..966aff4b5994da11dfa295a651e97ea5fd5d7cf2 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17e9b9c187afea9fb546c914f71b91f1cdb34a55 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b133c7117436c4c8d8fda02fe1087d22b47e6f9 Binary files /dev/null and b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc differ diff --git a/falcon/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..94f08307b741553cf282de11fc9a672865c1bd28 --- /dev/null +++ b/falcon/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py @@ -0,0 +1,2430 @@ +""" +Testing for the tree module (sklearn.tree). +""" +import copy +import pickle +from itertools import product +import struct +import io +import copyreg + +import pytest +import numpy as np +from numpy.testing import assert_allclose +from scipy.sparse import csc_matrix +from scipy.sparse import csr_matrix +from scipy.sparse import coo_matrix + +import joblib +from joblib.numpy_pickle import NumpyPickler + +from sklearn.random_projection import _sparse_random_matrix + +from sklearn.dummy import DummyRegressor + +from sklearn.metrics import accuracy_score +from sklearn.metrics import mean_squared_error +from sklearn.metrics import mean_poisson_deviance + +from sklearn.model_selection import train_test_split + +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import create_memmap_backed_data +from sklearn.utils._testing import ignore_warnings +from sklearn.utils._testing import skip_if_32bit + +from sklearn.utils.estimator_checks import check_sample_weights_invariance +from sklearn.utils.validation import check_random_state +from sklearn.utils import _IS_32BIT + +from sklearn.exceptions import NotFittedError + +from sklearn.tree import DecisionTreeClassifier +from sklearn.tree import DecisionTreeRegressor +from sklearn.tree import ExtraTreeClassifier +from sklearn.tree import ExtraTreeRegressor + +from sklearn import tree +from sklearn.tree._tree import TREE_LEAF, TREE_UNDEFINED +from sklearn.tree._tree import Tree as CythonTree +from sklearn.tree._tree import _check_n_classes +from sklearn.tree._tree import _check_value_ndarray +from sklearn.tree._tree import _check_node_ndarray +from sklearn.tree._tree import NODE_DTYPE + +from sklearn.tree._classes import CRITERIA_CLF +from sklearn.tree._classes import CRITERIA_REG +from sklearn import datasets + +from sklearn.utils import compute_sample_weight + + +CLF_CRITERIONS = ("gini", "log_loss") +REG_CRITERIONS = ("squared_error", "absolute_error", "friedman_mse", "poisson") + +CLF_TREES = { + "DecisionTreeClassifier": DecisionTreeClassifier, + "ExtraTreeClassifier": ExtraTreeClassifier, +} + +REG_TREES = { + "DecisionTreeRegressor": DecisionTreeRegressor, + "ExtraTreeRegressor": ExtraTreeRegressor, +} + +ALL_TREES: dict = dict() +ALL_TREES.update(CLF_TREES) +ALL_TREES.update(REG_TREES) + +SPARSE_TREES = [ + "DecisionTreeClassifier", + "DecisionTreeRegressor", + "ExtraTreeClassifier", + "ExtraTreeRegressor", +] + + +X_small = np.array( + [ + [0, 0, 4, 0, 0, 0, 1, -14, 0, -4, 0, 0, 0, 0], + [0, 0, 5, 3, 0, -4, 0, 0, 1, -5, 0.2, 0, 4, 1], + [-1, -1, 0, 0, -4.5, 0, 0, 2.1, 1, 0, 0, -4.5, 0, 1], + [-1, -1, 0, -1.2, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 1], + [-1, -1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1], + [-1, -2, 0, 4, -3, 10, 4, 0, -3.2, 0, 4, 3, -4, 1], + [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -3, 1], + [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1], + [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1], + [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -1, 0], + [2, 8, 5, 1, 0.5, -4, 10, 0, 1, -5, 3, 0, 2, 0], + [2, 0, 1, 1, 1, -1, 1, 0, 0, -2, 3, 0, 1, 0], + [2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0], + [1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0], + [3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1], + [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1], + [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1], + [2.11, 8, -6, -0.5, 0, 10, 0, 0, -3.2, 6, 0.5, 0, -1, -1], + [2, 0, 5, 1, 0.5, -2, 10, 0, 1, -5, 3, 1, 0, -1], + [2, 0, 1, 1, 1, -2, 1, 0, 0, -2, 0, 0, 0, 1], + [2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1], + [1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1], + [3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0], + ] +) + +y_small = [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0] +y_small_reg = [ + 1.0, + 2.1, + 1.2, + 0.05, + 10, + 2.4, + 3.1, + 1.01, + 0.01, + 2.98, + 3.1, + 1.1, + 0.0, + 1.2, + 2, + 11, + 0, + 0, + 4.5, + 0.201, + 1.06, + 0.9, + 0, +] + +# toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y = [-1, -1, -1, 1, 1, 1] +T = [[-1, -1], [2, 2], [3, 2]] +true_result = [-1, 1, 1] + +# also load the iris dataset +# and randomly permute it +iris = datasets.load_iris() +rng = np.random.RandomState(1) +perm = rng.permutation(iris.target.size) +iris.data = iris.data[perm] +iris.target = iris.target[perm] + +# also load the diabetes dataset +# and randomly permute it +diabetes = datasets.load_diabetes() +perm = rng.permutation(diabetes.target.size) +diabetes.data = diabetes.data[perm] +diabetes.target = diabetes.target[perm] + +digits = datasets.load_digits() +perm = rng.permutation(digits.target.size) +digits.data = digits.data[perm] +digits.target = digits.target[perm] + +random_state = check_random_state(0) +X_multilabel, y_multilabel = datasets.make_multilabel_classification( + random_state=0, n_samples=30, n_features=10 +) + +# NB: despite their names X_sparse_* are numpy arrays (and not sparse matrices) +X_sparse_pos = random_state.uniform(size=(20, 5)) +X_sparse_pos[X_sparse_pos <= 0.8] = 0.0 +y_random = random_state.randint(0, 4, size=(20,)) +X_sparse_mix = _sparse_random_matrix(20, 10, density=0.25, random_state=0).toarray() + + +DATASETS = { + "iris": {"X": iris.data, "y": iris.target}, + "diabetes": {"X": diabetes.data, "y": diabetes.target}, + "digits": {"X": digits.data, "y": digits.target}, + "toy": {"X": X, "y": y}, + "clf_small": {"X": X_small, "y": y_small}, + "reg_small": {"X": X_small, "y": y_small_reg}, + "multilabel": {"X": X_multilabel, "y": y_multilabel}, + "sparse-pos": {"X": X_sparse_pos, "y": y_random}, + "sparse-neg": {"X": -X_sparse_pos, "y": y_random}, + "sparse-mix": {"X": X_sparse_mix, "y": y_random}, + "zeros": {"X": np.zeros((20, 3)), "y": y_random}, +} + +for name in DATASETS: + DATASETS[name]["X_sparse"] = csc_matrix(DATASETS[name]["X"]) + + +def assert_tree_equal(d, s, message): + assert ( + s.node_count == d.node_count + ), "{0}: inequal number of node ({1} != {2})".format( + message, s.node_count, d.node_count + ) + + assert_array_equal( + d.children_right, s.children_right, message + ": inequal children_right" + ) + assert_array_equal( + d.children_left, s.children_left, message + ": inequal children_left" + ) + + external = d.children_right == TREE_LEAF + internal = np.logical_not(external) + + assert_array_equal( + d.feature[internal], s.feature[internal], message + ": inequal features" + ) + assert_array_equal( + d.threshold[internal], s.threshold[internal], message + ": inequal threshold" + ) + assert_array_equal( + d.n_node_samples.sum(), + s.n_node_samples.sum(), + message + ": inequal sum(n_node_samples)", + ) + assert_array_equal( + d.n_node_samples, s.n_node_samples, message + ": inequal n_node_samples" + ) + + assert_almost_equal(d.impurity, s.impurity, err_msg=message + ": inequal impurity") + + assert_array_almost_equal( + d.value[external], s.value[external], err_msg=message + ": inequal value" + ) + + +def test_classification_toy(): + # Check classification on a toy dataset. + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + clf = Tree(max_features=1, random_state=1) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + +def test_weighted_classification_toy(): + # Check classification on a weighted toy dataset. + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + + clf.fit(X, y, sample_weight=np.ones(len(X))) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + clf.fit(X, y, sample_weight=np.full(len(X), 0.5)) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + +@pytest.mark.parametrize("Tree", REG_TREES.values()) +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +def test_regression_toy(Tree, criterion): + # Check regression on a toy dataset. + if criterion == "poisson": + # make target positive while not touching the original y and + # true_result + a = np.abs(np.min(y)) + 1 + y_train = np.array(y) + a + y_test = np.array(true_result) + a + else: + y_train = y + y_test = true_result + + reg = Tree(criterion=criterion, random_state=1) + reg.fit(X, y_train) + assert_allclose(reg.predict(T), y_test) + + clf = Tree(criterion=criterion, max_features=1, random_state=1) + clf.fit(X, y_train) + assert_allclose(reg.predict(T), y_test) + + +def test_xor(): + # Check on a XOR problem + y = np.zeros((10, 10)) + y[:5, :5] = 1 + y[5:, 5:] = 1 + + gridx, gridy = np.indices(y.shape) + + X = np.vstack([gridx.ravel(), gridy.ravel()]).T + y = y.ravel() + + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + clf.fit(X, y) + assert clf.score(X, y) == 1.0, "Failed with {0}".format(name) + + clf = Tree(random_state=0, max_features=1) + clf.fit(X, y) + assert clf.score(X, y) == 1.0, "Failed with {0}".format(name) + + +def test_iris(): + # Check consistency on dataset iris. + for (name, Tree), criterion in product(CLF_TREES.items(), CLF_CRITERIONS): + clf = Tree(criterion=criterion, random_state=0) + clf.fit(iris.data, iris.target) + score = accuracy_score(clf.predict(iris.data), iris.target) + assert score > 0.9, "Failed with {0}, criterion = {1} and score = {2}".format( + name, criterion, score + ) + + clf = Tree(criterion=criterion, max_features=2, random_state=0) + clf.fit(iris.data, iris.target) + score = accuracy_score(clf.predict(iris.data), iris.target) + assert score > 0.5, "Failed with {0}, criterion = {1} and score = {2}".format( + name, criterion, score + ) + + +@pytest.mark.parametrize("name, Tree", REG_TREES.items()) +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +def test_diabetes_overfit(name, Tree, criterion): + # check consistency of overfitted trees on the diabetes dataset + # since the trees will overfit, we expect an MSE of 0 + reg = Tree(criterion=criterion, random_state=0) + reg.fit(diabetes.data, diabetes.target) + score = mean_squared_error(diabetes.target, reg.predict(diabetes.data)) + assert score == pytest.approx( + 0 + ), f"Failed with {name}, criterion = {criterion} and score = {score}" + + +@skip_if_32bit +@pytest.mark.parametrize("name, Tree", REG_TREES.items()) +@pytest.mark.parametrize( + "criterion, max_depth, metric, max_loss", + [ + ("squared_error", 15, mean_squared_error, 60), + ("absolute_error", 20, mean_squared_error, 60), + ("friedman_mse", 15, mean_squared_error, 60), + ("poisson", 15, mean_poisson_deviance, 30), + ], +) +def test_diabetes_underfit(name, Tree, criterion, max_depth, metric, max_loss): + # check consistency of trees when the depth and the number of features are + # limited + + reg = Tree(criterion=criterion, max_depth=max_depth, max_features=6, random_state=0) + reg.fit(diabetes.data, diabetes.target) + loss = metric(diabetes.target, reg.predict(diabetes.data)) + assert 0 < loss < max_loss + + +def test_probability(): + # Predict probabilities using DecisionTreeClassifier. + + for name, Tree in CLF_TREES.items(): + clf = Tree(max_depth=1, max_features=1, random_state=42) + clf.fit(iris.data, iris.target) + + prob_predict = clf.predict_proba(iris.data) + assert_array_almost_equal( + np.sum(prob_predict, 1), + np.ones(iris.data.shape[0]), + err_msg="Failed with {0}".format(name), + ) + assert_array_equal( + np.argmax(prob_predict, 1), + clf.predict(iris.data), + err_msg="Failed with {0}".format(name), + ) + assert_almost_equal( + clf.predict_proba(iris.data), + np.exp(clf.predict_log_proba(iris.data)), + 8, + err_msg="Failed with {0}".format(name), + ) + + +def test_arrayrepr(): + # Check the array representation. + # Check resize + X = np.arange(10000)[:, np.newaxis] + y = np.arange(10000) + + for name, Tree in REG_TREES.items(): + reg = Tree(max_depth=None, random_state=0) + reg.fit(X, y) + + +def test_pure_set(): + # Check when y is pure. + X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] + y = [1, 1, 1, 1, 1, 1] + + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name)) + + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(random_state=0) + reg.fit(X, y) + assert_almost_equal(reg.predict(X), y, err_msg="Failed with {0}".format(name)) + + +def test_numerical_stability(): + # Check numerical stability. + X = np.array( + [ + [152.08097839, 140.40744019, 129.75102234, 159.90493774], + [142.50700378, 135.81935120, 117.82884979, 162.75781250], + [127.28772736, 140.40744019, 129.75102234, 159.90493774], + [132.37025452, 143.71923828, 138.35694885, 157.84558105], + [103.10237122, 143.71928406, 138.35696411, 157.84559631], + [127.71276855, 143.71923828, 138.35694885, 157.84558105], + [120.91514587, 140.40744019, 129.75102234, 159.90493774], + ] + ) + + y = np.array([1.0, 0.70209277, 0.53896582, 0.0, 0.90914464, 0.48026916, 0.49622521]) + + with np.errstate(all="raise"): + for name, Tree in REG_TREES.items(): + reg = Tree(random_state=0) + reg.fit(X, y) + reg.fit(X, -y) + reg.fit(-X, y) + reg.fit(-X, -y) + + +def test_importances(): + # Check variable importances. + X, y = datasets.make_classification( + n_samples=5000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + + clf.fit(X, y) + importances = clf.feature_importances_ + n_important = np.sum(importances > 0.1) + + assert importances.shape[0] == 10, "Failed with {0}".format(name) + assert n_important == 3, "Failed with {0}".format(name) + + # Check on iris that importances are the same for all builders + clf = DecisionTreeClassifier(random_state=0) + clf.fit(iris.data, iris.target) + clf2 = DecisionTreeClassifier(random_state=0, max_leaf_nodes=len(iris.data)) + clf2.fit(iris.data, iris.target) + + assert_array_equal(clf.feature_importances_, clf2.feature_importances_) + + +def test_importances_raises(): + # Check if variable importance before fit raises ValueError. + clf = DecisionTreeClassifier() + with pytest.raises(ValueError): + getattr(clf, "feature_importances_") + + +def test_importances_gini_equal_squared_error(): + # Check that gini is equivalent to squared_error for binary output variable + + X, y = datasets.make_classification( + n_samples=2000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + + # The gini index and the mean square error (variance) might differ due + # to numerical instability. Since those instabilities mainly occurs at + # high tree depth, we restrict this maximal depth. + clf = DecisionTreeClassifier(criterion="gini", max_depth=5, random_state=0).fit( + X, y + ) + reg = DecisionTreeRegressor( + criterion="squared_error", max_depth=5, random_state=0 + ).fit(X, y) + + assert_almost_equal(clf.feature_importances_, reg.feature_importances_) + assert_array_equal(clf.tree_.feature, reg.tree_.feature) + assert_array_equal(clf.tree_.children_left, reg.tree_.children_left) + assert_array_equal(clf.tree_.children_right, reg.tree_.children_right) + assert_array_equal(clf.tree_.n_node_samples, reg.tree_.n_node_samples) + + +# TODO(1.3): Remove warning filter +@pytest.mark.filterwarnings("ignore:`max_features='auto'` has been deprecated in 1.1") +def test_max_features(): + # Check max_features. + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(max_features="auto") + reg.fit(diabetes.data, diabetes.target) + assert reg.max_features_ == diabetes.data.shape[1] + + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(max_features="auto") + clf.fit(iris.data, iris.target) + assert clf.max_features_ == 2 + + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_features="sqrt") + est.fit(iris.data, iris.target) + assert est.max_features_ == int(np.sqrt(iris.data.shape[1])) + + est = TreeEstimator(max_features="log2") + est.fit(iris.data, iris.target) + assert est.max_features_ == int(np.log2(iris.data.shape[1])) + + est = TreeEstimator(max_features=1) + est.fit(iris.data, iris.target) + assert est.max_features_ == 1 + + est = TreeEstimator(max_features=3) + est.fit(iris.data, iris.target) + assert est.max_features_ == 3 + + est = TreeEstimator(max_features=0.01) + est.fit(iris.data, iris.target) + assert est.max_features_ == 1 + + est = TreeEstimator(max_features=0.5) + est.fit(iris.data, iris.target) + assert est.max_features_ == int(0.5 * iris.data.shape[1]) + + est = TreeEstimator(max_features=1.0) + est.fit(iris.data, iris.target) + assert est.max_features_ == iris.data.shape[1] + + est = TreeEstimator(max_features=None) + est.fit(iris.data, iris.target) + assert est.max_features_ == iris.data.shape[1] + + +def test_error(): + # Test that it gives proper exception on deficient input. + for name, TreeEstimator in CLF_TREES.items(): + # predict before fit + est = TreeEstimator() + with pytest.raises(NotFittedError): + est.predict_proba(X) + + est.fit(X, y) + X2 = [[-2, -1, 1]] # wrong feature shape for sample + with pytest.raises(ValueError): + est.predict_proba(X2) + + # Wrong dimensions + est = TreeEstimator() + y2 = y[:-1] + with pytest.raises(ValueError): + est.fit(X, y2) + + # Test with arrays that are non-contiguous. + Xf = np.asfortranarray(X) + est = TreeEstimator() + est.fit(Xf, y) + assert_almost_equal(est.predict(T), true_result) + + # predict before fitting + est = TreeEstimator() + with pytest.raises(NotFittedError): + est.predict(T) + + # predict on vector with different dims + est.fit(X, y) + t = np.asarray(T) + with pytest.raises(ValueError): + est.predict(t[:, 1:]) + + # wrong sample shape + Xt = np.array(X).T + + est = TreeEstimator() + est.fit(np.dot(X, Xt), y) + with pytest.raises(ValueError): + est.predict(X) + with pytest.raises(ValueError): + est.apply(X) + + clf = TreeEstimator() + clf.fit(X, y) + with pytest.raises(ValueError): + clf.predict(Xt) + with pytest.raises(ValueError): + clf.apply(Xt) + + # apply before fitting + est = TreeEstimator() + with pytest.raises(NotFittedError): + est.apply(T) + + # non positive target for Poisson splitting Criterion + est = DecisionTreeRegressor(criterion="poisson") + with pytest.raises(ValueError, match="y is not positive.*Poisson"): + est.fit([[0, 1, 2]], [0, 0, 0]) + with pytest.raises(ValueError, match="Some.*y are negative.*Poisson"): + est.fit([[0, 1, 2]], [5, -0.1, 2]) + + +def test_min_samples_split(): + """Test min_samples_split parameter""" + X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE) + y = iris.target + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()): + TreeEstimator = ALL_TREES[name] + + # test for integer parameter + est = TreeEstimator( + min_samples_split=10, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + # count samples on nodes, -1 means it is a leaf + node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1] + + assert np.min(node_samples) > 9, "Failed with {0}".format(name) + + # test for float parameter + est = TreeEstimator( + min_samples_split=0.2, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + # count samples on nodes, -1 means it is a leaf + node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1] + + assert np.min(node_samples) > 9, "Failed with {0}".format(name) + + +def test_min_samples_leaf(): + # Test if leaves contain more than leaf_count training examples + X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE) + y = iris.target + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()): + TreeEstimator = ALL_TREES[name] + + # test integer parameter + est = TreeEstimator( + min_samples_leaf=5, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + out = est.tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert np.min(leaf_count) > 4, "Failed with {0}".format(name) + + # test float parameter + est = TreeEstimator( + min_samples_leaf=0.1, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + out = est.tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert np.min(leaf_count) > 4, "Failed with {0}".format(name) + + +def check_min_weight_fraction_leaf(name, datasets, sparse=False): + """Test if leaves contain at least min_weight_fraction_leaf of the + training set""" + if sparse: + X = DATASETS[datasets]["X_sparse"].astype(np.float32) + else: + X = DATASETS[datasets]["X"].astype(np.float32) + y = DATASETS[datasets]["y"] + + weights = rng.rand(X.shape[0]) + total_weight = np.sum(weights) + + TreeEstimator = ALL_TREES[name] + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)): + est = TreeEstimator( + min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y, sample_weight=weights) + + if sparse: + out = est.tree_.apply(X.tocsr()) + + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out, weights=weights) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert ( + np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf + ), "Failed with {0} min_weight_fraction_leaf={1}".format( + name, est.min_weight_fraction_leaf + ) + + # test case with no weights passed in + total_weight = X.shape[0] + + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)): + est = TreeEstimator( + min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + + if sparse: + out = est.tree_.apply(X.tocsr()) + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert ( + np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf + ), "Failed with {0} min_weight_fraction_leaf={1}".format( + name, est.min_weight_fraction_leaf + ) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_min_weight_fraction_leaf_on_dense_input(name): + check_min_weight_fraction_leaf(name, "iris") + + +@pytest.mark.parametrize("name", SPARSE_TREES) +def test_min_weight_fraction_leaf_on_sparse_input(name): + check_min_weight_fraction_leaf(name, "multilabel", True) + + +def check_min_weight_fraction_leaf_with_min_samples_leaf(name, datasets, sparse=False): + """Test the interaction between min_weight_fraction_leaf and + min_samples_leaf when sample_weights is not provided in fit.""" + if sparse: + X = DATASETS[datasets]["X_sparse"].astype(np.float32) + else: + X = DATASETS[datasets]["X"].astype(np.float32) + y = DATASETS[datasets]["y"] + + total_weight = X.shape[0] + TreeEstimator = ALL_TREES[name] + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)): + # test integer min_samples_leaf + est = TreeEstimator( + min_weight_fraction_leaf=frac, + max_leaf_nodes=max_leaf_nodes, + min_samples_leaf=5, + random_state=0, + ) + est.fit(X, y) + + if sparse: + out = est.tree_.apply(X.tocsr()) + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert np.min(leaf_weights) >= max( + (total_weight * est.min_weight_fraction_leaf), 5 + ), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format( + name, est.min_weight_fraction_leaf, est.min_samples_leaf + ) + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)): + # test float min_samples_leaf + est = TreeEstimator( + min_weight_fraction_leaf=frac, + max_leaf_nodes=max_leaf_nodes, + min_samples_leaf=0.1, + random_state=0, + ) + est.fit(X, y) + + if sparse: + out = est.tree_.apply(X.tocsr()) + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert np.min(leaf_weights) >= max( + (total_weight * est.min_weight_fraction_leaf), + (total_weight * est.min_samples_leaf), + ), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format( + name, est.min_weight_fraction_leaf, est.min_samples_leaf + ) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input(name): + check_min_weight_fraction_leaf_with_min_samples_leaf(name, "iris") + + +@pytest.mark.parametrize("name", SPARSE_TREES) +def test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input(name): + check_min_weight_fraction_leaf_with_min_samples_leaf(name, "multilabel", True) + + +def test_min_impurity_decrease(): + # test if min_impurity_decrease ensure that a split is made only if + # if the impurity decrease is at least that value + X, y = datasets.make_classification(n_samples=10000, random_state=42) + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()): + TreeEstimator = ALL_TREES[name] + + # Check default value of min_impurity_decrease, 1e-7 + est1 = TreeEstimator(max_leaf_nodes=max_leaf_nodes, random_state=0) + # Check with explicit value of 0.05 + est2 = TreeEstimator( + max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.05, random_state=0 + ) + # Check with a much lower value of 0.0001 + est3 = TreeEstimator( + max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.0001, random_state=0 + ) + # Check with a much lower value of 0.1 + est4 = TreeEstimator( + max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.1, random_state=0 + ) + + for est, expected_decrease in ( + (est1, 1e-7), + (est2, 0.05), + (est3, 0.0001), + (est4, 0.1), + ): + assert ( + est.min_impurity_decrease <= expected_decrease + ), "Failed, min_impurity_decrease = {0} > {1}".format( + est.min_impurity_decrease, expected_decrease + ) + est.fit(X, y) + for node in range(est.tree_.node_count): + # If current node is a not leaf node, check if the split was + # justified w.r.t the min_impurity_decrease + if est.tree_.children_left[node] != TREE_LEAF: + imp_parent = est.tree_.impurity[node] + wtd_n_node = est.tree_.weighted_n_node_samples[node] + + left = est.tree_.children_left[node] + wtd_n_left = est.tree_.weighted_n_node_samples[left] + imp_left = est.tree_.impurity[left] + wtd_imp_left = wtd_n_left * imp_left + + right = est.tree_.children_right[node] + wtd_n_right = est.tree_.weighted_n_node_samples[right] + imp_right = est.tree_.impurity[right] + wtd_imp_right = wtd_n_right * imp_right + + wtd_avg_left_right_imp = wtd_imp_right + wtd_imp_left + wtd_avg_left_right_imp /= wtd_n_node + + fractional_node_weight = ( + est.tree_.weighted_n_node_samples[node] / X.shape[0] + ) + + actual_decrease = fractional_node_weight * ( + imp_parent - wtd_avg_left_right_imp + ) + + assert ( + actual_decrease >= expected_decrease + ), "Failed with {0} expected min_impurity_decrease={1}".format( + actual_decrease, expected_decrease + ) + + +def test_pickle(): + """Test pickling preserves Tree properties and performance.""" + for name, TreeEstimator in ALL_TREES.items(): + if "Classifier" in name: + X, y = iris.data, iris.target + else: + X, y = diabetes.data, diabetes.target + + est = TreeEstimator(random_state=0) + est.fit(X, y) + score = est.score(X, y) + + # test that all class properties are maintained + attributes = [ + "max_depth", + "node_count", + "capacity", + "n_classes", + "children_left", + "children_right", + "n_leaves", + "feature", + "threshold", + "impurity", + "n_node_samples", + "weighted_n_node_samples", + "value", + ] + fitted_attribute = { + attribute: getattr(est.tree_, attribute) for attribute in attributes + } + + serialized_object = pickle.dumps(est) + est2 = pickle.loads(serialized_object) + assert type(est2) == est.__class__ + + score2 = est2.score(X, y) + assert ( + score == score2 + ), "Failed to generate same score after pickling with {0}".format(name) + for attribute in fitted_attribute: + assert_array_equal( + getattr(est2.tree_, attribute), + fitted_attribute[attribute], + err_msg=( + f"Failed to generate same attribute {attribute} after pickling with" + f" {name}" + ), + ) + + +def test_multioutput(): + # Check estimators on multi-output problems. + X = [ + [-2, -1], + [-1, -1], + [-1, -2], + [1, 1], + [1, 2], + [2, 1], + [-2, 1], + [-1, 1], + [-1, 2], + [2, -1], + [1, -1], + [1, -2], + ] + + y = [ + [-1, 0], + [-1, 0], + [-1, 0], + [1, 1], + [1, 1], + [1, 1], + [-1, 2], + [-1, 2], + [-1, 2], + [1, 3], + [1, 3], + [1, 3], + ] + + T = [[-1, -1], [1, 1], [-1, 1], [1, -1]] + y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]] + + # toy classification problem + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + y_hat = clf.fit(X, y).predict(T) + assert_array_equal(y_hat, y_true) + assert y_hat.shape == (4, 2) + + proba = clf.predict_proba(T) + assert len(proba) == 2 + assert proba[0].shape == (4, 2) + assert proba[1].shape == (4, 4) + + log_proba = clf.predict_log_proba(T) + assert len(log_proba) == 2 + assert log_proba[0].shape == (4, 2) + assert log_proba[1].shape == (4, 4) + + # toy regression problem + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(random_state=0) + y_hat = reg.fit(X, y).predict(T) + assert_almost_equal(y_hat, y_true) + assert y_hat.shape == (4, 2) + + +def test_classes_shape(): + # Test that n_classes_ and classes_ have proper shape. + for name, TreeClassifier in CLF_TREES.items(): + # Classification, single output + clf = TreeClassifier(random_state=0) + clf.fit(X, y) + + assert clf.n_classes_ == 2 + assert_array_equal(clf.classes_, [-1, 1]) + + # Classification, multi-output + _y = np.vstack((y, np.array(y) * 2)).T + clf = TreeClassifier(random_state=0) + clf.fit(X, _y) + assert len(clf.n_classes_) == 2 + assert len(clf.classes_) == 2 + assert_array_equal(clf.n_classes_, [2, 2]) + assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]]) + + +def test_unbalanced_iris(): + # Check class rebalancing. + unbalanced_X = iris.data[:125] + unbalanced_y = iris.target[:125] + sample_weight = compute_sample_weight("balanced", unbalanced_y) + + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + clf.fit(unbalanced_X, unbalanced_y, sample_weight=sample_weight) + assert_almost_equal(clf.predict(unbalanced_X), unbalanced_y) + + +def test_memory_layout(): + # Check that it works no matter the memory layout + for (name, TreeEstimator), dtype in product( + ALL_TREES.items(), [np.float64, np.float32] + ): + est = TreeEstimator(random_state=0) + + # Nothing + X = np.asarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # C-order + X = np.asarray(iris.data, order="C", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # F-order + X = np.asarray(iris.data, order="F", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Contiguous + X = np.ascontiguousarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # csr matrix + X = csr_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # csc_matrix + X = csc_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Strided + X = np.asarray(iris.data[::3], dtype=dtype) + y = iris.target[::3] + assert_array_equal(est.fit(X, y).predict(X), y) + + +def test_sample_weight(): + # Check sample weighting. + # Test that zero-weighted samples are not taken into account + X = np.arange(100)[:, np.newaxis] + y = np.ones(100) + y[:50] = 0.0 + + sample_weight = np.ones(100) + sample_weight[y == 0] = 0.0 + + clf = DecisionTreeClassifier(random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert_array_equal(clf.predict(X), np.ones(100)) + + # Test that low weighted samples are not taken into account at low depth + X = np.arange(200)[:, np.newaxis] + y = np.zeros(200) + y[50:100] = 1 + y[100:200] = 2 + X[100:200, 0] = 200 + + sample_weight = np.ones(200) + + sample_weight[y == 2] = 0.51 # Samples of class '2' are still weightier + clf = DecisionTreeClassifier(max_depth=1, random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert clf.tree_.threshold[0] == 149.5 + + sample_weight[y == 2] = 0.5 # Samples of class '2' are no longer weightier + clf = DecisionTreeClassifier(max_depth=1, random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert clf.tree_.threshold[0] == 49.5 # Threshold should have moved + + # Test that sample weighting is the same as having duplicates + X = iris.data + y = iris.target + + duplicates = rng.randint(0, X.shape[0], 100) + + clf = DecisionTreeClassifier(random_state=1) + clf.fit(X[duplicates], y[duplicates]) + + sample_weight = np.bincount(duplicates, minlength=X.shape[0]) + clf2 = DecisionTreeClassifier(random_state=1) + clf2.fit(X, y, sample_weight=sample_weight) + + internal = clf.tree_.children_left != tree._tree.TREE_LEAF + assert_array_almost_equal( + clf.tree_.threshold[internal], clf2.tree_.threshold[internal] + ) + + +def test_sample_weight_invalid(): + # Check sample weighting raises errors. + X = np.arange(100)[:, np.newaxis] + y = np.ones(100) + y[:50] = 0.0 + + clf = DecisionTreeClassifier(random_state=0) + + sample_weight = np.random.rand(100, 1) + with pytest.raises(ValueError): + clf.fit(X, y, sample_weight=sample_weight) + + sample_weight = np.array(0) + expected_err = r"Singleton.* cannot be considered a valid collection" + with pytest.raises(TypeError, match=expected_err): + clf.fit(X, y, sample_weight=sample_weight) + + +def check_class_weights(name): + """Check class_weights resemble sample_weights behavior.""" + TreeClassifier = CLF_TREES[name] + + # Iris is balanced, so no effect expected for using 'balanced' weights + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target) + clf2 = TreeClassifier(class_weight="balanced", random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Make a multi-output problem with three copies of Iris + iris_multi = np.vstack((iris.target, iris.target, iris.target)).T + # Create user-defined weights that should balance over the outputs + clf3 = TreeClassifier( + class_weight=[ + {0: 2.0, 1: 2.0, 2: 1.0}, + {0: 2.0, 1: 1.0, 2: 2.0}, + {0: 1.0, 1: 2.0, 2: 2.0}, + ], + random_state=0, + ) + clf3.fit(iris.data, iris_multi) + assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_) + # Check against multi-output "auto" which should also have no effect + clf4 = TreeClassifier(class_weight="balanced", random_state=0) + clf4.fit(iris.data, iris_multi) + assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_) + + # Inflate importance of class 1, check against user-defined weights + sample_weight = np.ones(iris.target.shape) + sample_weight[iris.target == 1] *= 100 + class_weight = {0: 1.0, 1: 100.0, 2: 1.0} + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight) + clf2 = TreeClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Check that sample_weight and class_weight are multiplicative + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight**2) + clf2 = TreeClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target, sample_weight) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + +@pytest.mark.parametrize("name", CLF_TREES) +def test_class_weights(name): + check_class_weights(name) + + +def check_class_weight_errors(name): + # Test if class_weight raises errors and warnings when expected. + TreeClassifier = CLF_TREES[name] + _y = np.vstack((y, np.array(y) * 2)).T + + # Incorrect length list for multi-output + clf = TreeClassifier(class_weight=[{-1: 0.5, 1: 1.0}], random_state=0) + err_msg = "number of elements in class_weight should match number of outputs." + with pytest.raises(ValueError, match=err_msg): + clf.fit(X, _y) + + +@pytest.mark.parametrize("name", CLF_TREES) +def test_class_weight_errors(name): + check_class_weight_errors(name) + + +def test_max_leaf_nodes(): + # Test greedy trees with max_depth + 1 leafs. + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + k = 4 + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_depth=None, max_leaf_nodes=k + 1).fit(X, y) + assert est.get_n_leaves() == k + 1 + + +def test_max_leaf_nodes_max_depth(): + # Test precedence of max_leaf_nodes over max_depth. + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + k = 4 + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y) + assert est.get_depth() == 1 + + +def test_arrays_persist(): + # Ensure property arrays' memory stays alive when tree disappears + # non-regression for #2726 + for attr in [ + "n_classes", + "value", + "children_left", + "children_right", + "threshold", + "impurity", + "feature", + "n_node_samples", + ]: + value = getattr(DecisionTreeClassifier().fit([[0], [1]], [0, 1]).tree_, attr) + # if pointing to freed memory, contents may be arbitrary + assert -3 <= value.flat[0] < 3, "Array points to arbitrary memory" + + +def test_only_constant_features(): + random_state = check_random_state(0) + X = np.zeros((10, 20)) + y = random_state.randint(0, 2, (10,)) + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(random_state=0) + est.fit(X, y) + assert est.tree_.max_depth == 0 + + +def test_behaviour_constant_feature_after_splits(): + X = np.transpose( + np.vstack(([[0, 0, 0, 0, 0, 1, 2, 4, 5, 6, 7]], np.zeros((4, 11)))) + ) + y = [0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3] + for name, TreeEstimator in ALL_TREES.items(): + # do not check extra random trees + if "ExtraTree" not in name: + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert est.tree_.max_depth == 2 + assert est.tree_.node_count == 5 + + +def test_with_only_one_non_constant_features(): + X = np.hstack([np.array([[1.0], [1.0], [0.0], [0.0]]), np.zeros((4, 1000))]) + + y = np.array([0.0, 1.0, 0.0, 1.0]) + for name, TreeEstimator in CLF_TREES.items(): + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert est.tree_.max_depth == 1 + assert_array_equal(est.predict_proba(X), np.full((4, 2), 0.5)) + + for name, TreeEstimator in REG_TREES.items(): + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert est.tree_.max_depth == 1 + assert_array_equal(est.predict(X), np.full((4,), 0.5)) + + +def test_big_input(): + # Test if the warning for too large inputs is appropriate. + X = np.repeat(10**40.0, 4).astype(np.float64).reshape(-1, 1) + clf = DecisionTreeClassifier() + with pytest.raises(ValueError, match="float32"): + clf.fit(X, [0, 1, 0, 1]) + + +def test_realloc(): + from sklearn.tree._utils import _realloc_test + + with pytest.raises(MemoryError): + _realloc_test() + + +def test_huge_allocations(): + n_bits = 8 * struct.calcsize("P") + + X = np.random.randn(10, 2) + y = np.random.randint(0, 2, 10) + + # Sanity check: we cannot request more memory than the size of the address + # space. Currently raises OverflowError. + huge = 2 ** (n_bits + 1) + clf = DecisionTreeClassifier(splitter="best", max_leaf_nodes=huge) + with pytest.raises(Exception): + clf.fit(X, y) + + # Non-regression test: MemoryError used to be dropped by Cython + # because of missing "except *". + huge = 2 ** (n_bits - 1) - 1 + clf = DecisionTreeClassifier(splitter="best", max_leaf_nodes=huge) + with pytest.raises(MemoryError): + clf.fit(X, y) + + +def check_sparse_input(tree, dataset, max_depth=None): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Gain testing time + if dataset in ["digits", "diabetes"]: + n_samples = X.shape[0] // 5 + X = X[:n_samples] + X_sparse = X_sparse[:n_samples] + y = y[:n_samples] + + for sparse_format in (csr_matrix, csc_matrix, coo_matrix): + X_sparse = sparse_format(X_sparse) + + # Check the default (depth first search) + d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) + + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + + y_pred = d.predict(X) + if tree in CLF_TREES: + y_proba = d.predict_proba(X) + y_log_proba = d.predict_log_proba(X) + + for sparse_matrix in (csr_matrix, csc_matrix, coo_matrix): + X_sparse_test = sparse_matrix(X_sparse, dtype=np.float32) + + assert_array_almost_equal(s.predict(X_sparse_test), y_pred) + + if tree in CLF_TREES: + assert_array_almost_equal(s.predict_proba(X_sparse_test), y_proba) + assert_array_almost_equal( + s.predict_log_proba(X_sparse_test), y_log_proba + ) + + +@pytest.mark.parametrize("tree_type", SPARSE_TREES) +@pytest.mark.parametrize( + "dataset", + ( + "clf_small", + "toy", + "digits", + "multilabel", + "sparse-pos", + "sparse-neg", + "sparse-mix", + "zeros", + ), +) +def test_sparse_input(tree_type, dataset): + max_depth = 3 if dataset == "digits" else None + check_sparse_input(tree_type, dataset, max_depth) + + +@pytest.mark.parametrize("tree_type", sorted(set(SPARSE_TREES).intersection(REG_TREES))) +@pytest.mark.parametrize("dataset", ["diabetes", "reg_small"]) +def test_sparse_input_reg_trees(tree_type, dataset): + # Due to numerical instability of MSE and too strict test, we limit the + # maximal depth + check_sparse_input(tree_type, dataset, 2) + + +def check_sparse_parameters(tree, dataset): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Check max_features + d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y) + s = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X_sparse, y) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check min_samples_split + d = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X, y) + s = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit( + X_sparse, y + ) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check min_samples_leaf + d = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y) + s = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit( + X_sparse, y + ) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check best-first search + d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y) + s = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X_sparse, y) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + +def check_sparse_criterion(tree, dataset): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Check various criterion + CRITERIONS = REG_CRITERIONS if tree in REG_TREES else CLF_CRITERIONS + for criterion in CRITERIONS: + d = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit( + X_sparse, y + ) + + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + +@pytest.mark.parametrize("tree_type", SPARSE_TREES) +@pytest.mark.parametrize("dataset", ["sparse-pos", "sparse-neg", "sparse-mix", "zeros"]) +@pytest.mark.parametrize("check", [check_sparse_parameters, check_sparse_criterion]) +def test_sparse(tree_type, dataset, check): + check(tree_type, dataset) + + +def check_explicit_sparse_zeros(tree, max_depth=3, n_features=10): + TreeEstimator = ALL_TREES[tree] + + # n_samples set n_feature to ease construction of a simultaneous + # construction of a csr and csc matrix + n_samples = n_features + samples = np.arange(n_samples) + + # Generate X, y + random_state = check_random_state(0) + indices = [] + data = [] + offset = 0 + indptr = [offset] + for i in range(n_features): + n_nonzero_i = random_state.binomial(n_samples, 0.5) + indices_i = random_state.permutation(samples)[:n_nonzero_i] + indices.append(indices_i) + data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i,)) - 1 + data.append(data_i) + offset += n_nonzero_i + indptr.append(offset) + + indices = np.concatenate(indices) + data = np.array(np.concatenate(data), dtype=np.float32) + X_sparse = csc_matrix((data, indices, indptr), shape=(n_samples, n_features)) + X = X_sparse.toarray() + X_sparse_test = csr_matrix((data, indices, indptr), shape=(n_samples, n_features)) + X_test = X_sparse_test.toarray() + y = random_state.randint(0, 3, size=(n_samples,)) + + # Ensure that X_sparse_test owns its data, indices and indptr array + X_sparse_test = X_sparse_test.copy() + + # Ensure that we have explicit zeros + assert (X_sparse.data == 0.0).sum() > 0 + assert (X_sparse_test.data == 0.0).sum() > 0 + + # Perform the comparison + d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) + + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + + Xs = (X_test, X_sparse_test) + for X1, X2 in product(Xs, Xs): + assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2)) + assert_array_almost_equal(s.apply(X1), d.apply(X2)) + assert_array_almost_equal(s.apply(X1), s.tree_.apply(X1)) + + assert_array_almost_equal( + s.tree_.decision_path(X1).toarray(), d.tree_.decision_path(X2).toarray() + ) + assert_array_almost_equal( + s.decision_path(X1).toarray(), d.decision_path(X2).toarray() + ) + assert_array_almost_equal( + s.decision_path(X1).toarray(), s.tree_.decision_path(X1).toarray() + ) + + assert_array_almost_equal(s.predict(X1), d.predict(X2)) + + if tree in CLF_TREES: + assert_array_almost_equal(s.predict_proba(X1), d.predict_proba(X2)) + + +@pytest.mark.parametrize("tree_type", SPARSE_TREES) +def test_explicit_sparse_zeros(tree_type): + check_explicit_sparse_zeros(tree_type) + + +@ignore_warnings +def check_raise_error_on_1d_input(name): + TreeEstimator = ALL_TREES[name] + + X = iris.data[:, 0].ravel() + X_2d = iris.data[:, 0].reshape((-1, 1)) + y = iris.target + + with pytest.raises(ValueError): + TreeEstimator(random_state=0).fit(X, y) + + est = TreeEstimator(random_state=0) + est.fit(X_2d, y) + with pytest.raises(ValueError): + est.predict([X]) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_1d_input(name): + with ignore_warnings(): + check_raise_error_on_1d_input(name) + + +def _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight): + est = TreeEstimator(random_state=0) + est.fit(X, y, sample_weight=sample_weight) + assert est.tree_.max_depth == 1 + + est = TreeEstimator(random_state=0, min_weight_fraction_leaf=0.4) + est.fit(X, y, sample_weight=sample_weight) + assert est.tree_.max_depth == 0 + + +def check_min_weight_leaf_split_level(name): + TreeEstimator = ALL_TREES[name] + + X = np.array([[0], [0], [0], [0], [1]]) + y = [0, 0, 0, 0, 1] + sample_weight = [0.2, 0.2, 0.2, 0.2, 0.2] + _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight) + + _check_min_weight_leaf_split_level(TreeEstimator, csc_matrix(X), y, sample_weight) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_min_weight_leaf_split_level(name): + check_min_weight_leaf_split_level(name) + + +def check_public_apply(name): + X_small32 = X_small.astype(tree._tree.DTYPE, copy=False) + + est = ALL_TREES[name]() + est.fit(X_small, y_small) + assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) + + +def check_public_apply_sparse(name): + X_small32 = csr_matrix(X_small.astype(tree._tree.DTYPE, copy=False)) + + est = ALL_TREES[name]() + est.fit(X_small, y_small) + assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_public_apply_all_trees(name): + check_public_apply(name) + + +@pytest.mark.parametrize("name", SPARSE_TREES) +def test_public_apply_sparse_trees(name): + check_public_apply_sparse(name) + + +def test_decision_path_hardcoded(): + X = iris.data + y = iris.target + est = DecisionTreeClassifier(random_state=0, max_depth=1).fit(X, y) + node_indicator = est.decision_path(X[:2]).toarray() + assert_array_equal(node_indicator, [[1, 1, 0], [1, 0, 1]]) + + +def check_decision_path(name): + X = iris.data + y = iris.target + n_samples = X.shape[0] + + TreeEstimator = ALL_TREES[name] + est = TreeEstimator(random_state=0, max_depth=2) + est.fit(X, y) + + node_indicator_csr = est.decision_path(X) + node_indicator = node_indicator_csr.toarray() + assert node_indicator.shape == (n_samples, est.tree_.node_count) + + # Assert that leaves index are correct + leaves = est.apply(X) + leave_indicator = [node_indicator[i, j] for i, j in enumerate(leaves)] + assert_array_almost_equal(leave_indicator, np.ones(shape=n_samples)) + + # Ensure only one leave node per sample + all_leaves = est.tree_.children_left == TREE_LEAF + assert_array_almost_equal( + np.dot(node_indicator, all_leaves), np.ones(shape=n_samples) + ) + + # Ensure max depth is consistent with sum of indicator + max_depth = node_indicator.sum(axis=1).max() + assert est.tree_.max_depth <= max_depth + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_decision_path(name): + check_decision_path(name) + + +def check_no_sparse_y_support(name): + X, y = X_multilabel, csr_matrix(y_multilabel) + TreeEstimator = ALL_TREES[name] + with pytest.raises(TypeError): + TreeEstimator(random_state=0).fit(X, y) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_no_sparse_y_support(name): + # Currently we don't support sparse y + check_no_sparse_y_support(name) + + +def test_mae(): + """Check MAE criterion produces correct results on small toy dataset: + + ------------------ + | X | y | weight | + ------------------ + | 3 | 3 | 0.1 | + | 5 | 3 | 0.3 | + | 8 | 4 | 1.0 | + | 3 | 6 | 0.6 | + | 5 | 7 | 0.3 | + ------------------ + |sum wt:| 2.3 | + ------------------ + + Because we are dealing with sample weights, we cannot find the median by + simply choosing/averaging the centre value(s), instead we consider the + median where 50% of the cumulative weight is found (in a y sorted data set) + . Therefore with regards to this test data, the cumulative weight is >= 50% + when y = 4. Therefore: + Median = 4 + + For all the samples, we can get the total error by summing: + Absolute(Median - y) * weight + + I.e., total error = (Absolute(4 - 3) * 0.1) + + (Absolute(4 - 3) * 0.3) + + (Absolute(4 - 4) * 1.0) + + (Absolute(4 - 6) * 0.6) + + (Absolute(4 - 7) * 0.3) + = 2.5 + + Impurity = Total error / total weight + = 2.5 / 2.3 + = 1.08695652173913 + ------------------ + + From this root node, the next best split is between X values of 3 and 5. + Thus, we have left and right child nodes: + + LEFT RIGHT + ------------------ ------------------ + | X | y | weight | | X | y | weight | + ------------------ ------------------ + | 3 | 3 | 0.1 | | 5 | 3 | 0.3 | + | 3 | 6 | 0.6 | | 8 | 4 | 1.0 | + ------------------ | 5 | 7 | 0.3 | + |sum wt:| 0.7 | ------------------ + ------------------ |sum wt:| 1.6 | + ------------------ + + Impurity is found in the same way: + Left node Median = 6 + Total error = (Absolute(6 - 3) * 0.1) + + (Absolute(6 - 6) * 0.6) + = 0.3 + + Left Impurity = Total error / total weight + = 0.3 / 0.7 + = 0.428571428571429 + ------------------- + + Likewise for Right node: + Right node Median = 4 + Total error = (Absolute(4 - 3) * 0.3) + + (Absolute(4 - 4) * 1.0) + + (Absolute(4 - 7) * 0.3) + = 1.2 + + Right Impurity = Total error / total weight + = 1.2 / 1.6 + = 0.75 + ------ + """ + dt_mae = DecisionTreeRegressor( + random_state=0, criterion="absolute_error", max_leaf_nodes=2 + ) + + # Test MAE where sample weights are non-uniform (as illustrated above): + dt_mae.fit( + X=[[3], [5], [3], [8], [5]], + y=[6, 7, 3, 4, 3], + sample_weight=[0.6, 0.3, 0.1, 1.0, 0.3], + ) + assert_allclose(dt_mae.tree_.impurity, [2.5 / 2.3, 0.3 / 0.7, 1.2 / 1.6]) + assert_array_equal(dt_mae.tree_.value.flat, [4.0, 6.0, 4.0]) + + # Test MAE where all sample weights are uniform: + dt_mae.fit(X=[[3], [5], [3], [8], [5]], y=[6, 7, 3, 4, 3], sample_weight=np.ones(5)) + assert_array_equal(dt_mae.tree_.impurity, [1.4, 1.5, 4.0 / 3.0]) + assert_array_equal(dt_mae.tree_.value.flat, [4, 4.5, 4.0]) + + # Test MAE where a `sample_weight` is not explicitly provided. + # This is equivalent to providing uniform sample weights, though + # the internal logic is different: + dt_mae.fit(X=[[3], [5], [3], [8], [5]], y=[6, 7, 3, 4, 3]) + assert_array_equal(dt_mae.tree_.impurity, [1.4, 1.5, 4.0 / 3.0]) + assert_array_equal(dt_mae.tree_.value.flat, [4, 4.5, 4.0]) + + +def test_criterion_copy(): + # Let's check whether copy of our criterion has the same type + # and properties as original + n_outputs = 3 + n_classes = np.arange(3, dtype=np.intp) + n_samples = 100 + + def _pickle_copy(obj): + return pickle.loads(pickle.dumps(obj)) + + for copy_func in [copy.copy, copy.deepcopy, _pickle_copy]: + for _, typename in CRITERIA_CLF.items(): + criteria = typename(n_outputs, n_classes) + result = copy_func(criteria).__reduce__() + typename_, (n_outputs_, n_classes_), _ = result + assert typename == typename_ + assert n_outputs == n_outputs_ + assert_array_equal(n_classes, n_classes_) + + for _, typename in CRITERIA_REG.items(): + criteria = typename(n_outputs, n_samples) + result = copy_func(criteria).__reduce__() + typename_, (n_outputs_, n_samples_), _ = result + assert typename == typename_ + assert n_outputs == n_outputs_ + assert n_samples == n_samples_ + + +def test_empty_leaf_infinite_threshold(): + # try to make empty leaf by using near infinite value. + data = np.random.RandomState(0).randn(100, 11) * 2e38 + data = np.nan_to_num(data.astype("float32")) + X_full = data[:, :-1] + X_sparse = csc_matrix(X_full) + y = data[:, -1] + for X in [X_full, X_sparse]: + tree = DecisionTreeRegressor(random_state=0).fit(X, y) + terminal_regions = tree.apply(X) + left_leaf = set(np.where(tree.tree_.children_left == TREE_LEAF)[0]) + empty_leaf = left_leaf.difference(terminal_regions) + infinite_threshold = np.where(~np.isfinite(tree.tree_.threshold))[0] + assert len(infinite_threshold) == 0 + assert len(empty_leaf) == 0 + + +@pytest.mark.parametrize("criterion", CLF_CRITERIONS) +@pytest.mark.parametrize( + "dataset", sorted(set(DATASETS.keys()) - {"reg_small", "diabetes"}) +) +@pytest.mark.parametrize("tree_cls", [DecisionTreeClassifier, ExtraTreeClassifier]) +def test_prune_tree_classifier_are_subtrees(criterion, dataset, tree_cls): + dataset = DATASETS[dataset] + X, y = dataset["X"], dataset["y"] + est = tree_cls(max_leaf_nodes=20, random_state=0) + info = est.cost_complexity_pruning_path(X, y) + + pruning_path = info.ccp_alphas + impurities = info.impurities + assert np.all(np.diff(pruning_path) >= 0) + assert np.all(np.diff(impurities) >= 0) + + assert_pruning_creates_subtree(tree_cls, X, y, pruning_path) + + +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +@pytest.mark.parametrize("dataset", DATASETS.keys()) +@pytest.mark.parametrize("tree_cls", [DecisionTreeRegressor, ExtraTreeRegressor]) +def test_prune_tree_regression_are_subtrees(criterion, dataset, tree_cls): + dataset = DATASETS[dataset] + X, y = dataset["X"], dataset["y"] + + est = tree_cls(max_leaf_nodes=20, random_state=0) + info = est.cost_complexity_pruning_path(X, y) + + pruning_path = info.ccp_alphas + impurities = info.impurities + assert np.all(np.diff(pruning_path) >= 0) + assert np.all(np.diff(impurities) >= 0) + + assert_pruning_creates_subtree(tree_cls, X, y, pruning_path) + + +def test_prune_single_node_tree(): + # single node tree + clf1 = DecisionTreeClassifier(random_state=0) + clf1.fit([[0], [1]], [0, 0]) + + # pruned single node tree + clf2 = DecisionTreeClassifier(random_state=0, ccp_alpha=10) + clf2.fit([[0], [1]], [0, 0]) + + assert_is_subtree(clf1.tree_, clf2.tree_) + + +def assert_pruning_creates_subtree(estimator_cls, X, y, pruning_path): + # generate trees with increasing alphas + estimators = [] + for ccp_alpha in pruning_path: + est = estimator_cls(max_leaf_nodes=20, ccp_alpha=ccp_alpha, random_state=0).fit( + X, y + ) + estimators.append(est) + + # A pruned tree must be a subtree of the previous tree (which had a + # smaller ccp_alpha) + for prev_est, next_est in zip(estimators, estimators[1:]): + assert_is_subtree(prev_est.tree_, next_est.tree_) + + +def assert_is_subtree(tree, subtree): + assert tree.node_count >= subtree.node_count + assert tree.max_depth >= subtree.max_depth + + tree_c_left = tree.children_left + tree_c_right = tree.children_right + subtree_c_left = subtree.children_left + subtree_c_right = subtree.children_right + + stack = [(0, 0)] + while stack: + tree_node_idx, subtree_node_idx = stack.pop() + assert_array_almost_equal( + tree.value[tree_node_idx], subtree.value[subtree_node_idx] + ) + assert_almost_equal( + tree.impurity[tree_node_idx], subtree.impurity[subtree_node_idx] + ) + assert_almost_equal( + tree.n_node_samples[tree_node_idx], subtree.n_node_samples[subtree_node_idx] + ) + assert_almost_equal( + tree.weighted_n_node_samples[tree_node_idx], + subtree.weighted_n_node_samples[subtree_node_idx], + ) + + if subtree_c_left[subtree_node_idx] == subtree_c_right[subtree_node_idx]: + # is a leaf + assert_almost_equal(TREE_UNDEFINED, subtree.threshold[subtree_node_idx]) + else: + # not a leaf + assert_almost_equal( + tree.threshold[tree_node_idx], subtree.threshold[subtree_node_idx] + ) + stack.append((tree_c_left[tree_node_idx], subtree_c_left[subtree_node_idx])) + stack.append( + (tree_c_right[tree_node_idx], subtree_c_right[subtree_node_idx]) + ) + + +@pytest.mark.parametrize("name", ALL_TREES) +@pytest.mark.parametrize("splitter", ["best", "random"]) +@pytest.mark.parametrize("X_format", ["dense", "csr", "csc"]) +def test_apply_path_readonly_all_trees(name, splitter, X_format): + dataset = DATASETS["clf_small"] + X_small = dataset["X"].astype(tree._tree.DTYPE, copy=False) + if X_format == "dense": + X_readonly = create_memmap_backed_data(X_small) + else: + X_readonly = dataset["X_sparse"] # CSR + if X_format == "csc": + # Cheap CSR to CSC conversion + X_readonly = X_readonly.tocsc() + + X_readonly.data = np.array(X_readonly.data, dtype=tree._tree.DTYPE) + ( + X_readonly.data, + X_readonly.indices, + X_readonly.indptr, + ) = create_memmap_backed_data( + (X_readonly.data, X_readonly.indices, X_readonly.indptr) + ) + + y_readonly = create_memmap_backed_data(np.array(y_small, dtype=tree._tree.DTYPE)) + est = ALL_TREES[name](splitter=splitter) + est.fit(X_readonly, y_readonly) + assert_array_equal(est.predict(X_readonly), est.predict(X_small)) + assert_array_equal( + est.decision_path(X_readonly).todense(), est.decision_path(X_small).todense() + ) + + +@pytest.mark.parametrize("criterion", ["squared_error", "friedman_mse", "poisson"]) +@pytest.mark.parametrize("Tree", REG_TREES.values()) +def test_balance_property(criterion, Tree): + # Test that sum(y_pred)=sum(y_true) on training set. + # This works if the mean is predicted (should even be true for each leaf). + # MAE predicts the median and is therefore excluded from this test. + + # Choose a training set with non-negative targets (for poisson) + X, y = diabetes.data, diabetes.target + reg = Tree(criterion=criterion) + reg.fit(X, y) + assert np.sum(reg.predict(X)) == pytest.approx(np.sum(y)) + + +@pytest.mark.parametrize("seed", range(3)) +def test_poisson_zero_nodes(seed): + # Test that sum(y)=0 and therefore y_pred=0 is forbidden on nodes. + X = [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 2], [1, 2], [1, 3]] + y = [0, 0, 0, 0, 1, 2, 3, 4] + # Note that X[:, 0] == 0 is a 100% indicator for y == 0. The tree can + # easily learn that: + reg = DecisionTreeRegressor(criterion="squared_error", random_state=seed) + reg.fit(X, y) + assert np.amin(reg.predict(X)) == 0 + # whereas Poisson must predict strictly positive numbers + reg = DecisionTreeRegressor(criterion="poisson", random_state=seed) + reg.fit(X, y) + assert np.all(reg.predict(X) > 0) + + # Test additional dataset where something could go wrong. + n_features = 10 + X, y = datasets.make_regression( + effective_rank=n_features * 2 // 3, + tail_strength=0.6, + n_samples=1_000, + n_features=n_features, + n_informative=n_features * 2 // 3, + random_state=seed, + ) + # some excess zeros + y[(-1 < y) & (y < 0)] = 0 + # make sure the target is positive + y = np.abs(y) + reg = DecisionTreeRegressor(criterion="poisson", random_state=seed) + reg.fit(X, y) + assert np.all(reg.predict(X) > 0) + + +def test_poisson_vs_mse(): + # For a Poisson distributed target, Poisson loss should give better results + # than squared error measured in Poisson deviance as metric. + # We have a similar test, test_poisson(), in + # sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py + rng = np.random.RandomState(42) + n_train, n_test, n_features = 500, 500, 10 + X = datasets.make_low_rank_matrix( + n_samples=n_train + n_test, n_features=n_features, random_state=rng + ) + # We create a log-linear Poisson model and downscale coef as it will get + # exponentiated. + coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) + y = rng.poisson(lam=np.exp(X @ coef)) + X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=n_test, random_state=rng + ) + # We prevent some overfitting by setting min_samples_split=10. + tree_poi = DecisionTreeRegressor( + criterion="poisson", min_samples_split=10, random_state=rng + ) + tree_mse = DecisionTreeRegressor( + criterion="squared_error", min_samples_split=10, random_state=rng + ) + + tree_poi.fit(X_train, y_train) + tree_mse.fit(X_train, y_train) + dummy = DummyRegressor(strategy="mean").fit(X_train, y_train) + + for X, y, val in [(X_train, y_train, "train"), (X_test, y_test, "test")]: + metric_poi = mean_poisson_deviance(y, tree_poi.predict(X)) + # squared_error might produce non-positive predictions => clip + metric_mse = mean_poisson_deviance(y, np.clip(tree_mse.predict(X), 1e-15, None)) + metric_dummy = mean_poisson_deviance(y, dummy.predict(X)) + # As squared_error might correctly predict 0 in train set, its train + # score can be better than Poisson. This is no longer the case for the + # test set. + if val == "test": + assert metric_poi < 0.5 * metric_mse + assert metric_poi < 0.75 * metric_dummy + + +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +def test_decision_tree_regressor_sample_weight_consistency(criterion): + """Test that the impact of sample_weight is consistent.""" + tree_params = dict(criterion=criterion) + tree = DecisionTreeRegressor(**tree_params, random_state=42) + for kind in ["zeros", "ones"]: + check_sample_weights_invariance( + "DecisionTreeRegressor_" + criterion, tree, kind="zeros" + ) + + rng = np.random.RandomState(0) + n_samples, n_features = 10, 5 + + X = rng.rand(n_samples, n_features) + y = np.mean(X, axis=1) + rng.rand(n_samples) + # make it positive in order to work also for poisson criterion + y += np.min(y) + 0.1 + + # check that multiplying sample_weight by 2 is equivalent + # to repeating corresponding samples twice + X2 = np.concatenate([X, X[: n_samples // 2]], axis=0) + y2 = np.concatenate([y, y[: n_samples // 2]]) + sample_weight_1 = np.ones(len(y)) + sample_weight_1[: n_samples // 2] = 2 + + tree1 = DecisionTreeRegressor(**tree_params).fit( + X, y, sample_weight=sample_weight_1 + ) + + tree2 = DecisionTreeRegressor(**tree_params).fit(X2, y2, sample_weight=None) + + assert tree1.tree_.node_count == tree2.tree_.node_count + # Thresholds, tree.tree_.threshold, and values, tree.tree_.value, are not + # exactly the same, but on the training set, those differences do not + # matter and thus predictions are the same. + assert_allclose(tree1.predict(X), tree2.predict(X)) + + +@pytest.mark.parametrize("Tree", [DecisionTreeClassifier, ExtraTreeClassifier]) +@pytest.mark.parametrize("n_classes", [2, 4]) +def test_criterion_entropy_same_as_log_loss(Tree, n_classes): + """Test that criterion=entropy gives same as log_loss.""" + n_samples, n_features = 50, 5 + X, y = datasets.make_classification( + n_classes=n_classes, + n_samples=n_samples, + n_features=n_features, + n_informative=n_features, + n_redundant=0, + random_state=42, + ) + tree_log_loss = Tree(criterion="log_loss", random_state=43).fit(X, y) + tree_entropy = Tree(criterion="entropy", random_state=43).fit(X, y) + + assert_tree_equal( + tree_log_loss.tree_, + tree_entropy.tree_, + f"{Tree!r} with criterion 'entropy' and 'log_loss' gave different trees.", + ) + assert_allclose(tree_log_loss.predict(X), tree_entropy.predict(X)) + + +def test_different_endianness_pickle(): + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + def reduce_ndarray(arr): + return arr.byteswap().newbyteorder().__reduce__() + + def get_pickle_non_native_endianness(): + f = io.BytesIO() + p = pickle.Pickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[np.ndarray] = reduce_ndarray + + p.dump(clf) + f.seek(0) + return f + + new_clf = pickle.load(get_pickle_non_native_endianness()) + new_score = new_clf.score(X, y) + assert np.isclose(score, new_score) + + +def test_different_endianness_joblib_pickle(): + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + class NonNativeEndiannessNumpyPickler(NumpyPickler): + def save(self, obj): + if isinstance(obj, np.ndarray): + obj = obj.byteswap().newbyteorder() + super().save(obj) + + def get_joblib_pickle_non_native_endianness(): + f = io.BytesIO() + p = NonNativeEndiannessNumpyPickler(f) + + p.dump(clf) + f.seek(0) + return f + + new_clf = joblib.load(get_joblib_pickle_non_native_endianness()) + new_score = new_clf.score(X, y) + assert np.isclose(score, new_score) + + +def get_different_bitness_node_ndarray(node_ndarray): + new_dtype_for_indexing_fields = np.int64 if _IS_32BIT else np.int32 + + # field names in Node struct with SIZE_t types (see sklearn/tree/_tree.pxd) + indexing_field_names = ["left_child", "right_child", "feature", "n_node_samples"] + + new_dtype_dict = { + name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items() + } + for name in indexing_field_names: + new_dtype_dict[name] = new_dtype_for_indexing_fields + + new_dtype = np.dtype( + {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())} + ) + return node_ndarray.astype(new_dtype, casting="same_kind") + + +def get_different_alignment_node_ndarray(node_ndarray): + new_dtype_dict = { + name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items() + } + offsets = [offset for dtype, offset in node_ndarray.dtype.fields.values()] + shifted_offsets = [8 + offset for offset in offsets] + + new_dtype = np.dtype( + { + "names": list(new_dtype_dict.keys()), + "formats": list(new_dtype_dict.values()), + "offsets": shifted_offsets, + } + ) + return node_ndarray.astype(new_dtype, casting="same_kind") + + +def reduce_tree_with_different_bitness(tree): + new_dtype = np.int64 if _IS_32BIT else np.int32 + tree_cls, (n_features, n_classes, n_outputs), state = tree.__reduce__() + new_n_classes = n_classes.astype(new_dtype, casting="same_kind") + + new_state = state.copy() + new_state["nodes"] = get_different_bitness_node_ndarray(new_state["nodes"]) + + return (tree_cls, (n_features, new_n_classes, n_outputs), new_state) + + +def test_different_bitness_pickle(): + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + def pickle_dump_with_different_bitness(): + f = io.BytesIO() + p = pickle.Pickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[CythonTree] = reduce_tree_with_different_bitness + + p.dump(clf) + f.seek(0) + return f + + new_clf = pickle.load(pickle_dump_with_different_bitness()) + new_score = new_clf.score(X, y) + assert score == pytest.approx(new_score) + + +def test_different_bitness_joblib_pickle(): + # Make sure that a platform specific pickle generated on a 64 bit + # platform can be converted at pickle load time into an estimator + # with Cython code that works with the host's native integer precision + # to index nodes in the tree data structure when the host is a 32 bit + # platform (and vice versa). + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + def joblib_dump_with_different_bitness(): + f = io.BytesIO() + p = NumpyPickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[CythonTree] = reduce_tree_with_different_bitness + + p.dump(clf) + f.seek(0) + return f + + new_clf = joblib.load(joblib_dump_with_different_bitness()) + new_score = new_clf.score(X, y) + assert score == pytest.approx(new_score) + + +def test_check_n_classes(): + expected_dtype = np.dtype(np.int32) if _IS_32BIT else np.dtype(np.int64) + allowed_dtypes = [np.dtype(np.int32), np.dtype(np.int64)] + allowed_dtypes += [dt.newbyteorder() for dt in allowed_dtypes] + + n_classes = np.array([0, 1], dtype=expected_dtype) + for dt in allowed_dtypes: + _check_n_classes(n_classes.astype(dt), expected_dtype) + + with pytest.raises(ValueError, match="Wrong dimensions.+n_classes"): + wrong_dim_n_classes = np.array([[0, 1]], dtype=expected_dtype) + _check_n_classes(wrong_dim_n_classes, expected_dtype) + + with pytest.raises(ValueError, match="n_classes.+incompatible dtype"): + wrong_dtype_n_classes = n_classes.astype(np.float64) + _check_n_classes(wrong_dtype_n_classes, expected_dtype) + + +def test_check_value_ndarray(): + expected_dtype = np.dtype(np.float64) + expected_shape = (5, 1, 2) + value_ndarray = np.zeros(expected_shape, dtype=expected_dtype) + + allowed_dtypes = [expected_dtype, expected_dtype.newbyteorder()] + + for dt in allowed_dtypes: + _check_value_ndarray( + value_ndarray, expected_dtype=dt, expected_shape=expected_shape + ) + + with pytest.raises(ValueError, match="Wrong shape.+value array"): + _check_value_ndarray( + value_ndarray, expected_dtype=expected_dtype, expected_shape=(1, 2) + ) + + for problematic_arr in [value_ndarray[:, :, :1], np.asfortranarray(value_ndarray)]: + with pytest.raises(ValueError, match="value array.+C-contiguous"): + _check_value_ndarray( + problematic_arr, + expected_dtype=expected_dtype, + expected_shape=problematic_arr.shape, + ) + + with pytest.raises(ValueError, match="value array.+incompatible dtype"): + _check_value_ndarray( + value_ndarray.astype(np.float32), + expected_dtype=expected_dtype, + expected_shape=expected_shape, + ) + + +def test_check_node_ndarray(): + expected_dtype = NODE_DTYPE + + node_ndarray = np.zeros((5,), dtype=expected_dtype) + + valid_node_ndarrays = [ + node_ndarray, + get_different_bitness_node_ndarray(node_ndarray), + get_different_alignment_node_ndarray(node_ndarray), + ] + valid_node_ndarrays += [ + arr.astype(arr.dtype.newbyteorder()) for arr in valid_node_ndarrays + ] + + for arr in valid_node_ndarrays: + _check_node_ndarray(node_ndarray, expected_dtype=expected_dtype) + + with pytest.raises(ValueError, match="Wrong dimensions.+node array"): + problematic_node_ndarray = np.zeros((5, 2), dtype=expected_dtype) + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + with pytest.raises(ValueError, match="node array.+C-contiguous"): + problematic_node_ndarray = node_ndarray[::2] + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + dtype_dict = {name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items()} + + # array with wrong 'threshold' field dtype (int64 rather than float64) + new_dtype_dict = dtype_dict.copy() + new_dtype_dict["threshold"] = np.int64 + + new_dtype = np.dtype( + {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())} + ) + problematic_node_ndarray = node_ndarray.astype(new_dtype) + + with pytest.raises(ValueError, match="node array.+incompatible dtype"): + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + # array with wrong 'left_child' field dtype (float64 rather than int64 or int32) + new_dtype_dict = dtype_dict.copy() + new_dtype_dict["left_child"] = np.float64 + new_dtype = np.dtype( + {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())} + ) + + problematic_node_ndarray = node_ndarray.astype(new_dtype) + + with pytest.raises(ValueError, match="node array.+incompatible dtype"): + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + +# TODO(1.3): Remove +def test_max_features_auto_deprecated(): + for Tree in CLF_TREES.values(): + tree = Tree(max_features="auto") + msg = ( + "`max_features='auto'` has been deprecated in 1.1 and will be removed in" + " 1.3. To keep the past behaviour, explicitly set `max_features='sqrt'`." + ) + with pytest.warns(FutureWarning, match=msg): + tree.fit(X, y) + + for Tree in REG_TREES.values(): + tree = Tree(max_features="auto") + msg = ( + "`max_features='auto'` has been deprecated in 1.1 and will be removed in" + " 1.3. To keep the past behaviour, explicitly set `max_features=1.0'`." + ) + with pytest.warns(FutureWarning, match=msg): + tree.fit(X, y) + + +def test_tree_deserialization_from_read_only_buffer(tmpdir): + """Check that Trees can be deserialized with read only buffers. + + Non-regression test for gh-25584. + """ + pickle_path = str(tmpdir.join("clf.joblib")) + clf = DecisionTreeClassifier(random_state=0) + clf.fit(X_small, y_small) + + joblib.dump(clf, pickle_path) + loaded_clf = joblib.load(pickle_path, mmap_mode="r") + + assert_tree_equal( + loaded_clf.tree_, + clf.tree_, + "The trees of the original and loaded classifiers are not equal.", + ) + + +@pytest.mark.parametrize("Tree", ALL_TREES.values()) +def test_min_sample_split_1_error(Tree): + """Check that an error is raised when min_sample_split=1. + + non-regression test for issue gh-25481. + """ + X = np.array([[0, 0], [1, 1]]) + y = np.array([0, 1]) + + # min_samples_split=1.0 is valid + Tree(min_samples_split=1.0).fit(X, y) + + # min_samples_split=1 is invalid + tree = Tree(min_samples_split=1) + msg = ( + r"'min_samples_split' .* must be an int in the range \[2, inf\) " + r"or a float in the range \(0.0, 1.0\]" + ) + with pytest.raises(ValueError, match=msg): + tree.fit(X, y)