在Clojure中生成指定大小的随机AST

3
我想生成一个随机的抽象语法树。
(def terminal-set #{'x 'R})
(def function-arity {'+ 2, '- 2, '* 2, '% 2})
(def function-set (into #{} (keys function-arity)))
(def terminal-vec (into [] terminal-set))
(def function-vec (into [] function-set))

;; protected division
(defn % [^Number x ^Number y]
  (if (zero? y)
    0
    (/ x y)))

具有指定的大小。
(defn treesize [tree] (count (flatten tree)))

根据Sean Luke在2013年出版的Essentials of Metaheuristics(卢卢出版社第二版),使用该书中的算法,链接为https://cs.gmu.edu/~sean/book/metaheuristics/
我们随机扩展非叶节点的树的范围,直到非叶节点的数量加上剩余的空位大于或等于所需的大小。然后,我们用叶节点填充剩余的插槽:

ptc2 algorithm

例如。
(+ (* x (+ x x)) x)

这段文字的翻译如下:

大小为7。

书中的算法使用指针/引用Q非常方便。在我的情况下,我必须使用某种递归来构建树。问题是我无法在所有使用递归的算法之间保持树的状态size,这会导致更大的树:

(defn ptc2-tree
  "Generate a random tree up to its `max-size`.
  Note: `max-size` is the number of nodes, not the same as its depth."
  [max-size]
  (if (> 2 max-size)
    (rand-nth terminal-vec)
    (let [fun   (rand-nth function-vec)
          arity (function-arity fun)]
      (cons fun (repeatedly arity #(ptc2-tree (- max-size arity 1)))))))

我还尝试使用 atom 的大小,但无论如何都不能得到我想要的确切树的大小,这取决于实现的大小问题。
除此之外,我还必须以某种方式随机插入新节点/树的位置。
我该如何编写这个算法?
编辑:对正确解决方案的最后润色。
(defn sequentiate [v] 
  (map #(if (seqable? %) (sequentiate %) %) (seq v)))
2个回答

3
下面这段内容是PTC2算法的逐字翻译,它并不是完全符合Clojure语言的惯用写法;你可能需要根据实际情况将其拆分成更小的函数/块。
(defn ptc2 [target-size]
  (if (= 1 target-size)
    (rand-nth terminal-vec)
    (let [f (rand-nth function-vec)
          arity (function-arity f)]
      ;; Generate a tree like [`+ nil nil] and iterate upon it
      (loop [ast (into [f] (repeat arity nil))
             ;; q will be something like ([1] [2]), being a list of paths to the
             ;; nil elements in the AST
             q (for [i (range arity)] [(inc i)])
             c 1]
        (if (< (+ c (count q)) target-size)
          ;; Replace one of the nils in the tree with a new node
          (let [a (rand-nth q)
                f (rand-nth function-vec)
                arity (function-arity f)]
            (recur (assoc-in ast a (into [f] (repeat arity nil)))
                   (into (remove #{a} q)
                         (for [i (range arity)] (conj a (inc i))))
                   (inc c)))
          ;; In the end, fill all remaining slots with terminals
          (reduce (fn [t path] (assoc-in t path (rand-nth terminal-vec)))
                  ast q))))))

您可以使用Clojure的loop结构(或reduce)来保持迭代状态 - 在此算法中,状态包括:
  • ast,它是表示正在构建的公式的嵌套向量,其中未完成的节点标记为nil
  • q,它对应于伪代码中的Q,是一个包含ast中未完成节点路径的列表,
  • 以及c,它是树中非叶节点的计数。
结果类似于:
(ptc2 10) ;; => [* [- R [% R [% x x]]] [- x R]]

我们使用向量(而不是列表)来创建AST,因为它允许我们使用assoc-in逐步构建树;如果需要,您可以自行将其转换为嵌套列表。

1
作为巧合,我一直在Tupelo Forest库中开发AST操作代码。您可以在此处查看示例代码,以及2017年Clojure/Conj的视频
以下展示了我如何解决这个问题。我尽可能使名称自明,所以应该很容易理解算法的执行过程。
基础知识:
(def op->arity {:add 2
                :sub 2
                :mul 2
                :div 2
                :pow 2})
(def op-set (set (keys op->arity)))
(defn choose-rand-op [] (rand-elem op-set))

(def arg-set #{:x :y})
(defn choose-rand-arg [] (rand-elem arg-set))

(defn num-hids [] (count (all-hids)))

辅助函数:

(s/defn hid->empty-kids :- s/Int
  [hid :- HID]
  (let [op             (hid->attr hid :op)
        arity          (grab op op->arity)
        kid-slots-used (count (hid->kids hid))
        result         (- arity kid-slots-used)]
    (verify (= 2 arity))
    (verify (not (neg? result)))
    result))

(s/defn node-has-empty-slot? :- s/Bool
  [hid :- HID]
  (pos? (hid->empty-kids hid)))

(s/defn total-empty-kids :- s/Int
  []
  (reduce +
    (mapv hid->empty-kids (all-hids))))

(s/defn add-op-node :- HID
  [op :- s/Keyword]
  (add-node {:tag :op :op op} )) ; add node w no kids

(s/defn add-leaf-node :- tsk/KeyMap
  [parent-hid :- HID
   arg :- s/Keyword]
  (kids-append parent-hid [(add-leaf {:tag :arg :arg arg})]))

(s/defn need-more-op? :- s/Bool
  [tgt-size :- s/Int]
  (let [num-op            (num-hids)
        total-size-so-far (+ num-op (total-empty-kids))
        result            (< total-size-so-far tgt-size)]
    result))

主算法:

(s/defn build-rand-ast :- tsk/Vec ; bush result
  [ast-size]
  (verify (<= 3 ast-size)) ; 1 op & 2 args minimum;  #todo refine this
  (with-debug-hid
    (with-forest (new-forest)
      (let [root-hid (add-op-node (choose-rand-op))] ; root of AST
        ; Fill in random op nodes into the tree
        (while (need-more-op? ast-size)
          (let [node-hid (rand-elem (all-hids))]
            (when (node-has-empty-slot? node-hid)
              (kids-append node-hid
                [(add-op-node (choose-rand-op))]))))
        ; Fill in random arg nodes in empty leaf slots
        (doseq [node-hid (all-hids)]
          (while (node-has-empty-slot? node-hid)
            (add-leaf-node node-hid (choose-rand-arg))))
        (hid->bush root-hid)))))

(defn bush->form [it]
  (let [head (xfirst it)
        tag  (grab :tag head)]
    (if (= :op tag)
      (list (kw->sym (grab :op head))
        (bush->form (xsecond it))
        (bush->form (xthird it)))
      (kw->sym (grab :arg head)))))

(dotest
  (let [tgt-size 13]
    (dotimes [i 5]
      (let [ast     (build-rand-ast tgt-size)
            res-str (pretty-str ast)]
        (nl)
        (println res-str)
        (println (pretty-str (bush->form ast))) ))))

它以分层的“bush”格式和Lisp形式打印结果。以下是两个典型结果:
[{:tag :op, :op :mul}
 [{:tag :op, :op :div}
  [{:tag :op, :op :pow}
   [{:tag :op, :op :sub}
    [{:tag :arg, :arg :y, :value nil}]
    [{:tag :arg, :arg :x, :value nil}]]
   [{:tag :op, :op :div}
    [{:tag :arg, :arg :y, :value nil}]
    [{:tag :arg, :arg :y, :value nil}]]]
  [{:tag :arg, :arg :y, :value nil}]]
 [{:tag :op, :op :pow}
  [{:tag :arg, :arg :x, :value nil}]
  [{:tag :arg, :arg :y, :value nil}]]]

(mul (div (pow (sub y x) (div y y)) y) (pow x y))


[{:tag :op, :op :div}
 [{:tag :op, :op :mul}
  [{:tag :op, :op :pow}
   [{:tag :arg, :arg :x, :value nil}]
   [{:tag :arg, :arg :y, :value nil}]]
  [{:tag :op, :op :add}
   [{:tag :op, :op :div}
    [{:tag :arg, :arg :x, :value nil}]
    [{:tag :arg, :arg :y, :value nil}]]
   [{:tag :arg, :arg :x, :value nil}]]]
 [{:tag :op, :op :mul}
  [{:tag :arg, :arg :x, :value nil}]
  [{:tag :arg, :arg :y, :value nil}]]]

(div (mul (pow x y) (add (div x y) x)) (mul x y))

为了简化,我使用了三个字母的操作码而不是数学符号,但是它们可以很容易地替换为Clojure函数符号名称,以输入到eval中。


谢谢!我的使用情况是基因编程(多个AST生成),这个解决方案比我选择的正确答案慢了大约5.8倍,我暂时不得不放弃它。顺便说一下,请检查一下在GitHub上源代码中的stackoverflow链接,可能是错误的链接。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接