Package Gnumed :: Package business :: Module gmClinNarrative
[frames] | no frames]

Source Code for Module Gnumed.business.gmClinNarrative

  1  """GNUmed clinical narrative business object.""" 
  2  #============================================================ 
  3  __version__ = "$Revision: 1.45 $" 
  4  __author__ = "Carlos Moro <cfmoro1976@yahoo.es>, Karsten Hilbert <Karsten.Hilbert@gmx.net>" 
  5  __license__ = 'GPL (for details see http://gnu.org)' 
  6   
  7  import sys, logging 
  8   
  9   
 10  if __name__ == '__main__': 
 11          sys.path.insert(0, '../../') 
 12  from Gnumed.pycommon import gmPG2, gmExceptions, gmBusinessDBObject, gmTools, gmDispatcher, gmHooks 
 13   
 14   
 15  try: 
 16          _('dummy-no-need-to-translate-but-make-epydoc-happy') 
 17  except NameError: 
 18          _ = lambda x:x 
 19   
 20   
 21  _log = logging.getLogger('gm.emr') 
 22  _log.info(__version__) 
 23   
 24   
 25  soap_cat2l10n = { 
 26          's': _('soap_S').replace(u'soap_', u''), 
 27          'o': _('soap_O').replace(u'soap_', u''), 
 28          'a': _('soap_A').replace(u'soap_', u''), 
 29          'p': _('soap_P').replace(u'soap_', u''), 
 30          #None: _('soap_ADMIN').replace(u'soap_', u'') 
 31          None: gmTools.u_ellipsis, 
 32          u'': gmTools.u_ellipsis 
 33  } 
 34   
 35  soap_cat2l10n_str = { 
 36          's': _('soap_Subjective').replace(u'soap_', u''), 
 37          'o': _('soap_Objective').replace(u'soap_', u''), 
 38          'a': _('soap_Assessment').replace(u'soap_', u''), 
 39          'p': _('soap_Plan').replace(u'soap_', u''), 
 40          None: _('soap_Administrative').replace(u'soap_', u'') 
 41  } 
 42   
 43  l10n2soap_cat = { 
 44          _('soap_S').replace(u'soap_', u''): 's', 
 45          _('soap_O').replace(u'soap_', u''): 'o', 
 46          _('soap_A').replace(u'soap_', u''): 'a', 
 47          _('soap_P').replace(u'soap_', u''): 'p', 
 48          #_('soap_ADMIN').replace(u'soap_', u''): None 
 49          gmTools.u_ellipsis: None 
 50  } 
 51   
 52  #============================================================ 
