importXLSX.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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','type']
  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,field):
  108. if not qv:
  109. return qv
  110. if not field['type']=='int':
  111. return qv
  112. try:
  113. return int(qv)
  114. except (TypeError,ValueError):
  115. print(f'Failed to parse {qv} as key')
  116. return None
  117. def parseDate(qv):
  118. if not qv:
  119. return qv
  120. #from xls format to native python format
  121. fmts=['datetime','pandas','%d.%m.%y','%Y-%m-%d %H:%M:%S.%f',\
  122. '%d/%m/%Y','%Y-%m-%d %H:%M:%S']
  123. usedFmt=None
  124. for fmt in fmts:
  125. usedFmt=fmt
  126. try:
  127. if fmt=='pandas':
  128. #print(f'Trying {qv} as pandas.Timestamp')
  129. date=pandas.Timestamp.to_pydatetime(qv)
  130. break
  131. elif fmt=='datetime':
  132. #print(f'Trying {qv} as datetime.datetime')
  133. if not isinstance(qv,datetime.datetime):
  134. raise TypeError('Not a datetime object')
  135. date=qv
  136. break
  137. else:
  138. #print(f'Trying {qv} with {fmt}')
  139. date=datetime.datetime.strptime(qv,fmt)
  140. break
  141. except TypeError:
  142. #print('Failed (type): {}'.format(type(qv)))
  143. continue
  144. except ValueError:
  145. #print('Failed (value)')
  146. continue
  147. #sometimes parsing fails
  148. try:
  149. return date.isoformat()
  150. except UnboundLocalError:
  151. print (f'Failed to parse {qv} as date, used {usedFmt}')
  152. return None
  153. def parseDouble(qv):
  154. try:
  155. return float(qv)
  156. except (ValueError,TypeError):
  157. return None
  158. #m
  159. def setMissingLookupValues(filename,xlsFieldName,project,lookup,\
  160. labkeyFieldName=None,dryRun=True):
  161. #list all possible values for a field
  162. #perhaps needs to be updated
  163. df=pandas.read_excel(filename)
  164. vars=df.columns
  165. vals=set([df.at[r,xlsFieldName] for r in df.index if not pandas.isna(df.at[r,xlsFieldName])])
  166. try:
  167. vals={v.item() for v in vals}
  168. except AttributeError:
  169. pass
  170. print(vals)
  171. if not labkeyFieldName:
  172. labkeyFieldName=xlsFieldName
  173. db=connectDB('onko-nix')
  174. ds=db.selectRows(project,'lists',lookup,[])
  175. #only record values from labkey (should be unique anyhow)
  176. setVals=set([r[labkeyFieldName] for r in ds['rows']])
  177. off=len(list(setVals))
  178. missing=sorted(list(vals-setVals))
  179. #print('Missing {}'.format(missing))
  180. n=len(missing)
  181. entries=[{'Key':'{}'.format(i+1+off),columnName:missing[i]} \
  182. for i in range(n)]
  183. print(entries)
  184. if dryRun:
  185. return
  186. db.modifyRows('insert',project,'lists',lookup,entries)
  187. def getAliasList(x):
  188. #split aliases by comma, taking into account quotation marks,
  189. #where commas are ignored
  190. if not x:
  191. return []
  192. #sophisticated spliting that ignores commas in double (and single!) quotes
  193. ar=re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', x)
  194. #remove the quotes afterwards
  195. ar=[s.replace('"','') for s in ar]
  196. ar=[s.strip() for s in ar]
  197. return ar
  198. def printErr(resp):
  199. #print error from server response
  200. try:
  201. print(resp['exception'])
  202. except KeyError:
  203. pass
  204. def findAlias(v,alias):
  205. #find matchng alias for field v from XLS
  206. try:
  207. return alias[v.strip()]
  208. except KeyError:
  209. pass
  210. #remove .N qualifiers, attach to the end by pandas.read_excel
  211. v=re.sub(r'(.*)\.[0-9]*$',r'\1',v.strip())
  212. try:
  213. return alias[v]
  214. except KeyError:
  215. pass
  216. return None
  217. def getSequenceNum(pMap,id):
  218. #updates pMap and return seqnum for this entry
  219. try:
  220. n=len(pMap[id])
  221. except KeyError:
  222. n=0
  223. seqNum=n+1
  224. if n==0:
  225. pMap[id]=[seqNum]
  226. else:
  227. pMap[id].append(seqNum)
  228. return seqNum
  229. def entryInList(r,entries):
  230. #is entry in list
  231. candidates=[x for x in entries if entriesMatch(x,r)]
  232. return len(candidates)>0
  233. def entriesMatch(x,r):
  234. #do a pair of entries match? Should we update data from one over the other?
  235. matchFields=['ParticipantId','SequenceNum']
  236. for f in matchFields:
  237. if x[f]!=r[f]:
  238. return False
  239. return True
  240. def validate(qv):
  241. #rough checks on value read from XLSX
  242. #NAN
  243. try:
  244. if math.isnan(qv):
  245. return None
  246. except TypeError:
  247. pass
  248. #NAD
  249. if pandas.isnull(qv):
  250. return None
  251. return qv
  252. #defaults for modify, getId and convertLookup
  253. def modify(qv,columnName):
  254. return qv
  255. def getId(df,r,pars):
  256. try:
  257. rawId=str(df.at[r,'ID'])
  258. except KeyError:
  259. msg='Getting id from field ID field. '
  260. msg+=' Overload getId function with getId=getIdFnc in importData'
  261. print(msg)
  262. raise KeyError
  263. return rawId.replace(' ','')
  264. def convertLookup(xlsColumnName):
  265. return True
  266. def rowValid(df,r,pars):
  267. return True
  268. def updateAndValidateEntry(e,pars):
  269. return True
  270. def importData(pars,filename,getId=getId,modify=modify,\
  271. convertLookup=convertLookup,dryRun=True,debug=True,
  272. rowValid=rowValid,updateAndValidateEntry=updateAndValidateEntry):
  273. #master routine that imports data based on pars,
  274. #applies user supplied functions modify, convertLookup and get Id and
  275. #updates relevant database
  276. #rowValid signals a valid row, argument is current row from xlsx
  277. #updateAndValidateEntry can add fields that can be computed from other fields in entry and allows to reject entries not matching a target pattern
  278. #some useful fields from pars (d is for default value)
  279. # - skiprows removes irelevant rows (number, d: 0)
  280. # - usecols is EXCEL like notations for cols taken (identifer, d: None for all)
  281. # - sheet_name selects sheet for import (number, d:0 for first sheet)
  282. # - seqNumOffset specify visit/sequenceNum offset (number, d:0 will result in 1)
  283. # - project - labkey project
  284. # - schema - labkey schema (list/study, d: study)
  285. # - query - labkey query
  286. # - additionalVars - values that are constant for the whole dataset, labeled by a valid alias for a labkey field
  287. skiprows=pars.get('skiprows',0)
  288. usecols=pars.get('usecols',None)
  289. sheet_name=pars.get('sheet_name',0)
  290. #set this is as sequenceNum for entries, or initial seqNum if more than a single entry is in the dataset
  291. seqNumOffset=pars.get('seqNumOffset',0)
  292. additionalVars=pars.get('additionalVars',{})
  293. idField=pars.get('idField','ParticipantId')
  294. fields=getFields(pars)
  295. lookupVars=getVariables(fields,fieldType='LOOKUP')
  296. dateVars=getVariables(fields,fieldType='DATE')
  297. doubleVars=getVariables(fields,fieldType='DOUBLE')
  298. usecols=pars.get('usecols',None)
  299. #convert dates to list
  300. dateVars=list(dateVars.keys())
  301. print(f'dateVars: {dateVars}')
  302. lookupMap={f:getLookupMap(pars,fields,f) for f in lookupVars}
  303. if debug:
  304. print(lookupMap)
  305. alias=getAlias(fields)
  306. print(f'aliases: {alias}')
  307. df=pandas.read_excel(filename,sheet_name=sheet_name,skiprows=skiprows,\
  308. usecols=usecols)
  309. vars=df.columns
  310. print(vars)
  311. pMap={}
  312. print('Index: {}'.format(len(df.index)))
  313. idx=df.index #for all
  314. if debug:
  315. idx=df.index[0:10] #for debug
  316. entries=[]
  317. for r in idx:
  318. if not rowValid(df,r,pars):
  319. continue
  320. id=getId(df,r,pars)
  321. entry={}
  322. entry[idField]=id
  323. for v in vars:
  324. qv=validate(df.at[r,v])
  325. qv=modify(qv,v)
  326. f=findAlias(v,alias)
  327. if not f:
  328. continue
  329. if f in lookupMap:
  330. if convertLookup(v):
  331. qv=parseLookup(lookupMap[f],qv)
  332. else:
  333. qv=asKey(qv,fields[f])
  334. if f in dateVars:
  335. qv=parseDate(qv)
  336. if f in doubleVars:
  337. qv=parseDouble(qv)
  338. try:
  339. numpyType=qv.dtype
  340. qv=qv.item()
  341. except AttributeError:
  342. pass
  343. entry[f]=qv
  344. #print('{}:{}/{}'.format(f,qv,type(qv)))
  345. for v in additionalVars:
  346. f=findAlias(v,alias)
  347. qv=additionalVars[v]
  348. if f in lookupMap:
  349. qv=parseLookup(lookupMap[f],qv)
  350. entry[f]=qv
  351. seqNum=getSequenceNum(pMap,id)
  352. entry['SequenceNum']=seqNum+seqNumOffset
  353. #set date also? Use pars to find dateVariable
  354. try:
  355. dateVariable=pars['dateVariable']
  356. entry['Date']=entry[dateVariable]
  357. except KeyError:
  358. pass
  359. if not updateAndValidateEntry(entry,pars):
  360. continue
  361. entries.append(entry)
  362. print(entries)
  363. #delete previous incarnations
  364. loadSafely(pars,entries,dryRun=dryRun)
  365. def loadSafely(pars,entries,dryRun=True):
  366. #allow additional keys in keyColumn
  367. db=getDB(pars)
  368. project=pars.get('project','DCIS/Study')
  369. schema=pars.get('schema','demographics')
  370. query=pars.get('query','demographics')
  371. idField=pars.get('idField','ParticipantId')
  372. #add columns from labkey that will be checked to find a match
  373. matchColumns=pars.get('matchColumns',[])
  374. #whether to insert new entries
  375. matchOnly=pars.get('matchOnly',False)
  376. #print rows to be inserted, debugging feature
  377. printRows=pars.get('printRows',False)
  378. updateRows=[]
  379. insertRows=[]
  380. selVal=[idField,'SequenceNum']
  381. selVal.extend(matchColumns)
  382. print(f'Matching by {selVal}')
  383. for entry in entries:
  384. qFilter=[{'variable':v,'value':'{}'.format(entry[v]),'oper':'eq'} for v in selVal]
  385. ds=db.selectRows(project,schema,query,qFilter)
  386. if len(ds['rows'])>0:
  387. r=ds['rows'][0]
  388. r.update(entry)
  389. updateRows.append(r)
  390. else:
  391. insertRows.append(entry)
  392. #update rows
  393. n=len(updateRows)
  394. print(f'Updating {n} entries')
  395. if printRows:
  396. print(updateRows)
  397. if n and not dryRun:
  398. printErr(db.modifyRows('update',project,schema,query,updateRows))
  399. #insert rows
  400. n=len(insertRows)
  401. print(f'Inserting {n} entries')
  402. if matchOnly:
  403. print('Inserting supressed by matchOnly flag')
  404. return
  405. if printRows:
  406. print(insertRows)
  407. if n and not dryRun:
  408. printErr(db.modifyRows('insert',project,schema,query,insertRows))