Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 58 lines (53 sloc) 2.218 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
(ns foreclojure.graphs
  (:require [incanter.charts :as chart]
            [incanter.core :as incanter]
            [incanter.stats :as stats])
  (:import [java.io ByteArrayInputStream
                                     ByteArrayOutputStream])
  (:use [compojure.core :only [defroutes GET]]
            [foreclojure.problems :only [solved-stats]]
            [useful.utils :only [with-adjustments]]))

(defn un-group
  "Turn a compact set of [data-point num-repetitions] pairs into a
bunch of repeated data points so that incanter will make a histogram
of them."
  [frequencies]
  (apply concat (for [[x count] frequencies]
                  (repeat count x))))

(defn fetch-score-frequencies [problem-id]
  (-> @solved-stats
      (get problem-id)
      (dissoc nil)))

(defn make-problem-plot [id best curr]
  (let [freqs (fetch-score-frequencies id)
        chart-data (un-group freqs)
        [best curr] [(or best curr) (or curr best)]
        chart (chart/histogram chart-data
                               :title (str "League scores: problem " id)
                               :x-label "Solution length"
                               :y-label "How often"
                               :nbins 25)]
    (when best
      (chart/add-pointer chart best 0
                         :text "your best"
                         :angle :ne))
    (when (and curr (not= curr best))
      (chart/add-pointer chart curr 0
                         :text "this"
                         :angle :ne))
    (when-not (> (count freqs) 1)
      (chart/add-text chart best (freqs best 0)
                      "Very little golfing data - chart may suck"))
    (doto chart (chart/set-theme :bw))))

(defn serve-plot [plot]
  (let [out (ByteArrayOutputStream.)
        in (do
             (incanter/save plot out)
             (ByteArrayInputStream. (.toByteArray out)))]
    {:response 200
     :headers {"Content-Type" "image/png"}
     :body in}))

(defroutes graph-routes
  (GET "/leagues/golf/:id" [id best curr]
    (with-adjustments #(when (seq %) (Integer/parseInt %)) [id best curr]
      (serve-plot (make-problem-plot id best curr)))))
Something went wrong with that request. Please try again.