aboutsummaryrefslogtreecommitdiff
path: root/scripts/precompute/list-traits-to-compute.scm
blob: 199f457765051944d3c515cc81961b719cdd31c9 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/bin/env guile \
-e main -s

Step p1 lists traits that need to be computed.

This is a script that fetches trait IDs from the GN database
directly. The direct database calls are used right now and ought to be
turned into a REST API.

Run from base dir with

    . .guix-shell -- guile -L . -e main -s ./scripts/precompute/list-traits-to-compute.scm

You may want to forward a mysql port if there is no DB locally

    ssh -L 3306:127.0.0.1:3306 -f -N tux02.genenetwork.org

test connection with mysql client:

    mysql -uwebqtlout -pwebqtlout -A -h 127.0.0.1 -P 3306 db_webqtl -e "show tables;"

you can ignore the IPv6 message:

    bind [::1]:3306: Cannot assign requested address

to create a clean slate, for now, update Locus_old with

    update ProbeSetXRef set Locus_old=NULL;

you should see

    MariaDB [db_webqtl]> select count(Locus_old) from ProbeSetXRef where Locus_old != NULL limit 5;
    +------------------+
    | count(Locus_old) |
    +------------------+
    |                0 |
    +------------------+

Now list the next 1000 trait IDs:

    . .guix-shell -- guile -L . -e main -s ./scripts/precompute/list-traits-to-compute.scm --next 1000

