Andy Lorenz

Yann Ponty
email: yann.ponty@lix.polytechnique.fr

Non-redundant random generation algorithms for weighted context-free grammars

Keywords: Context-free languages, Random generation, Weighted grammars, Non-redundant generation, Unranking, Recursive random generation

We address the non-redundant random generation of k words of length n in a context-free language. Additionally, we want to avoid a predefined set of words. We study a rejection-based approach, whose worst-case time complexity is shown to grow exponentially with k for some specifications and in the limit case of a coupon collector. We propose two algorithms respectively based on the recursive method and on an unranking approach. We show how careful implementations of these algorithms allow for a non-redundant generation of k words of length n in O(k • n • log n) arithmetic operations, after a precomputation of Θ(n) numbers. The overall complexity is therefore dominated by the generation of k words, and the non-redundancy comes at a negligible cost.

Introduction

The random generation of combinatorial objects has many direct applications in areas ranging from software testing [START_REF] Denise | Uniform random sampling of traces in very large models[END_REF] to bioinformatics [START_REF] Ponty | GenRGenS: Software for generating random genomic sequences and structures[END_REF]. It can help formulate conjectures on the average-case complexity of algorithms [START_REF] Bassino | On the average complexity of Moore's state minimization algorithm[END_REF], raises new fundamental mathematical questions, and motivates new developments on its underlying objects. These include, but are not limited to, generating functionology, arbitrary precision arithmetics and bijective combinatorics. Following the recursive framework introduced by Wilf [START_REF] Wilf | A unified setting for sequencing, ranking, and selection algorithms for combinatorial objects[END_REF], very elegant and general algorithms for the uniform random generation have been designed [START_REF] Flajolet | Calculus for the random generation of labelled combinatorial structures[END_REF] and implemented. Many optimizations of this approach have been developed, using specificities of certain classes of combinatorial structures [START_REF] Goldwurm | Random generation of words in an algebraic language in linear binary space[END_REF], or floating-point arithmetics [START_REF] Denise | Uniform random generation of decomposable structures using floating-point arithmetic[END_REF]. More recently, Boltzmann sampling [START_REF] Duchon | Boltzmann samplers for the random generation of combinatorial structures[END_REF], an algebraic approach based on analytic combinatorics, has drawn much attention, mostly owing to its minimal memory consumption and its intrinsic theoretical elegance.

For many applications, it is necessary to depart from uniform models [START_REF] Ding | A statistical sampling algorithm for RNA secondary structure prediction[END_REF][START_REF] Brlek | Non uniform random generation of generalized Motzkin paths[END_REF]. A striking example lies in a recent paradigm for the in silico analysis of the folding of Ribo-Nucleic Acids (RNAs). Instead of trying to predict a conformation of minimal free-energy, current approaches tend to focus on the ensemble properties of realizable conformations, assuming a Boltzmann probability distribution [START_REF] Ding | A statistical sampling algorithm for RNA secondary structure prediction[END_REF] on the entire set of conformations. Random generation is then performed, and complex structural features are evaluated in a statistical manner. In order to capture such features, a general non-uniform scheme was introduced by Denise et al [START_REF] Denise | Random generation of words of context-free languagesaccording to the frequencies of letters[END_REF], based on the concept of weighted context-free grammars. Recursive random generation algorithms were derived, with time and space complexities equivalent to that observed within the uniform distribution [START_REF] Flajolet | Calculus for the random generation of labelled combinatorial structures[END_REF]. This initial work was later completed toward general decomposable classes [START_REF] Denise | Controlled non uniform random generation of decomposable structures[END_REF] and a Boltzmann weighted sampling scheme, used as a preliminary step within a rejection-based algorithm for the multidimensional sampling of languages [START_REF] Bodini | Multi-dimensional Boltzmann sampling of languages[END_REF].

In a weighted probability distribution, the probability ratio between the most and least frequent words typically grows exponentially on the size of the generated objects. Therefore a typical set of independently generated objects may feature a large number of copies of the heaviest (i.e. most probable) objects. This redundancy, which can be useful in some context, such as the estimation the probability of each sample from its frequency, is completely uninformative in the context of weighted random generation, as the exact probability of any sampled object can be derived in a straightforward manner. Consequently it is a natural question to address the non-redundant random generation of combinatorial objects, i.e. the generation of a set of distinct objects.

The non-redundant random generation has, to the best of our knowledge, only been addressed indirectly through the introduction of the PowerSet construct by Zimmermann [START_REF] Zimmermann | Uniform random generation for the powerset construction[END_REF]. An algorithm in Θ(n 2 ) arithmetic operations, or a practical Θ(n 4 ) complexity in this case, was derived for recursive decomposable structures. The absence of redundancy in the generated set of structures was achieved respectively through rejection or an unranking algorithms. Unfortunately, these approaches do not transpose well to the case of weighted languages. Indeed, the former rejection algorithm may have exponential time-complexity in the average-case, as is shown later in the article. The unranking approach benefits from recent contributions by Martinez and Molinero [START_REF] Martinez | A generic approach for the unranking of labeled combinatorial classes[END_REF], who gave generic unranking procedures for labeled combinatorial classes, generalized by Weinberg and Nebel [START_REF] Weinberg | Non Uniform Generation of Combinatorial Objects[END_REF] to rule-weighted context-free grammars. However, the latter algorithm is restricted to integral weights, and requires a transformation of the grammar which may impact its complexity. Furthermore, the question of figuring out a rank which avoids a set of words was completely ignored by these works.

In this paper, we address the non-redundant generation of words from a context-free language. We remind or introduce in Section 2 some concepts and definitions related to weighted languages, and define our objective. In Section 3, we analyze the shortcomings of a naive rejection approach. We show that, although well-suited for the uniform distribution, the rejection approach may lead to prohibitive average-case complexities in the case of degenerate grammars, large sets of forbidden words, large weights values, or large sets of generated words. Then, in Section 4, we introduce the concept of immature words, which allows us to rephrase the random generation process as a step-by-step process. The resulting algorithm is based on the recursive method, coupled with a custom data structure to perform a generation of k sequences of length n at the cost of O(k • n log(n)) arithmetic operations after a precomputation in Θ(n) arithmetic operations. We also propose in Section 5 an unranking algorithm for weighted grammars which, coupled with a dedicated data structure that stores and helps avoid any forbidden word, also yields a O(k • n log(n)) algorithm after Θ(n) arithmetic operations. We conclude in Section 6 with a summary of our propositions and results, and outline some perspectives and open questions.

Notations and concepts

Context-free grammars

Let us remind, for the sake of completeness, some basic language-theoretic definitions. A context-free grammar is a 4-tuple G = (Σ, N , P, S) where

• Σ is the alphabet, i.e. a finite set of terminal symbols.

• N is a finite set of non-terminal symbols.

• P is the finite set of production rules, each of the form N → X, for N ∈ N any non-terminal and X ∈ {Σ ∪ N } * .

• S is the axiom of the grammar, i. e. the initial non-terminal.

A grammar G is then said to be in Binary Chomsky Normal Form (BCNF) iff each of its non-terminals N ∈ N is productive and can only be derived using a limited number of production rule (two for union type non-terminals, and one otherwise):

• Product type: N → N ′ . N ′′ with N ′ , N ′′ ∈ N ; • Union type: N → N ′ | N ′′ with N ′ , N ′′ ∈ N ;
• Terminal type: N → t with t ∈ Σ;

• Epsilon type: N → ε, iff N cannot be derived from self-referential nonterminals.

In the following, it will be assumed that the input grammar is given in BCNF. This restriction does not cause any loss of generality or performance, as it can be shown that any Chomsky Normal Form grammar can be transformed in linear time into an equivalent BCNF grammar, having equal number of rule up to a constant ratio.

Let L(N ) be the language associated to N ∈ Σ within a grammar G, i.e. the set of words composed of terminal symbols that can be generated starting from N through a sequence of derivations. One has

L(N ) =        L(N ′ ) × L(N ′′ ) If N → N ′ . N ′′ L(N ′ ) ∪ L(N ′′ ) If N → N ′ | N ′′ {t} If N → t {ε} If N → ε (1)
The language L(G) generated by a grammar G = (Σ, N , P, S) is then defined as L(S) the language associated with the axiom S. Finally, let us denote by L n the restriction of a language L to words of length n.

Weighted context-free grammars

Definition 2.1 (Weighted Grammar [START_REF] Denise | Random generation of words of context-free languagesaccording to the frequencies of letters[END_REF]). A weighted grammar G π is a 5-tuple G π = (π, Σ, N , P, S) where (Σ, N , P, S) define a context-free grammar and π : Σ → R + is a weighting function that associates a real-valued weight π t to each terminal symbols t.

This notion of weight naturally extends to any mature word w in a multiplicative fashion, i.e. such that π(w) = |w| i=1 π wi . It also extends additively on any set of words L through π(L) = w∈L π(w). One defines a π-weighted probability distribution over L such that

P(w | π, L) = π(w) w ′ ∈L π(w ′ ) = π(w) π(L) , ∀w ∈ L. (2)
The random generation of words of a given length n with respect to a weighted probability distribution has been addressed by previous works, and an algorithm in O(n log n) after O(n 2 ) arithmetic operations was described [START_REF] Denise | Random generation of words of context-free languagesaccording to the frequencies of letters[END_REF] and implemented [START_REF] Ponty | GenRGenS: Software for generating random genomic sequences and structures[END_REF].

