You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
typesetting/csp/hacs.rkt

503 lines
22 KiB
Racket

6 years ago
#lang debug racket
6 years ago
(require racket/generator graph sugar/debug)
6 years ago
(provide (all-defined-out))
(define-syntax when-debug
(let ()
(define debug #f)
(if debug
(make-rename-transformer #'begin)
(λ (stx) (syntax-case stx ()
[(_ . rest) #'(void)])))))
6 years ago
(define-syntax-rule (in-cartesian x)
(in-generator (let ([argss x])
(let loop ([argss argss][acc empty])
(if (null? argss)
(yield (reverse acc))
(for ([arg (in-list (car argss))])
6 years ago
(loop (cdr argss) (cons arg acc))))))))
6 years ago
(struct $csp (vars
constraints
[assignments #:auto]
[checks #:auto]) #:mutable #:transparent
#:auto-value 0)
6 years ago
(define csp? $csp?)
(define vars $csp-vars)
(define constraints $csp-constraints)
(define-syntax-rule (in-constraints csp) (in-list ($csp-constraints csp)))
(define-syntax-rule (in-vars csp) (in-list ($csp-vars csp)))
6 years ago
(define-syntax-rule (in-var-names csp) (in-list (map $var-name ($csp-vars csp))))
6 years ago
6 years ago
(struct $constraint (names proc) #:transparent
#:property prop:procedure
(λ (constraint csp)
(unless ($csp? csp)
(raise-argument-error '$constraint-proc "$csp" csp))
;; apply proc in many-to-many style
(for/and ([args (in-cartesian (map (λ (cname) ($csp-vals csp cname)) ($constraint-names constraint)))])
6 years ago
(apply ($constraint-proc constraint) args))))
6 years ago
6 years ago
(define (make-constraint [names null] [proc values])
($constraint names proc))
6 years ago
(define constraint-names $constraint-names)
(define constraint? $constraint?)
(define (csp->graphviz csp)
(define g (csp->graph csp))
(graphviz g #:colors (coloring/brelaz g)))
(define (csp->graph csp)
(for*/fold ([g (unweighted-graph/undirected (map var-name (vars csp)))])
([constraint (in-constraints csp)]
[edge (in-combinations (constraint-names constraint) 2)])
(apply add-edge! g edge)
g))
(struct $var (name domain) #:transparent)
(define var? $var?)
6 years ago
(define name? symbol?)
6 years ago
(define $var-vals $var-domain)
6 years ago
(define var-name $var-name)
6 years ago
(struct $cvar $var (past) #:transparent)
6 years ago
(struct $avar $var () #:transparent)
6 years ago
(define assigned-var? $avar?)
6 years ago
6 years ago
(define/contract (make-csp [vars null] [constraints null])
(() ((listof var?) (listof constraint?)) . ->* . csp?)
6 years ago
($csp vars constraints))
6 years ago
(define/contract (add-vars! csp names-or-procedure [vals-or-procedure empty])
6 years ago
((csp? (or/c (listof name?) procedure?)) ((or/c (listof any/c) procedure?)) . ->* . void?)
6 years ago
(for/fold ([vars ($csp-vars csp)]
#:result (set-$csp-vars! csp vars))
([name (in-list (if (procedure? names-or-procedure)
(names-or-procedure)
names-or-procedure))])
6 years ago
(when (memq name (map var-name vars))
6 years ago
(raise-argument-error 'add-vars! "var that doesn't already exist" name))
(append vars (list ($var name
(if (procedure? vals-or-procedure)
(vals-or-procedure)
vals-or-procedure))))))
(define/contract (add-var! csp name [vals-or-procedure empty])
6 years ago
((csp? name?) ((or/c (listof any/c) procedure?)) . ->* . void?)
6 years ago
(add-vars! csp (list name) vals-or-procedure))
(define/contract (add-constraints! csp proc namess [proc-name #false])
6 years ago
((csp? procedure? (listof (listof name?))) ((or/c #false name?)) . ->* . void?)
(set-$csp-constraints! csp (append (constraints csp)
6 years ago
(for/list ([names (in-list namess)])
6 years ago
(for ([name (in-list names)])
(check-name-in-csp! 'add-constraints! csp name))
(make-constraint names (if proc-name
(procedure-rename proc proc-name)
proc))))))
6 years ago
(define/contract (add-pairwise-constraint! csp proc var-names [proc-name #false])
6 years ago
((csp? procedure? (listof name?)) (name?) . ->* . void?)
6 years ago
(add-constraints! csp proc (combinations var-names 2) proc-name))
(define/contract (add-constraint! csp proc var-names [proc-name #false])
6 years ago
((csp? procedure? (listof name?)) (name?) . ->* . void?)
6 years ago
(add-constraints! csp proc (list var-names) proc-name))
(define/contract (alldiff= x y)
(any/c any/c . -> . boolean?)
(not (= x y)))
6 years ago
(struct $backtrack (names) #:transparent)
6 years ago
(define (backtrack! [names null]) (raise ($backtrack names)))
6 years ago
6 years ago
(define current-select-variable (make-parameter #f))
(define current-order-values (make-parameter #f))
(define current-inference (make-parameter #f))
(define current-solver (make-parameter #f))
6 years ago
(define current-random (make-parameter #t))
6 years ago
6 years ago
(define/contract (check-name-in-csp! caller csp name)
6 years ago
(symbol? csp? name? . -> . void?)
(define names (map var-name (vars csp)))
6 years ago
(unless (memq name names)
(raise-argument-error caller (format "one of these existing csp var names: ~v" names) name)))
6 years ago
(define/contract (csp-var csp name)
(csp? name? . -> . $var?)
(check-name-in-csp! 'csp-var csp name)
(for/first ([var (in-vars csp)]
#:when (eq? name (var-name var)))
6 years ago
var))
6 years ago
(define/contract ($csp-vals csp name)
6 years ago
(csp? name? . -> . (listof any/c))
(check-name-in-csp! 'csp-vals csp name)
($var-domain (csp-var csp name)))
6 years ago
(define order-domain-values values)
6 years ago
6 years ago
(define/contract (assigned-name? csp name)
6 years ago
(csp? name? . -> . any/c)
6 years ago
(for/or ([var (in-vars csp)]
6 years ago
#:when (assigned-var? var))
6 years ago
(eq? name (var-name var))))
6 years ago
6 years ago
(define (reduce-function-arity proc pattern)
6 years ago
(unless (match (procedure-arity proc)
[(arity-at-least val) (<= val (length pattern))]
[(? number? val) (= val (length pattern))])
(raise-argument-error 'reduce-arity (format "list of length ~a, same as procedure arity" (procedure-arity proc)) pattern))
(define reduced-arity-name (string->symbol (format "reduced-arity-~a" (object-name proc))))
6 years ago
(define-values (boxed-id-names vals) (partition box? pattern))
6 years ago
(define new-arity (length boxed-id-names))
6 years ago
(procedure-rename
(λ xs
6 years ago
(unless (= (length xs) new-arity)
6 years ago
(apply raise-arity-error reduced-arity-name new-arity xs))
(apply proc (for/fold ([acc empty]
[xs xs]
[vals vals]
#:result (reverse acc))
([pat-item (in-list pattern)])
6 years ago
(if (box? pat-item)
6 years ago
(values (cons (car xs) acc) (cdr xs) vals)
(values (cons (car vals) acc) xs (cdr vals))))))
reduced-arity-name))
(define/contract (reduce-constraint-arity csp [minimum-arity 3])
6 years ago
((csp?) ((or/c #false exact-nonnegative-integer?)) . ->* . csp?)
6 years ago
(let ([assigned-name? (curry assigned-name? csp)])
(define (partially-assigned? constraint)
(ormap assigned-name? ($constraint-names constraint)))
6 years ago
(make-csp (vars csp)
(for/list ([constraint (in-constraints csp)])
6 years ago
(cond
6 years ago
[(and (or (not minimum-arity) (<= minimum-arity (constraint-arity constraint)))
6 years ago
(partially-assigned? constraint))
(match-define ($constraint cnames proc) constraint)
($constraint (filter-not assigned-name? cnames)
;; pattern is mix of values and boxed symbols (indicating variables to persist)
;; use boxes here as cheap way to distinguish id symbols from value symbols
(let ([reduce-arity-pattern (for/list ([cname (in-list cnames)])
(if (assigned-name? cname)
(first ($csp-vals csp cname))
(box cname)))])
(reduce-function-arity proc reduce-arity-pattern)))]
[else constraint])))))
(define nassns 0)
(define (reset-assns!) (set! nassns 0))
6 years ago
(define/contract (assign-val csp name val)
6 years ago
(csp? name? any/c . -> . csp?)
(when-debug (set! nassns (add1 nassns)))
6 years ago
(make-csp
(for/list ([var (vars csp)])
6 years ago
(if (eq? name (var-name var))
($avar name (list val))
var))
6 years ago
(constraints csp)))
6 years ago
(define/contract (unassigned-vars csp)
6 years ago
(csp? . -> . (listof (and/c $var? (not/c assigned-var?))))
(filter-not assigned-var? (vars csp)))
6 years ago
6 years ago
(define/contract (first-unassigned-variable csp)
6 years ago
(csp? . -> . (or/c #false (and/c $var? (not/c assigned-var?))))
6 years ago
(match (unassigned-vars csp)
[(? empty?) #false]
6 years ago
[(cons x _) x]))
6 years ago
(define/contract (minimum-remaining-values csp)
6 years ago
(csp? . -> . (or/c #false (and/c $var? (not/c assigned-var?))))
6 years ago
(match (unassigned-vars csp)
[(? empty?) #false]
6 years ago
[xs (argmin (λ (var) (length ($var-domain var))) xs)]))
6 years ago
6 years ago
(define mrv minimum-remaining-values)
(define/contract (var-degree csp var)
6 years ago
(csp? $var? . -> . exact-nonnegative-integer?)
(for/sum ([constraint (in-constraints csp)]
#:when (memq (var-name var) ($constraint-names constraint)))
6 years ago
1))
6 years ago
(define/contract (blended-variable-selector csp)
6 years ago
(csp? . -> . (or/c #false (and/c $var? (not/c assigned-var?))))
6 years ago
(define uvars (unassigned-vars csp))
(cond
[(empty? uvars) #false]
[(findf singleton-var? uvars)]
[else (first (let* ([uvars-by-mrv (sort uvars < #:key (λ (var) (length ($var-domain var))))]
[uvars-by-degree (sort uvars-by-mrv > #:key (λ (var) (var-degree csp var)))])
uvars-by-degree))]))
6 years ago
(define/contract (remaining-values var)
($var? . -> . exact-nonnegative-integer?)
(length ($var-vals var)))
(define/contract (mrv-degree-hybrid csp)
6 years ago
(csp? . -> . (or/c #f $var?))
6 years ago
(define uvars (unassigned-vars csp))
(cond
[(empty? uvars) #false]
[else
;; minimum remaining values (MRV) rule
(define mrv-arg (argmin remaining-values uvars))
(match (filter (λ (var) (= (remaining-values mrv-arg) (remaining-values var))) uvars)
[(list winning-uvar) winning-uvar]
[(list mrv-uvars ...)
;; use degree as tiebreaker for mrv
(define max-degree-arg (argmax (λ (var) (var-degree csp var)) mrv-uvars))
;; use random tiebreaker for degree
6 years ago
(random-pick (filter (λ (var) (= (var-degree csp max-degree-arg) (var-degree csp var))) mrv-uvars))])]))
6 years ago
6 years ago
(define first-domain-value values)
(define (no-inference csp name) csp)
6 years ago
(define/contract (relating-only constraints names)
6 years ago
((listof $constraint?) (listof name?) . -> . (listof $constraint?))
6 years ago
(for*/list ([constraint (in-list constraints)]
[cnames (in-value ($constraint-names constraint))]
6 years ago
#:when (and (= (length names) (length cnames))
(for/and ([name (in-list names)])
6 years ago
(memq name cnames))))
constraint))
6 years ago
6 years ago
(define (binary-constraint? constraint)
(= 2 (constraint-arity constraint)))
(define (constraint-relates? constraint name)
6 years ago
(memq name ($constraint-names constraint)))
6 years ago
(define nfchecks 0)
(define (reset-nfcs!) (set! nfchecks 0))
6 years ago
(define/contract (forward-check csp aname)
6 years ago
(csp? name? . -> . csp?)
6 years ago
(define aval (first ($csp-vals csp aname)))
6 years ago
(define (check-var var)
(match var
6 years ago
;; don't check against assigned vars, or the reference var
;; (which is probably assigned but maybe not)
6 years ago
[(? (λ (x) (or (assigned-var? x) (eq? (var-name x) aname)))) var]
6 years ago
[($var name vals)
6 years ago
(match ((constraints csp) . relating-only . (list aname name))
6 years ago
[(? empty?) var]
[constraints
(define new-vals
(for/list ([val (in-list vals)]
#:when (for/and ([constraint (in-list constraints)])
6 years ago
(let ([proc ($constraint-proc constraint)])
(if (eq? name (first ($constraint-names constraint)))
(proc val aval)
(proc aval val)))))
val))
6 years ago
($cvar name new-vals (cons aname (if ($cvar? var)
($cvar-past var)
null)))])]))
6 years ago
(define checked-vars (map check-var (vars csp)))
(when-debug (set! nfchecks (+ (length checked-vars) nchecks)))
6 years ago
;; conflict-set will be empty if there are no empty domains
(define conflict-set (for*/list ([var (in-list checked-vars)]
#:when (empty? ($var-domain var))
6 years ago
[name (in-list ($cvar-past var))])
6 years ago
name))
6 years ago
;; for conflict-directed backjumping it's essential to forward-check ALL vars
;; (even after an empty domain is generated) and combine their conflicts
;; so we can discover the *most recent past var* that could be the culprit.
;; If we just bail out at the first conflict, we may backjump too far based on its history
;; (and thereby miss parts of the search tree)
(when (pair? conflict-set)
6 years ago
(backtrack! conflict-set))
6 years ago
;; Discard constraints that have produced singleton domains
;; (they have no further use)
(define nonsingleton-constraints
6 years ago
(for/list ([constraint (in-constraints csp)]
6 years ago
#:unless (and
6 years ago
(binary-constraint? constraint)
(constraint-relates? constraint aname)
6 years ago
(let ([other-name (first (remq aname ($constraint-names constraint)))])
(singleton-var? (csp-var csp other-name)))))
6 years ago
constraint))
6 years ago
(make-csp checked-vars nonsingleton-constraints))
6 years ago
(define/contract (constraint-checkable? c names)
6 years ago
($constraint? (listof name?) . -> . any/c)
6 years ago
;; constraint is checkable if all constraint names
;; are in target list of names.
6 years ago
(for/and ([cname (in-list ($constraint-names c))])
6 years ago
(memq cname names)))
6 years ago
(define/contract (constraint-arity constraint)
($constraint? . -> . exact-nonnegative-integer?)
(length ($constraint-names constraint)))
(define (singleton-var? var)
(= 1 (length ($var-domain var))))
(define nchecks 0)
(define (reset-nchecks!) (set! nchecks 0))
6 years ago
(define/contract (check-constraints csp [mandatory-names #f] #:conflicts [conflict-count? #f])
((csp?) ((listof name?) #:conflicts boolean?) . ->* . (or/c csp? exact-nonnegative-integer?))
6 years ago
;; this time, we're not limited to assigned variables
;; (that is, vars that have been deliberately assigned in the backtrack process thus far)
;; we also want to use "singleton" vars (that is, vars that have been reduced to a single domain value by forward checking)
6 years ago
(define singleton-varnames (for/list ([var (in-vars csp)]
6 years ago
#:when (singleton-var? var))
6 years ago
(var-name var)))
6 years ago
(define-values (checkable-constraints other-constraints)
6 years ago
(partition (λ (c) (and (constraint-checkable? c singleton-varnames)
6 years ago
(or (not mandatory-names)
6 years ago
(for/and ([name (in-list mandatory-names)])
6 years ago
(constraint-relates? c name)))))
(constraints csp)))
6 years ago
(cond
[conflict-count? (define conflict-count
(for/sum ([constraint (in-list checkable-constraints)]
#:unless (constraint csp))
6 years ago
1))
6 years ago
(when-debug (set! nchecks (+ conflict-count nchecks)))
conflict-count]
[else (for ([(constraint idx) (in-indexed (sort checkable-constraints < #:key constraint-arity))]
#:unless (constraint csp))
6 years ago
(when-debug (set! nchecks (+ (add1 idx) nchecks)))
(backtrack!))
6 years ago
;; discard checked constraints, since they have no further reason to live
(make-csp (vars csp) other-constraints)]))
6 years ago
6 years ago
(define/contract (make-nodes-consistent csp)
6 years ago
(csp? . -> . csp?)
6 years ago
;; todo: why does this function slow down searches?
6 years ago
(make-csp
6 years ago
(for/list ([var (in-vars csp)])
6 years ago
(match-define ($var name vals) var)
(define procs (for*/list ([constraint (in-constraints csp)]
[cnames (in-value ($constraint-names constraint))]
#:when (and (= 1 (length cnames)) (eq? name (car cnames))))
($constraint-proc constraint)))
($var name
(for*/fold ([vals vals])
([proc (in-list procs)])
(filter proc vals))))
6 years ago
(constraints csp)))
6 years ago
6 years ago
(define/contract (backtracking-solver
csp
6 years ago
#:select-variable [select-unassigned-variable
(or (current-select-variable) first-unassigned-variable)]
6 years ago
#:order-values [order-domain-values (or (current-order-values) first-domain-value)]
#:inference [inference (or (current-inference) no-inference)])
6 years ago
((csp?) (#:select-variable procedure? #:order-values procedure? #:inference procedure?) . ->* . generator?)
6 years ago
(generator ()
6 years ago
(let loop ([csp csp])
6 years ago
(match (select-unassigned-variable csp)
[#false (yield csp)]
6 years ago
[($var name domain)
6 years ago
(define (wants-backtrack? exn)
6 years ago
(and ($backtrack? exn) (or (let ([btns ($backtrack-names exn)])
(or (empty? btns) (memq name btns))))))
6 years ago
(for/fold ([conflicts null]
6 years ago
#:result (void))
([val (in-list (order-domain-values domain))])
(with-handlers ([wants-backtrack?
(λ (bt) (append conflicts (remq name ($backtrack-names bt))))])
6 years ago
(let* ([csp (assign-val csp name val)]
6 years ago
;; reduce constraints before inference,
;; to create more forward-checkable (binary) constraints
[csp (reduce-constraint-arity csp)]
6 years ago
[csp (inference csp name)]
[csp (check-constraints csp)])
(loop csp)))
6 years ago
conflicts)]))))
6 years ago
(define (random-pick xs)
(list-ref xs (random (length xs))))
6 years ago
6 years ago
(define (assign-random-vals csp)
(for/fold ([new-csp csp])
([name (in-var-names csp)])
(assign-val new-csp name (random-pick ($csp-vals csp name)))))
(define (make-min-conflcts-thread csp0 max-steps [main-thread (current-thread)])
(thread
(λ ()
;; Generate a complete assignment for all variables (probably with conflicts)
(for/fold ([csp (assign-random-vals csp0)])
([nth-step (in-range max-steps)])
;; Now repeatedly choose a random conflicted variable and change it
(match (conflicted-var-names csp)
[(? empty?) (thread-send main-thread csp) csp]
[names
(define name (random-pick names))
(define val (min-conflicts-value csp name ($csp-vals csp0 name)))
(assign-val csp name val)])))))
6 years ago
(define/contract (min-conflicts csp [max-steps 100])
6 years ago
(($csp?) (integer?) . ->* . generator?)
6 years ago
;; Solve a CSP by stochastic hillclimbing on the number of conflicts.
6 years ago
(generator ()
6 years ago
(for ([thread-count 4]) ; todo: what is ideal thread quantity?
(make-min-conflcts-thread csp max-steps))
6 years ago
(for ([i (in-naturals)])
(yield (thread-receive)))))
6 years ago
(define/contract (conflicted-var-names csp)
($csp? . -> . (listof name?))
;; Return a list of variables in current assignment that are conflicted
6 years ago
(for/list ([name (in-var-names csp)]
#:when (positive? (nconflicts csp name)))
6 years ago
name))
6 years ago
(define/contract (min-conflicts-value csp name vals)
($csp? name? (listof any/c) . -> . any/c)
;; Return the value that will give var the least number of conflicts
6 years ago
(define vals-by-conflict (sort vals < #:key (λ (val) (nconflicts csp name val))
#:cache-keys? #true))
(for/first ([val (in-list vals-by-conflict)]
6 years ago
#:unless (equal? val (first ($csp-vals csp name)))) ;; but change the value
6 years ago
val))
6 years ago
(define no-value-sig (gensym))
(define/contract (nconflicts csp name [val no-value-sig])
(($csp? name?) (any/c) . ->* . exact-nonnegative-integer?)
;; How many conflicts var: val assignment has with other variables.
(check-constraints (if (eq? val no-value-sig)
csp
6 years ago
(assign-val csp name val)) (list name) #:conflicts #true))
6 years ago
(define/contract (csp->assocs csp)
6 years ago
(csp? . -> . (listof (cons/c name? any/c)))
(for/list ([var (in-vars csp)])
6 years ago
(match var
[($var name domain) (cons name (first domain))])))
6 years ago
6 years ago
(define/contract (solve* csp
#:finish-proc [finish-proc csp->assocs]
6 years ago
#:solver [solver (or (current-solver) backtracking-solver)]
6 years ago
#:limit [max-solutions +inf.0])
((csp?) (#:finish-proc procedure? #:solver procedure? #:limit integer?) . ->* . (listof any/c))
(when-debug
(reset-assns!)
(reset-nfcs!)
(reset-nchecks!))
6 years ago
(for/list ([solution (in-producer (solver csp) (void))]
[idx (in-range max-solutions)])
6 years ago
(finish-proc solution)))
6 years ago
6 years ago
(define/contract (solve csp
#:finish-proc [finish-proc csp->assocs]
6 years ago
#:solver [solver (or (current-solver) backtracking-solver)])
6 years ago
((csp?) (#:finish-proc procedure? #:solver procedure?) . ->* . (or/c #false any/c))
6 years ago
(match (solve* csp #:finish-proc finish-proc #:solver solver #:limit 1)
6 years ago
[(list solution) solution]
[else #false]))
(define (<> a b) (not (= a b)))
(define (neq? a b) (not (eq? a b)))