Programming Search⌘K

Patternadvanced

Blackboard

Also called blackboard pattern, blackboard architecture, blackboard system.

In the blackboard pattern, independent knowledge sources add partial solutions to a shared data store, and a control component selects which source runs next.

Family
behavioral-design
Intent
Assemble knowledge from a variety of sources when no deterministic solution strategy is known.
Also called
blackboard system

Intent

The Blackboard pattern is used to assemble knowledge from a variety of sources when no deterministic solution strategy is known.3 Buschmann and his co-authors describe Blackboard as an architectural pattern in Pattern-Oriented Software Architecture, Volume 1.4

Problem

Some problems have no known fixed algorithm. Speech recognition is the first example: the pattern was identified by the members of the Hearsay-II project and first applied to speech recognition.1 Other uses include vehicle identification and tracking, protein structure identification and the interpretation of sonar signals.1

For such a problem, many specialized modules each know a part of the answer. Each module has its own representation. The system must combine large and diverse specialized modules and use complex, non-deterministic control strategies.1

Solution

The blackboard model defines three main components:1

  • The blackboard, a structured global memory that contains objects from the solution space.
  • The knowledge sources, specialized modules with their own representation.
  • The control component, which selects, configures and executes modules.
   +-------------------------------------------+
   |               blackboard                  |
   |   signal -> syllables -> words -> sentence |
   +-------------------------------------------+
        ^ read and write    ^           ^
        |                   |           |
   segmenter            lexicon      grammar     (knowledge sources)
        ^                   ^           ^
        +---------- control component --+
           selects the next source that can contribute

The metaphor is a group of specialists in a room with a large blackboard. The specialists all watch the blackboard and look for an opportunity to apply their expertise to the developing solution. When one of them writes something that lets another specialist apply their expertise, the second specialist records their contribution on the blackboard.2 A moderator keeps the specialists from all trying to write at the same time. In a blackboard system, the control shell does this work.2

To implement the pattern, first design the solution space, which gives the structure of the blackboard. Then identify the knowledge sources. These two activities are closely related. Then specify the control component.1

Example

The example files show one program in each language. The blackboard has four levels: a signal, syllables, words and a sentence. Each knowledge source can contribute when its input level is on the blackboard and its output level is not. The control component looks at the blackboard and runs a source that can contribute, until the sentence is there. The program prints:

segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
PythonGitHub
LEXICON = {"hel lo": "hello", "wor ld": "world"}


def segment(signal):
    return signal[0].split("-")


def lookup(syllables):
    pairs = [" ".join(syllables[i:i + 2]) for i in range(0, len(syllables), 2)]
    return [LEXICON[p] for p in pairs]


def parse(words):
    return [" ".join(words).capitalize() + "."]


# Each knowledge source: name, input level, output level, function.
SOURCES = [
    ("grammar", "words", "sentence", parse),
    ("lexicon", "syllables", "words", lookup),
    ("segmenter", "signal", "syllables", segment),
]

board = {"signal": ["hel-lo-wor-ld"]}

# The control component selects a source that can contribute now.
while "sentence" not in board:
    name, src, dst, run = next(
        s for s in SOURCES if s[1] in board and s[2] not in board
    )
    board[dst] = run(board[src])
    print(f"{name} adds {dst}: {' '.join(board[dst])}")
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. A dictionary is the blackboard, and functions are the knowledge sources.
#include <cctype>
#include <functional>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

using Data = std::vector<std::string>;

struct KnowledgeSource {
    std::string name, src, dst;
    std::function<Data(const Data&)> run;
};

std::string join(const Data& d) {
    std::string out;
    for (size_t i = 0; i < d.size(); ++i) out += (i ? " " : "") + d[i];
    return out;
}

int main() {
    const std::map<std::string, std::string> lexicon = {{"hel lo", "hello"}, {"wor ld", "world"}};
    const std::vector<KnowledgeSource> sources = {
        {"grammar", "words", "sentence", [](const Data& w) {
             std::string s = join(w);
             s[0] = static_cast<char>(std::toupper(static_cast<unsigned char>(s[0])));
             return Data{s + "."};
         }},
        {"lexicon", "syllables", "words", [&](const Data& syl) {
             Data words;
             for (size_t i = 0; i + 1 < syl.size(); i += 2) words.push_back(lexicon.at(syl[i] + " " + syl[i + 1]));
             return words;
         }},
        {"segmenter", "signal", "syllables", [](const Data& sig) {
             Data parts;
             std::stringstream ss(sig[0]);
             for (std::string p; std::getline(ss, p, '-');) parts.push_back(p);
             return parts;
         }},
    };

    std::map<std::string, Data> board = {{"signal", {"hel-lo-wor-ld"}}};

    // The control component selects a source that can contribute now.
    while (!board.count("sentence")) {
        for (const auto& ks : sources) {
            if (board.count(ks.src) && !board.count(ks.dst)) {
                board[ks.dst] = ks.run(board[ks.src]);
                std::cout << ks.name << " adds " << ks.dst << ": " << join(board[ks.dst]) << "\n";
                break;
            }
        }
    }
}
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. A std::map is the blackboard, and std::function values are the knowledge sources.
JavaGitHub
import java.util.*;
import java.util.function.Function;