Problem statement

In the following, we consider algorithmic solutions for the non-redundant generation of a collection of words of a given length, generated by an unambiguous weighted context-free grammar. Our precise goal is to simulate efficiently a sequence of independent calls to a random generation algorithm until a set of exactly k distinct words in a language L are obtained. The returned subset R ⊆ L n , |R| = k, can be generated in any order, and the random generation scenarios leading to an ordering σ of R can be decomposed as:

σ 1 → σ * 1 → σ 2 → (σ 1 | σ 2 ) * → . . . → σ k-1 → (σ 1 | • • • | σ k-1 ) * → σ k .
The successive calls made to the weighted random generator are independent, therefore the total probability p σ of getting a set R in a given order σ is given Algorithm 1 Non-redundant sequential meta-algorithm for the generation of k distinct words of length n, from a (weighted) context-free grammar G π = (π, Σ, N , P, S), avoiding a forbidden set of words F .

NonRedundantSequential(G π , k, n, F ): Perform some precomputations. . . R ← ∅ while |R| ≤ k do x ← DrawNonRed(S n , π(N n ), G π , F ) {Any non-redundant algorithm} Update some data structure. . . (R, F ) ← (R ∪ {x}, F ∪ {x}) end while return R by p σ = π(σ 1 ) π(L n ) • k i=2   m≥0 i-1 j=1 π(σ j ) π(L n ) m • π(σ i ) π(L n )   = π(σ 1 ) π(L n ) • k i=2   1 1 - i-1 j=1 π(σj ) π(Ln) • π(σ i ) π(L n )   = k i=1 π(σ i ) π(L n ) - i-1 j=1 π(σ j )
.

Summing over every possible permutation of the elements in R, one obtains

P(R | k, n) = σ∈S(R) k i=1 π(σ i ) π(L n ) - i-1 j=1 π(σ j ) (3)
where S(R) is the set of all permutations over the elements of R. The problem can then be restated as:

Weighted-Non-Redundant-Generation (wnrg)

Input: An unambiguous weighted grammar G π and two positive integers n and k.

Output: A set of words R ⊆ L(G) n of cardinality k with probability

P(R | k, n).
Note that the distribution described by Equation (3) naturally arises from a sequence of dependent calls (r 1 , . . . , r k ) to weighted generators for L, avoiding sets of words ∅, {r 1 }, . . . , {r 1 , . . . , r k-1 } respectively, as implemented in Algorithm 1. It is therefore sufficient to address the generation of a single word w, while avoiding a prescribed set F , in the weighted probability distribution P(w | π, L\F ).

Algorithm 2 Naive rejection algorithm for generating a word of length n, from a (weighted) context-free grammar G π , avoiding a forbidden set of words F . NaiveRejection(G π , n, F ): repeat t ← draw(G π , n) {One may use any available generation algorithm.} until t / ∈ F return t

Naive rejection algorithm

A naive rejection strategy for this problem consists in drawing words at random in an unconstrained way, rejecting those from the forbidden set until a valid word is generated, as implemented in Algorithm 2. As noted by Zimmermann [START_REF] Zimmermann | Uniform random generation for the powerset construction[END_REF], this approach is suitable for the uniform distribution of objects in general recursive specifications. This rejection strategy relies on an auxiliary generator draw(• • • ) of words from a (weighted) context-free languages, and we refer to previous works by Flajolet et al [START_REF] Flajolet | Calculus for the random generation of labelled combinatorial structures[END_REF][START_REF] Duchon | Boltzmann samplers for the random generation of combinatorial structures[END_REF], or Denise et al [START_REF] Denise | Uniform random generation of decomposable structures using floating-point arithmetic[END_REF] for efficient solutions for this problem. Proof. Let w be the word returned by the algorithm, and

F = {f i } |F | i=1 .
Let us characterize the sequences of words generated by draw, leading to the generation of w, by mean of a rational expression over an alphabet F ∪ {w}:

R w = (f 1 | f 2 | • • • | f |F | ) * .w.
Let p x = π(x)/π(L(G) n ) the probability of emission of any -possibly forbidden -word x ∈ L(G) n , then the cumulated probability of the sequences of calls to draw, leading to the generation of w, is such that

P(w) = p w +   |F | i=1 p fi   • p w +   |F | i=1 p fi   •   |F | i=1 p fi   • p w + • • • = p w 1 -|F | i=1 p fi = π(w) π(L(G) n ) -|F | i=1 π(f i ) = π(w) π(L(G) n \F ) .

Complexity analysis: Uniform distribution

Let us analyze the complexity of Algorithm 2, given L a context-free language, n ∈ N + a positive integer and F ⊂ L n a set of forbidden words, assuming a uniform distribution on L n .

One first remarks that the worst-case time-complexity of the algorithm is unbounded, as nothing prevents the algorithm from repeatedly generating the same word. An average-case analysis, however, draws a more contrasted picture of the time complexity. Theorem 3.2. In the uniform distribution, the naive rejection implemented in Algorithm 2 leads to an average-case complexity in

O |Ln| |Ln|-|F | • k log k • draw(n) ,
where draw(n) is the complexity of drawing a single word.

Proof. In the uniform model when F = ∅, the number of attempts required by the generation of the i-th word only depends on i and is independent from prior events. Thus the expected number X n,k of attempts for k distinct words of size n is given by

E(X n,k ) = k-1 i=0 l n l n -i = l n (H ln -H ln-k )
where l n := |L n | is the number of words of size n in the language and H i the harmonic number of order i, as pointed out by Flajolet et al [START_REF] Flajolet | Birthday paradox, coupon collectors, caching algorithms and self-organizing search[END_REF]. It follows that E(X n,k ) is trivially increasing with k, while remaining upper bounded by k • H k ∈ Θ(k log(k)) when k = l n (Coupon collector problem). Since the expected number of rejections due to a non-empty forbidden set F remains the same throughout the generation, and does not have any influence over the generated sequences, it can be considered independently and contributes to a factor |Ln| |Ln|-|F | . It follows that, unless the forbidden set dominates the set of words, the persample complexity of the naive rejection strategy remains largely unaffected (at most a factor O(log k), i.e. Ω(n) since k ∈ Ω(|Σ| n )) by the cumulated cost of rejections.

Complexity analysis: Weighted languages

Turning towards weighted context-free languages, one shows that a rejection strategy may have average-case complexity which is exponential on k, even in the most favorable case of an empty initial set of forbidden words.

Proposition 3.3. The generation of k distinct words, starting from an empty initial forbidden set F = ∅, may require a number of calls to draw that is exponential on k.

Proof. Consider the following grammar, generating the language denoted by the regular expression a * b * :

S → a . S | T T → b . T | ε
We adjoin a weight function π to this grammar, such that π(b) := α > 1 and π(a) := 1. The probability of any word ω m := a n-m b m in the language is

P(ω m ) = π(ω m ) ω∈L(S) |ω|=n π(ω) = α m n i=0 α i = α m+1 -α m α n+1 -1 < α m-n .
Now consider the set V n,k ⊂ S n of words having less than nk occurrences of the symbol b. The probability of generating a word from V n,k is then

P(V n,k ) = n-k i=0 P(ω n-k-i ) = α n-k+1 -1 α n+1 -1 < α -k
The expected number of generations before generating any element of V n,k is greater than α k . Since any non-redundant set of k sequences issued from S n must contain at least one sequence from V n,k , then the average-case time complexity of a naive rejection approach is in Ω(n • α k ), i.e. exponential on k the number of words. However, the above example is based on a regular language, and may not be typical of the rejection algorithm's behavior on general context-free languages. Indeed, it can be shown that, under a natural assumption, no single word can asymptotically contribute a significant portion of the distribution in simple type grammars.

Proposition 3.4. Let G π = (π, Σ, N , S, P) be a weighted grammar of simple type 1 . Assume that ω △ n the most probable (i.e. largest weight w.r.t. π) word of length n has weight π(ω △ n ) ∈ Θ(α n ), for some α > 0. Then the probability of ω △ decreases exponentially as n → ∞:

∃ β < 1 such that P(ω △ | π) = π(ω △ ) π(L(G π ) n ) ∈ Ω(β n ).
Proof. The Drmota-Lalley-Woods theorem [START_REF] Drmota | Systems of functional equations[END_REF][START_REF] Lalley | Finite range random walk on free groups and homogeneous trees[END_REF][START_REF] Woods | Coloring rules for finite trees, and probabilities of monadic second order sentences[END_REF] establishes that the generating function of any simple type grammar has a square-root type singularity. This powerful result relies on properties of the underlying system of functional equations, and therefore also holds for the coefficients of weighted generating functions [START_REF] Denise | Controlled non uniform random generation of decomposable structures[END_REF]. Therefore the overall weights W n := π(L(G π ) n ) -the coefficients of the weighted generating function -follow an expansion of the form

