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
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
49 gmTools.u_ellipsis: None
50 }
51
52
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
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
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
139
140
141
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
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
189
190
191
192
193
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
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
217
218
219
220
221 narrative = narrative.strip()
222 if narrative == u'':
223 return (True, None)
224
225
226
227
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
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
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):
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(cats)
302
303 cmd = u"""
304 SELECT
305 cvpn.*,
306 (SELECT rank FROM clin.soap_cat_ranks WHERE soap_cat = cvpn.soap_cat)
307 AS soap_rank
308 FROM
309 clin.v_pat_narrative cvpn
310 WHERE
311 %s
312 ORDER BY
313 date,
314 soap_rank
315 """ % u' AND '.join(where_parts)
316
317 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
318
319 filtered_narrative = [ cNarrative(row = {'pk_field': 'pk_narrative', 'idx': idx, 'data': row}) for row in rows ]
320
321 if since is not None:
322 filtered_narrative = filter(lambda narr: narr['date'] >= since, filtered_narrative)
323
324 if until is not None:
325 filtered_narrative = filter(lambda narr: narr['date'] < until, filtered_narrative)
326
327 if providers is not None:
328 filtered_narrative = filter(lambda narr: narr['provider'] in providers, filtered_narrative)
329
330 return filtered_narrative
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346 -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):
347
348 if (patient is None) and (episodes is None) and (issues is None) and (encounters is None):
349 raise ValueError('at least one of <patient>, <episodes>, <issues>, <encounters> must not be None')
350
351 if order_by is None:
352 order_by = u'ORDER BY vemrj.clin_when, vemrj.pk_episode, scr, vemrj.src_table'
353 else:
354 order_by = u'ORDER BY %s' % order_by
355
356 where_parts = []
357 args = {}
358
359 if patient is not None:
360 where_parts.append(u'pk_patient = %(pat)s')
361 args['pat'] = patient
362
363 if soap_cats is not None:
364
365
366 if None in soap_cats:
367 where_parts.append(u'((vemrj.soap_cat IN %(soap_cat)s) OR (vemrj.soap_cat IS NULL))')
368 soap_cats.remove(None)
369 else:
370 where_parts.append(u'vemrj.soap_cat IN %(soap_cat)s')
371 args['soap_cat'] = tuple(soap_cats)
372
373 if time_range is not None:
374 where_parts.append(u"vemrj.clin_when > (now() - '%s days'::interval)" % time_range)
375
376 if episodes is not None:
377 where_parts.append(u"vemrj.pk_episode IN %(epis)s")
378 args['epis'] = tuple(episodes)
379
380 if issues is not None:
381 where_parts.append(u"vemrj.pk_health_issue IN %(issues)s")
382 args['issues'] = tuple(issues)
383
384
385
386 cmd = u"""
387 SELECT
388 to_char(vemrj.clin_when, 'YYYY-MM-DD') AS date,
389 vemrj.clin_when,
390 coalesce(vemrj.soap_cat, '') as soap_cat,
391 vemrj.narrative,
392 vemrj.src_table,
393
394 (SELECT rank FROM clin.soap_cat_ranks WHERE soap_cat = vemrj.soap_cat) AS scr,
395
396 vemrj.modified_when,
397 to_char(vemrj.modified_when, 'YYYY-MM-DD HH24:MI') AS date_modified,
398 vemrj.modified_by,
399 vemrj.row_version,
400 vemrj.pk_episode,
401 vemrj.pk_encounter,
402 vemrj.soap_cat as real_soap_cat
403 FROM clin.v_emr_journal vemrj
404 WHERE
405 %s
406 %s""" % (
407 u'\n\t\t\t\t\tAND\n\t\t\t\t'.join(where_parts),
408 order_by
409 )
410
411 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
412 return rows
413
414
415
416 if __name__ == '__main__':
417
418 if len(sys.argv) < 2:
419 sys.exit()
420
421 if sys.argv[1] != 'test':
422 sys.exit()
423
424 from Gnumed.pycommon import gmI18N
425 gmI18N.activate_locale()
426 gmI18N.install_domain(domain = 'gnumed')
427
429 print "\nDiagnose test"
430 print "-------------"
431 diagnose = cDiag(aPK_obj=2)
432 fields = diagnose.get_fields()
433 for field in fields:
434 print field, ':', diagnose[field]
435 print "updatable:", diagnose.get_updatable_fields()
436 print "codes:", diagnose.get_codes()
437
438
439
440
442 print "\nnarrative test"
443 print "--------------"
444 narrative = cNarrative(aPK_obj=7)
445 fields = narrative.get_fields()
446 for field in fields:
447 print field, ':', narrative[field]
448 print "updatable:", narrative.get_updatable_fields()
449 print "codes:", narrative.get_codes()
450
451
452
453
454
455
456
457
458
460 results = search_text_across_emrs('cut')
461 for r in results:
462 print r
463
464
465
466 test_diag()
467 test_narrative()
468
469
470