public class Main {
    record KnowledgeSource(String name, String src, String dst, Function<List<String>, List<String>> run) {}

    static final Map<String, String> LEXICON = Map.of("hel lo", "hello", "wor ld", "world");

    public static void main(String[] args) {
        List<KnowledgeSource> sources = List.of(
            new KnowledgeSource("grammar", "words", "sentence", w -> {
                String s = String.join(" ", w);
                return List.of(Character.toUpperCase(s.charAt(0)) + s.substring(1) + ".");
            }),
            new KnowledgeSource("lexicon", "syllables", "words", syl -> {
                List<String> words = new ArrayList<>();
                for (int i = 0; i < syl.size(); i += 2) {
                    words.add(LEXICON.get(String.join(" ", syl.subList(i, i + 2))));
                }
                return words;
            }),
            new KnowledgeSource("segmenter", "signal", "syllables",
                sig -> List.of(sig.get(0).split("-"))));

        Map<String, List<String>> board = new HashMap<>();
        board.put("signal", List.of("hel-lo-wor-ld"));

        // The control component selects a source that can contribute now.
        while (!board.containsKey("sentence")) {
            KnowledgeSource ks = sources.stream()
                .filter(s -> board.containsKey(s.src()) && !board.containsKey(s.dst()))
                .findFirst().orElseThrow();
            board.put(ks.dst(), ks.run().apply(board.get(ks.src())));
            System.out.println(ks.name() + " adds " + ks.dst() + ": " + String.join(" ", board.get(ks.dst())));
        }
    }
}
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. A map is the blackboard, and records with functions are the knowledge sources.
using System;
using System.Collections.Generic;
using System.Linq;

var lexicon = new Dictionary<string, string> { ["hel lo"] = "hello", ["wor ld"] = "world" };

var sources = new List<KnowledgeSource>
{
    new("grammar", "words", "sentence", w =>
    {
        var s = string.Join(" ", w);
        return new List<string> { char.ToUpper(s[0]) + s[1..] + "." };
    }),
    new("lexicon", "syllables", "words", syl =>
        Enumerable.Range(0, syl.Count / 2)
            .Select(i => lexicon[syl[2 * i] + " " + syl[2 * i + 1]]).ToList()),
    new("segmenter", "signal", "syllables", sig => sig[0].Split('-').ToList()),
};

var board = new Dictionary<string, List<string>> { ["signal"] = new() { "hel-lo-wor-ld" } };

// The control component selects a source that can contribute now.
while (!board.ContainsKey("sentence"))
{
    var ks = sources.First(s => board.ContainsKey(s.Src) && !board.ContainsKey(s.Dst));
    board[ks.Dst] = ks.Run(board[ks.Src]);
    Console.WriteLine($"{ks.Name} adds {ks.Dst}: {string.Join(" ", board[ks.Dst])}");
}

record KnowledgeSource(string Name, string Src, string Dst, Func<List<string>, List<string>> Run);
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. A dictionary is the blackboard, and records with delegates are the knowledge sources.
JavaScriptGitHub
const LEXICON = new Map([["hel lo", "hello"], ["wor ld", "world"]]);

const segment = (signal) => signal[0].split("-");
const lookup = (syl) => {
  const words = [];
  for (let i = 0; i < syl.length; i += 2) words.push(LEXICON.get(syl.slice(i, i + 2).join(" ")));
  return words;
};
const parse = (words) => {
  const s = words.join(" ");
  return [s[0].toUpperCase() + s.slice(1) + "."];
};

// Each knowledge source: name, input level, output level, function.
const SOURCES = [
  { name: "grammar", src: "words", dst: "sentence", run: parse },
  { name: "lexicon", src: "syllables", dst: "words", run: lookup },
  { name: "segmenter", src: "signal", dst: "syllables", run: segment },
];

const board = new Map([["signal", ["hel-lo-wor-ld"]]]);

