proposal_database.rkt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #lang racket/base
  2. ;; This program updates an entry in a proposals database.
  3. (require racket/cmdline
  4. racket/date
  5. racket/list
  6. racket/format
  7. db
  8. "config.rkt") ; load configuration file
  9. (define progname "proposal_database.rkt")
  10. ; give us the date in YYYY-MM-DD format
  11. (date-display-format 'iso-8601)
  12. ; parameters
  13. ; start and end date to sub-select proposals within a given range
  14. (define start-date (make-parameter #f))
  15. (define end-date (make-parameter #f))
  16. ; if #t, use proposal type, submitting organiation, solicitation/call, and
  17. ; telescope name from the most recently submitted (i.e., highest ID) proposal
  18. (define reuse-params (make-parameter #f))
  19. ; Set up the mode as a parameter to be provided by command line switches
  20. (define mode (make-parameter #f))
  21. ; set up command line arguments
  22. (command-line
  23. #:program progname
  24. #:once-each
  25. [("-s" "--start-date") sd "Start of date range (YYYY-MM-DD)"
  26. (start-date sd)]
  27. [("-e" "--end-date") ed "End of date range (YYYY-MM-DD)"
  28. (end-date ed)]
  29. [("-r" "--reuse-parameters") "Reuse/auto-fill proposal type, submitting organization, solicitation/call and telescope name from the most recently added proposal."
  30. (reuse-params #t)]
  31. #:once-any
  32. [("--create-database") "Create a new database" (mode "create-database")]
  33. [("-a" "--add") "Add a new proposal" (mode "add")]
  34. [("-u" "--update") "Update a proposal outcome" (mode "update")]
  35. [("--stats") "Calculate and display summary statistics" (mode "stats")]
  36. [("--list-open") "Show all submitted (but not resolved) proposals" (mode "list-open")]
  37. [("--list-closed") "Show all resolved (accepted and rejected) proposals" (mode "list-closed")]
  38. [("--list-accepted") "Show accepted proposals" (mode "list-accepted")]
  39. [("--list-rejected") "Show rejected proposals" (mode "list-rejected")]
  40. [("--list-open-calls") "Show calls that have submitted (but not resolved) proposals" (mode "list-open-calls")]
  41. #:ps "Copyright 2019-2020, 2022-2025 George Privon")
  42. ; set up a condensed prompt for getting information
  43. (define (getinput prompt)
  44. (write-string prompt)
  45. (write-string ": ")
  46. (read-line))
  47. ; take a proposal result from the SQL search and write it out nicely
  48. (define (printentry entry issub)
  49. (displayln (string-append
  50. (number->string (vector-ref entry 0))
  51. ": "
  52. (vector-ref entry 1)
  53. "("
  54. (vector-ref entry 2)
  55. "; PI: "
  56. (vector-ref entry 4)
  57. (if (not issub)
  58. (string-append "; "
  59. (vector-ref entry 5))
  60. "")
  61. ") \""
  62. (vector-ref entry 3)
  63. "\"")))
  64. ; take a call result from the SQL search and write it out nicely
  65. (define (print-call-entry entry Nprop Nprop-PI)
  66. (displayln (string-append
  67. (vector-ref entry 1)
  68. " "
  69. (vector-ref entry 2)
  70. " ("
  71. (vector-ref entry 0)
  72. ") - "
  73. (number->string Nprop-PI)
  74. (cond [(> Nprop-PI 1) " PI proposals and "]
  75. [else " PI proposal and "])
  76. (number->string (- Nprop Nprop-PI))
  77. (cond [(> Nprop 1) " Co-I proposals "]
  78. [else " Co-I proposal "])
  79. "pending.")))
  80. (define (get-last-proposal-call conn)
  81. (displayln "Adopting proposal information from last submission")
  82. (last-proposal-call conn))
  83. ; get information from the most recent proposal submission
  84. (define (last-proposal-call conn)
  85. (vector->list (query-row conn "SELECT type, organization, solicitation, telescope FROM proposals ORDER BY id DESC LIMIT 1")))
  86. ; create the database and create the table
  87. (define (createdb dbloc)
  88. ; make sure we can use the sqlite3 connection
  89. (cond [(not (sqlite3-available?)) (error "Sqlite3 library not available.")])
  90. ; create the database and add the `proposals` table if it doesn't exist
  91. (cond [(file-exists? dbloc) (error "Database exists. Exiting.")])
  92. (write-string (string-append "Creating database " dbloc "\n"))
  93. (define conn (sqlite3-connect #:database dbloc
  94. #:mode 'create))
  95. (query-exec conn "CREATE TABLE proposals (ID INTEGER PRIMARY KEY,
  96. type TEXT NOT NULL,
  97. organization TEXT NOT NULL,
  98. solicitation TEXT NOT NULL,
  99. telescope TEXT DEFAULT '',
  100. orgpropID TEXT NOT NULL,
  101. PI TEXT NOT NULL,
  102. title TEXT NOT NULL,
  103. CoI TEXT NOT NULL,
  104. status TEXT NOT NULL,
  105. submitdate TEXT NOT NULL,
  106. resultdate TEXT DEFAULT '')")
  107. (disconnect conn)
  108. (write-string (string-append "Database created at " dbloc "\n")))
  109. ; check to see if we can access the database
  110. (define (checkdb conn)
  111. (cond [(connected? conn) (write-string "Database created successfully.")]
  112. [else (write-string "Could not connect to database.")]))
  113. ; add a new proposal to the database
  114. (define (addnew conn)
  115. ; full list of input fileds that we will need (these will be the prompts
  116. ; to the user)
  117. (define input-fields (list "Proposal type"
  118. "Submitting Organization"
  119. "Solicitation/Call"
  120. "Telescope"
  121. "Proposal Title"
  122. "PI"
  123. "CoIs"
  124. "Submit date (YYYY-MM-DD)"
  125. "Organization's propsal ID"))
  126. (displayln "Adding new proposal to database.")
  127. ; assume all these proposals are submitted, don't ask the user
  128. (define status "submitted")
  129. ; get the proposal information
  130. (define propinfo
  131. (cond
  132. ; if we're re-using parameters, get info from the most recent submission
  133. ; and append the user input for the remaining fields
  134. [(reuse-params) (append (get-last-proposal-call conn)
  135. (map getinput (list-tail input-fields 4)))]
  136. ; if not using previous information, ask the user for all inputs
  137. [else (map getinput input-fields)]))
  138. ; do the INSERT into the Sqlite database
  139. (let* ([add-proposal-info
  140. (prepare conn "INSERT INTO proposals (type, organization, solicitation, telescope, title, PI, CoI, submitdate, orgpropID, status) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")])
  141. (query-exec conn (bind-prepared-statement add-proposal-info
  142. (flatten (list propinfo status))))))
  143. ; update an entry with new status (accepted, rejected, etc.)
  144. (define (update conn ID)
  145. (displayln (string-append "Updating entry " (number->string ID)))
  146. (define entry (query-maybe-row conn "SELECT * FROM proposals WHERE ID=?" ID))
  147. (cond
  148. [(eq? #f entry) (error "Invalid ID. Row not found")])
  149. (displayln (string-append "Current status is: "
  150. (vector-ref entry 9)
  151. " ("
  152. (vector-ref entry 10)
  153. ")"))
  154. (write-string "Please enter new status: ")
  155. (define newstatus (read-line))
  156. ;(write-string "Please enter date of updated status (leave blank to use current date): ")
  157. ;(define resdate (read-line))
  158. (define resdate (date->string (seconds->date (current-seconds))))
  159. ; now update that entry
  160. (query-exec conn "UPDATE proposals SET status=?, resultdate=? WHERE ID=?"
  161. newstatus
  162. resdate
  163. ID)
  164. (displayln "Entry updated."))
  165. ; if the user selects a date range we need to decide which date to filter on
  166. ; If they're looking at submitted (i.e., open) proposals, use the submitted
  167. ; date.
  168. ; If they're looking at closed/resolved proposals, use the dates proposals
  169. ; were resolved.
  170. (define (date-for-selection submitted)
  171. (if submitted
  172. "submitdate"
  173. "resultdate"))
  174. ; retrieve and print proposals based on status
  175. (define (printprop conn
  176. #:submitted issub
  177. #:accepted [isaccept #f]
  178. #:rejected [isrej #f])
  179. (define selclause (string-append
  180. (if issub
  181. "status='submitted'"
  182. "status!='submitted'")
  183. ; find things that are "accepted" or "funded"
  184. (if isaccept
  185. " AND (status LIKE '%Accepted%' OR status LIKE '%Funded%')"
  186. "")
  187. ; find things that are "rejected"
  188. (if isrej
  189. " AND status LIKE '%Rejected%'"
  190. "")))
  191. ; generate a selection clause if the user requested a restricted range
  192. (define dateclause (string-append
  193. (if (or (start-date) (end-date))
  194. " AND "
  195. "")
  196. (if (start-date)
  197. (string-append
  198. " DATE("
  199. (date-for-selection issub)
  200. ") >= DATE('"
  201. (start-date)
  202. "') ")
  203. "")
  204. (if (and (start-date) (end-date))
  205. " AND "
  206. "")
  207. (if (end-date)
  208. (string-append
  209. " DATE("
  210. (date-for-selection issub)
  211. ") <= DATE('"
  212. (end-date)
  213. "') ")
  214. "")))
  215. (define props (query-rows conn (string-append "SELECT ID,telescope,solicitation,title,PI,status FROM proposals WHERE "
  216. selclause
  217. dateclause)))
  218. (display (string-append (number->string (length props))))
  219. (if issub
  220. (displayln " pending proposals found.")
  221. (cond
  222. [isaccept (displayln " accepted proposals found.")]
  223. [isrej (displayln " rejected proposals found.")]))
  224. (newline)
  225. ; print all the unresolved proposals to the screen
  226. (map (lambda (prop)
  227. (printentry prop issub))
  228. props))
  229. ; retrieve and print proposal calls
  230. (define (print-open-calls conn)
  231. (define call-entries (query-rows conn (string-append "SELECT DISTINCT organization,telescope,solicitation FROM proposals WHERE status='submitted'")))
  232. (display (string-append (number->string (length call-entries))))
  233. (displayln " pending calls found.")
  234. (newline)
  235. ; print all the unresolved proposals to the screen
  236. (map (lambda (call-entry)
  237. (define Nprop (query-value conn (string-append "SELECT COUNT(DISTINCT ID) from proposals WHERE status='submitted' AND solicitation='"
  238. (vector-ref call-entry 2)
  239. "'")))
  240. (define Nprop-PI
  241. (query-value conn (string-append "SELECT COUNT(DISTINCT ID) from proposals WHERE status='submitted' AND solicitation='"
  242. (vector-ref call-entry 2)
  243. "' AND PI LIKE '%"
  244. PIname
  245. "%'")))
  246. (print-call-entry call-entry Nprop Nprop-PI))
  247. call-entries))
  248. ; find proposals waiting for updates
  249. (define (findpending conn)
  250. (write-string "Updating proposals. ")
  251. (printprop conn #:submitted #t)
  252. (write-string "Please enter a proposal number to edit (enter 0 or nothing to exit): ")
  253. (define upID (read-line))
  254. (cond
  255. [(eq? (string->number upID) 0) (exit)]
  256. [(string->number upID) (update conn (string->number upID))]
  257. [else (exit)]))
  258. ; compute and print some statistics about proposals:
  259. ; - total number of proposals (since earliest date)
  260. ; - number of pending proposals
  261. ; - number of successful proposals and corresponding fraction of the total that are not pending
  262. ; - number of rejected proposals and corresponding fraction of the total that are not pending
  263. ; - do the above two for all proposals and for proposals that I PI'ed. (TODO: PI'ed separation not yet implemented)
  264. (define (proposal-stats conn)
  265. (displayln "Proposal statistics to date.\n")
  266. ; do statistics for all proposals
  267. (displayln "\tAll proposals")
  268. (let-values ([(Nprop Npending Nrejected) (get-stats conn)])
  269. (print-stats Nprop Npending Nrejected))
  270. ; do statistics for proposals as PI
  271. (displayln (string-append "\n\tPI'ed Proposals (by "
  272. PIname
  273. ")"))
  274. (let-values ([(Nprop Npending Nrejected) (get-stats conn #:selclause (string-append "PI LIKE '%"
  275. PIname
  276. "%'"))])
  277. (print-stats Nprop Npending Nrejected))
  278. )
  279. ; given numbers, format somewhat pretty output of proposal statistics
  280. (define (print-stats Nprop Npending Nrejected)
  281. (display (number->string Nprop))
  282. (display "\ttotal proposals entered (")
  283. (display (number->string (- Nprop Npending)))
  284. (display " proposals resolved; ")
  285. (display (number->string Npending))
  286. (displayln " proposals pending).")
  287. (define Naccepted (- Nprop Npending Nrejected))
  288. (display (number->string Naccepted))
  289. (display "\tproposals accepted (f=")
  290. (display (~r (/ Naccepted
  291. (- Nprop Npending))
  292. #:precision `(= 3)))
  293. (displayln " of resolved proposals).")
  294. (display (number->string Nrejected))
  295. (display "\tproposals rejected (f=")
  296. (display (~r (/ Nrejected
  297. (- Nprop Npending))
  298. #:precision `(= 3)))
  299. (displayln " of resolved proposals)."))
  300. ; retrieve proposal numbers from the database, for statistics
  301. (define (get-stats conn #:selclause [extrasel ""])
  302. (define mysel (if (eq? 0 (string-length extrasel))
  303. ""
  304. (string-append " AND "
  305. extrasel)))
  306. (define mysel-one (if (eq? 0 (string-length extrasel))
  307. ""
  308. (string-append " WHERE "
  309. extrasel)))
  310. (values
  311. ; total number of proposals
  312. (query-value conn
  313. (string-append "SELECT COUNT(DISTINCT ID) FROM proposals"
  314. mysel-one))
  315. ; Number of pending proposals
  316. (query-value conn
  317. (string-append "SELECT COUNT(DISTINCT ID) FROM proposals WHERE status='submitted'"
  318. mysel))
  319. ; Number of rejected proposals
  320. (query-value conn
  321. (string-append "SELECT COUNT(DISTINCT ID) FROM proposals WHERE status LIKE '%rejected%'"
  322. mysel))))
  323. ; make sure we can use the sqlite3 connection
  324. (define checkdblib
  325. (cond (not (sqlite3-available?))
  326. (error "Sqlite3 library not available.")))
  327. ; catch-all routine for when we need to access the database
  328. (define (querysys mode)
  329. ; check if the user would like to create the database or not
  330. (cond
  331. [(string=? "create-database" mode) (createdb dbloc)])
  332. ; see if we need write access or if we can use read only
  333. (define dbmode (if (or (string=? "add" mode)
  334. (string=? "update" mode))
  335. 'read/write
  336. 'read-only))
  337. ; open the database with the specified mode
  338. (define conn (sqlite3-connect #:database dbloc
  339. #:mode dbmode))
  340. ; now handle the user's request
  341. (cond
  342. [(string=? "create-database" mode) (checkdb conn)]
  343. [(string=? "add" mode) (addnew conn)]
  344. [(string=? "update" mode) (findpending conn)]
  345. [(string=? "stats" mode) (proposal-stats conn)]
  346. [(string=? "list-open-calls" mode) (print-open-calls conn)]
  347. [(string=? "list-open" mode) (printprop conn #:submitted #t)]
  348. [(string=? "list-closed" mode) (printprop conn #:submitted #f)]
  349. [(string=? "list-accepted" mode) (printprop conn #:submitted #f #:accepted #t)]
  350. [(string=? "list-rejected" mode) (printprop conn #:submitted #f #:rejected #t)]
  351. [else (error (string-append "Unknown mode. Try " progname " help\n\n"))])
  352. ; close the databse
  353. (disconnect conn))
  354. (querysys (mode))