Grammatical evolution

On this page 7

Grammatical evolution is a form of genetic programming in which each individual is a variable-length string of integers that a formal grammar translates into a program, expression or other structured output. In evolutionary computation, it is the best-known example of a grammar-based genotype-phenotype mapping, introduced in the late 1990s by Conor Ryan, J. J. Collins and Michael O’Neill.

The key idea is a clean separation of search and solution. Genetic operators work on simple linear genomes, while the grammar guarantees that every successfully mapped phenotype is syntactically valid in the target language, whether that language is arithmetic, Python, SQL or a domain-specific rule format.

How the genotype-phenotype mapping works

The mapping reads the genome codon by codon and uses each value to choose a production rule from a grammar written in Backus-Naur Form (BNF). Starting from the start symbol, the leftmost non-terminal is always expanded first.

The choice follows the modulo rule: the chosen production index equals the codon value modulo the number of alternatives for the current non-terminal. A codon of 203 applied to a non-terminal with 4 alternatives selects option 203 mod 4 = 3, counting from zero.

StepCodonNon-terminal and alternativesChoice and result
1220expr: 2 options (expr op expr, var)220 mod 2 = 0, expr op expr
2203expr: 2 options203 mod 2 = 1, var
317var: 2 options (x, y)17 mod 2 = 1, y
451op: 3 options (+, -, *)51 mod 3 = 0, +
59expr: 2 options9 mod 2 = 1, var
64var: 2 options4 mod 2 = 0, x, final y + x
Mapping a short genome with a toy expression grammar

If the genome runs out before all non-terminals are expanded, many implementations apply wrapping, reusing the genome from the start. When a maximum number of wraps is exceeded, the individual is marked invalid and usually receives the worst possible fitness.

Not every codon is used. Codons that follow the last expansion form an unexpressed tail, and codons consumed by non-terminals with a single alternative have no effect on the choice. This degenerate genetic code means that many genomes map to the same phenotype, which shapes how variation operators behave.

Key parameters and design choices

Grammatical evolution exposes more design choices than a standard genetic algorithm, because the grammar itself is part of the configuration. The table summarizes common settings and their effect.

ParameterCommon rangeEffect
Codon size8 bits or 0 to 2^31Larger values reduce mapping bias
Initial genome length20 to 200 codonsControls the size of early phenotypes
Maximum wraps0 to 10Trades reuse of codons against invalid individuals
CrossoverOne-point, variable length, probability 0.7 to 0.9Recombines genome segments
MutationPer-codon integer flip, 0.01 to 0.05Introduces new rule choices
InitializationRandom or sensible initializationDetermines starting tree depth diversity
Typical parameters in grammatical evolution

Sensible initialization, a ramped half-and-half method adapted from genetic programming, derives start genomes from derivation trees of controlled depth. It typically produces far fewer invalid individuals and more diverse initial populations than uniform random integer strings.

Grammatical evolution belongs to the genetic programming family, but it differs from tree-based genetic programming in where variation happens and how syntax is enforced.

MethodGenomeSyntax controlTypical strength
Tree-based genetic programmingSyntax treeTyped function and terminal setsDirect, well-studied operators
Grammatical evolutionInteger stringBNF grammar via mappingAny target language, easy to restrict
Cartesian genetic programmingInteger graph encodingFixed node gridCompact circuits and reuse of nodes
Structured grammatical evolutionOne gene list per non-terminalGrammar with bounded recursionHigher locality, no invalid individuals
Genetic algorithmFixed-length vectorNone beyond encodingParameter optimization
Grammatical evolution and neighboring methods

Because the grammar is external, domain knowledge can be injected without changing the search engine. Restricting the grammar to monotonic functions or to a safe subset of a language is often easier than writing custom typed operators for tree-based systems.

Typical applications

Grammatical evolution is used wherever solutions must obey a defined syntax and where the search space is too irregular for gradient methods.

  • Symbolic regression to discover readable formulas from data.
  • Automatic generation of trading rules and decision rules.
  • Synthesis of small programs and program repair in restricted languages.
  • Design of digital filters, controllers and game agent behaviors.
  • Evolving neural network architectures or hyperparameter configurations described by a grammar.

Open-source frameworks such as PonyGE2 in Python and GEVA in Java made the method accessible, and both let users supply a grammar file and a fitness function with little additional code.

Practical projects usually spend more effort on grammar design than on tuning operators. A grammar that permits deep recursion everywhere tends to produce oversized expressions, while a grammar that is too narrow can exclude the best solution entirely. Experienced users start with a small, balanced grammar, inspect the evolved phenotypes and then extend the grammar step by step.

Limitations and known problems

The main criticism of grammatical evolution is low locality. Because each codon is interpreted in the context of all previous choices, a change early in the genome can alter every later expansion, a behavior known as the ripple effect.

ProblemCauseMitigation
Ripple effectContext-dependent codon meaningStructured or position-independent variants
Invalid individualsGenome exhausted before mapping endsSensible initialization, limited wraps
BloatUnused tail codons and growing phenotypesSize limits, parsimony pressure
Mapping biasModulo rule with unequal recursion depthGrammar balancing, larger codon values
Redundant codeMany codon values map to the same ruleAccept as neutral variation or adjust grammar
Common problems and mitigations

Redundancy is not purely negative. Several studies treat the many-to-one mapping as neutral variation that helps populations drift across plateaus. Whether it helps or hurts depends strongly on the grammar and the problem, and results in the literature are mixed rather than conclusive.

The idea in brief

Grammatical evolution breeds computer programs from lists of numbers. Each number picks one option from a set of grammar rules. Read in order, the numbers build a formula or a small program.

The grammar works like a recipe template. It only allows valid combinations of ingredients. Evolution then keeps the number lists whose programs perform best and mixes and mutates them to find better ones.

A practical scenario

A process engineer at a chemical plant needs a readable formula that predicts product yield from temperature, pressure and catalyst concentration. A neural network would fit the data, but plant regulators expect an equation that engineers can inspect and verify.

The engineer writes a grammar allowing addition, multiplication, division, exponentials and the three input variables, with constants limited to a sensible range. Using a population of 500 individuals over 100 generations, grammatical evolution finds an expression with a small error on held-out batches and only seven operations.

Because the grammar excluded functions that would be physically meaningless, the resulting model was accepted for daily planning after review, and the team reused the same grammar file for a second production line.