53 -def _on_soap_modified():
54 """Always relates to the active patient.""" 55 gmHooks.run_hook_script(hook = u'after_soap_modified')
56 57 gmDispatcher.connect(_on_soap_modified, u'clin_narrative_mod_db') 58 59 #============================================================
60 -class cDiag(gmBusinessDBObject.cBusinessDBObject):
61 """Represents one real diagnosis. 62 """ 63 _cmd_fetch_payload = u"select *, xmin_clin_diag, xmin_clin_narrative from clin.v_pat_diag where pk_diag=%s" 64 _cmds_store_payload = [ 65 u"""update clin.clin_diag set 66 laterality=%()s, 67 laterality=%(laterality)s, 68 is_chronic=%(is_chronic)s::boolean, 69 is_active=%(is_active)s::boolean, 70 is_definite=%(is_definite)s::boolean, 71 clinically_relevant=%(clinically_relevant)s::boolean 72 where 73 pk=%(pk_diag)s and 74 xmin=%(xmin_clin_diag)s""", 75 u"""update clin.clin_narrative set 76 narrative=%(diagnosis)s 77 where 78 pk=%(pk_diag)s and 79 xmin=%(xmin_clin_narrative)s""", 80 u"""select xmin_clin_diag, xmin_clin_narrative from clin.v_pat_diag where pk_diag=%s(pk_diag)s""" 81 ] 82 83 _updatable_fields = [ 84 'diagnosis', 85 'laterality', 86 'is_chronic', 87 'is_active', 88 'is_definite', 89 'clinically_relevant' 90 ] 91 #--------------------------------------------------------
92 - def get_codes(self):
93 """ 94 Retrieves codes linked to this diagnosis 95 """ 96 cmd = u"select code, coding_system from clin.v_codes4diag where diagnosis=%s" 97 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [self._payload[self._idx['diagnosis']]]}]) 98 return rows
99 #--------------------------------------------------------
100 - def add_code(self, code=None, coding_system=None):
101 """ 102 Associates a code (from coding system) with this diagnosis. 103 """ 104 # insert new code 105 cmd = u"select clin.add_coded_phrase (%(diag)s, %(code)s, %(sys)s)" 106 args = { 107 'diag': self._payload[self._idx['diagnosis']], 108 'code': code, 109 'sys': coding_system 110 } 111 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}]) 112 return True
113 #============================================================
114 -class cNarrative(gmBusinessDBObject.cBusinessDBObject):
115 """Represents one clinical free text entry. 116 """ 117 _cmd_fetch_payload = u"select *, xmin_clin_narrative from clin.v_pat_narrative where pk_narrative=%s" 118 _cmds_store_payload = [ 119 u"""update clin.clin_narrative set 120 narrative = %(narrative)s, 121 clin_when = %(date)s, 122 soap_cat = lower(%(soap_cat)s), 123 fk_encounter = %(pk_encounter)s 124 where 125 pk=%(pk_narrative)s and 126 xmin=%(xmin_clin_narrative)s""", 127 u"""select xmin_clin_narrative from clin.v_pat_narrative where pk_narrative=%(pk_narrative)s""" 128 ] 129 130 _updatable_fields = [ 131 'narrative', 132 'date', 133 'soap_cat', 134 'pk_episode', 135 'pk_encounter' 136 ] 137 138 #xxxxxxxxxxxxxxxx 139 # support row_version in view 140 141 #--------------------------------------------------------
142 - def get_codes(self):
143 """Retrieves codes linked to *this* narrative. 144 """ 145 cmd = u"select code, xfk_coding_system from clin.coded_phrase where term=%s" 146 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': [self._payload[self._idx['narrative']]]}]) 147 return rows
148 #--------------------------------------------------------
149 - def add_code(self, code=None, coding_system=None):
150 """ 151 Associates a code (from coding system) with this narrative. 152 """ 153 # insert new code 154 cmd = u"select clin.add_coded_phrase (%(narr)s, %(code)s, %(sys)s)" 155 args = { 156 'narr': self._payload[self._idx['narrative']], 157 'code': code, 158 'sys': coding_system 159 } 160 gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}]) 161 return True
162 #--------------------------------------------------------
163 - def format(self, left_margin=u'', fancy=False, width=75):
164 165 if fancy: 166 # FIXME: add revision 167 txt = gmTools.wrap ( 168 text = _('%s: %s by %.8s\n%s') % ( 169 self._payload[self._idx['date']].strftime('%x %H:%M'), 170 soap_cat2l10n_str[self._payload[self._idx['soap_cat']]], 171 self._payload[self._idx['provider']], 172 self._payload[self._idx['narrative']] 173 ), 174 width = width, 175 initial_indent = u'', 176 subsequent_indent = left_margin + u' ' 177 ) 178 else: 179 txt = u'%s [%s]: %s (%.8s)' % ( 180 self._payload[self._idx['date']].strftime('%x %H:%M'), 181 soap_cat2l10n[self._payload[self._idx['soap_cat']]], 182 self._payload[self._idx['narrative']], 183 self._payload[self._idx['provider']] 184 ) 185 if len(txt) > width: 186 txt = txt[:width] + gmTools.u_ellipsis 187 188 return txt
189 190 # lines.append('-- %s ----------' % gmClinNarrative.soap_cat2l10n_str[soap_cat]) 191 192 #============================================================ 193 # convenience functions 194 #============================================================
195 -def search_text_across_emrs(search_term=None):
196 197 if search_term is None: 198 return [] 199 200 if search_term.strip() == u'': 201 return [] 202 203 cmd = u'select * from clin.v_narrative4search where narrative ~* %(term)s order by pk_patient limit 1000' 204 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': {'term': search_term}}], get_col_idx = False) 205 206 return rows
207 #============================================================
208 -def create_clin_narrative(narrative=None, soap_cat=None, episode_id=None, encounter_id=None):
209 """Creates a new clinical narrative entry 210 211 narrative - free text clinical narrative 212 soap_cat - soap category 213 episode_id - episodes's primary key 214 encounter_id - encounter's primary key 215 """ 216 # any of the args being None (except soap_cat) should fail the SQL code 217 218 # sanity checks: 219 220 # 1) silently do not insert empty narrative 221 narrative = narrative.strip() 222 if narrative == u'': 223 return (True, None) 224 225 # 2) also, silently do not insert true duplicates 226 # FIXME: this should check for .provider = current_user but 227 # FIXME: the view has provider mapped to their staff alias 228 cmd = u""" 229 select *, xmin_clin_narrative from clin.v_pat_narrative where 230 pk_encounter = %(enc)s 231 and pk_episode = %(epi)s 232 and soap_cat = %(soap)s 233 and narrative = %(narr)s 234 """ 235 args = { 236 'enc': encounter_id, 237 'epi': episode_id, 238 'soap': soap_cat, 239 'narr': narrative 240 } 241 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True) 242 if len(rows) == 1: 243 narrative = cNarrative(row = {'pk_field': 'pk_narrative', 'data': rows[0], 'idx': idx}) 244 return (True, narrative) 245 246 # insert new narrative 247 queries = [ 248 {'cmd': u"insert into clin.clin_narrative (fk_encounter, fk_episode, narrative, soap_cat) values (%s, %s, %s, lower(%s))", 249 'args': [encounter_id, episode_id, narrative, soap_cat] 250 }, 251 {'cmd': u"select currval('clin.clin_narrative_pk_seq')"} 252 ] 253 rows, idx = gmPG2.run_rw_queries(queries = queries, return_data=True) 254 255 narrative = cNarrative(aPK_obj = rows[0][0]) 256 return (True, narrative)
257 #------------------------------------------------------------
258 -def delete_clin_narrative(narrative=None):
259 """Deletes a clin.clin_narrative row by it's PK.""" 260 cmd = u"delete from clin.clin_narrative where pk=%s" 261 rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': [narrative]}]) 262 return True
263 #------------------------------------------------------------
264 -def get_narrative(since=None, until=None, encounters=None, episodes=None, issues=None, soap_cats=None, providers=None, patient=None, order_by=None):
265 """Get SOAP notes pertinent to this encounter. 266 267 since 268 - initial date for narrative items 269 until 270 - final date for narrative items 271 encounters 272 - list of encounters whose narrative are to be retrieved 273 episodes 274 - list of episodes whose narrative are to be retrieved 275 issues 276 - list of health issues whose narrative are to be retrieved 277 soap_cats 278 - list of SOAP categories of the narrative to be retrieved 279 """ 280 where_parts = [u'TRUE'] 281 args = {} 282 283 if encounters is not None: 284 where_parts.append(u'pk_encounter IN %(encs)s') 285 args['encs'] = tuple(encounters) 286 287 if episodes is not None: 288 where_parts.append(u'pk_episode IN %(epis)s') 289 args['epis'] = tuple(episodes) 290 291 if issues is not None: 292 where_parts.append(u'pk_health_issue IN %(issues)s') 293 args['issues'] = tuple(issues) 294 295 if patient is not None: 296 where_parts.append(u'pk_patient = %(pat)s') 297 args['pat'] = patient 298 299 if soap_cats is not None: 300 where_parts.append(u'soap_cat IN %(soap_cats)s') 301 args['soap_cats'] = tuple(soap_cats) 302 303 if order_by is None: 304 order_by = u'ORDER BY date, soap_rank' 305 else: 306 order_by = u'ORDER BY %s' % order_by 307 308 cmd = u""" 309 SELECT 310 cvpn.*, 311 (SELECT rank FROM clin.soap_cat_ranks WHERE soap_cat = cvpn.soap_cat) 312 AS soap_rank 313 FROM 314 clin.v_pat_narrative cvpn 315 WHERE 316 %s 317 %s 318 """ % ( 319 u' AND '.join(where_parts), 320 order_by 321 ) 322 323 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True) 324 325 filtered_narrative = [ cNarrative(row = {'pk_field': 'pk_narrative', 'idx': idx, 'data': row}) for row in rows ] 326 327 if since is not None: 328 filtered_narrative = filter(lambda narr: narr['date'] >= since, filtered_narrative) 329 330 if until is not None: 331 filtered_narrative = filter(lambda narr: narr['date'] < until, filtered_narrative) 332 333 if providers is not None: 334 filtered_narrative = filter(lambda narr: narr['provider'] in providers, filtered_narrative) 335 336 return filtered_narrative
337 338 # if issues is not None: 339 # filtered_narrative = filter(lambda narr: narr['pk_health_issue'] in issues, filtered_narrative) 340 # 341 # if episodes is not None: 342 # filtered_narrative = filter(lambda narr: narr['pk_episode'] in episodes, filtered_narrative) 343 # 344 # if encounters is not None: 345 # filtered_narrative = filter(lambda narr: narr['pk_encounter'] in encounters, filtered_narrative) 346 347 # if soap_cats is not None: 348 # soap_cats = map(lambda c: c.lower(), soap_cats) 349 # filtered_narrative = filter(lambda narr: narr['soap_cat'] in soap_cats, filtered_narrative) 350 351 #------------------------------------------------------------
352 -def get_as_journal(since=None, until=None, encounters=None, episodes=None, issues=None, soap_cats=None, providers=None, order_by=None, time_range=None, patient=None):
353 354 if (patient is None) and (episodes is None) and (issues is None) and (encounters is None): 355 raise ValueError('at least one of <patient>, <episodes>, <issues>, <encounters> must not be None') 356 357 if order_by is None: 358 order_by = u'ORDER BY vemrj.clin_when, vemrj.pk_episode, scr, vemrj.src_table' 359 else: 360 order_by = u'ORDER BY %s' % order_by 361 362 where_parts = [] 363 args = {} 364 365 if patient is not None: 366 where_parts.append(u'pk_patient = %(pat)s') 367 args['pat'] = patient 368 369 if soap_cats is not None: 370 # work around bug in psycopg2 not being able to properly 371 # adapt None to NULL inside tuples 372 if None in soap_cats: 373 where_parts.append(u'((vemrj.soap_cat IN %(soap_cat)s) OR (vemrj.soap_cat IS NULL))') 374 soap_cats.remove(None) 375 else: 376 where_parts.append(u'vemrj.soap_cat IN %(soap_cat)s') 377 args['soap_cat'] = tuple(soap_cats) 378 379 if time_range is not None: 380 where_parts.append(u"vemrj.clin_when > (now() - '%s days'::interval)" % time_range) 381 382 if episodes is not None: 383 where_parts.append(u"vemrj.pk_episode IN %(epis)s") 384 args['epis'] = tuple(episodes) 385 386 if issues is not None: 387 where_parts.append(u"vemrj.pk_health_issue IN %(issues)s") 388 args['issues'] = tuple(issues) 389 390 # FIXME: implement more constraints 391 392 cmd = u""" 393 SELECT 394 to_char(vemrj.clin_when, 'YYYY-MM-DD') AS date, 395 vemrj.clin_when, 396 coalesce(vemrj.soap_cat, '') as soap_cat, 397 vemrj.narrative, 398 vemrj.src_table, 399 400 (SELECT rank FROM clin.soap_cat_ranks WHERE soap_cat = vemrj.soap_cat) AS scr, 401 402 vemrj.modified_when, 403 to_char(vemrj.modified_when, 'YYYY-MM-DD HH24:MI') AS date_modified, 404 vemrj.modified_by, 405 vemrj.row_version, 406 vemrj.pk_episode, 407 vemrj.pk_encounter, 408 vemrj.soap_cat as real_soap_cat 409 FROM clin.v_emr_journal vemrj 410 WHERE 411 %s 412 %s""" % ( 413 u'\n\t\t\t\t\tAND\n\t\t\t\t'.join(where_parts), 414 order_by 415 ) 416 417 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True) 418 return rows
419 #============================================================ 420 # main 421 #------------------------------------------------------------ 422 if __name__ == '__main__': 423 424 if len(sys.argv) < 2: 425 sys.exit() 426 427 if sys.argv[1] != 'test': 428 sys.exit() 429 430 from Gnumed.pycommon import gmI18N 431 gmI18N.activate_locale() 432 gmI18N.install_domain(domain = 'gnumed') 433
434 - def test_diag():
435 print "\nDiagnose test" 436 print "-------------" 437 diagnose = cDiag(aPK_obj=2) 438 fields = diagnose.get_fields() 439 for field in fields: 440 print field, ':', diagnose[field] 441 print "updatable:", diagnose.get_updatable_fields() 442 print "codes:", diagnose.get_codes()
443 #print "adding code..." 444 #diagnose.add_code('Test code', 'Test coding system') 445 #print "codes:", diagnose.get_codes() 446
447 - def test_narrative():
448 print "\nnarrative test" 449 print "--------------" 450 narrative = cNarrative(aPK_obj=7) 451 fields = narrative.get_fields() 452 for field in fields: 453 print field, ':', narrative[field] 454 print "updatable:", narrative.get_updatable_fields() 455 print "codes:", narrative.get_codes()
456 #print "adding code..." 457 #narrative.add_code('Test code', 'Test coding system') 458 #print "codes:", diagnose.get_codes() 459 460 #print "creating narrative..." 461 #status, new_narrative = create_clin_narrative(narrative = 'Test narrative', soap_cat = 'a', episode_id=1, encounter_id=2) 462 #print new_narrative 463 464 #-----------------------------------------
465 - def test_search_text_across_emrs():
466 results = search_text_across_emrs('cut') 467 for r in results: 468 print r
469 #----------------------------------------- 470 471 #test_search_text_across_emrs() 472 test_diag() 473 test_narrative() 474 475 #============================================================ 476