κ ′ •α ′n n √ n (1 + O(1/n)), α ′ , κ ′ > 0. Since ω △ n is contributing to W n , then one has π(ω △ n ) ≤ π(L(G π ) n
) and therefore α < α ′ . The proposition follows directly from taking β := α ′ /α. Furthermore, one can easily design disconnected grammars such that, for any fixed length n, a subset of words M ⊂ L(G π ) n having maximal number of occurrences of a given symbol t has total cumulated probability 1α n , 0 < α < 1, in the weighted distribution. It follows that sampling more than 1 A grammar of simple type is mainly a grammar whose dependency graph is stronglyconnected and whose number of words follow an aperiodic progression (See [START_REF] Flajolet | Boltzmann sampling of unlabelled structures[END_REF] for a more complete definition). Such a grammar can easily be found for the avatars of the algebraic class of combinatorial structures (Dyck words, Motzkin paths, trees of fixed degree,...), all of which can be interpreted as trees. |M| words (e.g. a polynomial number of such words) can be extremely timeconsuming (typically requiring exponential-time in n). Finally, it is worth noticing that, in non-degenerate context-free languages, the weight of the least probable word ω ∇ n grows like Θ(α n ), α < 1, where the exact value of α depends on a subtle trade-off between structural properties of the language and its weight function π. In particular, α can become arbitrarily close to 0, by adequately increasing the weight π(t) of some terminal symbols. Sampling k = |L(G π ) n | words (Coupon Collector) then requires an expected Ω(α -n ) number of calls to draw, since the waiting time of the least probable word is clearly a lower-bound for the full collection. Since the number of words in a context-free language is bounded by |Σ| n and does not depend on the weight, then the average cost per generation may grow exponentially on n. This observation generalizes to many weighted languages, as shown by in Boisberranger et al [START_REF] Jérémie Du Boisberranger | The weighted words collector, 23rd Intern[END_REF].

A step-by-step recursive algorithm

A common approach to random generators for combinatorial objects [START_REF] Flajolet | Calculus for the random generation of labelled combinatorial structures[END_REF][START_REF] Denise | Random generation of words of context-free languagesaccording to the frequencies of letters[END_REF] consists of treating non-terminal symbols as independent generators. For instance, generating from an union-type non-terminal N → N ′ .N ′′ , involves two independent calls to dedicated generators for N ′ and N ′′ , either directly (Boltzmann sampling), or after figuring out suitable lengths for N ′ and N ′′ (Recursive method). Unfortunately, avoiding a predefined set of words breaks the independence assumption.

For instance, consider an unweighted grammar G, having axiom N , and rules:

N → N ′ .N ′′ , N ′ → a | b, and
N ′′ → a | b.
Remark that, starting from either N ′ or N ′′ , both the recursive method and Boltzmann sampling would chose one of the rules with probability 1/2. Assume now that some set F = {aa} has to be avoided, and that a sequential choice of derivations is adopted such that N ′ is fully derived before taking N ′′ into consideration. In this case, the derivation N ′′ → a must be forbidden iff N ′ → a was chosen. Moreover, the probabilities assigned to the derivations of N ′ must reflect the future unavailability of some choices for N ′′ . One possibility is to use altered probabilities such that {N ′ → 1/3 a, N ′ → 2/3 b}, and introduce conditional probabilities such that {N ′′ → 0 a, N ′′ → 1 b} when N ′ → a, and

{N ′′ → 1/2 a, N ′′ → 1/2 b} when N ′ → b.
The idea behind our step-by-step algorithm is to capture this dependency sequentially, by considering random generation scenarios as random (parse) walks. This perspective allows to determine the total contribution of all forbidden (i.e. previously encountered) words for each of the locally-accessible alternatives. These contributions can then be used to modify conditionally the precomputed probabilities, leading to an uniform (resp. weighted) generation within L(G) n /F , while keeping the computational cost to a reasonable level.

Immature words: A compact description of fixed-length sublanguages

Let us introduce the notion of immature words, defined as words on both the terminal and non-terminal alphabets, where prescribed lengths are additionally attached to any occurrence of a symbol. Formally, let G = (Σ, N , P, S) be a context-free grammar, then an immature word is any word

ω ∈ L ⊳ (G) ⊆ (Σ ∪ N ) × N + * ,
where L ⊳ (G) is the set of immature words generated from the axiom S. Such words may contain non-terminal symbols, and potentially require some further derivations before becoming a word on the terminal alphabet, or mature word. Intuitively, immature words correspond to intermediate states in a random generation scenario.

The language associated with an immature word ω is derived from the languages of its symbols through

L(ω) = i∈[1,|ω|] sm=ωi L(s) m (4)
where L(s) is defined as in Equation 1 with s ∈ N , and naturally extended on terminal symbols t ∈ Σ through L(t) = {t}. In the following, we use the notation π(ω) as a natural shorthand for π(L(ω)) and denote by π F (ω) := π(L(ω) ∩ F ) the total weight of all forbidden words in L(ω).

π F (abaS 1 S 5 ) p 1 p 2 p 3 p 1 = π(abaS 5 S 1 ) -π(abaS 5 S 1 ) π(abaU 6 ) -π(abaU 6 ) p 2 = π(abaS 3 S 3 ) -π(abaS 3 S 3 ) π(abaU 6 ) -π(abaU 6 ) p 3 = π(abaS 1 S 5 ) -π(abaS 1 S 5 ) π(abaU 6 ) -π(abaU 6 ) = π(abaaabbbb) π(abaU 6 ) -π(abaU 6 ) = π(abaabbabb) π(abaU 6 ) -π(abaU 6 ) = π(ababababb) π(abaU 6 ) -π(abaU 6 ) ∝ π(L(abaS 5 S 1 ) -F ) ∝ π(L(abaS 3 S 3 ) -F ) ∝ π(L(abaS 1 S 5 ) -F )
Figure 2: Snapshot of a step-by-step random scenario for the language consisting of prefix notations of binary trees of length 6, generated while avoiding F . The step-by-step algorithm chooses one out of three possible derivations for abaU 6 using probabilities proportional to the overall weights of accessible/admissible words.

Random generation as a random walk in language space

An atomic derivation, starting from a word ω = ω ′ . N . ω ′′ ∈ {Σ ∪ N } * , is the application of a production N → X to ω, that replaces N by the right-hand side X of the production, yielding ω ⇒ ω ′ .X.ω ′′ . Let us call derivation policy a deterministic strategy that points, in an immature word, to some non-terminal to be rewritten through an atomic derivation. Formally, a derivation policy is a function φ :

L(G) ∪ L ⊳ (G) → N ∪ {∅} such that φ : ω ∈ L(G) → ∅ ω ′ ∈ L ⊳ (G) → i ∈ [1, |ω ′ |] such that ω i ∈ N .
The unambiguity of a grammar requires that any generated word be generated by a unique sequence of derivation. A sequence of atomic derivations is then said to be consistent with a given derivation policy if the nonterminal rewritten at each step is the one pointed by the policy. This notion provides a convenient framework for defining the unambiguity of a grammar without explicit reference to parse trees. Definition 4.1 (Unambiguity). Let G = (Σ, N , P, S) be a context-free grammar and φ a derivation policy acting on G. The grammar G is said to be unambiguous if and only if, for each ω ∈ Σ * , there exists at most one sequence of atomic derivations that is consistent with φ and produces ω from S.

Any derivation leading to a mature word ω ∈ L(G) in an unambiguous grammar G can then be associated, in a one-to-one fashion, with a walk in the space of sublanguages associated with immature words, or parse walk, taking Algorithm 3 Step-by-step random generation algorithm. G π is a weighted grammar, ω an immature word, µ = π(ω) is the precomputed weight of the language generated from ω, and F ⊂ L(ω) is a set of forbidden words. steps consistent with a given derivation policy φ. More precisely, such a walk starts from the axiom S and, for any intermediate immature word X ∈ L ⊳ (G), the derivation policy φ points at a position φ(X), where a non-terminal X k can be found. The parse walk can then be extended using one of the derivations acting on X k (See Figures 1 and2), until a mature word in Σ * is reached.