The current logic is to list all datasets that contain a
BXD. (bxd-strain-id-names #:used-for-mapping? #t) fetches all ids and
strain names listed in GN. Note that this differs from the actual
genotype file.

To find the StrainId in a dataset:

MariaDB [db_webqtl]> SELECT StrainId,value from ProbeSetData WHERE Id=115467;
+----------+---------+
| StrainId | value   |
+----------+---------+
|        1 | 9.47169 |
|        2 | 9.21621 |
|        3 |   9.728 |
|        4 | 9.28976 |
|        5 | 9.55523 |
|        6 | 9.63562 ...

to speed things up a little we batch them up and check whether the BXD is part of it.
When that is the case we might as well write the phenotype file because we have the trait values.

!#

(use-modules (dbi dbi)
             (gn db mysql)
             (gn data dataset)
             (gn data hits)
             (gn data strains)
             (gn util convert)
             (gn runner gemma)
             ; (rnrs base)
             (hashing sha-2)
             (ice-9 getopt-long)
             (ice-9 match)
             (ice-9 textual-ports)
             (json)
             (rnrs bytevectors)
             (srfi srfi-1)
             (srfi srfi-9)
             (srfi srfi-19) ; time
             )

(define (get-trait db probeset-id)
  (dbi-query db (string-append "select Id,Chr,Mb,Name,Symbol,description from ProbeSet where Id=" (int-to-string probeset-id) " limit 1"))
  (get-row db)
  )

#!

The following is produced by gemma-wrapper as metadata

  "meta": {
    "type": "gemma-wrapper",
    "version": "0.99.7-pre1",
    "population": "BXD",
    "name": "HC_U_0304_R",
    "trait": "101500_at",
    "url": "https://genenetwork.org/show_trait?trait_id=101500_at&dataset=HC_U_0304_R",
    "archive_GRM": "46bfba373fe8c19e68be6156cad3750120280e2e-gemma-cXX.tar.xz",
    "archive_GWA": "779a54a59e4cd03608178db4068791db4ca44ab3-gemma-GWA.tar.xz",
    "dataid": 75629,
    "probesetid": 1097,
    "probesetfreezeid": 7
    }

!#


(define (write-json-ld id dataset-id recs)
  ;; see also https://www.w3.org/2018/jsonld-cg-reports/json-ld/
  (display id)
  (display ":")
  (display dataset-id)
  (newline)
  (let* [(traits (map (lambda (r)
                        (match r
                          [(strain-id . value) (cons (bxd-name strain-id) value)]
                          ))
                      (reverse recs)))
         (sha256 (sha-256->string (sha-256 (string->utf8 (scm->json-string traits)))))
         (json-data `(("@context" . "https://genenetwork.org/resource")
                      (type . traits)
                      (meta . ((version . "0.1")
                               (steps . ())
                               (sha256 . ((input-traits . ,sha256)))
                               (time . ,(date->string (time-utc->date (current-time))))))
                      (data .
                            ((,id .
                                  ((dataset . ,dataset-id)
                                   (traits . ,traits)))))))]
    (call-with-output-file (string-append (number->string id) ".json")
      (lambda (port)
        (put-string port (scm->json-string json-data))))
  ))

(define (write-phenotypes first-id num batch-size)
  (call-with-db
   (lambda (db)
   (begin
     ;; (let [(bxd-strains (memo-bxd-strain-id-names #:used-for-mapping? #t))]
       (display "writing-phenotypes...")
       (define (run-list-traits-to-compute db num prev-id)
         (let* [(count (if (< batch-size num)
                           batch-size
                           num))
                (rest (- num count))
                (hits (get-precompute-hits db prev-id count))
                (data-ids (map (lambda (h)
                                 (hit-data-id h))
                               hits))
                (data-str-ids (map (lambda (id) (string-append "Id=" (int-to-string id))) data-ids))
                (data-ids-query (string-join data-str-ids " OR "))
                (query (string-append "SELECT Id,StrainId,value FROM ProbeSetData WHERE " data-ids-query))
                ]
           (display query)
           (dbi-query db query)
           ;; ---- Walk each resulting trait
           (let [(id-traits (get-rows db '()))
                 (nrecs '())]
             (for-each (lambda (r)
                    (let* [(data-id (assoc-ref r "Id"))
                           (strain-id (assoc-ref r "StrainId"))
                           (value (assoc-ref r "value"))
                           (has-lst (assoc-ref nrecs data-id))
                           (lst (if has-lst
                                    (acons strain-id value has-lst)
                                    `((,strain-id . ,value)))
                                )]
                      (set! nrecs (assoc-set! nrecs data-id lst))))
                       id-traits)
             ;; --- create the json output as a file
             (for-each (lambda (r h)
                         ;; (let* [;; (probeset-id (assoc-ref hit "ProbeSetId"))
                                ;; (data-id (assoc-ref hit "DataId"))
                                ;; (data-id-str (int-to-string data-id))
                                ;; (probesetfreeze-id (assoc-ref hit "ProbeSetFreezeId"))
                                ;; (trait (get-trait db probeset-id))
                                ;; (trait-name (assoc-ref trait "Name"))
                                ;; (name (dataset-name db probesetfreeze-id))
                               ;; ]
                           (match r
                             ((id . recs) (if (has-bxd? recs)
                                              (write-json-ld id (hit-probeset-id h) recs)
                                              ))
                             )) nrecs hits)
             (if (> rest 0)
                 (run-list-traits-to-compute db rest (first (reverse data-ids)))) ;; start precompute
           )))
       (run-list-traits-to-compute db num first-id) ;; start precompute
       ))))


(define (main args)
  ;; (write args)
  (let* ((option-spec '( (version (single-char #\v) (value #f))
                         (start-id (single-char #\s) (value #t))
                         (next (single-char #\n) (value #t))
                         (help    (single-char #\h) (value #f))))
         (options (getopt-long args option-spec))
         (start-id (string->number (option-ref options 'start-id "0")))
         (next (string->number (option-ref options 'next "5")))
         (help-wanted (option-ref options 'help #f)))
    (if help-wanted
        (format #t "list-traits-to-compute writes JSON traits files from the GN DB
Usage: list-traits-to-compute [options...]
  -s, --start-id num  Start from ID (default 0)
  -n, --next count    In batches of count size (default 5)
  -h, --help          Display this help
")
        (write-phenotypes start-id next 500) ;; batch size 500 appears to work best on my machine
)))