// The control component selects a source that can contribute now.
while (!board.has("sentence")) {
  const ks = SOURCES.find((s) => board.has(s.src) && !board.has(s.dst));
  board.set(ks.dst, ks.run(board.get(ks.src)));
  console.log(`${ks.name} adds ${ks.dst}: ${board.get(ks.dst).join(" ")}`);
}
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. A Map is the blackboard, and functions are the knowledge sources.
TypeScriptGitHub
type Level = "signal" | "syllables" | "words" | "sentence";
type Board = Map<Level, string[]>;

interface KnowledgeSource {
  name: string;
  src: Level;
  dst: Level;
  run(input: string[]): string[];
}

const LEXICON = new Map<string, string>([["hel lo", "hello"], ["wor ld", "world"]]);

const SOURCES: KnowledgeSource[] = [
  {
    name: "grammar", src: "words", dst: "sentence",
    run: (w) => {
      const s = w.join(" ");
      return [s[0].toUpperCase() + s.slice(1) + "."];
    },
  },
  {
    name: "lexicon", src: "syllables", dst: "words",
    run: (syl) => {
      const words: string[] = [];
      for (let i = 0; i < syl.length; i += 2) words.push(LEXICON.get(syl.slice(i, i + 2).join(" "))!);
      return words;
    },
  },
  { name: "segmenter", src: "signal", dst: "syllables", run: (sig) => sig[0].split("-") },
];

const board: Board = new Map([["signal", ["hel-lo-wor-ld"]]]);

// The control component selects a source that can contribute now.
while (!board.has("sentence")) {
  const ks = SOURCES.find((s) => board.has(s.src) && !board.has(s.dst))!;
  board.set(ks.dst, ks.run(board.get(ks.src)!));
  console.log(`${ks.name} adds ${ks.dst}: ${board.get(ks.dst)!.join(" ")}`);
}
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. An interface describes a knowledge source, and a union type names the levels of the blackboard.
package main

import (
	"fmt"
	"strings"
)

type KnowledgeSource struct {
	Name, Src, Dst string
	Run            func([]string) []string
}

var lexicon = map[string]string{"hel lo": "hello", "wor ld": "world"}

func main() {
	sources := []KnowledgeSource{
		{"grammar", "words", "sentence", func(w []string) []string {
			s := strings.Join(w, " ")
			return []string{strings.ToUpper(s[:1]) + s[1:] + "."}
		}},
		{"lexicon", "syllables", "words", func(syl []string) []string {
			var words []string
			for i := 0; i+1 < len(syl); i += 2 {
				words = append(words, lexicon[syl[i]+" "+syl[i+1]])
			}
			return words
		}},
		{"segmenter", "signal", "syllables", func(sig []string) []string {
			return strings.Split(sig[0], "-")
		}},
	}

	board := map[string][]string{"signal": {"hel-lo-wor-ld"}}

	// The control component selects a source that can contribute now.
	for board["sentence"] == nil {
		for _, ks := range sources {
			_, haveSrc := board[ks.Src]
			_, haveDst := board[ks.Dst]
			if haveSrc && !haveDst {
				board[ks.Dst] = ks.Run(board[ks.Src])
				fmt.Printf("%s adds %s: %s\n", ks.Name, ks.Dst, strings.Join(board[ks.Dst], " "))
				break
			}
		}
	}
}
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. A map is the blackboard, and function values are the knowledge sources.
RustGitHub
use std::collections::HashMap;

type Data = Vec<String>;

struct KnowledgeSource {
    name: &'static str,
    src: &'static str,
    dst: &'static str,
    run: fn(&Data) -> Data,
}

fn segment(sig: &Data) -> Data {
    sig[0].split('-').map(String::from).collect()
}

fn lookup(syl: &Data) -> Data {
    let lexicon: HashMap<&str, &str> = [("hel lo", "hello"), ("wor ld", "world")].into();
    syl.chunks(2).map(|p| lexicon[p.join(" ").as_str()].to_string()).collect()
}

fn parse(words: &Data) -> Data {
    let s = words.join(" ");
    let mut chars = s.chars();
    let first = chars.next().unwrap().to_uppercase().collect::<String>();
    vec![format!("{}{}.", first, chars.as_str())]
}

