File: gmLOINC.html

package info (click to toggle)
gnumed-client 1.8.21%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 37,764 kB
  • sloc: python: 126,692; javascript: 6,113; sh: 1,195; xml: 36; makefile: 33
file content (1137 lines) | stat: -rw-r--r-- 62,413 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>Gnumed.business.gmLOINC API documentation</title>
<meta name="description" content="LOINC handling code …" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>Gnumed.business.gmLOINC</code></h1>
</header>
<section id="section-intro">
<p>LOINC handling code.</p>
<p><a href="http://loinc.org">http://loinc.org</a></p>
<p>license: GPL v2 or later</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python"># -*- coding: utf-8 -*-
&#34;&#34;&#34;LOINC handling code.

http://loinc.org

license: GPL v2 or later
&#34;&#34;&#34;
#============================================================
__author__ = &#34;K.Hilbert &lt;Karsten.Hilbert@gmx.net&gt;&#34;

import sys
import logging
import csv
import re as regex


if __name__ == &#39;__main__&#39;:
        sys.path.insert(0, &#39;../../&#39;)
from Gnumed.pycommon import gmPG2
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmMatchProvider


_log = logging.getLogger(&#39;gm.loinc&#39;)


origin_url = &#39;http://loinc.org&#39;
file_encoding = &#39;latin1&#39;                        # encoding is empirical
license_delimiter = &#39;Clip Here for Data&#39;
version_tag = &#39;LOINC(R) Database Version&#39;
name_long = &#39;LOINC® (Logical Observation Identifiers Names and Codes)&#39;
name_short = &#39;LOINC&#39;

loinc_fields = &#34;LOINC_NUM COMPONENT PROPERTY TIME_ASPCT SYSTEM SCALE_TYP METHOD_TYP RELAT_NMS CLASS SOURCE DT_LAST_CH CHNG_TYPE COMMENTS ANSWERLIST STATUS MAP_TO SCOPE NORM_RANGE IPCC_UNITS REFERENCE EXACT_CMP_SY MOLAR_MASS CLASSTYPE FORMULA SPECIES EXMPL_ANSWERS ACSSYM BASE_NAME FINAL NAACCR_ID CODE_TABLE SETROOT PANELELEMENTS SURVEY_QUEST_TEXT SURVEY_QUEST_SRC UNITSREQUIRED SUBMITTED_UNITS RELATEDNAMES2 SHORTNAME ORDER_OBS CDISC_COMMON_TESTS HL7_FIELD_SUBFIELD_ID EXTERNAL_COPYRIGHT_NOTICE EXAMPLE_UNITS INPC_PERCENTAGE LONG_COMMON_NAME&#34;.split()

#============================================================

LOINC_creatinine_quantity = [&#39;2160-0&#39;, &#39;14682-9&#39;, &#39;40264-4&#39;, &#39;40248-7&#39;]
LOINC_gfr_quantity = [&#39;33914-3&#39;, &#39;45066-8&#39;, &#39;48642-3&#39;, &#39;48643-1&#39;, &#39;50044-7&#39;, &#39;50210-4&#39;, &#39;50384-7&#39;, &#39;62238-1&#39;, &#39;69405-9&#39;, &#39;70969-1&#39;]
LOINC_height = [&#39;3137-7&#39;, &#39;3138-5&#39;, &#39;8301-4&#39;, &#39;8302-2&#39;, &#39;8305-5&#39;, &#39;8306-3&#39;, &#39;8307-1&#39;, &#39;8308-9&#39;]
LOINC_weight = [&#39;18833-4&#39;, &#39;29463-7&#39;, &#39;3141-9&#39;, &#39;3142-7&#39;, &#39;8335-2&#39;, &#39;8339-4&#39;, &#39;8344-4&#39;, &#39;8346-9&#39;, &#39;8351-9&#39;]
LOINC_rr_quantity = [&#39;8478-0&#39;, &#39;8448-3&#39;, &#39;8449-1&#39;, &#39;8456-6&#39;, &#39;8457-4&#39;, &#39;8458-2&#39;, &#39;55284-4&#39;, &#39;50403-5&#39;, &#39;50402-7&#39;, &#39;45372-0&#39;]
LOINC_heart_rate_quantity = [&#39;8867-4&#39;, &#39;67129-7&#39;, &#39;40443-4&#39;, &#39;69000-8&#39;, &#39;69001-6&#39;, &#39;68999-2&#39;]
LOINC_inr_quantity = [&#39;34714-6&#39;, &#39;46418-0&#39;, &#39;6301-6&#39;, &#39;38875-1&#39;]

#============================================================
# convenience functions
#------------------------------------------------------------
def format_loinc(loinc):
        data = loinc2data(loinc)
        if data is None:
                return None
        return gmTools.format_dict_like (
                dict(data),
                tabular = True,
                value_delimiters = None,
                values2ignore = [None, &#39;&#39;]
        )

#------------------------------------------------------------
def loinc2data(loinc):
        cmd = &#39;SELECT * FROM ref.loinc WHERE code = %(loinc)s&#39;
        args = {&#39;loinc&#39;: loinc}
        rows = gmPG2.run_ro_queries(queries = [{&#39;cmd&#39;: cmd, &#39;args&#39;: args}])
        if len(rows) == 0:
                return None
        return rows[0]

#------------------------------------------------------------
def loinc2term(loinc=None):

        # NOTE: will return [NULL] on no-match due to the coalesce()
        cmd = &#34;&#34;&#34;
SELECT coalesce (
        (SELECT term
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                code = %(loinc)s
                        AND
                lang = i18n.get_curr_lang()
        ),
        (SELECT term
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                code = %(loinc)s
                        AND
                lang = &#39;en_EN&#39;
        ),
        (SELECT term
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                code = %(loinc)s
        )
)&#34;&#34;&#34;
        args = {&#39;loinc&#39;: loinc}
        rows = gmPG2.run_ro_queries(queries = [{&#39;cmd&#39;: cmd, &#39;args&#39;: args}])

        if rows[0][0] is None:
                return []

        return [ r[0] for r in rows ]

#============================================================
# LOINCDBTXT handling
#------------------------------------------------------------
def split_LOINCDBTXT(input_fname=None, data_fname=None, license_fname=None):

        _log.debug(&#39;splitting LOINC source file [%s]&#39;, input_fname)

        if license_fname is None:
                license_fname = gmTools.get_unique_filename(prefix = &#39;loinc_license-&#39;, suffix = &#39;.txt&#39;)
        _log.debug(&#39;LOINC header: %s&#39;, license_fname)

        if data_fname is None:
                data_fname = gmTools.get_unique_filename(prefix = &#39;loinc_data-&#39;, suffix = &#39;.csv&#39;)
        _log.debug(&#39;LOINC data: %s&#39;, data_fname)

        loinc_file = open(input_fname, mode = &#39;rt&#39;, encoding = file_encoding, errors = &#39;replace&#39;)
        out_file = open(license_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, errors = &#39;replace&#39;)

        for line in loinc_file:

                if license_delimiter in line:
                        out_file.write(line)
                        out_file.close()
                        out_file = open(data_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, errors = &#39;replace&#39;)
                        continue

                out_file.write(line)

        out_file.close()

        return data_fname, license_fname

#============================================================
def map_field_names(data_fname=&#39;loinc_data.csv&#39;):

        csv_file = open(data_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)
        first_line = csv_file.readline()
        sniffer = csv.Sniffer()
        if sniffer.has_header(first_line):
                pass

#============================================================
def get_version(license_fname=&#39;loinc_license.txt&#39;):

        in_file = open(license_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)

        version = None
        for line in in_file:
                if line.startswith(version_tag):
                        version = line[len(version_tag):].strip()
                        break

        in_file.close()
        return version

#============================================================
def loinc_import(data_fname=None, license_fname=None, version=None, conn=None, lang=&#39;en_EN&#39;):

        if version is None:
                version = get_version(license_fname = license_fname)

        if version is None:
                raise ValueError(&#39;cannot detect LOINC version&#39;)

        _log.debug(&#39;importing LOINC version [%s]&#39;, version)

        # clean out staging area
        curs = conn.cursor()
        cmd = &#34;&#34;&#34;DELETE FROM staging.loinc_staging&#34;&#34;&#34;
        gmPG2.run_rw_queries(link_obj = curs, queries = [{&#39;cmd&#39;: cmd}])
        curs.close()
        conn.commit()
        _log.debug(&#39;staging table emptied&#39;)

        # import data from csv file into staging table
        csv_file = open(data_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)
        loinc_reader = gmTools.unicode_csv_reader(csv_file, delimiter = &#34;\t&#34;, quotechar = &#39;&#34;&#39;)
        curs = conn.cursor()
        cmd = &#34;&#34;&#34;INSERT INTO staging.loinc_staging values (%s%%s)&#34;&#34;&#34; % (&#39;%s, &#39; * (len(loinc_fields) - 1))
        first = False
        for loinc_line in loinc_reader:
                if not first:
                        first = True
                        continue
                gmPG2.run_rw_queries(link_obj = curs, queries = [{&#39;cmd&#39;: cmd, &#39;args&#39;: loinc_line}])
        curs.close()
        conn.commit()
        csv_file.close()
        _log.debug(&#39;staging table loaded&#39;)

        # create data source record
        in_file = open(license_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)
        desc = in_file.read()
        in_file.close()
        args = {&#39;ver&#39;: version, &#39;desc&#39;: desc, &#39;url&#39;: origin_url, &#39;name_long&#39;: name_long, &#39;name_short&#39;: name_short, &#39;lang&#39;: lang}
        queries = [
                # insert if not existing
                {&#39;args&#39;: args, &#39;cmd&#39;: &#34;&#34;&#34;
                        INSERT INTO ref.data_source (name_long, name_short, version) SELECT
                                %(name_long)s,
                                %(name_short)s,
                                %(ver)s
                        WHERE NOT EXISTS (
                                SELECT 1 FROM ref.data_source WHERE
                                        name_long = %(name_long)s
                                                AND
                                        name_short = %(name_short)s
                                                AND
                                        version = %(ver)s
                        )&#34;&#34;&#34;
                },
                # update non-unique fields
                {&#39;args&#39;: args, &#39;cmd&#39;: &#34;&#34;&#34;
                        UPDATE ref.data_source SET
                                description = %(desc)s,
                                source = %(url)s,
                                lang = %(lang)s
                        WHERE
                                name_long = %(name_long)s
                                        AND
                                name_short = %(name_short)s
                                        AND
                                version = %(ver)s
                        &#34;&#34;&#34;
                },
                # retrieve PK of data source
                {&#39;args&#39;: args, &#39;cmd&#39;: &#34;&#34;&#34;SELECT pk FROM ref.data_source WHERE name_short = %(name_short)s AND version = %(ver)s&#34;&#34;&#34;}
        ]
        curs = conn.cursor()
        rows = gmPG2.run_rw_queries(link_obj = curs, queries = queries, return_data = True)
        data_src_pk = rows[0][0]
        curs.close()
        _log.debug(&#39;data source record created or updated, pk is #%s&#39;, data_src_pk)

        # import from staging table to real table
        args = {&#39;src_pk&#39;: data_src_pk}
        queries = []
        queries.append ({
                &#39;args&#39;: args,
                &#39;cmd&#39;: &#34;&#34;&#34;
                        INSERT INTO ref.loinc (
                                fk_data_source, term, code
                        )
                        SELECT
                                %(src_pk)s,
                                coalesce (
                                        nullif(long_common_name, &#39;&#39;),
                                        (
                                                coalesce(nullif(component, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(property, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(time_aspect, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(system, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(scale_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(method_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;)
                                        )
                                ),
                                nullif(loinc_num, &#39;&#39;)
                        FROM
                                staging.loinc_staging st_ls
                        WHERE NOT EXISTS (
                                SELECT 1 FROM ref.loinc r_l WHERE
                                        r_l.fk_data_source = %(src_pk)s
                                                AND
                                        r_l.code = nullif(st_ls.loinc_num, &#39;&#39;)
                                                AND
                                        r_l.term =      coalesce (
                                                nullif(st_ls.long_common_name, &#39;&#39;),
                                                (
                                                        coalesce(nullif(st_ls.component, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.property, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.time_aspect, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.system, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.scale_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.method_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;)
                                                )
                                        )
                        )&#34;&#34;&#34;
        })
        queries.append ({
                &#39;args&#39;: args,
                &#39;cmd&#39;: &#34;&#34;&#34;
                        UPDATE ref.loinc SET
                                comment = nullif(st_ls.comments, &#39;&#39;),
                                component = nullif(st_ls.component, &#39;&#39;),
                                property = nullif(st_ls.property, &#39;&#39;),
                                time_aspect = nullif(st_ls.time_aspect, &#39;&#39;),
                                system = nullif(st_ls.system, &#39;&#39;),
                                scale_type = nullif(st_ls.scale_type, &#39;&#39;),
                                method_type = nullif(st_ls.method_type, &#39;&#39;),
                                related_names_1_old = nullif(st_ls.related_names_1_old, &#39;&#39;),
                                grouping_class = nullif(st_ls.class, &#39;&#39;),
                                loinc_internal_source = nullif(st_ls.source, &#39;&#39;),
                                dt_last_change = nullif(st_ls.dt_last_change, &#39;&#39;),
                                change_type = nullif(st_ls.change_type, &#39;&#39;),
                                answer_list = nullif(st_ls.answer_list, &#39;&#39;),
                                code_status = nullif(st_ls.status, &#39;&#39;),
                                maps_to = nullif(st_ls.map_to, &#39;&#39;),
                                scope = nullif(st_ls.scope, &#39;&#39;),
                                normal_range = nullif(st_ls.normal_range, &#39;&#39;),
                                ipcc_units = nullif(st_ls.ipcc_units, &#39;&#39;),
                                reference = nullif(st_ls.reference, &#39;&#39;),
                                exact_component_synonym = nullif(st_ls.exact_component_synonym, &#39;&#39;),
                                molar_mass = nullif(st_ls.molar_mass, &#39;&#39;),
                                grouping_class_type = nullif(st_ls.class_type, &#39;&#39;)::smallint,
                                formula = nullif(st_ls.formula, &#39;&#39;),
                                species = nullif(st_ls.species, &#39;&#39;),
                                example_answers = nullif(st_ls.example_answers, &#39;&#39;),
                                acs_synonyms = nullif(st_ls.acs_synonyms, &#39;&#39;),
                                base_name = nullif(st_ls.base_name, &#39;&#39;),
                                final = nullif(st_ls.final, &#39;&#39;),
                                naa_ccr_id = nullif(st_ls.naa_ccr_id, &#39;&#39;),
                                code_table = nullif(st_ls.code_table, &#39;&#39;),
                                is_set_root = nullif(st_ls.is_set_root, &#39;&#39;)::boolean,
                                panel_elements = nullif(st_ls.panel_elements, &#39;&#39;),
                                survey_question_text = nullif(st_ls.survey_question_text, &#39;&#39;),
                                survey_question_source = nullif(st_ls.survey_question_source, &#39;&#39;),
                                units_required = nullif(st_ls.units_required, &#39;&#39;),
                                submitted_units = nullif(st_ls.submitted_units, &#39;&#39;),
                                related_names_2 = nullif(st_ls.related_names_2, &#39;&#39;),
                                short_name = nullif(st_ls.short_name, &#39;&#39;),
                                order_obs = nullif(st_ls.order_obs, &#39;&#39;),
                                cdisc_common_tests = nullif(st_ls.cdisc_common_tests, &#39;&#39;),
                                hl7_field_subfield_id = nullif(st_ls.hl7_field_subfield_id, &#39;&#39;),
                                external_copyright_notice = nullif(st_ls.external_copyright_notice, &#39;&#39;),
                                example_units = nullif(st_ls.example_units, &#39;&#39;),
                                inpc_percentage = nullif(st_ls.inpc_percentage, &#39;&#39;),
                                long_common_name = nullif(st_ls.long_common_name, &#39;&#39;)
                        FROM
                                staging.loinc_staging st_ls
                        WHERE
                                fk_data_source = %(src_pk)s
                                        AND
                                code = nullif(st_ls.loinc_num, &#39;&#39;)
                                        AND
                                term = coalesce (
                                        nullif(st_ls.long_common_name, &#39;&#39;),
                                        (
                                                coalesce(nullif(st_ls.component, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.property, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.time_aspect, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.system, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.scale_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.method_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;)
                                        )
                                )
                &#34;&#34;&#34;
        })
        curs = conn.cursor()
        gmPG2.run_rw_queries(link_obj = curs, queries = queries)
        curs.close()
        conn.commit()
        _log.debug(&#39;transfer from staging table to real table done&#39;)

        # clean out staging area
        curs = conn.cursor()
        cmd = &#34;&#34;&#34;DELETE FROM staging.loinc_staging&#34;&#34;&#34;
        gmPG2.run_rw_queries(link_obj = curs, queries = [{&#39;cmd&#39;: cmd}])
        curs.close()
        conn.commit()
        _log.debug(&#39;staging table emptied&#39;)

        return True

#============================================================
_SQL_LOINC_from_test_type = &#34;&#34;&#34;
        -- from test type
        SELECT
                loinc AS data,
                loinc AS field_label,
                (loinc || &#39;: &#39; || abbrev || &#39; (&#39; || name || &#39;)&#39;) AS list_label
        FROM clin.test_type
        WHERE loinc %(fragment_condition)s
&#34;&#34;&#34;

_SQL_LOINC_from_i18n_coded_term = &#34;&#34;&#34;
        -- from coded term, in user language
        SELECT
                code AS data,
                code AS field_label,
                (code || &#39;: &#39; || term) AS list_label
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                lang = i18n.get_curr_lang()
                        AND
                (code %(fragment_condition)s
                        OR
                term %(fragment_condition)s)
&#34;&#34;&#34;

_SQL_LOINC_from_en_EN_coded_term = &#34;&#34;&#34;
        -- from coded term, in English
        SELECT
                code AS data,
                code AS field_label,
                (code || &#39;: &#39; || term) AS list_label
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                lang = &#39;en_EN&#39;
                        AND
                (code %(fragment_condition)s
                        OR
                term %(fragment_condition)s)
&#34;&#34;&#34;

_SQL_LOINC_from_any_coded_term = &#34;&#34;&#34;
        -- from coded term, in any language
        SELECT
                code AS data,
                code AS field_label,
                (code || &#39;: &#39; || term) AS list_label
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                (code %(fragment_condition)s
                        OR
                term %(fragment_condition)s)
&#34;&#34;&#34;

#------------------------------------------------------------
class cLOINCMatchProvider(gmMatchProvider.cMatchProvider_SQL2):

        _pattern = regex.compile(r&#39;^\D+\s+\D+$&#39;, regex.UNICODE)

        _normal_query = &#34;&#34;&#34;
                SELECT DISTINCT ON (list_label)
                        data,
                        field_label,
                        list_label
                FROM (
                        (%s) UNION ALL (
                        %s)
                ) AS all_known_loinc&#34;&#34;&#34; % (
                        _SQL_LOINC_from_test_type,
                        _SQL_LOINC_from_any_coded_term
                )
#--                     %s) UNION ALL (
#--                     %s) UNION ALL (
#               %
#                       _SQL_LOINC_from_i18n_coded_term,
#                       _SQL_LOINC_from_en_EN_coded_term,

        #--------------------------------------------------------
        def getMatchesByPhrase(self, aFragment):
                &#34;&#34;&#34;Return matches for aFragment at start of phrases.&#34;&#34;&#34;

                self._queries = [cLOINCMatchProvider._normal_query + &#39;\nORDER BY list_label\nLIMIT 75&#39;]
                return gmMatchProvider.cMatchProvider_SQL2.getMatchesByPhrase(self, aFragment)

        #--------------------------------------------------------
        def getMatchesByWord(self, aFragment):
                &#34;&#34;&#34;Return matches for aFragment at start of words inside phrases.&#34;&#34;&#34;

                if cLOINCMatchProvider._pattern.match(aFragment):
                        fragmentA, fragmentB = aFragment.split(&#39; &#39;, 1)
                        query1 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#39;~* %%(fragmentA)s&#39;}
                        self._args[&#39;fragmentA&#39;] = &#34;( %s)|(^%s)&#34; % (fragmentA, fragmentA)
                        query2 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#39;~* %%(fragmentB)s&#39;}
                        self._args[&#39;fragmentB&#39;] = &#34;( %s)|(^%s)&#34; % (fragmentB, fragmentB)
                        self._queries = [&#34;SELECT * FROM (\n(%s\n) INTERSECT (%s)\n) AS intersected_matches\nORDER BY list_label\nLIMIT 75&#34; % (query1, query2)]
                        return self._find_matches(&#39;dummy&#39;)

                self._queries = [cLOINCMatchProvider._normal_query + &#39;\nORDER BY list_label\nLIMIT 75&#39;]
                return gmMatchProvider.cMatchProvider_SQL2.getMatchesByWord(self, aFragment)

        #--------------------------------------------------------
        def getMatchesBySubstr(self, aFragment):
                &#34;&#34;&#34;Return matches for aFragment as a true substring.&#34;&#34;&#34;

                if cLOINCMatchProvider._pattern.match(aFragment):
                        fragmentA, fragmentB = aFragment.split(&#39; &#39;, 1)
                        query1 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#34;ILIKE %%(fragmentA)s&#34;}
                        self._args[&#39;fragmentA&#39;] = &#39;%%%s%%&#39; % fragmentA
                        query2 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#34;ILIKE %%(fragmentB)s&#34;}
                        self._args[&#39;fragmentB&#39;] = &#39;%%%s%%&#39; % fragmentB
                        self._queries = [&#34;SELECT * FROM (\n(%s\n) INTERSECT (%s)\n) AS intersected_matches\nORDER BY list_label\nLIMIT 75&#34; % (query1, query2)]
                        return self._find_matches(&#39;dummy&#39;)

                self._queries = [cLOINCMatchProvider._normal_query + &#39;\nORDER BY list_label\nLIMIT 75&#39;]
                return gmMatchProvider.cMatchProvider_SQL2.getMatchesBySubstr(self, aFragment)

#============================================================
# main
#------------------------------------------------------------
if __name__ == &#34;__main__&#34;:

        if len(sys.argv) &lt; 2:
                sys.exit()

        if sys.argv[1] != &#39;test&#39;:
                sys.exit()

        from Gnumed.pycommon import gmI18N

        gmI18N.activate_locale()
#       gmDateTime.init()

        #--------------------------------------------------------
        def test_loinc_split():
                print(split_LOINCDBTXT(input_fname = sys.argv[2]))
        #--------------------------------------------------------
        def test_loinc_import():
                loinc_import(version = &#39;2.26&#39;)
        #--------------------------------------------------------
        def test_loinc2term():
                term = loinc2term(sys.argv[2])
                print(sys.argv[2], &#39;-&gt;&#39;, term)

        #--------------------------------------------------------
        def test_format_loinc():
                loinc = sys.argv[2]
                print(loinc)
                print(format_loinc(loinc))

        #--------------------------------------------------------
        #test_loinc_split()
        #test_loinc_import()
        #test_loinc2term()
        test_format_loinc()

#============================================================</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="Gnumed.business.gmLOINC.format_loinc"><code class="name flex">
<span>def <span class="ident">format_loinc</span></span>(<span>loinc)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def format_loinc(loinc):
        data = loinc2data(loinc)
        if data is None:
                return None
        return gmTools.format_dict_like (
                dict(data),
                tabular = True,
                value_delimiters = None,
                values2ignore = [None, &#39;&#39;]
        )</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmLOINC.get_version"><code class="name flex">
<span>def <span class="ident">get_version</span></span>(<span>license_fname='loinc_license.txt')</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_version(license_fname=&#39;loinc_license.txt&#39;):

        in_file = open(license_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)

        version = None
        for line in in_file:
                if line.startswith(version_tag):
                        version = line[len(version_tag):].strip()
                        break

        in_file.close()
        return version</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmLOINC.loinc2data"><code class="name flex">
<span>def <span class="ident">loinc2data</span></span>(<span>loinc)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def loinc2data(loinc):
        cmd = &#39;SELECT * FROM ref.loinc WHERE code = %(loinc)s&#39;
        args = {&#39;loinc&#39;: loinc}
        rows = gmPG2.run_ro_queries(queries = [{&#39;cmd&#39;: cmd, &#39;args&#39;: args}])
        if len(rows) == 0:
                return None
        return rows[0]</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmLOINC.loinc2term"><code class="name flex">
<span>def <span class="ident">loinc2term</span></span>(<span>loinc=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def loinc2term(loinc=None):

        # NOTE: will return [NULL] on no-match due to the coalesce()
        cmd = &#34;&#34;&#34;
SELECT coalesce (
        (SELECT term
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                code = %(loinc)s
                        AND
                lang = i18n.get_curr_lang()
        ),
        (SELECT term
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                code = %(loinc)s
                        AND
                lang = &#39;en_EN&#39;
        ),
        (SELECT term
        FROM ref.v_coded_terms
        WHERE
                coding_system = &#39;LOINC&#39;
                        AND
                code = %(loinc)s
        )
)&#34;&#34;&#34;
        args = {&#39;loinc&#39;: loinc}
        rows = gmPG2.run_ro_queries(queries = [{&#39;cmd&#39;: cmd, &#39;args&#39;: args}])

        if rows[0][0] is None:
                return []

        return [ r[0] for r in rows ]</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmLOINC.loinc_import"><code class="name flex">
<span>def <span class="ident">loinc_import</span></span>(<span>data_fname=None, license_fname=None, version=None, conn=None, lang='en_EN')</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def loinc_import(data_fname=None, license_fname=None, version=None, conn=None, lang=&#39;en_EN&#39;):

        if version is None:
                version = get_version(license_fname = license_fname)

        if version is None:
                raise ValueError(&#39;cannot detect LOINC version&#39;)

        _log.debug(&#39;importing LOINC version [%s]&#39;, version)

        # clean out staging area
        curs = conn.cursor()
        cmd = &#34;&#34;&#34;DELETE FROM staging.loinc_staging&#34;&#34;&#34;
        gmPG2.run_rw_queries(link_obj = curs, queries = [{&#39;cmd&#39;: cmd}])
        curs.close()
        conn.commit()
        _log.debug(&#39;staging table emptied&#39;)

        # import data from csv file into staging table
        csv_file = open(data_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)
        loinc_reader = gmTools.unicode_csv_reader(csv_file, delimiter = &#34;\t&#34;, quotechar = &#39;&#34;&#39;)
        curs = conn.cursor()
        cmd = &#34;&#34;&#34;INSERT INTO staging.loinc_staging values (%s%%s)&#34;&#34;&#34; % (&#39;%s, &#39; * (len(loinc_fields) - 1))
        first = False
        for loinc_line in loinc_reader:
                if not first:
                        first = True
                        continue
                gmPG2.run_rw_queries(link_obj = curs, queries = [{&#39;cmd&#39;: cmd, &#39;args&#39;: loinc_line}])
        curs.close()
        conn.commit()
        csv_file.close()
        _log.debug(&#39;staging table loaded&#39;)

        # create data source record
        in_file = open(license_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)
        desc = in_file.read()
        in_file.close()
        args = {&#39;ver&#39;: version, &#39;desc&#39;: desc, &#39;url&#39;: origin_url, &#39;name_long&#39;: name_long, &#39;name_short&#39;: name_short, &#39;lang&#39;: lang}
        queries = [
                # insert if not existing
                {&#39;args&#39;: args, &#39;cmd&#39;: &#34;&#34;&#34;
                        INSERT INTO ref.data_source (name_long, name_short, version) SELECT
                                %(name_long)s,
                                %(name_short)s,
                                %(ver)s
                        WHERE NOT EXISTS (
                                SELECT 1 FROM ref.data_source WHERE
                                        name_long = %(name_long)s
                                                AND
                                        name_short = %(name_short)s
                                                AND
                                        version = %(ver)s
                        )&#34;&#34;&#34;
                },
                # update non-unique fields
                {&#39;args&#39;: args, &#39;cmd&#39;: &#34;&#34;&#34;
                        UPDATE ref.data_source SET
                                description = %(desc)s,
                                source = %(url)s,
                                lang = %(lang)s
                        WHERE
                                name_long = %(name_long)s
                                        AND
                                name_short = %(name_short)s
                                        AND
                                version = %(ver)s
                        &#34;&#34;&#34;
                },
                # retrieve PK of data source
                {&#39;args&#39;: args, &#39;cmd&#39;: &#34;&#34;&#34;SELECT pk FROM ref.data_source WHERE name_short = %(name_short)s AND version = %(ver)s&#34;&#34;&#34;}
        ]
        curs = conn.cursor()
        rows = gmPG2.run_rw_queries(link_obj = curs, queries = queries, return_data = True)
        data_src_pk = rows[0][0]
        curs.close()
        _log.debug(&#39;data source record created or updated, pk is #%s&#39;, data_src_pk)

        # import from staging table to real table
        args = {&#39;src_pk&#39;: data_src_pk}
        queries = []
        queries.append ({
                &#39;args&#39;: args,
                &#39;cmd&#39;: &#34;&#34;&#34;
                        INSERT INTO ref.loinc (
                                fk_data_source, term, code
                        )
                        SELECT
                                %(src_pk)s,
                                coalesce (
                                        nullif(long_common_name, &#39;&#39;),
                                        (
                                                coalesce(nullif(component, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(property, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(time_aspect, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(system, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(scale_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(method_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;)
                                        )
                                ),
                                nullif(loinc_num, &#39;&#39;)
                        FROM
                                staging.loinc_staging st_ls
                        WHERE NOT EXISTS (
                                SELECT 1 FROM ref.loinc r_l WHERE
                                        r_l.fk_data_source = %(src_pk)s
                                                AND
                                        r_l.code = nullif(st_ls.loinc_num, &#39;&#39;)
                                                AND
                                        r_l.term =      coalesce (
                                                nullif(st_ls.long_common_name, &#39;&#39;),
                                                (
                                                        coalesce(nullif(st_ls.component, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.property, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.time_aspect, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.system, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.scale_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                        coalesce(nullif(st_ls.method_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;)
                                                )
                                        )
                        )&#34;&#34;&#34;
        })
        queries.append ({
                &#39;args&#39;: args,
                &#39;cmd&#39;: &#34;&#34;&#34;
                        UPDATE ref.loinc SET
                                comment = nullif(st_ls.comments, &#39;&#39;),
                                component = nullif(st_ls.component, &#39;&#39;),
                                property = nullif(st_ls.property, &#39;&#39;),
                                time_aspect = nullif(st_ls.time_aspect, &#39;&#39;),
                                system = nullif(st_ls.system, &#39;&#39;),
                                scale_type = nullif(st_ls.scale_type, &#39;&#39;),
                                method_type = nullif(st_ls.method_type, &#39;&#39;),
                                related_names_1_old = nullif(st_ls.related_names_1_old, &#39;&#39;),
                                grouping_class = nullif(st_ls.class, &#39;&#39;),
                                loinc_internal_source = nullif(st_ls.source, &#39;&#39;),
                                dt_last_change = nullif(st_ls.dt_last_change, &#39;&#39;),
                                change_type = nullif(st_ls.change_type, &#39;&#39;),
                                answer_list = nullif(st_ls.answer_list, &#39;&#39;),
                                code_status = nullif(st_ls.status, &#39;&#39;),
                                maps_to = nullif(st_ls.map_to, &#39;&#39;),
                                scope = nullif(st_ls.scope, &#39;&#39;),
                                normal_range = nullif(st_ls.normal_range, &#39;&#39;),
                                ipcc_units = nullif(st_ls.ipcc_units, &#39;&#39;),
                                reference = nullif(st_ls.reference, &#39;&#39;),
                                exact_component_synonym = nullif(st_ls.exact_component_synonym, &#39;&#39;),
                                molar_mass = nullif(st_ls.molar_mass, &#39;&#39;),
                                grouping_class_type = nullif(st_ls.class_type, &#39;&#39;)::smallint,
                                formula = nullif(st_ls.formula, &#39;&#39;),
                                species = nullif(st_ls.species, &#39;&#39;),
                                example_answers = nullif(st_ls.example_answers, &#39;&#39;),
                                acs_synonyms = nullif(st_ls.acs_synonyms, &#39;&#39;),
                                base_name = nullif(st_ls.base_name, &#39;&#39;),
                                final = nullif(st_ls.final, &#39;&#39;),
                                naa_ccr_id = nullif(st_ls.naa_ccr_id, &#39;&#39;),
                                code_table = nullif(st_ls.code_table, &#39;&#39;),
                                is_set_root = nullif(st_ls.is_set_root, &#39;&#39;)::boolean,
                                panel_elements = nullif(st_ls.panel_elements, &#39;&#39;),
                                survey_question_text = nullif(st_ls.survey_question_text, &#39;&#39;),
                                survey_question_source = nullif(st_ls.survey_question_source, &#39;&#39;),
                                units_required = nullif(st_ls.units_required, &#39;&#39;),
                                submitted_units = nullif(st_ls.submitted_units, &#39;&#39;),
                                related_names_2 = nullif(st_ls.related_names_2, &#39;&#39;),
                                short_name = nullif(st_ls.short_name, &#39;&#39;),
                                order_obs = nullif(st_ls.order_obs, &#39;&#39;),
                                cdisc_common_tests = nullif(st_ls.cdisc_common_tests, &#39;&#39;),
                                hl7_field_subfield_id = nullif(st_ls.hl7_field_subfield_id, &#39;&#39;),
                                external_copyright_notice = nullif(st_ls.external_copyright_notice, &#39;&#39;),
                                example_units = nullif(st_ls.example_units, &#39;&#39;),
                                inpc_percentage = nullif(st_ls.inpc_percentage, &#39;&#39;),
                                long_common_name = nullif(st_ls.long_common_name, &#39;&#39;)
                        FROM
                                staging.loinc_staging st_ls
                        WHERE
                                fk_data_source = %(src_pk)s
                                        AND
                                code = nullif(st_ls.loinc_num, &#39;&#39;)
                                        AND
                                term = coalesce (
                                        nullif(st_ls.long_common_name, &#39;&#39;),
                                        (
                                                coalesce(nullif(st_ls.component, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.property, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.time_aspect, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.system, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.scale_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;) ||
                                                coalesce(nullif(st_ls.method_type, &#39;&#39;) || &#39;:&#39;, &#39;&#39;)
                                        )
                                )
                &#34;&#34;&#34;
        })
        curs = conn.cursor()
        gmPG2.run_rw_queries(link_obj = curs, queries = queries)
        curs.close()
        conn.commit()
        _log.debug(&#39;transfer from staging table to real table done&#39;)

        # clean out staging area
        curs = conn.cursor()
        cmd = &#34;&#34;&#34;DELETE FROM staging.loinc_staging&#34;&#34;&#34;
        gmPG2.run_rw_queries(link_obj = curs, queries = [{&#39;cmd&#39;: cmd}])
        curs.close()
        conn.commit()
        _log.debug(&#39;staging table emptied&#39;)

        return True</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmLOINC.map_field_names"><code class="name flex">
<span>def <span class="ident">map_field_names</span></span>(<span>data_fname='loinc_data.csv')</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def map_field_names(data_fname=&#39;loinc_data.csv&#39;):

        csv_file = open(data_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, errors = &#39;replace&#39;)
        first_line = csv_file.readline()
        sniffer = csv.Sniffer()
        if sniffer.has_header(first_line):
                pass</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmLOINC.split_LOINCDBTXT"><code class="name flex">
<span>def <span class="ident">split_LOINCDBTXT</span></span>(<span>input_fname=None, data_fname=None, license_fname=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def split_LOINCDBTXT(input_fname=None, data_fname=None, license_fname=None):

        _log.debug(&#39;splitting LOINC source file [%s]&#39;, input_fname)

        if license_fname is None:
                license_fname = gmTools.get_unique_filename(prefix = &#39;loinc_license-&#39;, suffix = &#39;.txt&#39;)
        _log.debug(&#39;LOINC header: %s&#39;, license_fname)

        if data_fname is None:
                data_fname = gmTools.get_unique_filename(prefix = &#39;loinc_data-&#39;, suffix = &#39;.csv&#39;)
        _log.debug(&#39;LOINC data: %s&#39;, data_fname)

        loinc_file = open(input_fname, mode = &#39;rt&#39;, encoding = file_encoding, errors = &#39;replace&#39;)
        out_file = open(license_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, errors = &#39;replace&#39;)

        for line in loinc_file:

                if license_delimiter in line:
                        out_file.write(line)
                        out_file.close()
                        out_file = open(data_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, errors = &#39;replace&#39;)
                        continue

                out_file.write(line)

        out_file.close()

        return data_fname, license_fname</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="Gnumed.business.gmLOINC.cLOINCMatchProvider"><code class="flex name class">
<span>class <span class="ident">cLOINCMatchProvider</span></span>
<span>(</span><span>queries=None, context=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Match provider which searches matches
in possibly several database tables.</p>
<p>queries:
- a list of unicode strings
- each string is a query
- each string must contain: "&hellip; WHERE <column> %(fragment_condition)s &hellip;"
- each string can contain in the where clause: "&hellip; %(<ctxt_key1>)s &hellip;"
- each query must return (data, list_label, field_label)</p>
<p>context definitions to be used in the queries, example:
{'ctxt_key1': {'where_part': 'AND country = %(country)s', 'placeholder': 'country'}}</p>
<p>client code using .set_context() must use the 'placeholder':
<phrasewheel>/<match provider>.set_context('country', 'Germany')</p>
<p>full example query:</p>
<pre><code>    query = u" " "
            SELECT DISTINCT ON (list_label)
                    pk_encounter
                            AS data,
                    to_char(started, 'YYYY Mon DD (HH24:MI)') || ': ' || l10n_type || ' [#' || pk_encounter || ']'
                            AS list_label,
                    to_char(started, 'YYYY Mon DD') || ': ' || l10n_type
                            AS field_label
            FROM
                    clin.v_pat_encounters
            WHERE
                    (
                            l10n_type %(fragment_condition)s
                                    OR
                            type %(fragment_condition)s
                    )       %(ctxt_patient)s
            ORDER BY
                    list_label
            LIMIT
                    30
    " " "
    context = {'ctxt_patient': {
            'where_part': u'AND pk_patient = %(PLACEHOLDER)s',
            'placeholder': u'PLACEHOLDER'
    }}
    self.mp = gmMatchProvider.cMatchProvider_SQL2(queries = query, context = context)
    self.set_context(context = 'PLACEHOLDER', val = '&lt;THE VALUE&gt;')
</code></pre>
<p>_SQL_data2match:
SQL to retrieve a match by, say, primary key
wherein the only keyword argument is 'pk'</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class cLOINCMatchProvider(gmMatchProvider.cMatchProvider_SQL2):

        _pattern = regex.compile(r&#39;^\D+\s+\D+$&#39;, regex.UNICODE)

        _normal_query = &#34;&#34;&#34;
                SELECT DISTINCT ON (list_label)
                        data,
                        field_label,
                        list_label
                FROM (
                        (%s) UNION ALL (
                        %s)
                ) AS all_known_loinc&#34;&#34;&#34; % (
                        _SQL_LOINC_from_test_type,
                        _SQL_LOINC_from_any_coded_term
                )
#--                     %s) UNION ALL (
#--                     %s) UNION ALL (
#               %
#                       _SQL_LOINC_from_i18n_coded_term,
#                       _SQL_LOINC_from_en_EN_coded_term,

        #--------------------------------------------------------
        def getMatchesByPhrase(self, aFragment):
                &#34;&#34;&#34;Return matches for aFragment at start of phrases.&#34;&#34;&#34;

                self._queries = [cLOINCMatchProvider._normal_query + &#39;\nORDER BY list_label\nLIMIT 75&#39;]
                return gmMatchProvider.cMatchProvider_SQL2.getMatchesByPhrase(self, aFragment)

        #--------------------------------------------------------
        def getMatchesByWord(self, aFragment):
                &#34;&#34;&#34;Return matches for aFragment at start of words inside phrases.&#34;&#34;&#34;

                if cLOINCMatchProvider._pattern.match(aFragment):
                        fragmentA, fragmentB = aFragment.split(&#39; &#39;, 1)
                        query1 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#39;~* %%(fragmentA)s&#39;}
                        self._args[&#39;fragmentA&#39;] = &#34;( %s)|(^%s)&#34; % (fragmentA, fragmentA)
                        query2 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#39;~* %%(fragmentB)s&#39;}
                        self._args[&#39;fragmentB&#39;] = &#34;( %s)|(^%s)&#34; % (fragmentB, fragmentB)
                        self._queries = [&#34;SELECT * FROM (\n(%s\n) INTERSECT (%s)\n) AS intersected_matches\nORDER BY list_label\nLIMIT 75&#34; % (query1, query2)]
                        return self._find_matches(&#39;dummy&#39;)

                self._queries = [cLOINCMatchProvider._normal_query + &#39;\nORDER BY list_label\nLIMIT 75&#39;]
                return gmMatchProvider.cMatchProvider_SQL2.getMatchesByWord(self, aFragment)

        #--------------------------------------------------------
        def getMatchesBySubstr(self, aFragment):
                &#34;&#34;&#34;Return matches for aFragment as a true substring.&#34;&#34;&#34;

                if cLOINCMatchProvider._pattern.match(aFragment):
                        fragmentA, fragmentB = aFragment.split(&#39; &#39;, 1)
                        query1 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#34;ILIKE %%(fragmentA)s&#34;}
                        self._args[&#39;fragmentA&#39;] = &#39;%%%s%%&#39; % fragmentA
                        query2 = cLOINCMatchProvider._normal_query % {&#39;fragment_condition&#39;: &#34;ILIKE %%(fragmentB)s&#34;}
                        self._args[&#39;fragmentB&#39;] = &#39;%%%s%%&#39; % fragmentB
                        self._queries = [&#34;SELECT * FROM (\n(%s\n) INTERSECT (%s)\n) AS intersected_matches\nORDER BY list_label\nLIMIT 75&#34; % (query1, query2)]
                        return self._find_matches(&#39;dummy&#39;)

                self._queries = [cLOINCMatchProvider._normal_query + &#39;\nORDER BY list_label\nLIMIT 75&#39;]
                return gmMatchProvider.cMatchProvider_SQL2.getMatchesBySubstr(self, aFragment)</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2">cMatchProvider_SQL2</a></li>
<li><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider">cMatchProvider</a></li>
</ul>
<h3>Inherited members</h3>
<ul class="hlist">
<li><code><b><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2">cMatchProvider_SQL2</a></b></code>:
<ul class="hlist">
<li><code><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getAllMatches" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getAllMatches">getAllMatches</a></code></li>
<li><code><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getMatches" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider.getMatches">getMatches</a></code></li>
<li><code><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getMatchesByPhrase" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getMatchesByPhrase">getMatchesByPhrase</a></code></li>
<li><code><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getMatchesBySubstr" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getMatchesBySubstr">getMatchesBySubstr</a></code></li>
<li><code><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getMatchesByWord" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.getMatchesByWord">getMatchesByWord</a></code></li>
<li><code><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.setThresholds" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider.setThresholds">setThresholds</a></code></li>
<li><code><a title="Gnumed.pycommon.gmMatchProvider.cMatchProvider_SQL2.set_context" href="gmMatchProvider.html#Gnumed.pycommon.gmMatchProvider.cMatchProvider.set_context">set_context</a></code></li>
</ul>
</li>
</ul>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="Gnumed.business" href="http://www.gnumed.de/downloads/docs/api/business/index.html">Gnumed.business</a></code></li>
</ul>
</li>
<li><h3><a href="gmLOINC.html#header-functions">Functions</a></h3>
<ul class="two-column">
<li><code><a title="Gnumed.business.gmLOINC.format_loinc" href="gmLOINC.html#Gnumed.business.gmLOINC.format_loinc">format_loinc</a></code></li>
<li><code><a title="Gnumed.business.gmLOINC.get_version" href="gmLOINC.html#Gnumed.business.gmLOINC.get_version">get_version</a></code></li>
<li><code><a title="Gnumed.business.gmLOINC.loinc2data" href="gmLOINC.html#Gnumed.business.gmLOINC.loinc2data">loinc2data</a></code></li>
<li><code><a title="Gnumed.business.gmLOINC.loinc2term" href="gmLOINC.html#Gnumed.business.gmLOINC.loinc2term">loinc2term</a></code></li>
<li><code><a title="Gnumed.business.gmLOINC.loinc_import" href="gmLOINC.html#Gnumed.business.gmLOINC.loinc_import">loinc_import</a></code></li>
<li><code><a title="Gnumed.business.gmLOINC.map_field_names" href="gmLOINC.html#Gnumed.business.gmLOINC.map_field_names">map_field_names</a></code></li>
<li><code><a title="Gnumed.business.gmLOINC.split_LOINCDBTXT" href="gmLOINC.html#Gnumed.business.gmLOINC.split_LOINCDBTXT">split_LOINCDBTXT</a></code></li>
</ul>
</li>
<li><h3><a href="gmLOINC.html#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="Gnumed.business.gmLOINC.cLOINCMatchProvider" href="gmLOINC.html#Gnumed.business.gmLOINC.cLOINCMatchProvider">cLOINCMatchProvider</a></code></h4>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.10.0</a>.</p>
</footer>
</body>
</html>