forked from OHDSI/OSIM-v5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOSIM5_package.sql
5354 lines (4774 loc) · 194 KB
/
OSIM5_package.sql
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
--================================================================================
-- POSTGRES PACKAGE OSIM5 v2.1.000
-- Person Condition Drug Simulator
--
--
--================================================================================
-- Postgres Version -
--
-- Georgia Tech Research Institute
-- Any scientific publication that is based on this work should include a
-- reference to ____________________
--
-- Original Version -
--
-- Observational Medical Outcomes Partnership
-- 06 January 2011
--
-- Oracle PL/SQL Package for analysis and simulation of patient data
--
-- ?2011 Foundation for the National Institutes of Health (FNIH)
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy
-- of the License at http://omop.fnih.org/publiclicense.
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Any
-- redistributions of this work or any derivative work or modification based on
-- this work should be accompanied by the following source attribution: "This
-- work is based on work by the Observational Medical Outcomes Partnership
-- (OMOP) and used under license from the FNIH at
-- http://omop.fnih.org/publiclicense.
--
-- Any scientific publication that is based on this work should include a
-- reference to http://omop.fnih.org.
--
--================================================================================
--
-- DESCRIPTION
--
-- This package contains methods to analyze an existing CDM format database to
-- populate a series of stratified probability and transition tables.
--
-- The package also includes methods to use the probability and transition tables
-- to simulate data with similar characteristics of the analyzed CDM database.
--
-- Additionally, optional methods are included to adjust prevalence levels for
-- known outcomes and preventative drug therapies.
--
-- A series of bucketing functions may be modified to adjust stratifaction
-- ranges for age, condition, and drug counts. However, the bucketing functions
-- used during the analysis phase must match the bucket functions used during
-- the simulation.
--
--================================================================================
--
-- CHANGE LOG
-- v0.1.000 - 17 May 2010 - R Murray (ProSanos) - Proof of Concept
-- v1.1.000 - 15 Jul 2010 - R Murray (ProSanos) - Condition Simulation
-- v1.2.000 - 27 Sep 2010 - R Murray (ProSanos) - Drug Simulation
-- v1.3.000 - 01 Oct 2010 - R Murray (ProSanos) - Drug Outcome Simulation
-- v1.4.000 - 22 Oct 2010 - R Murray (ProSanos) - Modified subsequent drug era logic
-- to distribute drawn total exposure across
-- drawn count eras over drawn duration
-- v1.5.000 - 10 Nov 2010 - R Murray (ProSanos) - Additional parameters and procedures
-- for parallelization
-- v1.5.001 - 08 Dec 2010 - R Murray (ProSanos) - Added condition and drug era type
-- to analysis and simulation
-- v1.5.002 - 06 Jan 2011 - R Murray (UBC) - Fixed potential division by zero in outcomes
-- v1.5.003 - 02 Feb 2011 - R Murray (UBC) - Code reorganization
-- V1.5.004 - 05 Feb 2011 - R Murray (UBC) - Fixed Year of Birth error
-- V1.5.005 - 15 Feb 2011 - R Murray (UBC) - Modified min and max db date to only
-- use observation period dates
-- V2.1.000 - 27 Mar 2018 - K Mukadam (GTRI) - Modified code for OMOP CDM v5 and converted to PostgreSQL
--================================================================================
-- TODO
-- Outcome/risk function update
-- Fix logging (issue due to PostgreSQL i.e. no autonomous transactions)
--================================================================================
SET SEARCH_PATH TO synthetic_data_generation, public;
CREATE EXTENSION IF NOT EXISTS tablefunc; -- for norm_random function
DROP TYPE IF EXISTS COND_TRANSITION CASCADE;
CREATE TYPE COND_TRANSITION AS (
gender_concept_id INTEGER,
age_range INTEGER,
cond_count_bucket INTEGER,
time_remaining INTEGER,
condition1_concept_id INTEGER,
condition2_concept_id INTEGER,
delta_days FLOAT );
DROP TYPE IF EXISTS DRUG_COND_OUTCOME CASCADE;
CREATE TYPE DRUG_COND_OUTCOME AS (
person_id INTEGER,
drug_era_id INTEGER,
condition_era_id INTEGER);
DROP TYPE IF EXISTS CONCEPT_VECTOR CASCADE;
/*=========================================================================
| FUNCTION CONDITION_COUNT_BUCKET
|
| Returns Condition Count Bucket (maximum condition count value) for conditon count.
| This function can be altered to change stratification.
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__condition_count_bucket(BIGINT)
RETURNS INTEGER AS $$
DECLARE condition_count ALIAS FOR $1;
BEGIN
CASE TRUE
WHEN condition_count <= 2 THEN RETURN 2;
WHEN condition_count <= 7 THEN RETURN 7;
WHEN condition_count <= 25 THEN RETURN 25;
ELSE RETURN 2000;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| FUNCTION DRUG_COUNT_BUCKET
|
| Returns Drug Count Bucket (maximum condition count value) for drug count.
| This function can be altered to change stratification.
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__drug_count_bucket(BIGINT)
RETURNS INTEGER AS $$
DECLARE drug_count ALIAS FOR $1;
BEGIN
CASE TRUE
WHEN drug_count <= 2 THEN RETURN 2;
WHEN drug_count <= 7 THEN RETURN 7;
WHEN drug_count <= 25 THEN RETURN 25;
ELSE RETURN 2000;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| FUNCTION PROCEDURE_COUNT_BUCKET
|
| Returns Procedure Count Bucket (maximum condition count value) for procedure count.
| This function can be altered to change stratification.
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__procedure_count_bucket(BIGINT)
RETURNS INTEGER AS $$
DECLARE procedure_count ALIAS FOR $1;
BEGIN
CASE TRUE
WHEN procedure_count <= 2 THEN RETURN 2;
WHEN procedure_count <= 7 THEN RETURN 7;
WHEN procedure_count <= 25 THEN RETURN 25;
ELSE RETURN 2000;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| FUNCTION AGE_BUCKET
|
| Returns Age Bucket (maximum age value) for age.
| This function can be altered to change stratification.
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__age_bucket (NUMERIC)
RETURNS INTEGER AS $$
DECLARE age ALIAS FOR $1;
BEGIN
CASE TRUE
WHEN age IS NULL THEN RETURN NULL;
WHEN age < 6 THEN RETURN 6;
WHEN age < 14 THEN RETURN 14;
WHEN age < 20 THEN RETURN 20;
WHEN age < 55 THEN RETURN 55;
WHEN age < 70 THEN RETURN 70;
ELSE RETURN 120;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| FUNCTION time_observed_bucket
|
| Function to create time bucket from days reaming
|
| Currently full semi years remaining
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__time_observed_bucket (INTEGER)
RETURNS INTEGER AS $$
DECLARE days ALIAS FOR $1;
BEGIN
CASE TRUE
WHEN days > 0 THEN RETURN FLOOR((1+days) / 182.625);
ELSE RETURN 0;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| CREATE FUNCTION ROUND_DAYS
|
| Rounds days > 75 to 30 day increments (90,120,150,..)
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__round_days(INTEGER)
RETURNS INTEGER AS $$
DECLARE days ALIAS FOR $1;
BEGIN
CASE
WHEN days <= 75 THEN RETURN ROUND(days);
ELSE RETURN ROUND(days/30) * 30;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
CREATE OR REPLACE FUNCTION OSIM__round_days(BIGINT)
RETURNS INTEGER AS $$
DECLARE days ALIAS FOR $1;
BEGIN
CASE
WHEN days <= 75 THEN RETURN ROUND(days);
ELSE RETURN ROUND(days/30) * 30;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| CREATE FUNCTION RANDOMIZE_DAYS
|
| Adds +- 15 to rounded 30 day values > 45
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__randomize_days(INTEGER)
RETURNS INTEGER AS $$
DECLARE days ALIAS FOR $1;
BEGIN
CASE TRUE
WHEN days <= 75 THEN RETURN ROUND(days);
ELSE RETURN ROUND(days - 15 + random() * 30);
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| CREATE FUNCTION DURATION_DAYS_BUCKET
|
| Rounds days > 6 to 30 day increments (90,120,150,..)
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__duration_days_bucket(INTEGER)
RETURNS INTEGER AS $$
DECLARE
days ALIAS FOR $1;
BEGIN
CASE TRUE
WHEN days <= 7 THEN RETURN 7;
ELSE RETURN 8;
END CASE;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| CREATE FUNCTION min_num
|
| Returns the lesser of two INTEGERs
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__min_num (INTEGER, INTEGER)
RETURNS INTEGER AS $$
DECLARE
value1 ALIAS FOR $1;
value2 ALIAS FOR $2;
BEGIN
RETURN CASE WHEN value1 <= value2 THEN value1 ELSE value2 END;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| FUNCTION get_first_cond_transitions
|
| retrieves every first condition era transition
|
| This is slower as a function than as a view, but allows it to be part of
| the OSIM package and eliminates a circular dependency that makes
| compiling difficult.
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__get_first_cond_transitions()
RETURNS SETOF COND_TRANSITION AS $$
DECLARE
rs COND_TRANSITION;
BEGIN
for rs in SELECT
strata.gender_concept_id,
coalesce(osim__age_bucket(LAG(strata.age,1)
OVER (PARTITION BY strata.person_id
ORDER BY condition_era_start_date, condition_concept_id)),strata.age)
AS age_range,
OSIM__condition_count_bucket(strata.condition_concepts) AS cond_count_bucket,
OSIM__time_observed_bucket(strata.observation_period_end_date -
coalesce(LAG(cond.condition_era_start_date,1)
OVER (PARTITION BY strata.person_id
ORDER BY condition_era_start_date, condition_concept_id),
strata.observation_period_start_date)) AS time_remaining,
coalesce(LAG(condition_concept_id,1)
OVER (PARTITION BY strata.person_id
ORDER BY condition_era_start_date, condition_concept_id),-1)
AS condition1_concept_id,
condition_concept_id AS condition2_concept_id,
OSIM__ROUND_DAYS(cond.condition_era_start_date -
coalesce(LAG(cond.condition_era_start_date,1)
OVER (PARTITION BY strata.person_id
ORDER BY condition_era_start_date, condition_concept_id),
strata.observation_period_start_date)) AS delta_days
FROM v_src_person_strata strata
INNER JOIN v_src_first_conditions cond
ON strata.person_id = cond.person_id
ORDER BY 1,2,3,4
LOOP
RETURN NEXT rs;
END LOOP;
RETURN;
END;
$$ LANGUAGE 'plpgsql';
/*=========================================================================
| FUNCTION get_outcome_drug_eras
|
| retrieves drug eras with outcomes matching outcome definition
|
| This is slower as a function than as a view, but allows it to be part of
| the OSIM package and eliminates a circular dependency that makes
| compiling difficult.
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__get_outcome_drug_eras (INTEGER, INTEGER, VARCHAR, INTEGER, INTEGER)
RETURNS SETOF osim_drug_era AS $$
DECLARE
drug_concept_id ALIAS FOR $1;
condition_concept_id ALIAS FOR $2;
outcome_risk_type ALIAS FOR $3;
outcome_onset_days_min ALIAS FOR $4;
outcome_onset_days_max ALIAS FOR $5;
p_drug_concept_id INTEGER;
p_condition_concept_id INTEGER;
outcomes_cur CURSOR FOR
SELECT DISTINCT drug.*
FROM osim_drug_era drug
INNER JOIN
(SELECT DISTINCT
person_id,
FIRST_VALUE(drug_era_id)
OVER (PARTITION BY person_id
ORDER BY drug_era_start_date) AS drug_era_id,
FIRST_VALUE(drug_era_start_date)
OVER (PARTITION BY person_id
ORDER BY drug_era_start_date) AS drug_era_start_date
FROM osim_drug_era
WHERE drug_concept_id = p_drug_concept_id) first_drug
ON drug.person_id = first_drug.person_id
INNER JOIN osim_condition_era cond ON drug.person_id = cond.person_id
AND cond.condition_concept_id = p_condition_concept_id
WHERE drug.drug_concept_id = p_drug_concept_id
AND 1 =
CASE
WHEN outcome_risk_type = 'first exposure' THEN
CASE
WHEN drug.drug_era_start_date = first_drug.drug_era_start_date THEN 1
ELSE 0
END
ELSE 1
END
AND 1 =
CASE
WHEN (outcome_risk_type = 'insidious'
OR outcome_risk_type = 'accumulative') THEN
CASE
WHEN cond.condition_era_start_date
BETWEEN drug.drug_era_start_date AND drug.drug_era_end_date THEN 1
ELSE 0
END
WHEN cond.condition_era_start_date
BETWEEN drug.drug_era_start_date + coalesce(outcome_onset_days_min ,0)
AND drug.drug_era_start_date
+ coalesce(outcome_onset_days_max, drug.drug_era_end_date
- drug.drug_era_start_date) THEN 1
ELSE 0
END;
BEGIN
p_drug_concept_id := drug_concept_id;
p_condition_concept_id := condition_concept_id;
FOR rs IN outcomes_cur LOOP
RETURN NEXT ROW(rs);
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
/*=========================================================================
| FUNCTION get_outcome_eras
|
| retrieves person_id, drug_era_id, and condition_era_ids for outcomes
| matching the definition
|
| This is slower as a function than as a view, but allows it to be part of
| the OSIM package and eliminates a circular dependency that makes
| compiling difficult.
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION OSIM__get_outcome_eras (INTEGER, INTEGER, VARCHAR, INTEGER, INTEGER)
RETURNS SETOF DRUG_COND_OUTCOME As $$
DECLARE
drug_concept_id ALIAS FOR $1;
condition_concept_id ALIAS FOR $2;
outcome_risk_type ALIAS FOR $3;
outcome_onset_days_min ALIAS FOR $4;
outcome_onset_days_max ALIAS FOR $5;
p_drug_concept_id INTEGER;
p_condition_concept_id INTEGER;
outcomes_cur CURSOR FOR
SELECT DISTINCT
drug.person_id,
drug.drug_era_id,
cond.condition_era_id
FROM osim_drug_era drug
INNER JOIN
(SELECT DISTINCT
person_id,
FIRST_VALUE(drug_era_id)
OVER (PARTITION BY person_id
ORDER BY drug_era_start_date) AS drug_era_id,
FIRST_VALUE(drug_era_start_date)
OVER (PARTITION BY person_id
ORDER BY drug_era_start_date) AS drug_era_start_date
FROM osim_drug_era
WHERE drug_concept_id = p_drug_concept_id) first_drug
ON drug.person_id = first_drug.person_id
INNER JOIN osim_condition_era cond ON drug.person_id = cond.person_id
AND cond.condition_concept_id = p_condition_concept_id
WHERE drug.drug_concept_id = p_drug_concept_id
AND 1 =
CASE
WHEN outcome_risk_type = 'first exposure' THEN
CASE
WHEN drug.drug_era_start_date = first_drug.drug_era_start_date THEN 1
ELSE 0
END
ELSE 1
END
AND 1 =
CASE
WHEN (outcome_risk_type = 'insidious'
OR outcome_risk_type = 'accumulative') THEN
CASE
WHEN cond.condition_era_start_date
BETWEEN drug.drug_era_start_date AND drug.drug_era_end_date THEN 1
ELSE 0
END
WHEN cond.condition_era_start_date
BETWEEN drug.drug_era_start_date + coalesce(outcome_onset_days_min ,0)
AND drug.drug_era_start_date
+ coalesce(outcome_onset_days_max, drug.drug_era_end_date
- drug.drug_era_start_date) THEN 1
ELSE 0
END;
BEGIN
p_drug_concept_id := drug_concept_id;
p_condition_concept_id := condition_concept_id;
FOR rs IN outcomes_cur LOOP
RETURN NEXT ROW(rs);
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
/*=========================================================================
| CREATE OR REPLACE FUNCTION INSERT_LOG
|
| Insert timestamped message into process log and also performs
| DBMS_OUTPUT.PUT_LINE of the message.
|
| This is an autonomous_transacton with its own nested commit,
| so the run log is actively updated and can be viewed while the simulator
| is running.
| Update - Since Postgres does not support commit statements or autonomous transactions,
this does not work as expected
|==========================================================================
*/
CREATE OR REPLACE FUNCTION insert_log(text, text)
RETURNS VOID AS $$
DECLARE
m ALIAS FOR $1;
procedure_name ALIAS FOR $2;
BEGIN
INSERT INTO osim_log (stored_procedure_name, message)
VALUES (procedure_name, m);
END;
$$ LANGUAGE plpgsql;
-- CREATE OR REPLACE FUNCTION insert_log_atx(text, text)
-- RETURNS VOID AS $$
-- DECLARE
-- m ALIAS FOR $1;
-- procedure_name ALIAS FOR $2;
-- open_connections TEXT [] := PUBLIC.dblink_get_connections();
-- --v_conn_str text := 'port=5432 dbname=postgres host=ohdsi_v5.i3l.gatech.edu user=ohdsi_admin_user password=J4ckets_4_synpUf';
-- v_conn_str text := 'port=5432 dbname=postgres host=localhost user=kausarm password=Pass@123';
-- v_query text;
-- my_dblink_name TEXT := 'logging_dblink' ;
-- BEGIN
-- IF open_connections IS NULL
-- OR NOT open_connections @> ARRAY [ my_dblink_name ] THEN
-- PERFORM PUBLIC.dblink_connect(
-- my_dblink_name, v_conn_str);
-- raise debug 'New db link connection made' ;
-- ELSE
-- raise debug 'Db link connection exists, re-using' ;
-- END IF;
--
-- v_query := 'SELECT true FROM insert_log_atx( ' || quote_nullable(m) ||
-- ',' || quote_nullable(procedure_name) || ')';
-- PERFORM PUBLIC.dblink_exec(my_dblink_name, v_query);
--
-- -- PERFORM * FROM dblink(v_conn_str, v_query) AS p (ret boolean);
-- END;
-- $$ LANGUAGE plpgsql;
/*=========================================================================
| CREATE OR REPLACE FUNCTION INS_SRC_DB_ATTRIBUTES
|
| Analyze source CDM database and store results for:
| min_db_date
| max_db_date
| condition_occurrence_type
| drug_exposure_type
| persons count
| condition_eras count
|
|==========================================================================
*/
CREATE OR REPLACE FUNCTION ins_src_db_attributes()
RETURNS VOID AS $$
DECLARE
db_min_date DATE;
db_max_date DATE;
persons_count INTEGER;
condition_eras_count INTEGER;
drug_eras_count INTEGER;
procedure_occurrences_count INTEGER;
-- db_cond_era_type_code VARCHAR(3);
-- db_drug_era_type_code VARCHAR(3);
num_rows INTEGER;
MESSAGE text;
BEGIN
PERFORM insert_log('Getting general Source Database Counts', 'ins_src_db_attributes');
SELECT MIN(min_db_date)
INTO db_min_date
FROM
(SELECT MIN(observation_period_start_date) AS min_db_date
FROM v_src_observation_period) t1;
SELECT MAX(max_db_date)
INTO db_max_date
FROM
(SELECT MAX(observation_period_end_date) AS max_db_date
FROM v_src_observation_period) t2;
SELECT COUNT(DISTINCT person.person_id)
INTO persons_count
FROM v_src_person person;
SELECT COUNT(DISTINCT cond.condition_occurrence_id)
INTO condition_eras_count
FROM v_src_condition_era1_ids cond;
SELECT COUNT(DISTINCT drug.drug_exposure_id)
INTO drug_eras_count
FROM v_src_drug_era1_ids drug;
SELECT COUNT(DISTINCT procedure.procedure_occurrence_id)
INTO procedure_occurrences_count
FROM v_src_procedure_occurrence1_ids procedure;
MESSAGE := 'Source CDM Attributes:'
|| ' db_min_date=' || db_min_date
|| ', db_max_date=' || db_max_date
|| ', persons_count=' || persons_count
|| ', condition_eras_count=' || condition_eras_count
|| ', drug_eras_count=' || drug_eras_count;
-- insert_log(MESSAGE, 'ins_src_db_attributes');
TRUNCATE TABLE osim_src_db_attributes;
INSERT INTO osim_src_db_attributes
(db_min_date, db_max_date, persons_count, condition_eras_count,
drug_eras_count, procedure_occurrences_count)
SELECT db_min_date, db_max_date, persons_count, condition_eras_count,
drug_eras_count, procedure_occurrences_count;
GET DIAGNOSTICS num_rows = ROW_COUNT;
MESSAGE := num_rows || ' rows inserted into osim_src_db_attributes.';
--COMMIT;
--PERFORM pg_background_launch('SELECT insert_log(MESSAGE, ''ins_src_db_attributes'');');
PERFORM insert_log(MESSAGE, 'ins_src_db_attributes');
--PERFORM pg_background_launch('SELECT insert_log(''Processing complete'', ''ins_src_db_attributes'');');
PERFORM insert_log('Processing complete', 'ins_src_db_attributes');
raise notice 'Processing complete ins_src_db_attributes, rows = %', num_rows;
EXCEPTION
WHEN OTHERS THEN
raise notice '% %', SQLERRM, SQLSTATE;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION ins_gender_probability()
/*=========================================================================
| PROCEDURE INS_GENDER_PROBABILITY
|
| Pr(Gender)
|
| Analyze source CDM database and store results for:
| Gender Probability
|
|==========================================================================
*/
RETURNS VOID AS $$
DECLARE
num_rows INTEGER;
MESSAGE TEXT;
BEGIN
PERFORM insert_log('Starting Gender Probability Analysis', 'ins_gender_probability');
TRUNCATE TABLE osim_gender_probability;
--COMMIT;
INSERT /*+ append nologging */ INTO osim_gender_probability
(gender_concept_id, n, accumulated_probability)
SELECT
gender_concept_id,
n,
SUM(probability)
OVER
(ORDER BY probability DESC
ROWS UNBOUNDED PRECEDING) accumulated_probability
FROM
(SELECT DISTINCT
gender_concept_id,
COUNT(*) AS n,
1.0 * COUNT(*) / NULLIF(SUM(COUNT(*)) OVER(),0) AS probability
FROM v_src_person_strata strata
GROUP BY gender_concept_id) t1;
GET DIAGNOSTICS num_rows = ROW_COUNT;
MESSAGE := num_rows || ' rows inserted into osim_gender_probability.';
PERFORM insert_log(MESSAGE, 'ins_gender_probability');
--COMMIT;
-- Ensure last accumulated_probability = 1.0
UPDATE osim_gender_probability
SET accumulated_probability = 1.0
WHERE oid IN
(SELECT DISTINCT
FIRST_VALUE(oid)
OVER
(ORDER BY accumulated_probability DESC)
FROM osim_gender_probability);
--COMMIT;
PERFORM insert_log('Processing complete', 'ins_gender_probability');
raise notice 'Processing complete ins_gender_probability, rows = %', num_rows;
EXCEPTION
WHEN OTHERS THEN
PERFORM insert_log('Exception', 'ins_gender_probability');
raise notice '% %', SQLERRM, SQLSTATE;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION ins_age_at_obs_probability()
/*=========================================================================
| PROCEDURE INS_AGE_AT_OBS_PROBABILITY
|
| Pr(Age | Gender)
|
| Analyze source CDM database and store results for:
| Age Probability at beginning of observation period
| Based on Gender
|
|==========================================================================
*/
RETURNS VOID AS $$
DECLARE
num_rows INTEGER;
MESSAGE text;
BEGIN
PERFORM insert_log('Starting Age Probability Analysis', 'ins_age_at_obs_probability');
TRUNCATE TABLE osim_age_at_obs_probability;
--COMMIT;
INSERT /*+ append nologging */ INTO osim_age_at_obs_probability
(gender_concept_id, age_at_obs, n, accumulated_probability)
SELECT
gender_concept_id,
age_at_obs,
n,
SUM(probability)
OVER
(PARTITION BY gender_concept_id
ORDER BY probability DESC ROWS UNBOUNDED PRECEDING) accumulated_probability
FROM
(SELECT
strata.gender_concept_id,
strata.age AS age_at_obs,
COUNT(person_id) AS n,
1.0 * COUNT(person_id) / NULLIF(SUM(COUNT(person_id)) OVER(PARTITION BY gender_concept_id),0) AS probability
FROM v_src_person_strata strata
GROUP BY gender_concept_id, age) t1;
GET DIAGNOSTICS num_rows = ROW_COUNT;
MESSAGE := num_rows || ' rows inserted into osim_age_at_obs_probability.';
PERFORM insert_log(MESSAGE, 'ins_age_at_obs_probability');
--COMMIT;
-- Ensure last accumulated_probability = 1.0
UPDATE osim_age_at_obs_probability
SET accumulated_probability = 1.0
WHERE oid IN
(SELECT DISTINCT
FIRST_VALUE(oid)
OVER
(PARTITION BY gender_concept_id
ORDER BY accumulated_probability DESC)
FROM osim_age_at_obs_probability);
--COMMIT;
PERFORM insert_log('Processing complete', 'ins_age_at_obs_probability');
raise notice 'Processing complete ins_age_at_obs_probability, rows = %', num_rows;
EXCEPTION
WHEN OTHERS THEN
PERFORM insert_log('Exception', 'ins_age_at_obs_probability');
raise notice '% %', SQLERRM, SQLSTATE;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION ins_cond_count_probability()
/*=========================================================================
| PROCEDURE INS_COND_COUNT_PROBABILITY
|
| Pr(Condition Concepts | Age, Gender)
|
| Analyze source CDM database and store results for:
| INTEGER of Distinct Condition Concepts Probability
| Based on Age and Gender
|
|==========================================================================
*/
RETURNS VOID AS $$
DECLARE
num_rows INTEGER;
MESSAGE text;
BEGIN
PERFORM insert_log('Starting Condition Concept Count Probability Analysis', 'ins_cond_count_probability');
TRUNCATE TABLE osim_cond_count_probability;
--COMMIT;
INSERT /*+ append nologging */ INTO osim_cond_count_probability
SELECT
gender_concept_id,
age_at_obs,
NULL AS cond_era_count,
cond_count AS cond_concept_count,
n,
SUM(probability) OVER
(PARTITION BY gender_concept_id, age_at_obs
ORDER BY probability DESC ROWS UNBOUNDED PRECEDING) accumulated_probability
FROM
(SELECT DISTINCT
strata.gender_concept_id,
strata.age AS age_at_obs,
strata.condition_concepts AS cond_count,
COUNT(strata.person_id) AS n,
1.0 * COUNT(strata.person_id)/ NULLIF(SUM(COUNT(strata.person_id)) OVER(PARTITION BY strata.gender_concept_id, strata.age),0) AS probability
FROM v_src_person_strata strata
GROUP BY strata.gender_concept_id, strata.age, strata.condition_concepts) t1
ORDER BY 1,2,6;
GET DIAGNOSTICS num_rows = ROW_COUNT;
MESSAGE := num_rows || ' rows inserted into osim_cond_count_probability.';
PERFORM insert_log(MESSAGE, 'ins_cond_count_probability');
raise notice 'Inserted ins_cond_count_probability, rows = %', num_rows;
--COMMIT;
UPDATE osim_cond_count_probability
SET accumulated_probability = 1.0
WHERE oid IN
(SELECT DISTINCT
FIRST_VALUE(oid)
OVER
(PARTITION BY gender_concept_id, age_at_obs
ORDER BY accumulated_probability DESC)
FROM osim_cond_count_probability);
--COMMIT;
PERFORM insert_log('Processing complete', 'ins_cond_count_probability');
raise notice 'Processing complete ins_cond_count_probability';
EXCEPTION
WHEN OTHERS THEN
PERFORM insert_log('Exception', 'ins_cond_count_probability');
GET STACKED DIAGNOSTICS MESSAGE = PG_EXCEPTION_CONTEXT;
RAISE NOTICE 'context: >>%<<', MESSAGE;
raise notice '% %', SQLERRM, SQLSTATE;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION ins_time_obs_probability()
/*=========================================================================
| PROCEDURE ins_time_obs_probability
|
| Pr(Semi Years Observed | Condition Concept Bucket, Age, Gender)
|
| Analyze source CDM database and store results for:
| INTEGER of Distinct Condition Concepts Probability
| Based on Age and Gender
|
|==========================================================================
*/
RETURNS VOID AS $$
DECLARE
num_rows INTEGER;
MESSAGE text;
BEGIN
PERFORM insert_log('Starting Observed Years Probability Analysis', 'ins_time_obs_probability');
TRUNCATE TABLE osim_time_obs_probability;
--COMMIT;
INSERT /*+ append nologging */ INTO osim_time_obs_probability
SELECT
gender_concept_id,
age_at_obs,
cond_count_bucket,
semi_years_obs,
n,
SUM(probability) OVER
(PARTITION BY gender_concept_id, age_at_obs, cond_count_bucket
ORDER BY probability DESC ROWS UNBOUNDED PRECEDING) accumulated_probability
FROM
(SELECT DISTINCT
strata.gender_concept_id,
strata.age AS age_at_obs,
strata.cond_count_bucket,
strata.semi_years_obs,
COUNT(strata.person_id) AS n,
1.0 * COUNT(strata.person_id)/ NULLIF(SUM(COUNT(strata.person_id)) OVER(PARTITION BY strata.gender_concept_id, strata.age,
strata.cond_count_bucket), 0) AS probability
FROM
(SELECT
person_id,
gender_concept_id,
age,
OSIM__condition_count_bucket(condition_concepts) AS cond_count_bucket,
OSIM__time_observed_bucket(obs_duration_days) AS semi_years_obs
FROM v_src_person_strata) strata
GROUP BY strata.gender_concept_id, strata.age,
strata.cond_count_bucket, strata.semi_years_obs) t1
ORDER BY 1,2,3,6;
GET DIAGNOSTICS num_rows = ROW_COUNT;
MESSAGE := num_rows || ' rows inserted into osim_years_obs_probability.';
PERFORM insert_log(MESSAGE, 'ins_time_obs_probability');
raise notice 'Inserted ins_time_obs_probability, rows = %', num_rows;
--COMMIT;
UPDATE osim_time_obs_probability
SET accumulated_probability = 1.0
WHERE oid IN
(SELECT DISTINCT
FIRST_VALUE(oid)
OVER
(PARTITION BY gender_concept_id, age_at_obs, cond_count_bucket
ORDER BY accumulated_probability DESC)
FROM osim_time_obs_probability);
--COMMIT;
PERFORM insert_log('Processing complete', 'ins_time_obs_probability');
raise notice 'Processing complete ins_time_obs_probability';
EXCEPTION
WHEN OTHERS THEN
PERFORM insert_log('Exception', 'ins_time_obs_probability');
raise notice '% %', SQLERRM, SQLSTATE;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION ins_first_cond_probability()
/*=========================================================================
| PROCEDURE ins_first_cond_probability
|
| Pr(Condition | Age, Gender, Condition Count, Time Remaining, Prior Condition)
|
| Analyze source CDM database and store results for:
| Initial Distinct Condition Concept Era
| Based on INTEGER of Distinct Condition Concepts, Age, Gender, Time
| Remaining (unit is integer of full semi years remaining in person's
| Observation Period, and Prior Condition Concept
|
| Prior Condition Concept = -1 to retrieve initial Condition Concept
|
|==========================================================================
*/
RETURNS VOID AS $$
DECLARE
num_rows INTEGER;
MESSAGE text;
BEGIN
PERFORM insert_log('Starting First Condition Concept Probability Analysis', 'ins_first_cond_probability');
TRUNCATE TABLE osim_first_cond_probability;
--COMMIT;
-- Drop Indexes for Quicker Insertion
BEGIN
DROP INDEX osim_first_cond_ix1;
DROP INDEX osim_first_cond_ix2;
EXCEPTION
WHEN OTHERS THEN
PERFORM insert_log('Probability indexes are already removed', 'ins_first_cond_probability');
END;
--COMMIT;
INSERT /*+ append nologging */ INTO osim_first_cond_probability
(gender_concept_id, age_range, cond_count_bucket,
time_remaining, condition1_concept_id, condition2_concept_id,
delta_days, n, accumulated_probability)
SELECT
gender_concept_id,
age_range,
cond_count_bucket,
time_remaining,
condition1_concept_id,
condition2_concept_id,
delta_days,
n,
SUM(probability)
OVER
(PARTITION BY
gender_concept_id,
age_range,
cond_count_bucket,
condition1_concept_id,
time_remaining
ORDER BY probability DESC
ROWS UNBOUNDED PRECEDING) accumulated_probability
FROM
(SELECT
gender_concept_id,
age_range,
cond_count_bucket,
time_remaining,
condition1_concept_id,
condition2_concept_id,
delta_days,