/
main.go
343 lines (290 loc) · 8.63 KB
/
main.go
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
/*
Get Mesh terms for PMIDs
1 - Read pmids from stdin
i.e. "bunzip2 -c pmid_distinct_random_sorted.txt.bz2 |..."
2 - Create 1 + n files:
pubmed.mesh.gz - id on one line followed by indented mesh terms, one per line
pubmed_xml_0.gz
pubmed_xml_....n.gz
XML downloaded, in 5000 record chunks
Find largest PMID: MAX PMID: https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&reldate=60&datetype=pdat&retmax=1
NCBI: large jobs:
"In order not to overload the E-utility servers, NCBI recommends that users post no more than three URL requests per second and limit large jobs to either weekends or between 9:00 PM and 5:00 AM Eastern time during weekdays. "
- https://www.ncbi.nlm.nih.gov/books/NBK25497/
*/
import (
"bufio"
//"bytes"
"compress/gzip"
"crypto/tls"
//"encoding/xml"
//"fmt"
// "crypto/tls"
"errors"
"flag"
"fmt"
"github.com/gnewton/gopubmed"
// "io"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var recordsPerFile = 50000
//////////
var recordsPerHttpRequest = 50
var recordsPerHttpRequestAfterHours = 150
var timeMin float64 = 2.0
var timeMax float64 = 8.0
var timeMinAfterHours float64 = 0.25
var timeMaxAfterHours float64 = 1.5
////////
var readFromStdin = false
var writeMesh = false
var defaultIdFile = "ids.txt"
const baseXmlFileName = "pubmed_xml_"
var meshFileName = "pubmed.mesh.gz"
var inputFileName = ""
var verbose = false
func init() {
//gopubmed.Debug = true
flag.StringVar(&inputFileName, "f", inputFileName, "Name of input file with one pmid per line, if used")
flag.StringVar(&meshFileName, "M", meshFileName, "File to write pmids and mesh terms")
flag.BoolVar(&readFromStdin, "c", readFromStdin, "Read pmids from stdin, one per line")
flag.IntVar(&recordsPerFile, "n", recordsPerFile, "Number of records per output file")
flag.IntVar(&recordsPerHttpRequest, "t", recordsPerHttpRequest, "Number of records per http request to pubmed")
flag.IntVar(&recordsPerHttpRequestAfterHours, "T", recordsPerHttpRequestAfterHours, "Number of records per http request to pubmed, after hours")
flag.BoolVar(&verbose, "v", verbose, "verbose output")
flag.Parse()
if inputFileName == "" && !readFromStdin {
fmt.Println("Either set -c for stdin or -f to read from a file\n")
flag.Usage()
os.Exit(1)
}
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
tr := &http.Transport{
ResponseHeaderTimeout: time.Second * 500,
DisableKeepAlives: false,
DisableCompression: false,
}
var wXml *gzip.Writer = nil
var ww *bufio.Writer = nil
var xFile *os.File = nil
mylog("Opening meshFile file: " + meshFileName)
meshFile, err2 := os.Create(meshFileName)
if err2 != nil {
return
}
gzBufferedMeshWriter := gzip.NewWriter(meshFile)
numIdsPerUrl := findNumIdsPerUrl()
pmids := make([]string, numIdsPerUrl)
urlFetcher := gopubmed.Fetcher{
Ssl: true,
Transport: &http.Transport{
ResponseHeaderTimeout: time.Second * 500,
DisableKeepAlives: false,
DisableCompression: false,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
allCount := 0
count := 0
reader, err := makeReader()
if err != nil {
log.Fatal(err)
}
first := true
chunkCount := 0
for {
thisNumIdsPerUrl := findNumIdsPerUrl()
if numIdsPerUrl != thisNumIdsPerUrl {
numIdsPerUrl = thisNumIdsPerUrl
pmids = make([]string, numIdsPerUrl)
}
line, err := reader.ReadString('\n')
if err != nil {
// You may check here if err == io.EOF
break
}
line = strings.TrimSpace(line)
err = lineChecker(line)
if err != nil {
log.Fatal(err)
}
//mylog(line)
pmids[count] = line
if wXml == nil {
wXml, ww, xFile = makeXmlWriter(allCount, pmids[0])
}
count = count + 1
// Collected enough pmids: get their XML from NIH
if count == numIdsPerUrl {
getPubmedRecords(&urlFetcher, first, gzBufferedMeshWriter, wXml, tr, pmids)
checkTime()
first = false
count = 0
zeroArray(pmids)
} else {
}
allCount += 1
chunkCount += 1
// Start new xml file: close old one: open new one
if chunkCount > recordsPerFile {
fmt.Fprintln(wXml, endPubmedArticleSet)
wXml.Flush()
wXml.Close()
ww.Flush()
wXml, ww, xFile = makeXmlWriter(allCount, pmids[0])
chunkCount = 0
first = true
}
if allCount%500 == 0 {
mylog("Count: " + strconv.Itoa(allCount))
}
}
if count != 0 {
getPubmedRecords(&urlFetcher, first, gzBufferedMeshWriter, wXml, tr, pmids)
}
fmt.Fprintln(wXml, endPubmedArticleSet)
wXml.Flush()
wXml.Close()
ww.Flush()
gzBufferedMeshWriter.Flush()
gzBufferedMeshWriter.Close()
xFile.Close()
}
func zeroArray(a []string) {
for i := 0; i < len(a); i++ {
a[i] = ""
}
}
func getPubmedRecords(urlFetcher *gopubmed.Fetcher, first bool, meshWriter *gzip.Writer, xmlWriter *gzip.Writer, transport *http.Transport, pmids []string) {
preUrlTime := time.Now()
articles, raw, err := urlFetcher.GetArticlesAndRaw(pmids)
if err != nil {
log.Fatal(err)
}
s := string(raw[:len(raw)])
mylog("Records returned: " + strconv.Itoa(len(articles)))
for i := 0; i < len(articles); i++ {
pubmedArticle := articles[i]
if pubmedArticle.MedlineCitation != nil && pubmedArticle.MedlineCitation.MeshHeadingList != nil && pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading != nil {
fmt.Fprint(meshWriter, articles[i].MedlineCitation.PMID.Text)
for j := 0; j < len(pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading); j++ {
fmt.Fprint(meshWriter, "|")
fmt.Fprint(meshWriter, pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading[j].DescriptorName.Attr_UI)
fmt.Fprint(meshWriter, "::"+pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading[j].DescriptorName.Text)
if len(pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading[j].QualifierName) > 0 {
fmt.Fprint(meshWriter, "=")
for q := 0; q < len(pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading[j].QualifierName); q++ {
if q != 0 {
fmt.Fprint(meshWriter, "&")
}
fmt.Fprint(meshWriter, pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading[j].QualifierName[q].Attr_UI)
fmt.Fprint(meshWriter, "::"+pubmedArticle.MedlineCitation.MeshHeadingList.MeshHeading[j].QualifierName[q].Text)
}
}
}
fmt.Fprintln(meshWriter, "")
}
}
if !first {
s = removeFirstNLines(s, 3)
// s = strings.Replace(s, startXml, "", -1)
// s = strings.Replace(s, docType, "", -1)
// s = strings.Replace(s, startPubmedArticleSet, "", -1)
}
s = strings.Replace(s, endPubmedArticleSet, "<!-- breakset -->", -1)
xmlWriter.Write([]byte(s))
postUrlTime := time.Now()
mylog("Total request time:" + postUrlTime.Sub(preUrlTime).String())
}
func makeXmlWriter(fileCount int, startPmid string) (*gzip.Writer, *bufio.Writer, *os.File) {
xmlFileName := "./" + baseXmlFileName + startPmid + ".gz"
xmlFile, err := os.Create(xmlFileName)
if err != nil {
return nil, nil, nil
}
mylog("Opening XML record file: " + xmlFileName)
ww := bufio.NewWriter(xmlFile)
return gzip.NewWriter(ww), ww, xmlFile
}
func findNumIdsPerUrl() int {
if afterHours() {
return recordsPerHttpRequestAfterHours
}
return recordsPerHttpRequest
}
func makeDelayTime() float64 {
if afterHours() {
mylog(" NCBI after hours")
return timeMinAfterHours + rand.Float64()*timeMaxAfterHours
} else {
return timeMin + rand.Float64()*timeMax
}
}
func afterHours() bool {
now := time.Now().UTC()
hour, _, _ := now.Clock()
//return hour < 8 || hour > 18
// hours in UTC; need US East coast (location of NCBI)
return hour < 12 || hour > 22
}
func checkTime() {
now := time.Now()
rand.Seed(int64(now.Nanosecond()/9999999 + now.Second()*100 + now.Hour()))
sleepSeconds := makeDelayTime()
duration := (time.Duration)(sleepSeconds)
time.Sleep(duration * time.Second)
}
func makeReader() (*bufio.Reader, error) {
var inputFile *os.File
if readFromStdin {
mylog("Reading from stdin")
inputFile = os.Stdin
} else {
if inputFileName == "" {
return nil, errors.New("Empty input file name")
}
var err error
inputFile, err = os.Open(inputFileName)
if err != nil {
return nil, err
}
}
reader := bufio.NewReader(inputFile)
return reader, nil
}
func lineChecker(l string) error {
if len(l) == 0 {
return errors.New("Error: Empty line")
}
var n int
var err error
if n, err = strconv.Atoi(l); err != nil {
return errors.New("Error: Expecting pmid (integer); found[" + l + "]")
}
if n <= 0 {
return errors.New("Error: pmids are positive integers; found [" + l + "]")
}
return nil
}
func removeFirstNLines(s string, n int) string {
for i := 0; i < 3; i++ {
n := strings.Index(s, "\n")
s = s[n+1:]
}
return s
}
func mylog(m string) {
if verbose {
log.Println(m)
}
}