importXLSX.py 11 KB

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