importXLSX.py 11 KB

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