fn main() {
    let sources = [
        KnowledgeSource { name: "grammar", src: "words", dst: "sentence", run: parse },
        KnowledgeSource { name: "lexicon", src: "syllables", dst: "words", run: lookup },
        KnowledgeSource { name: "segmenter", src: "signal", dst: "syllables", run: segment },
    ];
    let mut board: HashMap<&str, Data> = HashMap::new();
    board.insert("signal", vec!["hel-lo-wor-ld".to_string()]);

    // The control component selects a source that can contribute now.
    while !board.contains_key("sentence") {
        let ks = sources
            .iter()
            .find(|s| board.contains_key(s.src) && !board.contains_key(s.dst))
            .unwrap();
        let out = (ks.run)(&board[ks.src]);
        println!("{} adds {}: {}", ks.name, ks.dst, out.join(" "));
        board.insert(ks.dst, out);
    }
}
Output
segmenter adds syllables: hel lo wor ld
lexicon adds words: hello world
grammar adds sentence: Hello world.
  • Verdict: idiom. A HashMap is the blackboard, and function pointers are the knowledge sources.

Consequences

The benefits:

  • The pattern gives effective solutions for complex systems in which different modules must be combined dynamically to solve a problem.1
  • It gives reusability, changeability and robustness.1 The knowledge sources are independent, so it is easy to change and maintain them. It is easy to experiment with different approaches.3
  • Only conclusions that are supported by data and other hypotheses survive.3
  • Multiple processes can work closer together on separate threads, and poll and react when necessary.1

The costs:

  • The control component generally takes the form of a complex scheduler. It uses a set of domain-specific heuristics to rate the relevance of the knowledge sources that can run.1

A fixed order of steps is not a blackboard. Here each source runs once in a fixed order. The grammar runs before there are words, so the program stops with no sentence:

This code runs but gives a wrong answer on purpose.

LEXICON = {"hel lo": "hello", "wor ld": "world"}
board = {"signal": "hel-lo-wor-ld"}


def segmenter(b):
    if "signal" in b:
        b["syllables"] = b["signal"].split("-")


def lexicon(b):
    if "syllables" in b:
        s = b["syllables"]
        b["words"] = [LEXICON[" ".join(s[i:i + 2])] for i in range(0, len(s), 2)]


def grammar(b):
    if "words" in b:
        b["sentence"] = " ".join(b["words"]).capitalize() + "."


for source in [grammar, lexicon, segmenter]:  # a fixed order, no control
    source(board)
print("sentence:", board.get("sentence"))
Output
sentence: None

When not to use it

  • A deterministic algorithm for the problem is known.3 Then a direct program, or a pipeline of steps, is simpler.
  • The parts of the solution must be produced in an order that is known before the program runs.
  • Rated knowledge sources. The control component can rate each knowledge source that can run and select the best one.1 Here two lexicons can turn syllables into words, and the control selects the one with the higher rating:
board = {"syllables": ["wor", "ld"]}
sources = [
    ("short lexicon", 0.4, {"wor ld": "word"}),
    ("long lexicon", 0.9, {"wor ld": "world"}),
]


def rate(source):
    name, rating, table = source
    return rating if " ".join(board["syllables"]) in table else 0.0


name, rating, table = max(sources, key=rate)  # the control rates the sources
board["words"] = [table[" ".join(board["syllables"])]]
print(f"{name} ({rating}) adds words: {' '.join(board['words'])}")
Output
long lexicon (0.9) adds words: world
  • Control knowledge sources. In the BB1 system, the control itself used the same blackboard model. Control knowledge sources could monitor whether problem solving was going as expected or had stalled.2
  • Mediator. In both patterns, the parts do not call each other directly. In a blackboard, the knowledge sources share only the data on the blackboard, and the control component selects, configures and executes them.1

Known uses

  • Hearsay-II. A speech recognition system, and one of the well-known early academic blackboard systems.2
  • BB1 and GBB. Two foundational blackboard systems. BB1 focused on opportunistic planning and control, and GBB focused on efficiency.2
  • Copycat and Numbo. Douglas Hofstadter's projects are also blackboard systems.2
  • RADARSAT-1. The PLAN component of the Mission Control System for this Canadian Earth observation satellite.2
  • Adobe Acrobat Capture. It used a blackboard system to decompose and recognize image pages.2
  • Game AI. Blackboards are considered a standard AI tool in video games.2

References

  1. Blackboard (design pattern), Wikipedia, lead; Structure; Implementation; Applications; Consequences
  2. Blackboard system, Wikipedia, lead and its citation of Erman, Hayes-Roth, Lesser and Reddy (1980); Metaphor; Components; Implementations
  3. Examples to Accompany: Design Patterns, Elements of Reusable Object-Oriented Software, AG Communication Systems, 1999, Blackboard, page A-38
  4. Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad and Michael Stal, Pattern-Oriented Software Architecture, Volume 1: A System of Patterns, John Wiley and Sons, Chapter 2, Architectural Patterns, Blackboard

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/11V81G/text.yaml