StepByStep(ω, µ, G π , F , φ) : if µ ≤ π F (ω) then return Error else if φ(ω) = ∅ then return ω {ω is a mature word, generation is over} 5: end if (ω ′ , N m , ω ′′ ) ← ω [1,φ(ω)-1] , ω φ(ω) , ω [φ(ω)+1,|ω|] r ← rand(µ -π F (ω)) {r is random, uniformly in [0, π(L(ω)/F ))} if N → N ′ | N ′′ then {Union type} µ ′ ← µ • π(N ′ m )/π(N m ) 10: r ← r -(µ ′ -π F (ω ′ .N ′ m .ω ′′ )) if r < 0 then return StepByStep(ω ′ .N ′ m .ω ′′ , µ ′ , G π , F ) else return StepByStep(ω ′ .N ′′ m .ω ′′ , µ • π(N ′′ m )/π(N m ), G π , F ) 15: end if else if N → N ′ . N ′′ then {Product type} for all i ∈ [1, n -1] do {Boustrophedon order 1, n -1, 2, n -2 . . .} µ i ← µ • π(N ′ i ) • π(N ′′ m-i )/π(N m ) r ← r -(µ i -π F (ω ′ .N ′ i .N ′′ m-i .ω ′′ )) 20: if r < 0 then return StepByStep(ω ′ .N ′ i .N ′′ m-i .ω ′′ , µ i , G π , F ) end if end for else if N → t then {Terminal

A step-by-step algorithm

Let us now describe and validate Algorithm 3, based on the recursive method introduced by Wilf [START_REF] Wilf | A unified setting for sequencing, ranking, and selection algorithms for combinatorial objects[END_REF], which uses the concepts of immature words to linearize the generation of words. More specifically, the algorithm draws a random word through a sequence of local choices (atomic derivations) using probabilities that are proportional to the cumulated weight of accessible non-forbidden words, as illustrated by Figure 2. To grant access to such weights in reasonable time, the cumulated weights of languages generated by non-terminals are precomputed recursively [START_REF] Denise | Controlled non uniform random generation of decomposable structures[END_REF], and a dedicated tree-like data structure is introduced to gain efficient access to the contribution of forbidden words. Proof. Let us start with some observations to simplify the proof. First, since µ = π(ω), then the variables µ ′ and µ i of Algorithm 3 respectively obey

µ ′ = π(ω) • π(N ′ m ) π(N m ) = π(ω ′ ).π(N m ).π(ω ′′ ) • π(N ′ m ) π(N m ) = π(ω ′ .N ′ m .ω ′′ ) (5)
µ i = π(ω) • π(N ′ i ) • π(N ′′ m-i ) π(N m ) = π(ω ′ .N ′ i .N ′′ m-i .ω ′′ ). ( 6
)
Secondly for any immature word ω, one has

π(ω) -π F (ω) = π(L(ω)) -π(L(ω) ∩ F ) = π(L(ω)\F ).
We now show that, provided that µ = π(ω) holds, then any word in L(ω) is generated with respect to a weighted distribution on L(ω)\F . Let d be the maximum number of recursive calls needed for the generation of a mature word from a given immature word ω, then one has:

Base: The d = 0 case corresponds to an already mature word ω, for which the associated language is limited to {ω}. In this case, ω has probability 1 in the weighted distribution, and is indeed always generated. Inductive step: Assuming that the theorem holds for d ≤ n, we investigate the probabilities of emission of words that require d = n + 1 derivations. Let N m be the non-terminal pointed by φ, then:

• N → N ′ | N ′′ : Let us first assume that the derivation N * m ⇒ N ′ m is chosen with probability µ ′ -π F (ω ′ .N ′ m .ω ′′ ) µ -π F (ω) = π(ω ′ .N ′ m .ω ′′ ) -π F (ω ′ .N ′ m .ω ′′ ) π(ω) -π F (ω) = π(L(ω ′ .N ′ m .ω ′′ )\F ) π(L(ω)\F )
.

The recursive call to StepByStep(ω ′ .N ′ m .ω ′′ , µ ′ , G π , F ) indeed satisfy µ ′ = π(ω ′ .N ′ m .ω ′′ )
, and subsequently generates a mature word x using at most n recursive calls. The induction hypothesis holds, and the emission probability of x ∈ L(ω ′ .N ′ m .ω ′′ )\F is therefore given by π(x)/π(L(ω ′ .N ′ m .ω ′′ )\F ). The overall probability of issuing x starting from ω is then

π(L(ω ′ .N ′ m .ω ′′ )\F ) π(L(ω)\F ) . π(x) π(L(ω ′ .N ′ m .ω ′′ )\F ) = π(x) π(L(ω)\F )
in which one recognizes the weighted distribution on L(ω)\F , and the argument applies symmetrically to

N ′′ m . • N → N ′ . N ′′ : A repartition N m ⇒ N ′ i . N ′′ m-i , i ∈ [1, m -1] is chosen with probability µ ′ -π F (ω ′ .N ′ i .N ′′ m-i .ω ′′ ) µ -π F (ω) = π(ω ′ .N ′ i .N ′′ m-i .ω ′′ ) -π F (ω ′ .N ′ i .N ′′ m-i .ω ′′ ) π(ω) -π F (ω) = π(L(ω ′ .N ′ i .N ′′ m-i .ω ′′ )\F ) π(L(ω)\F )
.

A recursive call is then made on an immature word ω ′ .N ′ i .N ′′ m-i .ω ′′ , using weight µ i . As established in Equation 6, one has µ i = π(ω ′ .N ′ i .N ′′ m-i .ω ′′ ), therefore the induction hypothesis applies, and any word x ∈ L(ω ′ .N ′ i .N ′′ m-i .ω ′′ ) is generated by the recursive call with probability

π(x) π(L(ω ′ .N ′ i .N ′′ m-i .ω ′′ )\F )
.

The emission probability of x ∈ L(ω ′ .N ′ i .N ′′ m-i .ω ′′ ) from ω is then given by π(L(ω ′ .N ′ i .N ′′ m-i .ω ′′ )\F ) π(L(ω)\F ) . π(x) π(L(ω ′ .N ′ i .N ′′ m-i .ω ′′ )\F ) = π(x) π(L(ω)\F )
.

• N → t: The emission probability for any word x emitted from ω equals that of the word issued from ω ′ .t.ω ′′ . It is then given by

π(x) π(L(ω ′ .t.ω ′′ )\F ) = π(x)
π(L(ω)\F ) according to the induction hypothesis, which applies since π(ω ′ .t.ω ′′ ) = π(ω ′ .N.ω ′′ ).

Complexities and data structures

The overall complexity of Algorithm 3 depends critically on efficient algorithms and data structures for:

1. Accessing the weights of languages associated with non-terminals. 2. Computing the total weight π F (ω) := π(L(ω) ∩ F ) of all forbidden words accessible from an immature word ω.

Investigating the partitions N *

m ⇒ N ′ i . N ′′ m-i for product rules. 4. Handling large numbers.

Weights of non-terminals

As is usual within the recursive approach [START_REF] Denise | Random generation of words of context-free languagesaccording to the frequencies of letters[END_REF], the total weights π(N i ) of languages generated from each non-terminal N must be readily available during the generation at generation time. A precomputation of these numbers can be performed in Θ(n) arithmetic operations, thanks to the algebraic, therefore holonomic, nature of the weighted counting generating functions. Indeed, the coefficients of an holonomic generating function obey a linear recurrence with polynomial coefficients in n. Such a recurrence can be algorithmically determined from the system of functional equations induced by the context-free grammar (e.g. using the Maple package GFun [START_REF] Salvy | Gfun: a maple package for the manipulation of generating and holonomic functions in one variable[END_REF]). Proof. Let us first remark that, in any BCNF grammar, any parse walk p n that produces a mature word of length n, involves Θ(n) derivations (i.e. has length in Θ(n)). To that purpose, let us discuss the number of occurrences of each type of rules in p n , by reasoning on the associated parse tree. First, let us observe that each letter in the mature word can be bijectively associated with the application of a terminal rule, thus p n contains exactly n applications of terminal rules. Then, product rules induce a binary structure in the parse tree, whose leaves correspond to the n terminal letters. Therefore, p n contains exactly n-1 applications of product rules. Finally, sequences of union-type rules can be found before any occurrence of a product or terminal rule. However, it should be noted that the unambiguity of the grammar forbids derivations of the form N ⇒ * N . The length of any union-type derivations sequence therefore cannot exceed |N | + 1. Treating |N | as a constant, the total number of occurrences of union rules is then in O(n), and we conclude that the total number of derivations involved in p n is indeed Θ(n). Assume now that the parse walks of the elements of F are available as a set T of sequences of immature words. We introduce a data structure, the weighted tree of forbidden walks, a decorated prefix-tree whose nodes are in bijection with the set of immature words in T , and such that the overall weight π F (ω) := π(L(ω) ∩ F ) is attached to each node labeled ω.

A data structure for forbidden words

The idea is to descend into the tree during the execution of Algorithm 3, simply fetching the precomputed contributions π F (ω) of forbidden words, that are attached to local nodes. Implementation-wise, an argument g is added to Algorithm 3 (omitted in the pseudocode for the sake of readability), holding the node associated with ω if any, or ∅ otherwise. One then gets access in O(1) operations to the forbidden weight π F (ω) of ω, and in O(log(n)) to that of its children nodes π

F (ω ′ .N ′ .ω ′′ ), π F (ω ′ .N ′′ .N ′′ m-i .ω ′′ ), or π F (ω ′ .N ′ i .N ′′ m-i .ω ′′
), e.g. using AVL trees [START_REF] Adelson-Velskii | An algorithm for the organization of information[END_REF] to store the children of a node. Once an atomic derivation ω ⇒ ω ′ is chosen at random, the suitable child g ′ of g (or ∅, if no word from F can be computed from ω), is fed to the recursive call.

A tree update operation must then be performed, as illustrated by Figure 3:

• First, a top-down stage descends into the tree, ensuring efficient access to π F (ω), until a new mature word w d is generated. Absent nodes are then added, corresponding to the proper suffix of the parse walk (Blue nodes).

At each step, one needs to test the presence/absence of a given immature word within the children of the current node. Since the degree of a node is bounded by Θ(n), then this operation can be performed in Θ(log(n)) time, using a dedicated AVL tree to store the children of a node. The total time complexity of a single top-down descent is therefore in Θ(n log(n)) basic instructions.

• Then, a unique new weight π F (w d ) is created and attached to the nodes in the proper suffix of the parse walk (Blue nodes). A bottom-up stage propagates the weight of the generated (mature) word to his ancestors, all the way up to the root. The weights associated with branching nodes along the path are incremented by π F (w d ). Since Θ(n) nodes can be found from the leaf to the initial immature word S n , then the complexity of this stage is at most in Θ(n) arithmetic operations.

Note that the immature words used to label each node do not require an explicit encoding (which may otherwise result in a Θ(n 2 ) time complexity). Indeed, the immature words found on consecutive nodes may only differ on at most two positions, owing to the binary nature of products. Therefore, one may only store the difference between consecutive immature words, leading to a space complexity in Θ(|F |•n) bits. By the same token, the memory requirement can be limited to 2 • |F | large numbers, by observing that a unary node and its unique successor have same value for π F (•), and that the memory representation this number can be shared.

Boustrophedon order for product non-terminals

For product-type non-terminal rules, one may possibly have to investigate Θ(n) possible candidate partitions of the length, leading to a worst-case complexity in Θ(n 2 ) arithmetic operations. Therefore, we use a Boustrophedon order [START_REF] Flajolet | Calculus for the random generation of labelled combinatorial structures[END_REF] (1, n -1, 2, n -2, . . .) to investigate possible decompositions N m ⇒ N ′ i .N ′′ m-i . As previously shown [START_REF] Flajolet | Calculus for the random generation of labelled combinatorial structures[END_REF], this simple device reduces the total number of execution of the body of the innermost loop (Algorithm 3, line 18) to O(n log(n)) in the worst case scenario.

Arbitrary precision arithmetics

Although efficient algebraic generators exist even for some classes of transcendent probabilities [START_REF] Flajolet | On buffon machines and numbers[END_REF], it is reasonable, for all practical purpose, to assume that weights are provided as floating point numbers of bounded (yet arbitrarily large) precision. Since the language is context-free, the numbers involved in the precomputations of N i and in the tree of forbidden words scale like O(α n ) for some explicit α. It follows that operations performed on such numbers may take time O(n log(n) log log(n)) [START_REF] Van Der Hoeven | Relax, but don't be too lazy[END_REF], while the space occupied by their encoding grows like O(n).

Non-redundant unranking algorithm

As an alternative approach, let us propose a weighted unranking algorithm, which consists in two distinct parts:

• An unranking algorithm for generating words from a weighted context free grammar, presented in Section 5.1

• An algorithm that samples random numbers uniformly within a gapped union of intervals, to be used in the unranking algorithm to ensure nonredundant generation, presented in Section 5.2.

Our main result is summarized by the following theorem.

Weighted Unranking algorithm

Unranking algorithms, formalized by Wilf [START_REF] Wilf | A unified setting for sequencing, ranking, and selection algorithms for combinatorial objects[END_REF], usually take as input a rank in the interval [0, |L|), for |L| the number of words in a language, and output a word from the language that is uniquely associated to this rank according to some predefined ordering. It follows that calling an unranking procedure, starting from a uniformly-generated rank, immediately gives a uniformly generated random object.

Generic unranking algorithms have been proposed for the uniform generation of words from a context-free language [START_REF] Martinez | A generic approach for the unranking of labeled combinatorial classes[END_REF]. Through grammar transformations aiming at the introduction a controlled ambiguity, Weinberg and Nebel [START_REF] Weinberg | Non Uniform Generation of Combinatorial Objects[END_REF] extended their construct to special cases of non-uniform generation. For the sake of self-completeness, we reformulate, and mildly generalize, the above algorithms.

Statement of the problem

For a given length n, let us assume a total ordering on the words in L(S) n , and denote by w 1 , . . . , w |L(S)| the ordered list of words in L(S) n . One can then split the interval [0, π(L(S))[ into |L(S)| pieces of width π(w 1 ), π(w 2 ), . . . , π(w |L(S)| ) respectively, each piece being associated to a particular word. Denoting the j-th interval by I j , one has

I j = j-1 k=1 π(w k ), j k=1 π(w k ) .
The goal of our generalized unranking is to take as input a number r ∈ [0, π(L(S))[, to figure out the interval I j = [L j , R j [ such that L j ≤ r < R j , and to return the corresponding word w k . Upon starting the unranking procedure from a uniformly generated random real number in [0, π(L(S))[, this word is to be selected with probability proportional to the width of its interval, i.e. its weight. It follows that the whole procedure constitutes a random generation algorithm for the weighted probability distribution presented in Equation 2.

Total ordering for words of length n

For each non-terminal N ∈ N , let us introduce a dedicated order relation • N •, defining an arbitrary notion of precedence on L(N ) m≤n the set of words of length m generated from N . For the sake of simplicity, let us write A N B as a shorthand for a N b, ∀(a, b) ∈ A × B. The order relation • N • is defined by w N w, ∀w ∈ L(N ) m≤n , and recursively defined by:

• Union type N → N ′ | N ′′ . Then, ∀m ≤ n, one has: -L(N ′ m ) N L(N ′′ m ); -∀w 1 , w 2 ∈ L(N ′ m ) (resp. L(N ′′ m )), w 1 N w 2 iff w 1 N ′ w 2 (resp. w 1 N ′′ w 2 ). • Product type N → N ′ .N ′′ . Then, ∀m ≤ n, ∀j, j ′ ∈ [1, m -1], one has: -If j < j ′ , then L(N ′ j .N ′′ m-j ) N L(N ′ j ′ .N ′′ m-j ′ ); -If j = j ′ then ∀(u, v), (u ′ , v ′ ) ∈ L(N ′ j ) × L(N ′′ m-j ): * If u N ′ u ′ , then u.v N u ′ .v ′ ; * If u = u ′ , then u.v N u ′ .v ′ iff v N ′′ v ′ .
• Terminal type N → t: L(N n ) = {t}, and one has t N t.

Let us then denote by • r • := • S • the order induced on the language generated by the axiom S of the grammar. It is easily verified that • r • constitutes a total order over L(S n ).

Ranking algorithm

Let x ∈ R + be a positive real number, and I = [L, R[⊂ R an interval, let us overload the sum operator through I + x := [L + x, R + x[ for the sake of simplicity. Then an algorithm Rank for computing the ranking interval of any word w ∈ L(N ) n can be outlined as:

π(N ′ i-2 ) π(N ′′ n-i+2 ) π(N ′ i-1 ) π(N ′′ n-i+1 ) π(N ′ i ) π(N ′′ n-i ) L ′ R ′ L ′′ R ′′ π(w ′′ ) π(w ′ )
Figure 4: Water filling illustration of the ranking/unranking principle for the • r • order in product type non-terminals. Each word w ′ .w ′′ ∈ L(N ′ i .N ′′ n-i ) is uniquely associated with a rectangular compartment of total area π(w ′ ) • π(w ′′ ). The ranking of a word w = w ′ .w ′′ can be adequately compared to the interval on the volume of water (in blue), which upon injection in the matrix, partly fills the compartment associated with w, assuming a water flow in a left-to-right/top-to-bottom lexicographic order. The unranking stage simply consists in searching for the compartment which is partly filled upon injection of a given volume r.

• Union type N → N ′ | N ′′ : if w ∈ N ′ n then return Rank(w, N ′ n ). Otherwise w ∈ N ′′ n , and return π(N ′ n ) + Rank(w, N ′′ n ).
• Product type N → N ′ .N ′′ : Since the grammar is unambiguous, then there only exists one decomposition w = w ′ .w ′′ such that w ′ ∈ L(N ′ ) and w ′′ ∈ L(N ′′ ). Let us then define

[L ′ , R ′ [ := Rank w ′ , N ′ |w ′ | and [L ′′ , R ′′ [ := Rank w ′′ , N ′′ |w ′′ |
As illustrated by Figure 4, the returned interval must then be

[L, R[:=   |w ′ |-1 i=1 π(N ′ i .N ′ n-i ) + L ′ • π(N ′′ n-i ) + L ′′ • π(w ′ ), L + π(w ′ ) • π(w ′′ )   .
• Terminal type N → t: Return [0, π(t)[.

Unranking algorithm

Let us now turn to Algorithm 4, which implements unranking for the relation • r • and mostly consists in inverting the calculation presented in the Section 5.1.3.

, I R [ Unrank(N m , r): if N → N ′ | N ′′ then {Union type} if r < π(N ′ m ) then return Unrank(N ′ m , r) else 5: (w ′′ , [I L , I R [) =Unrank(N ′′ m , r -π(N ′ m )) return (w ′′ , [I L + π(N ′ m ), I R + π(N ′ m )[) end if else if N → N ′ .N ′′ then {Product type} L ← 0 10:
for all i ∈ [1, m -1] do if π(N ′ i ) • π(N ′′ m-i ) ≤ r then r ← r -π(N ′ i ) • π(N ′′ m-i ) L ← L + π(N ′ i ) • π(N ′′ m-i ) else {Found the right decomposition} 15: (w ′ , [L ′ , R ′ [) = Unrank(N ′ i , r π(N ′′ m-i ) ) (w ′′ , [L ′′ , R ′ [) = Unrank N ′′ m-i , r-L N ′ •π(N ′′ m-i ) π(w ′ ) I L = L + L ′ • π(N ′′ n-i ) + L ′′ • π(w ′ ) I R = I L + π(w ′ ) • π(w ′′ ) return (w ′ .w ′′ , [I L , I R [) 20: end if end for else if N → t then {Terminal type} return (t, [0, π(t)]) end if
Sketch of proof. First let us outline a proof of correctness by induction for the unranking procedure, starting from the initial case of terminal rules, where the algorithm returns the only word t, associated with an interval [0, π(t)[.

In the case of union rules, one either need to remove the added contribution π(N ′ m ) when r ≥ π(N ′ m ) before proceeding to unrank within L(N ′′ m ), or directly unrank within L(N ′ m ) otherwise. For products rules, one first remarks that

|w ′ |-1 i=1 π(N ′ i .N ′ n-i
) is exactly the quantity computed within L in section 5.1.3, so one is left to ensure that the remaining part of r indeed generates its corresponding word. Namely, let us assume that w = w ′ .w ′′ ∈ L(N ′ i .N ′′ n-i ), where w ′ and w ′′ are associated with intervals

[L ′ , L ′ + π(w ′ )[ in L(N ′ i ) and [L ′′ , L ′′ + π(w ′′ )[ in L(N ′′ n-i ) respectively. Therefore the interval associated with w (after subtraction of L) is I = [x, x + π(w ′ ) • π(w ′′ )[ with x := L ′ • π(N ′′ n-i ) + L ′′ • π(w ′ ).
Therefore computing, as done by Algorithm 4, the quantity r ′ := r/π(N ′′ m-i ) for any r ∈ I gives

L ′ + L ′′ π(N ′′ n-i ) • π(w ′ ) ≤ r ′ < L ′ + (L ′′ + π(w ′′ )) π(N ′′ n-i ) • π(w ′ ).
Since L ′′ is a partial sum of the weights in L(N ′′ n-i ), one has 0

≤ L ′′ ≤ π(N ′′ n-i )- π(w |L(N ′′ n-i )|
) and both bounds are tight (reached by the first and last words). It follows that

L ′ ≤ r ′ < L ′ + π(w ′ )
in which one recognizes the interval associated with w ′ within L(N ′ i ). The recursive unranking on L(N ′′ i ) is given as argument r ′′ :=

r-L ′ •π(N ′′ m-i ) π(w ′ ) which, for r ∈ I, gives L ′′ ≤ r ′′ < L ′′ + π(w ′′ )
in which one recognizes the interval associated with w ′′ within L(N ′′ i ). We conclude on the correctness of the algorithm by reminding that the unambiguity of the grammar prevents multiple parsings (i.e. different intervals) to contribute to the generation of a given word.

The complexity of the algorithm is established by the following observations:

• The numbers π(N m ) involved in the unranking procedure can be precomputed thanks to the existence of linear recurrences for the coefficients of holonomic generating functions, as discussed in Section 4.5.1. They can then be precomputed in Θ(n) arithmetic operations, requiring storage for |N | • Θ(n) large numbers.

• The order of investigation of possible decompositions can be modified in Algorithm 4, line 10 to adopt a Boustrophedon order as discussed in Section 4.5.3, decreasing the worst-case complexity of the algorithm from O(n 2 ) to O(n log(n)) in the worst-case. The total ordering on words can then be redefined to account for such a change, and the proof of correctness is easily adapted.

Random generation of numbers in gapped intervals

In the previous section, a simple weighted unranking algorithm was proposed. Therefore by generating a random number r uniformly in [0, π(L)[, and using the Unranking algorithm, a word w can be generated with respect to the weighted distribution over a language L. However when a forbidden set F is given, one additionally needs to avoid any interval associated with a forbidden word. In other words, one can no longer draw a random number uniformly in [0, π(L)[, but rather in

I F := ∪ w / ∈F I w = [0, π(L)[\(∪ w∈F I w ).
Since the intervals I w are mutually disjoint subsets of [0, π(L)[, a possible strategy consists in drawing a random number r ∈ [0, π(L)π(F )[, and increment r by some quantity δ r,F that sends r + δ r,F into I F . Considering Figure 5, one observes that δ r,F can be inductively defined as the total weight of all forbidden words smaller than the word found at r + δ r,F . In general, one could order the forbidden words in F and traverse F to compute δ r,F , but this would 0 π(L) Algorithm 5 ModRandom: Takes a uniform random number and a node, and returns a uniform random number that avoids any interval associated with already generated words.

0 π(L/F )
ModRandom(r, v) if v = ∅ then return r end if (T L , T R , w, [L w, R w [, µ w ) ← v 5: if r < L w -µ w then ModRandom(r, T L ) else ModRandom(r + µ wi + π( wi ), T R ) end if
induce spending an additional O(|F |) arithmetic operations per generation. For this reason, the intervals of forbidden words are gathered in a balanced binary tree structure that grants access to δ r,F in O(log(|F |)) operations.

AVL tree for forbidden intervals

For each (word, interval) pair produced by the unrank algorithm, a corresponding node is inserted into an AVL tree [START_REF] Adelson-Velskii | An algorithm for the organization of information[END_REF], i.e. a self-balancing binary search tree, whose height after k insertions can be limited to Θ(log(k)) through balancing operations. Since the intervals associated with the forbidden set are non overlapping, then they can be compared and therefore stored within an AVL tree. It follows that the insertion and lookup of k intervals can be performed in Θ(k log(k)) comparisons in the worst-case scenario.

Let us then define recursively our tree as either the empty tree, denoted by ∅, or a 5-tuple v = (T L , T R , w, I w , µ w) where:

• T L and T R are respectively the left and right children of the tree. Both can possibly be empty trees.

• w and I w := [L w, R w [ are a forbidden word and its corresponding interval.

• µ w is the total weight of forbidden intervals in the left subtree.

Let us remind that the nodes of an AVL tree are such that any node in a left subtree is less than or equal to its root, itself being less than or equal to any node of its right subtree. Also let us remark that, upon inserting in a tree v w a new word w′ = w associated with an interval I w′ = [L w′ , R w′ [), the value µ w , initialized at 0, can be easily updated into a new value µ ′ w such that µ ′ w = µ w + π( w) If w′ r w, i.e. w′ is inserted in the left subtree T L of v µ w Otherwise (7) Assuming the tree is correctly built, Algorithm 5 simply descends into the tree, and computes δ r,F incrementally. For a given node v = (T L , T R , w, I w , µ w ), the algorithm determines if r corresponds to a word in the interval covered by T L , by comparing r to L wµ w the total mass of allowed words in T L . If smaller, then r remains unmodified and the algorithm is run recursively on T L . If greater, then the final interval reached by r is greater than I w , and fits in the right subtree T R . The value r is then incremented by the total mass µ w + π( w) of forbidden words smaller than T R , and this value is used within a recursive call on T R . This process is terminated when the empty tree ∅ is reached, and the current value of r is returned. In other words, the returned value r is distant from its original value by the sum of weights µ w on the left subtrees whose intervals are dominated by r, in which one recognizes the definition of δ r,F . Proof. The outline of the proof is as follows: First we establish a technical invariant on the subset of values passed to Algorithm 5. Using this invariant, we show that the final value returned by ModRandom avoids every forbidden interval, and that any interval can be reached. Let us start with some notations, followed by a technical lemma. Let v i be the i-th node in the tree and let us denote by [a, . . . , i, . . . , b] the indices of nodes accessible from v i . Then let us denote by H i the interval that is dominated by v i , defined as

Correctness

H i = R wa-1 , L wb+1 - b k=a π( wk ) where R wi , i ∈ [1, |F |], the upper bound (resp. L wi , i ∈ [1, |F |],
the lower bound) of the forbidden interval of index i is extended by R w0 = 0 (resp. L w|F| = π(L)).

Lemma 5.4. Let v i = (T L , T R , w, [L wi , R wi [, µ w ) be a node in the tree. Then the set of values r passed as argument to ModRandom jointly with v i is exactly H i .

Proof. Let us prove this claim by induction on the depth D of recursive calls. Clearly in the initial call (D = 0), v i is the root node and H i is the whole interval [0, π(L)π(F )[ from which r is drawn uniformly, so our claim holds. Assume now that the set of possible values for r is exactly H i := [R wa-1 , L wb+1b k=a π( wk )[ at a given depth D = M , then let us investigate the recursive calls. Two cases arise, depending on the value of r:

• When r ∈ A = [R wa-1 , L wi -µ wi [, then ModRandom is called on v j :=
T L with unmodified value r ′ := r. Thanks to the binary search tree structure, the indices of the forbidden nodes on the left subtree are [a, . . . , i-1],

and

H j = [R wa-1 , L wi - i-1 k=a π( wk )[. Since µ wi = i-1
k=a π( wk ) (def.), then H j = A, and any value r ′ ∈ H j can therefore be passed to the subsequent call.

B ′ = L wi + π( wi ), L wb+1 - b k=a π( wk ) + i-1 k=a π( wk ) + π( wi ) = R wi , L wb+1 - b k=i+1 π( wk ) = H j .
Finally, since r can be any value in B, then any value r ′ ∈ H j can be passed to ModRandom for some value r ∈ B.

Consequently at depth D = M +1, the values r ′ provided to ModRandom over a subtree v j are exactly H j , and this property therefore holds for any D ≥ 0.

Let us show that forbidden intervals are indeed avoided. Let us consider a node v i = (T L , T R , w, [L w , R w[, µ w ), giving rise to a call ModRandom(r ′ , ∅), itself returning the final value. Since, for this node, Lemma 5.4 holds, then the value passed to this call is any r ∈ [R wi-1 , L wi+1π( wi )[. Therefore either r < L wi and r ∈ [R wi-1 , L wi [ is returned, or r ≥ L wi and r+π( wi ) ∈ [R wi , L wi+1 [ is returned. It follows that any returned value r ′ falls between two consecutive forbidden intervals (resp. within the ending intervals [0, L w1 [ or [R w|F| , π(L)[), and therefore cannot fall in a forbidden interval.

Furthermore let us prove that any two calls ModRandom(r ′ , ∅) and ModRandom(r ′′ , ∅) from v i and v j respectively, i = j, give rise to distinct intervals. Recall that, as pointed out in the previous paragraph, the possibly generated intervals from a node v i are [R wi-1 , L wi [ if T L = ∅, and [R wi , L wi+1 [ if T R = ∅. Therefore, by contradiction, any two calls giving rise to similar intervals would have to involve consecutive nodes v i and v i+1 such that the right subtree v i is T Ri = ∅ and the left subtree of v i+1 is T Li+1 = ∅. Since such two nodes would represent consecutive values, then one would appears in a subtree of the other, otherwise the first common ancestor v j of v i and v i+1 would be such that v i < v j < v i + 1 and the two nodes would not be consecutive. Since v i < v i+1 , then either v i would be found in the left subtree of v i+1 (and then T Li+1 = ∅), or v i+1 would be found in the right subtree of v i (and then T Ri = ∅). Both situations contradict the premisses, thus any interval

[R wi-1 , L wi [, i ∈ [1, |F | + 1]
is generated by at most a call over a single empty tree node ∅.

We conclude with the remark that there are exactly |F |+1 leaves in a binary tree with |F | inner nodes. Since there are also

|F | + 1 intervals [R wi-1 , L wi [, i ∈ [1, |F | + 1]
which are generated by at most one leave, then any such interval is generated, and ModRandom is therefore a bijection of [0, π

(L) -π(F )[ into ∪ |F |+1 i=1 [R wi-1 , L wi [= [0, π(L)[\(∪ |F | i=1 I wi ).
Finally, since the map ModRandom involves only shifts and no scaling, it follows that the map is measure preserving. Thus the algorithm alters uniformly generated random numbers over

[0, π(L) -π(F )[ into uniform random numbers over [0, π(L)[\(∪ |F | i=1 I wi ).

Complexity considerations

As can be seen in Equation 7, updating the values µ v in a tree with m nodes can be done in O(log(m)) arithmetic operations upon insertion of a new node. However the AVL structure also requires a post-processing consisting of O(log(m)) shifts to keep the tree balanced. The shift operation involves taking two nodes v i < v j that are connected in the tree and switching their ancestrality. Namely, if v i was the first node of the left subtree of v j , then v j becomes become the first node of the right subtree of v i (and vice-versa). The effect of this operation is local, therefore in any pair (v i , v j ) of nodes inverted by a shift operation, the values µ vi and µ vj can be updated in O(1) arithmetic operations, and the overall cost of k insertions remains in O(k log(k)) arithmetic operations.

Each internal node maintains a possibly large number µ, therefore Θ(|F |) numbers need be stored in the tree. The ratio of probability between the most and least probable structure grows like Ω(α n ), therefore at least Θ(n) bits needs be used for the numbers.

Conclusion and perspectives

We addressed the random generation of non-redundant sets of sequences from context-free languages, while avoiding a predefined set of words. We first investigated the efficiency of a rejection approach. Such an approach was found to be acceptable in the uniform case. By contrast, for weighted languages, we showed that for some languages the expected number of rejections would grow exponentially on the desired number of generated sequences for at least two parameters. Furthermore, we showed that in typical context-free languages and for fixed length, the probability distribution can be dominated by a small number of sequences. We proposed a first algorithm for this problem, based on the recursive approach. The correctness of the algorithm was demonstrated, and its efficient implementation discussed. This algorithm was showed to perform a non-redundant generation of k distinct structures in O(k • n log(n)), after a precomputation in Θ(n • |N |) arithmetic operations, and requires storage of O(n • |N | + k) large numbers, and a data structure consisting of Θ(n • k) nodes. We explored a second approach, based on a ranking/unranking approach for the same task, and obtained an algorithm in O(n • |N | + k • n log n) complexity, with the slightly decreased memory consumption of O(n • |N | + k) large numbers. These complexities hold in the worst-case scenario, and remain mostly unaffected by the magnitude of weights being used.

Different impact of fixed-precision arithmetics implementations

When using arbitrary (or sufficient) precision arithmetics, the complexity and storage of the two algorithms are the same. However, practical implementations may involve using fixed-precision arithmetic, in which case significant differences between the two methods arise. The complexity of both algorithms can be improved significantly if one uses fixed-precision arithmetic. However, in both cases, the algorithms suffer from a quantifiable loss of precision.

If the ratio between the weight of the smallest word and the weight of the language is small, then built-in floating point operations may be used, giving some advantages to the unranking approach with respect to its memory consumption. Indeed, the cost of storing the data structure will then dominate the memory consumption of the recursive version (O(n • |N | + n • k)), while the memory complexity of the unranking algorithm gently decreases to (O(n • |N | + k)).

However, we believe the recursive method to be more stable numerically than the unranking approach. Indeed, the weights accessible on the alternative choice in the usual generation are typically comparable. Therefore, it will typically take an large number of generations for the recursive algorithm to fully deplete one of the alternatives. By contrast, the unranking algorithm may very quickly isolate a poorly contributing set of words after very few generation. For instance, if the second word in the ordering is generated first, then the data structure may practically forbid the first element, choosing it with 0 probability because of the rounding error. This point therefore seems favorable to the recursive algorithm.

Perspectives

Let us briefly outline a few perspectives to the current work:

• Decomposable structures: One natural extension of the current work concerns the random generation of the more general class of decomposable structures [START_REF] Flajolet | Calculus for the random generation of labelled combinatorial structures[END_REF]. Indeed, such aspects like the pointing and unpointing operator are not explicitly accounted for in the current work. Furthermore, the generation of labeled structures might be amenable to similar techniques in order to avoid a redundant generation. It is unclear, however, how one may extend the notion of parse tree in this context. Intrinsic ambiguity issues might arise, for instance while using the unranking operator.

• Non-redundant Boltzmann sampling. Another direction for an efficient implementation of the non-redundant generation may rely on an extension of Boltzmann samplers [START_REF] Duchon | Boltzmann samplers for the random generation of combinatorial structures[END_REF]. Indeed, the prefix-tree introduced by the step-by-step algorithm could, in principle, be used as is to correct the probabilities used by Boltzmann sampling. However, it is unclear how such a correction may impact the probability of rejection, and consequently degrade the performances of the resulting algorithm.

• Accommodating general sets of forbidden words. Both the stepby-step and unranking algorithms require the preliminary insertion of the forbidden set F into a dedicated data structure (prefix tree/AVL tree), both requiring the parse trees/walks of any word in F to be available.

When such an information is not available, one could in principle parse the words in F to build the tree. In general this may require F run of a n 3-ε parsing algorithm, leading to an impractical O(n 3-ε • |F |) complexity. In practice, it seems more fruitful to simply run the algorithm starting from an empty tree, and to test after each generation if the generated word is found in F . If so, reject it after adding its parse walk, available to the algorithm without further computation since the word was just created, to the tree. Since this update is made at most once for each word in F , then the worst-case complexity of generating k words remains bounded by O(|F | • n log(n)) arithmetic operations.

• Finally, step v) removes extraneous unary non-terminals: P N = {(N → N ′ . N ′′ )}, or P N = {(N → N ′ ), (N → N ′′ )}, N ′ , N ′′ ∈ N .

The derivation rules available for the set of non-terminals, created during the transformation, are initially in BCNF. Note that the only modification performed on productions of new non-terminals substitute a non-terminal for another, thereby keeping the rules BCNF-compliant. Finally, the constraint on the initial CNF guarantees that the only epsilon rule is derived from the axiom, either in a single production or through a sequence of non-referential productions created at step iv). Therefore one concludes that the produced grammar is indeed in BCNF.

The proposed transformation from a CNF to an equivalent BCNF can be implemented in linear time, through a careful ordering of the removals performed by step v), and the number of rules is at most increased by a constant factor.

Proposition 3 . 1 (

 31 Correctness of a naive rejection algorithm). Any word returned by Algorithm 2 is drawn with respect to the weighted distribution on L(G) n \F .

1 a 1 a 1 a a a a b b b b b

 111 S 1 S 5 a b a S 3 S 3 a b a S 5 S 1 a b a b S 5 a b a b T 5 a b a b a U 4 a b a b a S 1 S 3 a b a b a S 3 S 1 a b a b a b S 3 a b a b a b T 3 a b a b a b a U 2 a b a b a b a S 1 S 1 a b a b a b a b S 1 a b a b a b a b b a b a b a T 3 S 1 a b a b a a U 2 S 1 a b a b a a S 1 S 1 S 1 a b a b a a b S 1 S 1 a b a b a a b b S 1 a b a b a a b b b a b a T 3 S 3 a b a a U 2 S 3 a b a a S 1 S 1 S 3 a b a a b S 1 S 3 a b a a b b S 3 a b a a b b T 3 a b a a b b a U 2 a b a a b b a S 1 S 1 a b a a b b a b S 1 a b a a b b a b b a b a T 5 S 1 a b a a U 4 S 1 a b a a S 1 S 3 S 1 a b a a S 3 S 1 S 1 a b a a b S 3 S 1 a b a a b T 3 S 1 a b a a b a U 2 S 1 a b a a b a S 1 S 1 S 1 a b a a b a b S 1 S 1 a b a a b a b b S 1 a b a a b a b b b a b a a T 3 S 1 S 1 a b a a a U 2 S 1 S 1 a b a a a S 1 S 1 S 1 S 1 a b a a a b S 1 S 1 S 1 a b a a a b b S 1 S 1 a b a a a b b b S b a S 1 S 3 a a b b a S 3 S 1 a a b b a b S 3 a a b b a b T 3 a a b b a b a U 2 a a b b a b a S 1 S 1 a a b b a b a b S 1 a a b b a b a b b a a b b a T 3 S 1 a a b b a a U 2 S 1 a a b b a a S 1 S 1 S 1 a a b b a a b S 1 S 1 a a b b a a b b S a b a U 2 S 1 a a b a b a S 1 S 1 S 1 a a b a b a b S 1 S 1 a a b a b a b b S 1 a a b a b a b b b a a b a T 3 S 1 S 1 a a b a a U 2 S 1 S 1 a a b a a S 1 S 1 S 1 S 1 a a b a a b S 1 S 1 S 1 a a b a a b b S 1 S 1 a a b a a b b b S 1 a a b a a b b b b a a T 3 S 3 S 1 a a a U 2 S 3 S 1 a a a S 1 S 1 S 3 S 1 a a a b S 1 S 3 S 1 a a a b b S 3 S 1 a a a b b T 3 S 1 a a a b b a U 2 S 1 a a a b b a S 1 S 1 S 1 a a a b b a b S 1 S 1 a a a b b a b b S 1 a a a b b a b b b a a T 5 S 1 S 1 a a a U 4 S 1 S 1 a a a S 1 S 3 S 1 S 1 a a a S 3 S 1 S 1 S 1 a a a b S 3 S 1 S 1 a a a b T 3 S 1 S 1 a a a b a U 2 S 1 S 1 a a a b a S 1 S 1 S 1 S 1 a a a b a b S 1 S 1 S 1 a a a b a b b S 1 S 1 a a a b a b b b S 1 a a a b a b b b b a a a T 3 S 1 S 1 S 1 a a a a U 2 S 1 S 1 S 1 a a a a S 1 S 1 S 1 S 1 S 1 a a a a b S 1 S 1 S 1 S 1 a a a a b b S 1 S 1 S 1 a a a a b b b S 1 S 1 a a a a b b b b S

Figure 1 :

 1 Figure 1: Trees of all walks associated with prefix notations of binary trees, having length n ∈ [1, 9] and generated by the BCNF grammar {S → T | b, T → a . U, U → S . S}, under the leftmost first derivation policy φ L .

  5 S 1 ) π(abaS 1 S 5 ) π(abaS 3 S 3 ) π F (abaS 5 S 1 )

  type}

25 :

 25 return StepByStep(ω ′ .t.ω ′′ , µ, G π , F , φ) end ifWhere: rand(x): Draws a random number uniformly in [0, x) π F (ω) := π(L(ω) ∩ F ): Total weight of forbidden words in L(ω)

Theorem 4 . 2 .

 42 Algorithm 3 generates k distinct words of length n from a weighted grammar G π in O(n • |N | + k • n log n) arithmetic operations, while storing O(n • |N | + k) numbers, and a data structure consisting of Θ(n • k) nodes.Proof. As discussed in Section 4.5, Algorithm 3 generates a word in O(n log(n)) arithmetic operations, assuming that some correcting terms π F (ω) are available at runtime. In Section 4.5.2, a data structure is introduced that returns this value in O(log(n)) time. Namely, one has that O(n log(n)) times, a search in O(log(n)) is performed followed by an arithmetic operation involving large (at least polynomial on n, usually exponential) numbers. It follows that the cost of accessing the data structure is dominated by the cost of the following arithmetic operations, and the overall cost of generating k words is in O(k • n log(n)) arithmetic operations. After each generation, the data structure is updated in Θ(n) arithmetic operations, and the complexity is therefore dominated by the cost of the generation. The precomputation required by the StepByStep algorithm involves Θ(n • |N |) arithmetic operations, and the storage of Θ(n • |N |) numbers. The data structure for π F (ω) has Θ(n • k) nodes and contains Θ(k) different numbers, thus the overall complexity.

4. 4 . Correctness Proposition 4 . 3 .

 443 Assuming that µ = π(ω), Algorithm 3 draws a word at random according to the π-weighted distribution on L(ω)\F , or returns error iff L(ω)\F = ∅.

Proposition 4 . 4 .

 44 The total weight π F (ω) of all forbidden words generated from an immature word ω can be accessed by Algorithm 3 in O(log(n)) time, at the cost of an update operation in Θ(n) arithmetic operations, while storing Θ(|F |) additional numbers.

Figure 3 :

 3 Figure3: Illustration of the update operation for the weighted tree for forbidden walks, for our running example. Initial tree (Left): Each node is associated with an immature word ω and its overall weight of forbidden words π F (ω) (some unary nodes are contracted for the sake of readability). During the execution of Algorithm 3, the tree is traversed to grant efficient access to π F (ω). Updated tree (Right): After generating a new (mature) word w d := abaaabbbb, the proper suffix of the parse walk is added to the tree (Blue nodes), associated with the additional weight πw d , which must then be propagated back to the root (bold branch), using at most Θ(n) arithmetic operations.

Theorem 5 . 1 .

 51 Using an unranking approach, k distinct words of length n can be generated from a weighted grammar G π in O(n • |N | + k • n log n) arithmetic operations, while storing O(n • |N | + k) large numbers. Proof. In Section 5.1.4, we introduce Algorithm 4, a general unranking procedure which transforms, in O(n log(n)) arithmetic operations, any random number drawn uniformly in the interval [0, π(L(G π ) n )[ into a random word in L(G π ) n with respect to a weighted distribution. Furthermore, Section 5.2 introduces a dedicated data structure, coupled with Algorithm 5 which draws numbers in the subset [0, π(L(G π ) n )[ while avoiding contributions of forbidden words, and uses O(k log(k)) arithmetic operations. The precomputation required by the Algorithm 4 involves Θ(n • |N |) arithmetic operations, and a storage of Θ(n • |N |) numbers. Maintaining the data structure used by Algorithm 5 requires the storage of Θ(k) numbers.

Proposition 5 . 2 .Algorithm 4

 524 Given a real number r ∈ [0, π(L(G) n )[ Algorithm 4 produces the word associated with an interval I, r ∈ I, in O(n log(n)) arithmetic operations after a precomputation in Θ(|N | • n) arithmetic operations involving storage of Θ(|N | • n) numbers. Unranking algorithm. Returns a word w and an interval [I L

8 FrFigure 5 :

 85 Figure5: Illustration of the shift function δ. In order to avoid any forbidden words, one needs to shift rightward a random number r by the total weight of forbidden words (red area) that are found leftward.

Proposition 5 . 3 .

 53 The function ModRandom computed by Algorithm 5 is a bijection from [0, π(L)π(F ))[ onto [0, π(L)[\(∪ w∈F I w ) with uniform density.

•

  When r ∈ B = [L wiµ wi , L wb+1 -b k=a π( wk )[, then ModRandom is called on v j := T R with value r ′ := r + µ wi + π( wi ). The indices of the forbidden nodes on the right subtree are [i + 1, . . . , b], so one has H j = [R wi , L wb+1 -b k=i+1 π( wk )[. The image B ′ of the interval B through a shift of value µ wi + π( wi ) is then

Acknowledgements

The author would like to thank A. Denise, C. Herrbach, and an anonymous reviewer for thought-provoking remarks and helpful suggestions. This work was supported by the French Agence Nationale de la Recherche as part of the Magnum project (ANR 2010 BLAN 0204).

Appendix A. Expressivity of the binary Chomsky normal form

Let us show that the assumption of a BCNF can be made without loss of generality (or performance). Indeed, it is a classic result that any context-free grammar G can be transformed into a Chomsky Normal Form (CNF) grammar that generates the same language.

Appendix A.1. From CNF to BCNF grammars: An algorithm From such a grammar, an equivalent grammar in BCNF can be simply and efficiently obtained through the following transformation: i) For each terminal t (resp. empty word ε) create a new non-terminal N t (resp. N ε ) whose sole production is N t → t (resp. N t → ε); ii) Replace any occurrence of t (resp. ε) within a production rule with its dedicated non-terminal N t (resp. N ε ); iii) Replace any rule N → N ′ .N ′′ , where N has more than one derivation, with rules N → N • and N • → N ′ .N ′′ , where N • is a newly created nonterminal; iv) For any non-terminal N having multiple production rules

, and replace the rules of N with a tree-like equivalent hierarchy of binary rules. For instance, one may create chained rules, such that

Finally, remove every non-terminal whose sole production is N → N ′ , replacing any occurrence of N by N ′ in any derivation rule.

Appendix A.2. Correctness

The equivalence of the resulting grammar to the input one in CNF trivially follows from the language-preserving nature of the substitutions performed at each step. Furthermore, it is easily verified that the resulting grammar is in BCNF. Indeed, consider the set P N of derivation rules available for any former non-terminal N , along the transformation:

• Before executing the transformation: P N consists an arbitrary number of terminal rules (N → N ′ ), binary-product (N → N ′ . N ′′ ) rules, or possibly an epsilon rule for the axiom (S → ε);

• Steps i) and ii) remove terminal symbols: After their execution, P N contains an arbitrary number of unary (N → N ′ ) or binary (N → N ′ . N ′′ ) rules;

•