From 8dd2505bd26127a6704e0f16a50d93bda4da2fb3 Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Sun, 20 Sep 2015 10:57:31 -0400 Subject: [PATCH] Add the random_element() function for cones. --- mjo/cone/cone.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/mjo/cone/cone.py b/mjo/cone/cone.py index 1d04084..1a3ee3b 100644 --- a/mjo/cone/cone.py +++ b/mjo/cone/cone.py @@ -750,3 +750,60 @@ def is_lyapunov_like(L,K): """ return all([(L*x).inner_product(s) == 0 for (x,s) in discrete_complementarity_set(K)]) + + +def random_element(K): + r""" + Return a random element of ``K`` from its ambient vector space. + + ALGORITHM: + + The cone ``K`` is specified in terms of its generators, so that + ``K`` is equal to the convex conic combination of those generators. + To choose a random element of ``K``, we assign random nonnegative + coefficients to each generator of ``K`` and construct a new vector + from the scaled rays. + + A vector, rather than a ray, is returned so that the element may + have non-integer coordinates. Thus the element may have an + arbitrarily small norm. + + EXAMPLES: + + A random element of the trivial cone is zero:: + + sage: set_random_seed() + sage: K = Cone([], ToricLattice(0)) + sage: random_element(K) + () + sage: K = Cone([(0,)]) + sage: random_element(K) + (0) + sage: K = Cone([(0,0)]) + sage: random_element(K) + (0, 0) + sage: K = Cone([(0,0,0)]) + sage: random_element(K) + (0, 0, 0) + + TESTS: + + Any cone should contain an element of itself:: + + sage: set_random_seed() + sage: K = random_cone(max_rays = 8) + sage: K.contains(random_element(K)) + True + + """ + V = K.lattice().vector_space() + F = V.base_ring() + coefficients = [ F.random_element().abs() for i in range(K.nrays()) ] + vector_gens = map(V, K.rays()) + scaled_gens = [ coefficients[i]*vector_gens[i] + for i in range(len(vector_gens)) ] + + # Make sure we return a vector. Without the coercion, we might + # return ``0`` when ``K`` has no rays. + v = V(sum(scaled_gens)) + return v -- 2.44.2