importXLSX.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. import os
  2. import pandas
  3. import sys
  4. import importlib
  5. import re
  6. import datetime
  7. import chardet
  8. import json
  9. import math
  10. #same directory!
  11. import labkeyInterface
  12. import labkeyDatabaseBrowser
  13. import labkeyFileBrowser
  14. def connectDB(server):
  15. net=labkeyInterface.labkeyInterface()
  16. qfile='{}.json'.format(server)
  17. fconfig=os.path.join(os.path.expanduser('~'),'.labkey',qfile)
  18. net.init(fconfig)
  19. net.getCSRF()
  20. return labkeyDatabaseBrowser.labkeyDB(net)
  21. def getDB(pars):
  22. try:
  23. return pars['db']
  24. except KeyError:
  25. pass
  26. server=pars.get('server','onko-nix')
  27. db=connectDB(server)
  28. pars['db']=db
  29. return db
  30. def getFields(pars):
  31. project=pars.get('project','DCIS/Study')
  32. schema=pars.get('schema','demographics')
  33. query=pars.get('query','demographics')
  34. db=getDB(pars)
  35. #data on query structure are both in queryDesign and selectRows/metadata content
  36. dsgn=db.getQueryDesign(project,schema,query)
  37. dsgnFields={f['name']:f for f in dsgn['fields']}
  38. ds=db.selectRows(project,schema,query,[])
  39. mdFields={x['name']:x for x in ds['metaData']['fields']}
  40. #in principle, any property from mdFields could get copied
  41. #to content reported from dsgnFields
  42. #try/except to robustify against missing components
  43. copyFields=['lookup']
  44. for f in dsgnFields:
  45. try:
  46. dsgnFields[f].update({x:mdFields[f][x] for x in copyFields})
  47. except KeyError:
  48. # print('{}: {}'.format(p,len(pMap[p])))
  49. pass
  50. return dsgnFields
  51. def getAlias(fields):
  52. fieldMap={}
  53. for f in fields.values():
  54. aliasList=getAliasList(f['importAliases'])
  55. fieldMap.update({x:f['name'] for x in aliasList})
  56. return fieldMap
  57. def invertMap(qmap):
  58. return {qmap[x]:x for x in qmap}
  59. def getVariables(fields,fieldType='LOOKUP',fieldName=None):
  60. #get list of variables of particular type to help manage import
  61. #if type is LOOKUP also return data on lookup query
  62. if fieldName:
  63. return {fieldName:fields[fieldName]['lookupQuery']}
  64. if fieldType=='LOOKUP':
  65. return {f['name']:f['lookupQuery'] for f in fields.values() \
  66. if f['lookupQuery']}
  67. if fieldType=='DATE':
  68. return {f['name']:fieldType for f in fields.values() \
  69. if f['rangeURI'].find('dateTime')>-1}
  70. if fieldType=='DOUBLE':
  71. return {f['name']:fieldType for f in fields.values() \
  72. if f['rangeURI'].find('double')>-1}
  73. return {}
  74. def getLookupMap(pars,fields,fieldName):
  75. #get possible values of categorical variables/factors from labkey
  76. try:
  77. lookup=fields[fieldName]['lookup']
  78. except KeyError:
  79. print(fields[fieldName])
  80. raise KeyError(f'Could not find lookup for {fieldName}')
  81. schema=lookup['schemaName']
  82. query=lookup['queryName']
  83. key=lookup['keyColumn']
  84. val=lookup['displayColumn']
  85. project=lookup.get('containerPath',pars['project'])
  86. db=getDB(pars)
  87. ds=db.selectRows(project,schema,query,[])
  88. cMap={r[val]:r[key] for r in ds['rows']}
  89. return cMap
  90. def parseLookup(lookup,qv):
  91. #parse/convert lookup
  92. #is it key?
  93. try:
  94. return lookup[qv]
  95. except KeyError:
  96. pass
  97. if pandas.isna(qv):
  98. return qv
  99. try:
  100. qv=qv.item()
  101. qv=str(qv)
  102. return lookup[qv]
  103. except AttributeError:
  104. pass
  105. qv=qv.replace('Č','C')
  106. return lookup[qv]
  107. def asKey(qv):
  108. if not qv:
  109. return qv
  110. try:
  111. return int(qv)
  112. except (TypeError,ValueError):
  113. print(f'Failed to parse {qv} as key')
  114. return None
  115. def parseDate(qv):
  116. if not qv:
  117. return qv
  118. #from xls format to native python format
  119. fmts=['datetime','pandas','%d.%m.%y','%Y-%m-%d %H:%M:%S.%f',\
  120. '%d/%m/%Y','%Y-%m-%d %H:%M:%S']
  121. usedFmt=None
  122. for fmt in fmts:
  123. usedFmt=fmt
  124. try:
  125. if fmt=='pandas':
  126. #print(f'Trying {qv} as pandas.Timestamp')
  127. date=pandas.Timestamp.to_pydatetime(qv)
  128. break
  129. elif fmt=='datetime':
  130. #print(f'Trying {qv} as datetime.datetime')
  131. if not isinstance(qv,datetime.datetime):
  132. raise TypeError('Not a datetime object')
  133. date=qv
  134. break
  135. else:
  136. #print(f'Trying {qv} with {fmt}')
  137. date=datetime.datetime.strptime(qv,fmt)
  138. break
  139. except TypeError:
  140. #print('Failed (type): {}'.format(type(qv)))
  141. continue
  142. except ValueError:
  143. #print('Failed (value)')
  144. continue
  145. #sometimes parsing fails
  146. try:
  147. return date.isoformat()
  148. except UnboundLocalError:
  149. print (f'Failed to parse {qv} as date, used {usedFmt}')
  150. return None
  151. def parseDouble(qv):
  152. try:
  153. return float(qv)
  154. except (ValueError,TypeError):
  155. return None
  156. #m
  157. def setMissingLookupValues(filename,xlsFieldName,project,lookup,\
  158. labkeyFieldName=None,dryRun=True):
  159. #list all possible values for a field
  160. #perhaps needs to be updated
  161. df=pandas.read_excel(filename)
  162. vars=df.columns
  163. vals=set([df.at[r,xlsFieldName] for r in df.index if not pandas.isna(df.at[r,xlsFieldName])])
  164. try:
  165. vals={v.item() for v in vals}
  166. except AttributeError:
  167. pass
  168. print(vals)
  169. if not labkeyFieldName:
  170. labkeyFieldName=xlsFieldName
  171. db=connectDB('onko-nix')
  172. ds=db.selectRows(project,'lists',lookup,[])
  173. #only record values from labkey (should be unique anyhow)
  174. setVals=set([r[labkeyFieldName] for r in ds['rows']])
  175. off=len(list(setVals))
  176. missing=sorted(list(vals-setVals))
  177. #print('Missing {}'.format(missing))
  178. n=len(missing)
  179. entries=[{'Key':'{}'.format(i+1+off),columnName:missing[i]} \
  180. for i in range(n)]
  181. print(entries)
  182. if dryRun:
  183. return
  184. db.modifyRows('insert',project,'lists',lookup,entries)
  185. def getAliasList(x):
  186. #split aliases by comma, taking into account quotation marks,
  187. #where commas are ignored
  188. if not x:
  189. return []
  190. #sophisticated spliting that ignores commas in double (and single!) quotes
  191. ar=re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', x)
  192. #remove the quotes afterwards
  193. ar=[s.replace('"','') for s in ar]
  194. ar=[s.strip() for s in ar]
  195. return ar
  196. def printErr(resp):
  197. #print error from server response
  198. try:
  199. print(resp['exception'])
  200. except KeyError:
  201. pass
  202. def findAlias(v,alias):
  203. #find matchng alias for field v from XLS
  204. try:
  205. return alias[v.strip()]
  206. except KeyError:
  207. pass
  208. #remove .N qualifiers, attach to the end by pandas.read_excel
  209. v=re.sub(r'(.*)\.[0-9]*$',r'\1',v.strip())
  210. try:
  211. return alias[v]
  212. except KeyError:
  213. pass
  214. return None
  215. def getSequenceNum(pMap,id):
  216. #updates pMap and return seqnum for this entry
  217. try:
  218. n=len(pMap[id])
  219. except KeyError:
  220. n=0
  221. seqNum=n+1
  222. if n==0:
  223. pMap[id]=[seqNum]
  224. else:
  225. pMap[id].append(seqNum)
  226. return seqNum
  227. def entryInList(r,entries):
  228. #is entry in list
  229. candidates=[x for x in entries if entriesMatch(x,r)]
  230. return len(candidates)>0
  231. def entriesMatch(x,r):
  232. #do a pair of entries match? Should we update data from one over the other?
  233. matchFields=['ParticipantId','SequenceNum']
  234. for f in matchFields:
  235. if x[f]!=r[f]:
  236. return False
  237. return True
  238. def validate(qv):
  239. #rough checks on value read from XLSX
  240. #NAN
  241. try:
  242. if math.isnan(qv):
  243. return None
  244. except TypeError:
  245. pass
  246. #NAD
  247. if pandas.isnull(qv):
  248. return None
  249. return qv
  250. #defaults for modify, getId and convertLookup
  251. def modify(qv,columnName):
  252. return qv
  253. def getId(df,r):
  254. try:
  255. rawId=str(df.at[r,'ID'])
  256. except KeyError:
  257. msg='Getting id from field ID field. '
  258. msg+=' Overload getId function with getId=getIdFnc in importData'
  259. print(msg)
  260. raise KeyError
  261. return rawId.replace(' ','')
  262. def convertLookup(xlsColumnName):
  263. return True
  264. def rowValid(df,r):
  265. return True
  266. def updateAndValidateEntry(e):
  267. return True
  268. def importData(pars,filename,getId=getId,modify=modify,\
  269. convertLookup=convertLookup,dryRun=True,debug=True,
  270. rowValid=rowValid,updateAndValidateEntry=updateAndValidateEntry):
  271. #master routine that imports data based on pars,
  272. #applies user supplied functions modify, convertLookup and get Id and
  273. #updates relevant database
  274. #rowValid signals a valid row, argument is current row from xlsx
  275. #updateAndValidateEntry can add fields that can be computed from other fields in entry and allows to reject entries not matching a target pattern
  276. #some useful fields from pars (d is for default value)
  277. # - skiprows removes irelevant rows (number, d: 0)
  278. # - usecols is EXCEL like notations for cols taken (identifer, d: None for all)
  279. # - sheet_name selects sheet for import (number, d:0 for first sheet)
  280. # - seqNumOffset specify visit/sequenceNum offset (number, d:0 will result in 1)
  281. # - project - labkey project
  282. # - schema - labkey schema (list/study, d: study)
  283. # - query - labkey query
  284. # - additionalVars - values that are constant for the whole dataset, labeled by a valid alias for a labkey field
  285. skiprows=pars.get('skiprows',0)
  286. usecols=pars.get('usecols',None)
  287. sheet_name=pars.get('sheet_name',0)
  288. #set this is as sequenceNum for entries, or initial seqNum if more than a single entry is in the dataset
  289. seqNumOffset=pars.get('seqNumOffset',0)
  290. additionalVars=pars.get('additionalVars',{})
  291. idField=pars.get('idField','ParticipantId')
  292. fields=getFields(pars)
  293. lookupVars=getVariables(fields,fieldType='LOOKUP')
  294. dateVars=getVariables(fields,fieldType='DATE')
  295. doubleVars=getVariables(fields,fieldType='DOUBLE')
  296. usecols=pars.get('usecols',None)
  297. #convert dates to list
  298. dateVars=list(dateVars.keys())
  299. print(f'dateVars: {dateVars}')
  300. lookupMap={f:getLookupMap(pars,fields,f) for f in lookupVars}
  301. if debug:
  302. print(lookupMap)
  303. alias=getAlias(fields)
  304. print(f'aliases: {alias}')
  305. df=pandas.read_excel(filename,sheet_name=sheet_name,skiprows=skiprows,\
  306. usecols=usecols)
  307. vars=df.columns
  308. print(vars)
  309. pMap={}
  310. print('Index: {}'.format(len(df.index)))
  311. idx=df.index #for all
  312. if debug:
  313. idx=df.index[0:10] #for debug
  314. entries=[]
  315. for r in idx:
  316. if not rowValid(df,r):
  317. continue
  318. id=getId(df,r)
  319. entry={}
  320. entry[idField]=id
  321. for v in vars:
  322. qv=validate(df.at[r,v])
  323. qv=modify(qv,v)
  324. f=findAlias(v,alias)
  325. if not f:
  326. continue
  327. if f in lookupMap:
  328. if convertLookup(v):
  329. qv=parseLookup(lookupMap[f],qv)
  330. else:
  331. qv=asKey(qv)
  332. if f in dateVars:
  333. qv=parseDate(qv)
  334. if f in doubleVars:
  335. qv=parseDouble(qv)
  336. try:
  337. numpyType=qv.dtype
  338. qv=qv.item()
  339. except AttributeError:
  340. pass
  341. entry[f]=qv
  342. #print('{}:{}/{}'.format(f,qv,type(qv)))
  343. for v in additionalVars:
  344. f=findAlias(v,alias)
  345. qv=additionalVars[v]
  346. if f in lookupMap:
  347. qv=parseLookup(lookupMap[f],qv)
  348. entry[f]=qv
  349. seqNum=getSequenceNum(pMap,id)
  350. entry['SequenceNum']=seqNum+seqNumOffset
  351. #set date also? Use pars to find dateVariable
  352. try:
  353. dateVariable=pars['dateVariable']
  354. entry['Date']=entry[dateVariable]
  355. except KeyError:
  356. pass
  357. if not updateAndValidateEntry(entry):
  358. continue
  359. entries.append(entry)
  360. print(entries)
  361. #delete previous incarnations
  362. loadSafely(pars,entries,dryRun=dryRun)
  363. def loadSafely(pars,entries,dryRun=True):
  364. #allow additional keys in keyColumn
  365. db=getDB(pars)
  366. project=pars.get('project','DCIS/Study')
  367. schema=pars.get('schema','demographics')
  368. query=pars.get('query','demographics')
  369. idField=pars.get('idField','ParticipantId')
  370. #add columns from labkey that will be checked to find a match
  371. matchColumns=pars.get('matchColumns',[])
  372. #whether to insert new entries
  373. matchOnly=pars.get('matchOnly',False)
  374. #print rows to be inserted, debugging feature
  375. printRows=pars.get('printRows',False)
  376. updateRows=[]
  377. insertRows=[]
  378. selVal=[idField,'SequenceNum']
  379. selVal.extend(matchColumns)
  380. print(f'Matching by {selVal}')
  381. for entry in entries:
  382. qFilter=[{'variable':v,'value':'{}'.format(entry[v]),'oper':'eq'} for v in selVal]
  383. ds=db.selectRows(project,schema,query,qFilter)
  384. if len(ds['rows'])>0:
  385. r=ds['rows'][0]
  386. r.update(entry)
  387. updateRows.append(r)
  388. else:
  389. insertRows.append(entry)
  390. #update rows
  391. n=len(updateRows)
  392. print(f'Updating {n} entries')
  393. if printRows:
  394. print(updateRows)
  395. if n and not dryRun:
  396. printErr(db.modifyRows('update',project,schema,query,updateRows))
  397. #insert rows
  398. n=len(insertRows)
  399. print(f'Inserting {n} entries')
  400. if matchOnly:
  401. print('Inserting supressed by matchOnly flag')
  402. return
  403. if printRows:
  404. print(insertRows)
  405. if n and not dryRun:
  406. printErr(db.modifyRows('insert',project,schema,query,insertRows))