From 07c2068bea16b1abdce9e3da5f9ef06aaf6cba50 Mon Sep 17 00:00:00 2001 From: rkishony <62783755+rkishony@users.noreply.github.com> Date: Wed, 15 Dec 2021 14:33:14 +0200 Subject: [PATCH] Add files via upload --- UTI_analysis/Adjucted_OR_PURCHandRES.m | 176 ++++++ ...djusted_risk_of_recurrence_treat_notreat.m | 194 +++++++ .../Patient_demographics_table_agecat.m | 113 ++++ UTI_analysis/Prev_res_OR_byYear2.m | 93 +++ UTI_analysis/Prev_res_OR_exactly1.m | 106 ++++ UTI_analysis/README.txt | 34 ++ UTI_analysis/UTI_analysis_and_figures.m | 129 +++++ UTI_analysis/changed_res_bac_alldrugs.m | 49 ++ UTI_analysis/correct_treatment_adjusted_OR.m | 213 +++++++ .../correct_treatment_adjusted_OR_S_IR.m | 110 ++++ .../correct_treatment_fails_reccomend_drug.m | 539 ++++++++++++++++++ ...rect_treatment_fails_reccomend_drug_S_IR.m | 174 ++++++ ...ent_fails_reccomend_drug_v9_2testperiods.m | 373 ++++++++++++ UTI_analysis/hatch.m | 286 ++++++++++ .../initally_ecoli_gained_res_changed_bac.m | 113 ++++ .../mismatched_vs_matched_recurrence_rate.m | 93 +++ UTI_analysis/mode_of_reccurence_pie_charts.m | 108 ++++ .../mode_of_recurrence_treated_untreated.m | 108 ++++ UTI_analysis/my_fit.m | 55 ++ UTI_analysis/net_change_resistance.m | 114 ++++ UTI_analysis/rate_res_by_species.m | 60 ++ ...nce_correctly_prescribed_treat_v_untreat.m | 79 +++ UTI_analysis/risk_recurrence_by_day.m | 63 ++ .../species_change_matrix_gained_res.m | 143 +++++ UTI_analysis/species_prevalence_table.m | 16 + UTI_analysis/susceptibiltiy_change_matrix2.m | 112 ++++ Wound_analysis/OR_wounds.m | 197 +++++++ .../Patient_demographics_table_wounds2.m | 95 +++ Wound_analysis/README.txt | 25 + .../changed_res_bac_alldrugs_wounds.m | 52 ++ .../fail_split_by_week_SIR_all_wound.m | 125 ++++ ...atched_vs_mathced_recurrence_rate_wounds.m | 87 +++ .../mode_of_reccurence_pie_charts_wounds.m | 102 ++++ Wound_analysis/my_fit.m | 55 ++ Wound_analysis/num_sucep_matched.m | 13 + Wound_analysis/rate_res_by_species_wounds.m | 60 ++ Wound_analysis/reccomend_drugs.m | 283 +++++++++ .../risk_recurrence_by_day_wounds.m | 65 +++ .../species_change_matrix_gained_res_wound.m | 123 ++++ Wound_analysis/species_prevalence_table.m | 16 + .../susceptibiltiy_change_matrix_wounds.m | 79 +++ Wound_analysis/wound_analysis_and_figures.m | 82 +++ 42 files changed, 5112 insertions(+) create mode 100644 UTI_analysis/Adjucted_OR_PURCHandRES.m create mode 100644 UTI_analysis/Adjusted_risk_of_recurrence_treat_notreat.m create mode 100644 UTI_analysis/Patient_demographics_table_agecat.m create mode 100644 UTI_analysis/Prev_res_OR_byYear2.m create mode 100644 UTI_analysis/Prev_res_OR_exactly1.m create mode 100644 UTI_analysis/README.txt create mode 100644 UTI_analysis/UTI_analysis_and_figures.m create mode 100644 UTI_analysis/changed_res_bac_alldrugs.m create mode 100644 UTI_analysis/correct_treatment_adjusted_OR.m create mode 100644 UTI_analysis/correct_treatment_adjusted_OR_S_IR.m create mode 100644 UTI_analysis/correct_treatment_fails_reccomend_drug.m create mode 100644 UTI_analysis/correct_treatment_fails_reccomend_drug_S_IR.m create mode 100644 UTI_analysis/correct_treatment_fails_reccomend_drug_v9_2testperiods.m create mode 100644 UTI_analysis/hatch.m create mode 100644 UTI_analysis/initally_ecoli_gained_res_changed_bac.m create mode 100644 UTI_analysis/mismatched_vs_matched_recurrence_rate.m create mode 100644 UTI_analysis/mode_of_reccurence_pie_charts.m create mode 100644 UTI_analysis/mode_of_recurrence_treated_untreated.m create mode 100644 UTI_analysis/my_fit.m create mode 100644 UTI_analysis/net_change_resistance.m create mode 100644 UTI_analysis/rate_res_by_species.m create mode 100644 UTI_analysis/risk_reccurence_correctly_prescribed_treat_v_untreat.m create mode 100644 UTI_analysis/risk_recurrence_by_day.m create mode 100644 UTI_analysis/species_change_matrix_gained_res.m create mode 100644 UTI_analysis/species_prevalence_table.m create mode 100644 UTI_analysis/susceptibiltiy_change_matrix2.m create mode 100644 Wound_analysis/OR_wounds.m create mode 100644 Wound_analysis/Patient_demographics_table_wounds2.m create mode 100644 Wound_analysis/README.txt create mode 100644 Wound_analysis/changed_res_bac_alldrugs_wounds.m create mode 100644 Wound_analysis/fail_split_by_week_SIR_all_wound.m create mode 100644 Wound_analysis/mismatched_vs_mathced_recurrence_rate_wounds.m create mode 100644 Wound_analysis/mode_of_reccurence_pie_charts_wounds.m create mode 100644 Wound_analysis/my_fit.m create mode 100644 Wound_analysis/num_sucep_matched.m create mode 100644 Wound_analysis/rate_res_by_species_wounds.m create mode 100644 Wound_analysis/reccomend_drugs.m create mode 100644 Wound_analysis/risk_recurrence_by_day_wounds.m create mode 100644 Wound_analysis/species_change_matrix_gained_res_wound.m create mode 100644 Wound_analysis/species_prevalence_table.m create mode 100644 Wound_analysis/susceptibiltiy_change_matrix_wounds.m create mode 100644 Wound_analysis/wound_analysis_and_figures.m diff --git a/UTI_analysis/Adjucted_OR_PURCHandRES.m b/UTI_analysis/Adjucted_OR_PURCHandRES.m new file mode 100644 index 0000000..f399981 --- /dev/null +++ b/UTI_analysis/Adjucted_OR_PURCHandRES.m @@ -0,0 +1,176 @@ +function [] = Adjucted_OR_PURCHandRES(UTI_cases,params) +% function takes the UTI_case structure and optional params and performs +% regresion for each antibitoic to calulate demographics adjusted odds +% ratio of risk of early recurrence, for cases susceptibitlyi-matched +% treated cases including both past infection susceptibiltiy and past +% antibiotic purchases + +%Adjusted for following demographics: +X_age = UTI_cases.Demog.Age; +X_age(:,6) = []; %reference age +X_demog = [X_age, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg UTI_cases.Demog.any_prev_cath ]; +number_of_drugs = 7; %not including ofloxacin for consistency with drug recommendatoins +num_prev_purch = UTI_cases.num_prev_purch; % also now include num prev purch of treated drug + +min_1 = 10; +%% OR specifically StoR failure given any previous resistance to drug +clear y_SSR p_SSR ciu_SSR cil_SSR se_SSR + +sen_res = params.resistant_group; % gained res +seall = zeros(size(X_demog,2) +3, number_of_drugs); +yall = zeros(size(X_demog,2) +3, number_of_drugs); +pall = zeros(size(X_demog,2) +3, number_of_drugs); + +for drug = 1:number_of_drugs +SMP_to_use = find(UTI_cases.any_SRmeasurement(:,drug)>0 & (UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_purch = num_prev_purch(SMP_to_use ,drug)>0 ; +any_previous_R = UTI_cases.num_of_previous_R(SMP_to_use ,drug)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1) any_previous_purch(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y, min_1); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end + +y_SSR(2:2:number_of_drugs*2) = exp(yall(end-1,:)); +p_SSR(2:2:number_of_drugs*2) = pall(end-1,:); +se_SSR(2:2:number_of_drugs*2) = seall(end-1,:); +cil_SSR(2:2:number_of_drugs*2) = exp(yall(end-1,:) - seall(end-1,:)); +ciu_SSR(2:2:number_of_drugs*2) = exp(yall(end-1,:) + seall(end-1,:)); + +x1 = yall(end,:) +se1 = seall(end,:) + +y_SSR_purch(2:2:number_of_drugs*2) = exp(yall(end,:)); +p_SSR_purch(2:2:number_of_drugs*2) = pall(end,:); +se_SSR_purch(2:2:number_of_drugs*2) = seall(end,:); +cil_SSR_purch(2:2:number_of_drugs*2) = exp(yall(end,:) - seall(end,:)); +ciu_SSR_purch(2:2:number_of_drugs*2) = exp(yall(end,:) + seall(end,:)); + +x1_purch = yall(end,:); +se1_purch = seall(end,:); + + +%% remained Sensitive +sen_res = params.sensitive_group; +seall = zeros(size(X_demog,2) +3, number_of_drugs); +yall = zeros(size(X_demog,2) +3, number_of_drugs); +pall = zeros(size(X_demog,2) +3, number_of_drugs); + +for drug = 1:number_of_drugs +SMP_to_use = find(UTI_cases.any_SRmeasurement(:,drug)>0 & (UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_purch = num_prev_purch(SMP_to_use ,drug)>0 ; +any_previous_R = UTI_cases.num_of_previous_R(SMP_to_use ,drug)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1) any_previous_purch(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y,min_1); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end +% +y_SSR(1:2:number_of_drugs*2-1) = exp(yall(end-1,:)); +p_SSR(1:2:number_of_drugs*2-1) = pall(end-1,:); +se_SSR(1:2:number_of_drugs*2-1) = seall(end-1,:); +cil_SSR(1:2:number_of_drugs*2-1) = exp(yall(end-1,:) - seall(end-1,:)); +ciu_SSR(1:2:number_of_drugs*2-1) = exp(yall(end-1,:) + seall(end-1,:)); + +y_SSR_purch(1:2:number_of_drugs*2) = exp(yall(end,:)); +p_SSR_purch(1:2:number_of_drugs*2) = pall(end,:); +se_SSR_purch(1:2:number_of_drugs*2) = seall(end,:); +cil_SSR_purch(1:2:number_of_drugs*2) = exp(yall(end,:) - seall(end,:)); +ciu_SSR_purch(1:2:number_of_drugs*2) = exp(yall(end,:) + seall(end,:)); + +%% +subplot(2,2,1) +b1 = bar(y_SSR(1:number_of_drugs*2), 'FaceColor','flat', 'BarWidth', 0.8); +hold on + +b1(1).CData(1:2:number_of_drugs*2-1,:) = ones(number_of_drugs,1)*params.SS_color; +b1.CData(2:2:number_of_drugs*2,:) = ones(number_of_drugs,1)*params.SR_color; +%plot(b1.XData,cil_SSR,'kx'); +%plot(b1.XData,ciu_SSR,'kx'); +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; + +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); + +hold on +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii)> 0.001 + plot(b1.XData(ii), y_SSR(ii)+1, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.001 && p_SSR(ii)> 0.00001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.00001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+1 y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + end +end +% c.se(c.p> 0.05) = 0; +% hold on +% errorbar(c.coef(2:end),c.se(2:end),'.') +xticks((1:2:number_of_drugs*2)+0.5); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); + +ylabel({'Adjusted odds ratio of early recurrence'; ... + 'given past resitant sample'}, 'FontSize' , 8); + +text(0,6.5,'{\it * P<0.01}'); +text(0,6,'{\it** P<0.001}'); +text(0,5.5,'{\it*** P<0.00001}'); + +set(gca, 'YScale', 'log'); +ylim([1 7]) +title('past resistant isolates') + + +%% +subplot(2,2,2) +b1 = bar(y_SSR_purch(1:number_of_drugs*2), 'FaceColor','flat', 'BarWidth', 0.8); +hold on + +b1(1).CData(1:2:number_of_drugs*2-1,:) = ones(number_of_drugs,1)*params.SS_color; +b1.CData(2:2:number_of_drugs*2,:) = ones(number_of_drugs,1)*params.SR_color; +%plot(b1.XData,cil_SSR,'kx'); +%plot(b1.XData,ciu_SSR,'kx'); +errneg = y_SSR_purch - cil_SSR_purch; +errpos = ciu_SSR_purch -y_SSR_purch; + +errorbar(b1.XData,y_SSR_purch,errneg,errpos,'k', 'LineStyle','none'); + +hold on +for ii = 1:length(y_SSR_purch) + if p_SSR_purch(ii)< 0.01 && p_SSR_purch(ii)> 0.001 + plot(b1.XData(ii), y_SSR_purch(ii)+1, '*k', 'MarkerSize',4) + elseif p_SSR_purch(ii) <= 0.001 && p_SSR(ii)> 0.00001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR_purch(ii)+1 y_SSR_purch(ii)+1], '*k', 'MarkerSize',4) + elseif p_SSR_purch(ii) <= 0.00001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR_purch(ii)+1 y_SSR_purch(ii)+1 y_SSR_purch(ii)+1], '*k', 'MarkerSize',4) + end +end +% c.se(c.p> 0.05) = 0; +% hold on +% errorbar(c.coef(2:end),c.se(2:end),'.') +xticks((1:2:number_of_drugs*2)+0.5); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); + +ylabel({'Adjusted odds ratio of early recurrence'; ... + 'given a past antibitoic purchase'}, 'FontSize' , 8); + +text(0,6.5,'{\it * P<0.01}'); +text(0,6,'{\it** P<0.001}'); +text(0,5.5,'{\it*** P<0.00001}'); + +set(gca, 'YScale', 'log'); + +ylim([1 7]) +title('past purchases') +end \ No newline at end of file diff --git a/UTI_analysis/Adjusted_risk_of_recurrence_treat_notreat.m b/UTI_analysis/Adjusted_risk_of_recurrence_treat_notreat.m new file mode 100644 index 0000000..a11a381 --- /dev/null +++ b/UTI_analysis/Adjusted_risk_of_recurrence_treat_notreat.m @@ -0,0 +1,194 @@ +function [] = Adjusted_risk_of_recurrence_treat_notreat(UTI_cases,params) +% function takes the UTI_case structure and optional params and performs +% regresion to calulate demographics adjusted odds ratio of risk of early recurrence +% given treatment with specific antiboitic compared to untreated + +number_of_drugs = params.number_drugs; +X_age = UTI_cases.Demog.Age; +X_age(:,6) = []; %reference age +X_demog = [X_age, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg ]; + + +%% OR of StoR failure given treated vs untreated +clear y_SSR p_SSR ciu_SSR cil_SSR se_SSR +%exclude treatment fails less than 5 days + +sen_res = params.resistant_group; + +seall_gained = zeros(size(X_demog,2) +2, number_of_drugs); +yall_gained = zeros(size(X_demog,2) +2, number_of_drugs); +pall_gained = zeros(size(X_demog,2) +2, number_of_drugs); + +for drug = 1:number_of_drugs + +SMP_to_use = find((UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag & (UTI_cases.PCR_sameday(:,drug)==1 | UTI_cases.PCR_sameday(:,10)==1)); +treated = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug) | UTI_cases.PCR_sameday(SMP_to_use ,10); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), treated(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y, 50); +seall_gained(:,drug) = c.se; +yall_gained(:,drug) = c.coef; +pall_gained(:, drug) = c.p; + +end +% + +yall_gained(isnan(yall_gained)) = 0; +y_SSR(1:number_of_drugs) = exp(yall_gained(end,:)); +p_SSR(1:number_of_drugs) = pall_gained(end,:); +se_SSR(1:number_of_drugs) = seall_gained(end,:); +cil_SSR(1:number_of_drugs) = exp(yall_gained(end,:) - seall_gained(end,:)); +ciu_SSR(1:number_of_drugs) = exp(yall_gained(end,:) + seall_gained(end,:)); + +subplot(3,1,1) +b1 = bar(y_SSR(1:number_of_drugs), 'FaceColor','flat', 'BarWidth', 0.8); +hold on + +b1(1).CData(1:number_of_drugs,:) = ones(number_of_drugs,1)*params.SR_color; +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); + +hold on +above_gap = 0.5; +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii) > 0.001 + plot(b1.XData(ii), y_SSR(ii)+above_gap, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.001 && p_SSR(ii)> 0.0001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+above_gap y_SSR(ii)+above_gap], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.0001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+above_gap y_SSR(ii)+above_gap y_SSR(ii)+above_gap], '*k', 'MarkerSize',4) + end +end + +xticks(1:number_of_drugs); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); +ylabel({'Adjusted odds ratio of infections sensitive';... + 'to the focal antibiotic gaining resistance when';... + ' either treated with the focal antibiotic or untreated'}, 'FontSize', 8); +xlabel('focal antibiotic') +set(gca, 'YScale', 'log'); +ylim([1 6]) + +%% OR of any failure given treated vs untreated for intially sensitive cases +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); + +subplot(3,1,2) +sen_res = [1 2 3]; % any recurrence + + +for drug = 1:number_of_drugs + +SMP_to_use = find((UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag & (UTI_cases.PCR_sameday(:,drug)==1 | UTI_cases.PCR_sameday(:,10)==1)); +treated = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug) | UTI_cases.PCR_sameday(SMP_to_use ,10); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), treated(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y, 50); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end + +yall(isnan(yall)) = 0; +y_SSR(1:number_of_drugs) = exp(yall(end,:)); +p_SSR(1:number_of_drugs) = pall(end,:); +se_SSR(1:number_of_drugs) = seall(end,:); +cil_SSR(1:number_of_drugs) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(1:number_of_drugs) = exp(yall(end,:) + seall(end,:)); +b1 = bar(y_SSR(1:number_of_drugs), 'FaceColor','flat', 'BarWidth', 0.8); +hold on +b1(1).CData(1:number_of_drugs,:) = ones(number_of_drugs,1)*[0.4 0.4 0.4]; +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); + +hold on +above_gap = 0.05; +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii)> 0.01 + plot(b1.XData(ii), y_SSR(ii)+above_gap, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.01 && p_SSR(ii)> 0.0001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+above_gap y_SSR(ii)+above_gap], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.0001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+above_gap y_SSR(ii)+above_gap y_SSR(ii)+above_gap], '*k', 'MarkerSize',4) + end +end + +xticks(1:number_of_drugs); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); +ylabel({'Adjusted odds ratio of infections sensitive';... + 'to the focal antibiotic resulting in early recurrence when';... + ' either treated with the focal antibiotic or untreated'}, 'FontSize', 8); +xlabel('focal antibiotic') +text(9,0.15,'{\it * P<0.01}'); +text(9,0.14,'{\it** P<0.0001}'); +text(9,0.13,'{\it*** P<0.00001}'); +set(gca, 'YScale', 'log'); +ylim([0.2 1.4]) + +%% OR of any failure given treated vs untreated for intially resistant cases +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); +subplot(3,1,3) +sen_res = [1 2 3]; % any recurrence + +for drug = 1:number_of_drugs + +SMP_to_use = find(UTI_cases.SMP_Res(:,drug)== 3 & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag & (UTI_cases.PCR_sameday(:,drug)==1 | UTI_cases.PCR_sameday(:,10)==1)); +treated = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug) | UTI_cases.PCR_sameday(SMP_to_use ,10); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), treated(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y, 50); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end +yall(isnan(yall)) = 0; +y_SSR(1:number_of_drugs) = exp(yall(end,:)); +p_SSR(1:number_of_drugs) = pall(end,:); +se_SSR(1:number_of_drugs) = seall(end,:); +cil_SSR(1:number_of_drugs) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(1:number_of_drugs) = exp(yall(end,:) + seall(end,:)); +b1 = bar(y_SSR(1:number_of_drugs), 'FaceColor','flat', 'BarWidth', 0.8); +hold on +b1(1).CData(1:number_of_drugs,:) = ones(number_of_drugs,1)*[0.75 0.75 0.75]; +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); +hold on +above_gap = 0.05; +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii)> 0.01 + plot(b1.XData(ii), y_SSR(ii)+above_gap, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.01 && p_SSR(ii)> 0.0001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+above_gap y_SSR(ii)+above_gap], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.0001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+above_gap y_SSR(ii)+above_gap y_SSR(ii)+above_gap], '*k', 'MarkerSize',4) + end +end +xticks(1:number_of_drugs); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); +ylabel({'Adjusted odds ratio of infections resistant';... + 'to the focal antibiotic resulting in early recurrence when';... + ' either treated with the focal antibiotic or untreated'}, 'FontSize', 8); +xlabel('focal antibiotic') +text(9,0.15,'{\it * P<0.01}'); +text(9,0.14,'{\it** P<0.0001}'); +text(9,0.13,'{\it*** P<0.00001}'); +set(gca, 'YScale', 'log'); +ylim([0.2 1.4]) diff --git a/UTI_analysis/Patient_demographics_table_agecat.m b/UTI_analysis/Patient_demographics_table_agecat.m new file mode 100644 index 0000000..5780016 --- /dev/null +++ b/UTI_analysis/Patient_demographics_table_agecat.m @@ -0,0 +1,113 @@ +function [] = Patient_demographics_table_agecat(UTI_cases) +% funtion takes UTI_case struc and makes a table of patient demographics numbers and % +% for all antibiotic treated cases. Writes table to the Tables directory. Table +% lists the following demographics: + +names ={'Female'; 'Male';'Pregnant';'Age 0-9';'Age 10-19';... + 'Age 20-29';'Age 30-39';'Age 40-49';'Age 50-59';'Age 60-69';'Age 70-79';'Age 80-89';'Age >90';... + 'Prev SMPs 0-1'; 'Prev SMPs 2-4';'Prev SMPs 5+'; 'diab'; 'CKD'; 'Dialysis'; 'Prev30daysCath'; 'anyPrevCath'}; + +%% check relevant susceptitibltiy is measured + +for drug= 1:8 + relavant_suceptib_measured(:,drug) = UTI_cases.PCR_sameday(:,drug) == 1 & UTI_cases.SMP_Res(:, drug) ~= 0; + relavant_suceptib_notmeasured(:,drug) = UTI_cases.PCR_sameday(:,drug) == 1 & UTI_cases.SMP_Res(:, drug) == 0; + suceptib_matched(:,drug) = UTI_cases.PCR_sameday(:,drug) == 1 & ismember(UTI_cases.SMP_Res(:, drug), [1 2]); + suceptib_mismatched(:,drug) = UTI_cases.PCR_sameday(:,drug) == 1 & ismember(UTI_cases.SMP_Res(:, drug), 3); + treat_fail(:,drug) = UTI_cases.PCR_sameday(:,drug) == 1 & UTI_cases.treatfailure; +end +relavant_suceptib_measured_any = (sum(relavant_suceptib_measured,2)); + +%% all treated cases with relevant susceptitilbity measured +UTI_cases.hasdiag = UTI_cases.hasdiag & relavant_suceptib_measured_any; +Demog_treated = UTI_cases.Demog(UTI_cases.hasdiag & UTI_cases.PCR_sameday_any ,:); +any_SRmeasurement_treated = sum(UTI_cases.any_SRmeasurement_byyear(UTI_cases.hasdiag & UTI_cases.PCR_sameday_any,:,:),3); + +predictive_numbers(1) = nnz(Demog_treated.Gender); +predictive_numbers(2) = nnz(~Demog_treated.Gender); +predictive_numbers(3) = nnz(Demog_treated.Preg); + +for ii = 1:10 +predictive_numbers(ii+3) = nnz(Demog_treated.Age(:,ii)); +end + +prev_smp_range = [0 1 4 ]; +any_SRmeasurement = max(any_SRmeasurement_treated,[],2); +predictive_numbers(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2))); +predictive_numbers(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3))); +predictive_numbers(16) = nnz(any_SRmeasurement > prev_smp_range(3)); + +predictive_numbers(17) = nnz(Demog_treated.has_daibetes); +predictive_numbers(18) = nnz(Demog_treated.has_CKD); +predictive_numbers(19) = nnz(Demog_treated.has_dialysis); +predictive_numbers(20) = nnz(Demog_treated.any_prev60days_cath); +predictive_numbers(21) = nnz(Demog_treated.any_prev_cath); + + +predictive_per(1) = nnz(Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per(2) = nnz(~Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per(3) = nnz(Demog_treated.Preg)/length(Demog_treated.Gender); + +for ii = 1:10 +predictive_per(ii+3) = nnz(Demog_treated.Age(:,ii))/length(Demog_treated.Age(:,1)); +end + +predictive_per(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2)))/length(any_SRmeasurement); +predictive_per(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3)))/length(any_SRmeasurement); +predictive_per(16) = nnz(any_SRmeasurement > prev_smp_range(3))/length(any_SRmeasurement); +predictive_per(17) = nnz(Demog_treated.has_daibetes)/length(Demog_treated.has_daibetes); +predictive_per(18) = nnz(Demog_treated.has_CKD)/length(Demog_treated.has_CKD); +predictive_per(19) = nnz(Demog_treated.has_dialysis)/length(Demog_treated.has_dialysis); +predictive_per(20) = nnz(Demog_treated.any_prev60days_cath)/length(Demog_treated.any_prev60days_cath); +predictive_per(21) = nnz(Demog_treated.any_prev_cath)/length(Demog_treated.any_prev_cath); +%% treatment failures +Demog_treated = UTI_cases.Demog(UTI_cases.hasdiag & UTI_cases.PCR_sameday_any & UTI_cases.treatfailure,:); +any_SRmeasurement_treated = sum(UTI_cases.any_SRmeasurement_byyear(UTI_cases.hasdiag & UTI_cases.PCR_sameday_any & UTI_cases.treatfailure,:,:),3); + +predictive_numbers_fails(1) = nnz(Demog_treated.Gender); +predictive_numbers_fails(2) = nnz(~Demog_treated.Gender); +predictive_numbers_fails(3) = nnz(Demog_treated.Preg); + +for ii = 1:10 +predictive_numbers_fails(ii+3) = nnz(Demog_treated.Age(:,ii)); +end + +any_SRmeasurement = max(any_SRmeasurement_treated,[],2); +predictive_numbers_fails(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2))); +predictive_numbers_fails(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3))); +predictive_numbers_fails(16) = nnz(any_SRmeasurement > prev_smp_range(3)); +predictive_numbers_fails(17) = nnz(Demog_treated.has_daibetes); +predictive_numbers_fails(18) = nnz(Demog_treated.has_CKD); +predictive_numbers_fails(19) = nnz(Demog_treated.has_dialysis); +predictive_numbers_fails(20) = nnz(Demog_treated.any_prev60days_cath); +predictive_numbers_fails(21) = nnz(Demog_treated.any_prev_cath); + +predictive_per_fails(1) = nnz(Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per_fails(2) = nnz(~Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per_fails(3) = nnz(Demog_treated.Preg)/length(Demog_treated.Gender); + +for ii = 1:10 +predictive_per_fails(ii+3) = nnz(Demog_treated.Age(:,ii))/length(Demog_treated.Age(:,1)); +end + +predictive_per_fails(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2)))/length(any_SRmeasurement); +predictive_per_fails(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3)))/length(any_SRmeasurement); +predictive_per_fails(16) = nnz(any_SRmeasurement > prev_smp_range(3))/length(any_SRmeasurement); +predictive_per_fails(17) = nnz(Demog_treated.has_daibetes)/length(Demog_treated.has_daibetes); +predictive_per_fails(18) = nnz(Demog_treated.has_CKD)/length(Demog_treated.has_CKD); +predictive_per_fails(19) = nnz(Demog_treated.has_dialysis)/length(Demog_treated.has_dialysis); +predictive_per_fails(20) = nnz(Demog_treated.any_prev60days_cath)/length(Demog_treated.any_prev60days_cath); +predictive_per_fails(21) = nnz(Demog_treated.any_prev_cath)/length(Demog_treated.any_prev_cath); + + +%% make and write table + + Demographics_table_cases = table(names,predictive_numbers',round(predictive_per*100)'... + ,predictive_numbers_fails',round(predictive_per_fails*100)'); + +filename = 'Tables/Patient_demographics_table.xlsx'; +writetable(Demographics_table_cases,filename); + +% sum(Demographics_table_cases.Var2(1:2)) +% sum(Demographics_table_cases.Var2(5:14)) +end \ No newline at end of file diff --git a/UTI_analysis/Prev_res_OR_byYear2.m b/UTI_analysis/Prev_res_OR_byYear2.m new file mode 100644 index 0000000..c1efbe1 --- /dev/null +++ b/UTI_analysis/Prev_res_OR_byYear2.m @@ -0,0 +1,93 @@ +function [] = Prev_res_OR_byYear2(UTI_cases,params) +% function takes the UTI_case structure and optional params and performs +% regresion for each antibitoic to calulate demographics adjusted odds +% ratio of risk of early recurrence, for cases susceptibitlyi-matched +% treated cases by year of past infection resistance + +%Adjusted for demographics: +X_age = UTI_cases.Demog.Age; +X_age(:,6) = [];%reference age +zeroto39 = sum(X_age(:,1:4),2); % larger bin for lower ages since less data +eightyplus = sum(X_age(:,end-1:end),2); +X_demog = [zeroto39 X_age(:,5:end-2) eightyplus, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg]; +number_of_drugs = 7; %not including ofloxacin for consistency with drug recommendatoins + +figure; +hold on +set(gcf,'color','w') +clf; set(gcf,'name','Fig. S10 resistance by year prior'); +set(gcf,'units','centimeters','Position',[1 1 8 20]); + +for xx = 1:4 + + subplot(4,1,xx) + +any_SRmeasurement_1year = UTI_cases.any_SRmeasurement_byyear(:,:,xx); +num_of_previous_R_1year = UTI_cases.num_of_previous_R_byyear(:,:,xx); + +%% OR specifically StoR failure given any previous resistance to drug +clear y_SSR p_SSR ciu_SSR cil_SSR se_SSR + +sen_res = 3; + +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); + +for drug = 1:number_of_drugs +SMP_to_use = find(any_SRmeasurement_1year(:,drug)>0 & (UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_R = num_of_previous_R_1year(SMP_to_use ,drug)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y, 50); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end + +y_SSR(1:1:number_of_drugs) = exp(yall(end,:)); +p_SSR(1:1:number_of_drugs) = pall(end,:); +se_SSR(1:1:number_of_drugs) = seall(end,:); +cil_SSR(1:1:number_of_drugs) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(1:1:number_of_drugs) = exp(yall(end,:) + seall(end,:)); + +b1 = bar(y_SSR(1:number_of_drugs), 'FaceColor','flat', 'BarWidth', 0.8); +hold on +% +b1(1).CData(1:1:number_of_drugs,:) = ones(number_of_drugs,1)*params.SR_color; +%b1.CData(2:2:number_of_drugs_7*2,:) = ones(number_of_drugs_7,1)*params.SR_color; +%plot(b1.XData,cil_SSR,'kx'); +%plot(b1.XData,ciu_SSR,'kx'); +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; +% + errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); +% +hold on +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii)> 0.001 + plot(b1.XData(ii), y_SSR(ii)+1, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.001 && p_SSR(ii)> 0.00001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.00001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+1 y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + end +end +set(gca,'xticklabel',{[]}) +if xx == 4 +xticks((1:1:number_of_drugs)); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); +end +if xx == 3 +ylabel({'Adjusted odds ratio of S-R failure for patients with';... + 'any previous resistance to the drug compared to sensitive'}); +end + set(gca, 'YScale', 'log'); + ylim([1 8]) + title(['Year ' num2str(xx)]) +end +end diff --git a/UTI_analysis/Prev_res_OR_exactly1.m b/UTI_analysis/Prev_res_OR_exactly1.m new file mode 100644 index 0000000..444741a --- /dev/null +++ b/UTI_analysis/Prev_res_OR_exactly1.m @@ -0,0 +1,106 @@ +function [] = Prev_res_OR_exactly1(UTI_cases,params) +% function takes the UTI_case structure and optional params and performs +% regresion for each antibitoic to calulate demographics adjusted odds +% ratio of risk of early recurrence, for cases susceptibitlyi-matched +% with exactly 1 past infections (either S or R). + +%Adjusted for demographics: +X_age = UTI_cases.Demog.Age; +X_age(:,6) = [];%reference age +zeroto39 = sum(X_age(:,1:4),2); % larger bin for lower ages since less data +eightyplus = sum(X_age(:,end-1:end),2); +X_demog = [zeroto39 X_age(:,5:end-2) eightyplus, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg]; +number_of_drugs = 7; %not including ofloxacin for consistency with drug recommendatoins + +subplot(2,2,3) +%% OR StoR failure given any previous resistance to drug +clear y_SSR p_SSR ciu_SSR cil_SSR se_SSR + +sen_res = params.resistant_group; + +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); + +for drug = 1:number_of_drugs + +SMP_to_use = find(UTI_cases.any_SRmeasurement_byyear(:,drug,1)==1 & (UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_R = UTI_cases.num_of_previous_R_byyear(SMP_to_use ,drug,1)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y, 50); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end + +y_SSR(2:2:number_of_drugs*2) = exp(yall(end,:)); +p_SSR(2:2:number_of_drugs*2) = pall(end,:); +se_SSR(2:2:number_of_drugs*2) = seall(end,:); +cil_SSR(2:2:number_of_drugs*2) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(2:2:number_of_drugs*2) = exp(yall(end,:) + seall(end,:)); + +%% remained sensitive +clear yall pall seall +sen_res = params.sensitive_group; + +for drug = 1:number_of_drugs +SMP_to_use = find(UTI_cases.any_SRmeasurement_byyear(:,drug,1)==1 & (UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_R = UTI_cases.num_of_previous_R_byyear(SMP_to_use ,drug,1)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y,50); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end + +y_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:)); +p_SSR(1:2:number_of_drugs*2-1) = pall(end,:); +se_SSR(1:2:number_of_drugs*2-1) = seall(end,:); +cil_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:) + seall(end,:)); + +%% plot the data +b1 = bar(y_SSR(1:number_of_drugs*2), 'FaceColor','flat', 'BarWidth', 0.8); +hold on + +b1(1).CData(1:2:number_of_drugs*2-1,:) = ones(number_of_drugs,1)*params.SS_color; +b1.CData(2:2:number_of_drugs*2,:) = ones(number_of_drugs,1)*params.SR_color; +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); + +hold on +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii)> 0.001 + plot(b1.XData(ii), y_SSR(ii)+1, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.001 && p_SSR(ii)> 0.00001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.00001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+1 y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + end +end + +xticks((1:2:number_of_drugs*2)+0.5); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); + +ylabel({'Adjusted odds ratio of early recurrence'; ... + 'given a prior resitant sample in the past year'}, 'FontSize' , 8); + +text(0,6.5,'{\it * P<0.01}'); +text(0,6,'{\it** P<0.001}'); +text(0,5.5,'{\it*** P<0.00001}'); + +set(gca, 'YScale', 'log'); +yticks(1:8) +ylim([0.4 8.5]) + +end diff --git a/UTI_analysis/README.txt b/UTI_analysis/README.txt new file mode 100644 index 0000000..0676a71 --- /dev/null +++ b/UTI_analysis/README.txt @@ -0,0 +1,34 @@ +Run the main script UTI_analysis_and_figures.m to perform the analysis and generate the figures. +The code requires the UTI_cases structure, which contains the following data: + + SMP_Res_drug_names: {8×1 cell} % cell array of names of each of 8 antibiotic susceptibilties measured. + RandomID: [182571×1 double] % array of unique patient identifier for each case + SMP_Res: [182571×8 double] % array of current infection susceptibiltiy to each antibiotic. S = 1, I = 2, R = 3, 0 = unmeasured. If multiple isolates, maximal resistance is used. + hasdiag: [182571×1 logical] % logical array is case had associated UTI diagnosis. + num_of_previous_R: [182571×8 double] % array of number of previous infections patient has had which were resistant to each antibiotic. + num_of_previous_S: [182571×8 double] % array of number of previous infections patient has had which were sensitive to each antibiotic. + any_SRmeasurement: [182571×8 double] % array of number of previous infections patient has had with any susceptibiltiy measured to each antibiotic + num_of_previous_SMPs: [182571×1 double] % array of number of previous infections patient has had. + SamplingDate: [182571×1 double] % array of date of current sample + changed_bac: [182571×1 double] % logical array did future recurrent infection change species + new_bac: [182571×1 double] % array of species code for future recurrent infection. + bug: [182571×1 double] % array of species code for current infection. + bug_all: {182571×1 cell} % cell array of species code for all isolates in current infection. + new_bug: {182571×1 cell} % cell array of species code for all isolates in future recurrent infection. NaN if no recurrence. + nBac: [182571×1 double] % cell array of species code for all isolates in current infection. + next_res: [182571×8 double] % array of future recurrent infection maximal resistance to each antibiotic. NaN if no recurrence. + RES: {182571×8 cell} % suceptibilty of each isolate in current infection. + new_RES: {182571×8 cell} % suceptibilty of each isolate in future recurrent infection. NaN if no recurrence. + date_diff: [182571×1 double] %number of days between current and future recurrent infection. NaN if no recurrence. + treatfailure: [182571×1 logical] % logical vector if any of the 5 antibiotics were prescribed + num_of_previous_R_byyear: [182571×8×4 double] % array of number of previous infections patient has had which were resistant to each of 8 antibiotic for each 4 years prior. + num_of_previous_S_byyear: [182571×8×4 double] % array of number of previous infections patient has had which were sensitive to each of 8 antibiotic for each 4 years prior. + any_SRmeasurement_byyear: [182571×8×4 double] % array of number of previous infections patient has had with any susceptibiltiy measured to each of 8 antibiotic for each 4 years prior. + PCR_sameday_any: [182571×1 logical] % logical array if any of the 8 antibiotics were prescribed + PCR_sameday: [182571×9 logical] % logical array of which antibitoic was prescribed. Column 9 is untreated. + PCR_sameday_names: {1×9 cell} % names of each prescribed antibitoics. 9 is untreated + Demog: [182571×8 table] % table of demographics of each case, including age bracket, gender, pregnancy, previous catheter use + agem: [10×1 double] % midpoint of each age bracket in demograhics. + num_prev_purch: [182571×8 double] % array of number of times the patient was previosuly prescribed each antibiotic. + Bugs: [609×2 table] % table of species names and codes. + \ No newline at end of file diff --git a/UTI_analysis/UTI_analysis_and_figures.m b/UTI_analysis/UTI_analysis_and_figures.m new file mode 100644 index 0000000..e325f34 --- /dev/null +++ b/UTI_analysis/UTI_analysis_and_figures.m @@ -0,0 +1,129 @@ +%% perform UTI analysis and makes figures for +% Minimizing antibiotic-induced emergence of antibiotic resistance in +% bacterial infections +% Mathew Stracy 2021 +%% loads the UTI_cases structure. Each line in the struct represents a UTI case +clearvars -except UTI_cases +if ~exist('UTI_cases') % load the data + load('UTI_cases.mat'); +end +if ~isfolder('Tables') + mkdir('Tables') +end + +%% parameters +params.number_drugs = 8; +% sensitivity grouping Sensitive = 1; Intermediate = 2; Resistant = 3; +params.sensitive_group = [1 2]; +SIR= 1:3; params.resistant_group = SIR(~ismember(SIR, params.sensitive_group)); +clear SIR +% figure colors +params.SS_color = [0.1 0.13 0.5]; params.SR_color = [0 0.95 0.95]; +params.RR_color = [0.5 0 0.5]; params.RS_color = [0.95 0 0.95]; +params.new_order = [1 2 8 3:7]; %drug order for figures + +%% generate Table S1 patient demographics +Patient_demographics_table_agecat(UTI_cases); + +%% Fig 1B +mismatched_vs_matched_recurrence_rate(UTI_cases,params) + +%% Fig 1C +mode_of_reccurence_pie_charts(UTI_cases,params) + +%% Fig 1D +figure +set(gcf,'color','w','name','Fig. 1D','units','centimeters','Position',[1 1 20 7]) +risk_reccurence_correctly_prescribed_treat_v_untreat(UTI_cases,params) + +%% Fig S3 +figure +set(gcf,'color','w', 'name','Fig. S3','units','centimeters','Position',[1 1 17 7.5]); +net_change_resistance(UTI_cases,params) + +%% Fig 1E rate of recuurence by day +figure +set(gcf,'color','w','name','Fig. 1E','units','centimeters','Position',[1 1 11 6]); +risk_recurrence_by_day(UTI_cases,params) +drawnow + +%% Fig S6 Mode of recurrence by day for treated and untreated UTIs. Mode of recurrence by day for treated and untreated UTIs. +figure +set(gcf,'color','w', 'name','Fig. S6 Mode of recurrence','units','centimeters','Position',[1 1 16 26]); +mode_of_recurrence_treated_untreated(UTI_cases,params) +drawnow + +%% Fig 1F matrix UTIs +figure +set(gcf,'color','w', 'name','Fig. 1F Susceptibiltiy change matrix', 'units','centimeters','Position',[1 1 12 10]); +susceptibiltiy_change_matrix2(UTI_cases,params) +drawnow + +%% Fig 2E +figure; +set(gcf,'color','w', 'name','Fig. 2F', 'units','centimeters','Position',[1 1 18 10]); +initally_ecoli_gained_res_changed_bac(UTI_cases,params) + +%% Fig 2G +figure +set(gcf,'color','w', 'name','Fig. 2G UTIs', 'units','centimeters','Position',[1 1 5 9]); +changed_res_bac_alldrugs(UTI_cases,params) + +%% Fig 3B +figure; +set(gcf,'color','w', 'name','Fig. 3B Adjusted OR'); +correct_treatment_adjusted_OR(UTI_cases,params) +drawnow + +%% Fig 3DEF +correct_treatment_fails_reccomend_drug(UTI_cases,params) +drawnow +%% Supp Fig S5 +figure; +set(gcf,'color','w') +clf; set(gcf,'name','Fig. S5 Adjusted risk of recurrence and emergence of resistance with and without antibiotic treatment'); +set(gcf,'units','centimeters','Position',[1 1 10 30]); +Adjusted_risk_of_recurrence_treat_notreat(UTI_cases,params) + +%% Supp Fig S8 +figure; +set(gcf,'color','w', 'name','Fig. S8 Rates of resistance by species UTIs',... +'units','centimeters','Position',[1 1 25 18]); +rate_res_by_species(UTI_cases,params); + +%% Supp Fig S10 +Prev_res_OR_byYear2(UTI_cases,params) + +%% Supp Fig S11 +figure; +set(gcf,'color','w', 'name','Fig. S11', 'units','centimeters','Position',[1 1 25 18]); +Adjucted_OR_PURCHandRES(UTI_cases,params) +Prev_res_OR_exactly1(UTI_cases,params) + +%% Supp Fig S14BC +correct_treatment_fails_reccomend_drug_v9_2testperiods(UTI_cases,params) +drawnow +%% Supp Fig 9 +species_change_matrix_gained_res(UTI_cases,params) + +%% Supp Fig S16 intermediate grouped with resistant +figure; +set(gcf,'color','w', 'name','Fig. S16', 'units','centimeters','Position',[1 1 25 10]); +subplot(1,2,1) +correct_treatment_adjusted_OR_S_IR(UTI_cases,params); +correct_treatment_fails_reccomend_drug_S_IR(UTI_cases,params) +drawnow + +%% Supp Table S4 +species_prevalence_table(UTI_cases) + +%% save the figures +if ~isfolder('Figures') + mkdir('Figures') +end +FigList = findobj(allchild(0), 'flat', 'Type', 'figure'); +for iFig = 1:length(FigList) + FigHandle = FigList(iFig); + FigName = get(FigHandle, 'name'); + saveas(FigHandle,['Figures/' FigName '.fig']) +end \ No newline at end of file diff --git a/UTI_analysis/changed_res_bac_alldrugs.m b/UTI_analysis/changed_res_bac_alldrugs.m new file mode 100644 index 0000000..0df44a9 --- /dev/null +++ b/UTI_analysis/changed_res_bac_alldrugs.m @@ -0,0 +1,49 @@ +function [] = changed_res_bac_alldrugs(UTI_cases,params) +%function takes the UTI_case structure and optional params and calulates +% the rate of change of species in gained-resistance early recurrences + +for drug = 1:params.number_drugs + +%next res is resistant +index = cellfun(@(x) ismember(x,params.resistant_group), UTI_cases.new_RES(:,drug),'UniformOutput',false); +%only resistant next UTI_cases.Bugs +resistant_nextres_UTI_cases.Bugs = cellfun(@(v,x)v(x),UTI_cases.new_bug,index,'UniformOutput',false); +%are any of the next resistant UTI_cases.Bugs not those in original infection +[M2,X2] = cellfun(@ismember,resistant_nextres_UTI_cases.Bugs,UTI_cases.bug_all,'UniformOutput',false); + +resistant_nextres_UTI_cases.Bugs_members = cellfun(@(v,x)v(x),UTI_cases.new_bug,M2,'UniformOutput',false); +M3 = cellfun(@not,M2,'UniformOutput',false); +resistant_nextres_UTI_cases.Bugs_notmembers = cellfun(@(v,x)v(x),UTI_cases.new_bug,M3,'UniformOutput',false); + +initially_sensitive = (UTI_cases.SMP_Res(:,drug) == 1 | UTI_cases.SMP_Res(:,drug) == 2); +to_use = find(initially_sensitive & UTI_cases.treatfailure & UTI_cases.PCR_sameday(:,drug)); + +changed_species = cell2mat( resistant_nextres_UTI_cases.Bugs_notmembers(to_use)); +[GC,GR] = groupcounts(changed_species) ; +table(UTI_cases.Bugs.Name(ismember(UTI_cases.Bugs.Code, GR)),GC); + +same_species = cell2mat( resistant_nextres_UTI_cases.Bugs_members(to_use)); +[GC,GR] = groupcounts(same_species) ; +table(UTI_cases.Bugs.Name(ismember(UTI_cases.Bugs.Code, GR)),GC); + +changed(drug) = length(changed_species); +stayed(drug) = length(same_species); + +ratio_changed(drug) = changed(drug)./(changed(drug) + stayed(drug)); +ratio_error(drug) = sqrt((ratio_changed(drug)).*(1-(ratio_changed(drug)))./(changed(drug)+stayed(drug))); +nums(drug) = (changed(drug) + stayed(drug)) ; + +end + +ratio_changed2 = sum(changed)./(sum(changed) + sum(stayed)); +ratio_error2 = sqrt((ratio_changed2).*(1-(ratio_changed2))./(sum(changed) + sum(stayed))); +ratio_changed2(2) = 0.7466; % for wound infection data see wound analysis to generate this +ratio_error2(2) = 0.0253; % for wound infection data see wound analysis to generate this +bar(ratio_changed2, 'FaceColor',params.SR_color) +xticklabels({'UTIs', 'Wounds'}) +xtickangle(45) +hold on +errorbar(1:length(ratio_changed2),ratio_changed2,ratio_error2, 'k', 'LineStyle','none') +ylabel('% of SR caused by different species') +ylim([0 1]) + diff --git a/UTI_analysis/correct_treatment_adjusted_OR.m b/UTI_analysis/correct_treatment_adjusted_OR.m new file mode 100644 index 0000000..4381653 --- /dev/null +++ b/UTI_analysis/correct_treatment_adjusted_OR.m @@ -0,0 +1,213 @@ +function [] = correct_treatment_adjusted_OR(UTI_cases,params) +% function takes the UTI_case structure and optional params and performs +% regresion for each antibitoic to calulate demographics adjusted odds +% ratio of risk of early recurrence, for cases susceptibitlyi-matched treated cases which gained resistance +% and remained sensitive. Fuction writes table of regressoin coefficients +% to the Tables directory. + +%Adjusted for following demographics: +X_age = UTI_cases.Demog.Age; +X_age(:,6) = []; %reference age +X_demog = [X_age, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg UTI_cases.Demog.any_prev_cath ]; +features = {'Age 0-9', 'Age 10-19', 'Age 20-29', 'Age 30-39', 'Age 40-49', 'Age 60-69', 'Age 70-79', 'Age 80-89', 'Age 90-100', 'Gender', 'Pregnancy', 'Catheter', 'Prev Resistance'}; + +number_of_drugs = 7; %not including ofloxacin for consistency with drug recommendatoins +%% OR specifically StoR failure given any previous resistance to drug +clear y_SSR p_SSR ciu_SSR cil_SSR se_SSR + +sen_res = params.resistant_group; + +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); +min_1 = 10; + +for drug = 1:number_of_drugs +%use cases sentivie to antibiotic +SMP_to_use = find(UTI_cases.any_SRmeasurement(:,drug)>0 & (UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_R = UTI_cases.num_of_previous_R(SMP_to_use ,drug)>0 ; +% gain of resistance early recurrences +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +%treated with antibiotic +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +%do regression +c = my_fit(X, Y, min_1); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end + +y_SSR(2:2:number_of_drugs*2) = exp(yall(end,:)); %OR +p_SSR(2:2:number_of_drugs*2) = pall(end,:); +se_SSR(2:2:number_of_drugs*2) = seall(end,:); +cil_SSR(2:2:number_of_drugs*2) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(2:2:number_of_drugs*2) = exp(yall(end,:) + seall(end,:)); + +x1 = yall(end,:); +se1 = seall(end,:); + +%% Write TableS4 +features = pad(features); +antibiotic_names = pad(UTI_cases.SMP_Res_drug_names); +yall = yall(2:end,:); +pall = pall(2:end,:); +seall= seall(2:end,:); +CIL = yall - seall; +CIU = yall + seall; + +pstrs = cell(size(pall)) ; +for i = 1:size(pall,1) + for j = 1:size(pall,2) + pstrs{i,j} = '' ; + if pall(i,j)<0.01 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.001 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.0001, pstrs{i,j} = [pstrs{i,j}, '*']; end + end +end + +drug_order = [1 2; 3 4; 5 6; 7 7]; +fid = fopen('Tables/Table_S7_AdgustedOR_SR.txt', 'w'); + +for jj = 1:size(drug_order,1) + +fprintf(fid,'%-12s',''); +for drug = drug_order(jj,:) + fprintf(fid,antibiotic_names{drug}); + fprintf(fid,'%-12s',''); +end +fprintf(fid,'\n') ; +for ii = 1:size(yall,1) + fprintf(fid,[features{ii} ' ']); +for drug = drug_order(jj,:) + coefs_tmp = [yall(ii, drug) CIL(ii, drug) CIU(ii, drug) pstrs(ii, drug)]; + fprintf(fid,'%5.2f [%5.2f,%5.2f]%-3s ',coefs_tmp{:}) ; + fprintf(fid,'%-7s',''); +end +fprintf(fid,'\n') ; +end +fprintf(fid,'\n') ; +end +fprintf(fid,'* P<0.01 ** P<0.0001 *** P<0.000001\n\n\n'); +fclose(fid) ; + +%% OR specifically StoR failure given any previous resistance to drug +sen_res = params.sensitive_group; + +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); + +for drug = 1:number_of_drugs +SMP_to_use = find(UTI_cases.any_SRmeasurement(:,drug)>0 & (UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_R = UTI_cases.num_of_previous_R(SMP_to_use ,drug)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y,min_1); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; + +end + +y_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:)); +p_SSR(1:2:number_of_drugs*2-1) = pall(end,:); +se_SSR(1:2:number_of_drugs*2-1) = seall(end,:); + +cil_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:) + seall(end,:)); + +b1 = bar(y_SSR(1:number_of_drugs*2), 'FaceColor','flat', 'BarWidth', 0.8); +hold on + +b1(1).CData(1:2:number_of_drugs*2-1,:) = ones(number_of_drugs,1)*params.SS_color; +b1.CData(2:2:number_of_drugs*2,:) = ones(number_of_drugs,1)*params.SR_color; +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); + +hold on +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii)> 0.001 + plot(b1.XData(ii), y_SSR(ii)+1, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.001 && p_SSR(ii)> 0.00001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.00001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+1 y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + end +end + +xticks((1:2:number_of_drugs*2)+0.5); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); + +ylabel({'Adjusted odds ratio of early UTI recurrence';... + 'given any past resistant sample'}); + +text(0,6.5,'{\it * P<0.01}'); +text(0,6,'{\it** P<0.001}'); +text(0,5.5,'{\it*** P<0.00001}'); + +set(gca, 'YScale', 'log'); +ylim([1 7]) + + +%% TableS8 + +yall = yall(2:end,:); +pall = pall(2:end,:); +seall= seall(2:end,:); +CIL = yall - seall; +CIU = yall + seall; + +pstrs = cell(size(pall)) ; +for i = 1:size(pall,1) + for j = 1:size(pall,2) + pstrs{i,j} = '' ; + if pall(i,j)<0.01 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.001 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.0001, pstrs{i,j} = [pstrs{i,j}, '*']; end + end +end + +drug_order = [1 2; 3 4; 5 6; 7 7]; +fid = fopen('Tables/Table_S8_AdgustedOR_SS.txt', 'w'); + +for jj = 1:size(drug_order,1) + +fprintf(fid,'%-12s',''); +for drug = drug_order(jj,:) + fprintf(fid,antibiotic_names{drug}); + fprintf(fid,'%-12s',''); +end +fprintf(fid,'\n') ; +for ii = 1:size(yall,1) + fprintf(fid,[features{ii} ' ']); +for drug = drug_order(jj,:) + coefs_tmp = [yall(ii, drug) CIL(ii, drug) CIU(ii, drug) pstrs(ii, drug)]; + fprintf(fid,'%5.2f [%5.2f,%5.2f]%-3s ',coefs_tmp{:}) ; + fprintf(fid,'%-7s',''); +end +fprintf(fid,'\n') ; +end +fprintf(fid,'\n') ; +end +fprintf(fid,'* P<0.01 ** P<0.0001 *** P<0.000001\n\n\n'); +fclose(fid) ; + +%% +x2 = yall(end,:); +se2 = seall(end,:); + +z = (x1 - x2)./sqrt(se1.^2 + se2.^2); +p = normcdf(-z); + +min(p); +max(p); + +end \ No newline at end of file diff --git a/UTI_analysis/correct_treatment_adjusted_OR_S_IR.m b/UTI_analysis/correct_treatment_adjusted_OR_S_IR.m new file mode 100644 index 0000000..1b042c4 --- /dev/null +++ b/UTI_analysis/correct_treatment_adjusted_OR_S_IR.m @@ -0,0 +1,110 @@ +function [] = correct_treatment_adjusted_OR_S_IR(UTI_cases,params) +% function takes the UTI_case structure and optional params and performs +% regresion for each antibitoic to calulate demographics adjusted odds +% ratio of risk of early recurrence, for cases susceptibitlyi-matched treated cases which gained resistance +% and remained sensitive. Intermediate now grouped with resistant + +X_age = UTI_cases.Demog.Age; +X_age(:,6) = []; % refence +X_demog = [X_age, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg UTI_cases.Demog.any_prev_cath ]; +number_of_drugs = 7; %not including ofloxacin for consistency with drug recommendations +min_1 = 10; + +%% OR specifically StoR failure given any previous resistance to drug +clear y_SSR p_SSR ciu_SSR cil_SSR se_SSR + +sen_res = [2 3]; % intermediate grouped with resistant + +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); + +for drug = 1:number_of_drugs + +SMP_to_use = find(UTI_cases.any_SRmeasurement(:,drug)>0 & ismember(UTI_cases.SMP_Res(:,drug), 1) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_R = UTI_cases.num_of_previous_R(SMP_to_use ,drug)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y, min_1); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; +end + +y_SSR(2:2:number_of_drugs*2) = exp(yall(end,:)); +p_SSR(2:2:number_of_drugs*2) = pall(end,:); +se_SSR(2:2:number_of_drugs*2) = seall(end,:); +cil_SSR(2:2:number_of_drugs*2) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(2:2:number_of_drugs*2) = exp(yall(end,:) + seall(end,:)); + +x1 = yall(end,:); +se1 = seall(end,:); + + +%% OR specifically StoR failure given any previous resistance to drug +sen_res = [1]; % intermediate not grouped with sensitive + +seall = zeros(size(X_demog,2) +2, number_of_drugs); +yall = zeros(size(X_demog,2) +2, number_of_drugs); +pall = zeros(size(X_demog,2) +2, number_of_drugs); + +for drug = 1:number_of_drugs +SMP_to_use = find(UTI_cases.any_SRmeasurement(:,drug)>0 & ismember(UTI_cases.SMP_Res(:,drug),1) & UTI_cases.next_res(:, drug) ~=0 & UTI_cases.hasdiag); +any_previous_R = UTI_cases.num_of_previous_R(SMP_to_use ,drug)>0 ; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +c = my_fit(X, Y,min_1); +seall(:,drug) = c.se; +yall(:,drug) = c.coef; +pall(:, drug) = c.p; + +end + +y_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:)); +p_SSR(1:2:number_of_drugs*2-1) = pall(end,:); +se_SSR(1:2:number_of_drugs*2-1) = seall(end,:); + +cil_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:) - seall(end,:)); +ciu_SSR(1:2:number_of_drugs*2-1) = exp(yall(end,:) + seall(end,:)); + +b1 = bar(y_SSR(1:number_of_drugs*2), 'FaceColor','flat', 'BarWidth', 0.8); +hold on + +b1(1).CData(1:2:number_of_drugs*2-1,:) = ones(number_of_drugs,1)*params.SS_color; +b1.CData(2:2:number_of_drugs*2,:) = ones(number_of_drugs,1)*params.SR_color; +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); + +hold on +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.01 && p_SSR(ii)> 0.001 + plot(b1.XData(ii), y_SSR(ii)+1, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.001 && p_SSR(ii)> 0.00001 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.00001 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+1 y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + end +end + +xticks((1:2:number_of_drugs*2)+0.5); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:number_of_drugs)); +xtickangle(45); + +ylabel({'Adjusted odds ratio of early UTI recurrence';... + 'given any past resistant sample'}); + +text(0,6.5,'{\it * P<0.01}'); +text(0,6,'{\it** P<0.001}'); +text(0,5.5,'{\it*** P<0.00001}'); + +set(gca, 'YScale', 'log'); +ylim([1 7]) + +end \ No newline at end of file diff --git a/UTI_analysis/correct_treatment_fails_reccomend_drug.m b/UTI_analysis/correct_treatment_fails_reccomend_drug.m new file mode 100644 index 0000000..60695b7 --- /dev/null +++ b/UTI_analysis/correct_treatment_fails_reccomend_drug.m @@ -0,0 +1,539 @@ +function [] = correct_treatment_fails_reccomend_drug(UTI_cases,params) +% function takes the UTI_case structure and optional params and treains and tests +% regressoin model to predict risk of gain of resistance for all susceptibility-matched treated cases cases + + +X_age = UTI_cases.Demog.Age; +X_age(:,6) = []; % reference age +X_demog = [X_age, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg UTI_cases.Demog.any_prev_cath]; +number_of_drugs = 7; % not including orflox as not measured in test period +sen_res = params.resistant_group; +%% seperate training data and test data +test_date_start = datenum('2018-05-01') ; +test_date_end = datenum('2019-07-01') ; +test_date_range = test_date_start:test_date_end; +test_data = ismember(UTI_cases.SamplingDate, test_date_range); +fprintf('Testing using %.2f percent of the data\n' ,nnz(test_data)/length(test_data)*100) + +%% Regression for StoR failure given any previous resistance to drug +clear coef +warning('off','stats:glmfit:IterationLimit'); +any_SRmeasurement = UTI_cases.any_SRmeasurement; +num_of_previous_R = UTI_cases.num_of_previous_R; +num_of_previous_S = UTI_cases.num_of_previous_S; + +figure; +set(gcf,'color','w', 'name','Fig. S12', 'units','centimeters','Position',[1 1 15 15]); + +%loop over all antibiotics +for drug = 1:number_of_drugs +%use cases sentivie to antibiotic +SMP_to_use = find( ismember(UTI_cases.SMP_Res(:,drug), params.sensitive_group) & ~test_data & UTI_cases.hasdiag); +%number past infections sen or res to the antibiotic +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +%gained resistance treatment failure +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +%treated with antibiotic +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial','logit') ; +coef(:,drug) = glm.B; +% plots the AUC for training period +scores = glmval(glm.B,X,'logit') ; +[X,Y,T,AUC] = perfcurve(Y,scores,1); +AUC_all(drug) = AUC; +subplot(4,2,drug) +plot(X,Y); +xlabel('False positive rate') ; +ylabel('True positive rate'); +title([UTI_cases.SMP_Res_drug_names{drug} ' AUC:' num2str(AUC)]); + +end + +%% test data: +clear P +P = nan(height(UTI_cases.Demog),number_of_drugs); +treatfails_gainedres_toprch = zeros(height(UTI_cases.Demog),number_of_drugs); +%patient was correctly prescribed a drug from the used drugs +was_correctly_prescribed = sum(UTI_cases.PCR_sameday(:,1:number_of_drugs) & ismember(UTI_cases.SMP_Res(:,1:number_of_drugs), params.sensitive_group),2) > 0; + +for drug = 1:number_of_drugs + +SMP_to_use = find(was_correctly_prescribed & test_data & UTI_cases.hasdiag); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use, num_previous_R num_previous_S]; +P(SMP_to_use, drug) = glmval(coef(:,drug),X,'logit') ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfails = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +treatfails_gainedres_toprch(SMP_to_use, drug) = treatfails & drug_prch_temp; +% reassign any mismatched (or unknown Res) probabilities to > 1 +index = find(ismember(UTI_cases.SMP_Res(SMP_to_use,drug), [0 3])); +P(SMP_to_use(index), drug) = 1.1; % mismatched treatments are not used +X_test = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +Y = treatfailure(drug_prch_temp==1); +scores = glmval(coef(:,drug),X_test,'logit') ; +% plots the AUC for test period +[X_test,Y,T,AUC2] = perfcurve(Y,scores,1); +AUC_all2(drug) = AUC2; +subplot(4,2,drug) +hold on +plot(X_test,Y,'r'); +xlabel('False positive rate') ; +ylabel('True positive rate'); +title([UTI_cases.SMP_Res_drug_names{drug} ' AUC train:' num2str(AUC_all(drug)) 'AUC test:' num2str(AUC_all2(drug))]); +end +treatfails_gainedres_toprch = logical(sum(treatfails_gainedres_toprch,2)); + +%% pick antibiotic with lowest P +clear M best_drug +withPdata_index = find(sum(isnan(P),2)== 0); +P_nonans = P(withPdata_index,:); +real_prch = UTI_cases.PCR_sameday(withPdata_index, 1:number_of_drugs); +real_treatfails_gainedres_toprch = treatfails_gainedres_toprch(withPdata_index); +real_res = UTI_cases.SMP_Res(withPdata_index, 1:number_of_drugs); +[M,best_drug_temp] = min(P_nonans,[],2); +best_drug = zeros(size(P_nonans,1),number_of_drugs); +for ii = 1:number_of_drugs +best_drug(best_drug_temp == ii,ii) = 1; +end + +%% Test that data all have a prch amoung the chosen drugs +fprintf('There are %.0f samples without a PRCH (should be zero)\n' ,(length(real_prch) - nnz(sum(real_prch,2)>0))) + +% Test that there are no actually inccorectly prescribed samples +incorrectly_presribed = nnz(sum(ismember(real_res, params.resistant_group) & real_prch,2)); +fprintf('There are %.0f samples incorrectly prescribed (should be zero)\n' ,incorrectly_presribed) + +correctly_presribed = nnz(sum(ismember(real_res, params.sensitive_group) & real_prch,2)); +fprintf('%.0f out of %.0f samples are actuall correctly prescribed (should be all)\n' ,correctly_presribed, length(real_res)) + +reccomended_correctly_presribed = logical(sum(ismember(real_res, params.sensitive_group) & best_drug,2)); +fprintf('%.0f out of %.0f BEST RECCOMENDED samples are correctly prescribed (should be all)\n' ,nnz(reccomended_correctly_presribed), length(reccomended_correctly_presribed)) + +%% are the NON COST ADJUSTED prescribed and best reccomended the same? +prescribed_pred_matched = logical(sum(best_drug & real_prch,2)); +fprintf('Mean rate of S->R fail for pysician/recommended (no cost adj) MATCHED is: %.2f %%\n' ,mean(real_treatfails_gainedres_toprch(prescribed_pred_matched))*100) +fprintf('Mean rate of S->R fail for pysician/recommended (no cost adj) NOT MATCHED is: %.2f %%\n' ,mean(real_treatfails_gainedres_toprch(~prescribed_pred_matched))*100) + +%% was there alternative available +num_w_alternative = nnz(best_drug & ~real_prch)/ (nnz(best_drug & real_prch) + nnz(best_drug & ~real_prch))*100; +disp(['in ' num2str(num_w_alternative) ' of cases an alternative (non cost adj) drug w/ lower P was avavilable']); + +%% cost adjusted to give equal numbers of reccomended drugs to actual purchased drugs +rng('default'); rng(1); +P_nonans = P_nonans+rand(size(P_nonans))/100000; % to help with the cost adjusting + +Fr0= zeros(1, number_of_drugs); +for ii = 1:number_of_drugs +Fr0(ii) = nnz(real_prch(:,ii)); +end +Fr0 = Fr0./size(real_prch,1); +iter_params = [1 0.9 0.9 1e4]; +d = size(P_nonans,2) ; +n = size(P_nonans,1) ; +tol = iter_params(2) / n ; +relax = iter_params(3) ; +niter = iter_params(4) ; +dcost = iter_params(1) * ones(1,d) ; +cost = zeros(1,d) ; +exitflag = 1 ; +Fr = Fr0 ; +%iterative cost ajust P +for i = 1:niter + cost = cost + dcost.*sign(Fr-Fr0) ; + cost = cost - mean(cost) ; + dcost = dcost*relax ; + + [p,treat] = min(P_nonans+cost,[],2) ; + treat(p>1) = 0 ; + Fr = histc(treat,1:d)' ./ n ; + err = max(abs(Fr-Fr0)) ; + %Fr + if err0); +random_drug_noprev = real_prch; +num = 1:number_of_drugs; +for ii = 1:length(incorrectly_prescribed) + random_drug_noprev(incorrectly_prescribed(ii),1:number_of_drugs)= zeros(1,number_of_drugs); +numstemp = num(had_prev_resistance_nonans(incorrectly_prescribed(ii),1:number_of_drugs) == 0 & ismember(real_res(incorrectly_prescribed(ii),1:number_of_drugs), params.sensitive_group)); +if ~isempty(numstemp) +random_drug_noprev(incorrectly_prescribed(ii),numstemp(randi(length(numstemp)))) = 1; +end +end + + +%% bootstrap data and plot predicted risk +reccomended_cost_correctly_presribed = logical(sum(ismember(real_res, params.sensitive_group) & best_drug_costadjust,2)); +fprintf('%.0f out of %.0f COST ADJUSTED BEST RECCOMENDED samples are correctly prescribed (should be all)\n' ,nnz(reccomended_cost_correctly_presribed), length(reccomended_cost_correctly_presribed)) + +real = mean(P_nonans(real_prch ==1)); +best_cost = mean(P_nonans(best_drug_costadjust ==1)); +best = mean(P_nonans(best_drug ==1)); +random_noprev = mean(P_nonans(random_drug_noprev ==1)); + +realPs = P_nonans(real_prch ==1); +best_costPs = P_nonans(best_drug_costadjust ==1); +bestPs = P_nonans(best_drug ==1); +random_noprevPs = P_nonans(random_drug_noprev ==1); +num_bootstraps = 1000; + +real_boot = bootstrp(num_bootstraps,@mean,realPs); +best_cost_boot = bootstrp(num_bootstraps,@mean,best_costPs); +best_boot = bootstrp(num_bootstraps,@mean,bestPs); +random_noprev_boot = bootstrp(num_bootstraps,@mean,random_noprevPs); + +random_noprev_CI = prctile(random_noprev_boot,[2.5 97.5]) ; +real_CI = prctile(real_boot,[2.5 97.5]) ; +best_CI = prctile(best_boot,[2.5 97.5]) ; +best_cost_CI = prctile(best_cost_boot,[2.5 97.5]) ; + +figure; +set(gcf,'color','w', 'name','Fig. 4E', 'units','centimeters','Position',[1 1 10 10]); +b1= bar([mean(real_boot) mean(random_noprev_boot) mean(best_cost_boot) mean(best_boot)]); +hold on +%errorbar(b1(1).XData,b1(1).YData,[std(random_boot) std(real_boot) std(best_cost_boot) std(best_boot)],'k', 'LineStyle','none') +errorbar(b1(1).XData,b1(1).YData,[ mean(real_boot)-real_CI(1) mean(random_noprev_boot)-random_noprev_CI(1) mean(best_cost_boot)-best_cost_CI(1) mean(best_boot)-best_CI(1) ],... + [ -mean(real_boot)+real_CI(2) -mean(random_noprev_boot)+random_noprev_CI(1) -mean(best_cost_boot)+best_cost_CI(2) -mean(best_boot)+best_CI(2) ],'k', 'LineStyle','none') +xticklabels({'Physician','Random no prevR','Recomended cost adj','Recommended'}) +xtickangle( 45 ) +ylabel('predicted probability of aquiring resistance') +plot(1:4,mean(real_treatfails_gainedres_toprch)*ones(1,4),'k--'); + +%% errors between models +dprb = real_boot-best_boot ; +sd = std(dprb) ; mn = mean(dprb) ; pval = 1-normcdf(mn/sd) +dprb = real_boot-best_cost_boot ; +sd = std(dprb) ; mn = mean(dprb) ; pval = 1-normcdf(mn/sd) + +%% plot bar chart of gained-resistance rate for cases split by if the treatment reccomended or not + +clear x +below_thresh = zeros(size(P_nonans)); +for drug = 1:number_of_drugs +threshold(drug) = prctile(P_nonans(P_nonans(:,drug)<1,drug),85); % binarize into top 15% bottom 85%. See paper +below_thresh(:,drug) = P_nonans(:,drug) < threshold(drug); +below_thresh(P_nonans(:,drug) > 1,drug) = NaN; +end + +above_thresh = below_thresh == 0; +below_thresh = below_thresh == 1; + +was_reccomended = logical(real_prch) & ismember(real_res, [ 1 2]) & below_thresh; +was_not_reccomended = logical(real_prch) & ismember(real_res, [ 1 2]) & above_thresh; + +p = zeros(1,number_of_drugs); +for drug = 1:number_of_drugs + x(1,1,drug) = nnz(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + x(2,1,drug) = nnz(~real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + x(1,2,drug) = nnz(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + x(2,2,drug) = nnz(~real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + + rate_gain_res_rec2(drug) = nnz(real_treatfails_gainedres_toprch(was_reccomended(:,drug)))/length(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + total_number_rec2 = length(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + + rate_gain_res_rec2_error(drug) = sqrt((rate_gain_res_rec2(drug)*(1-rate_gain_res_rec2(drug)))/total_number_rec2); + + rate_gain_res_notrec(drug) = nnz(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug)))/length(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + total_number_notrec = length(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + rate_gain_res_notrec_error(drug) = sqrt((rate_gain_res_notrec(drug)*(1-rate_gain_res_notrec(drug)))/total_number_notrec); + + [h1,p1] = fishertest(x(:,:,drug)); + p_fisher(drug) = p1; + + n1 = x(1,1,drug); N1 = sum(x(1:2,1,drug)); + n2 = x(1,2,drug); N2 = sum(x(1:2,2,drug)); + % Pooled estimate of proportion + p0 = (n1+n2) / (N1+N2); + % Expected counts under H0 (null hypothesis) + n10 = N1 * p0; + n20 = N2 * p0; + % Chi-square test + observed = [n1 N1-n1 n2 N2-n2]; + expected = [n10 N1-n10 n20 N2-n20]; + chi2stat = sum((observed-expected).^2 ./ expected); + p(drug) = 1 - chi2cdf(chi2stat,1); + + + +end + + +% +figure; +set(gcf,'color','w', 'name','Fig. 4D', 'units','centimeters','Position',[1 1 15 10]); +width = 0.5; +gap = 1.8; +plot([0 7*gap+3], [0 0],'k') + +for ii = 1:number_of_drugs +hold on +xpos = ii*gap-0.32; +hd3(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 rate_gain_res_notrec(1,ii)*100 rate_gain_res_notrec(1,ii)*100],'w','EdgeColor','k', 'FaceColor', [0.78 0.13 0.13]); % using MATLAB "patch" to establish the border +errorbar(xpos, rate_gain_res_notrec(1,ii)*100,rate_gain_res_notrec_error(1,ii)*100,'k', 'LineStyle','none') +end + +for ii = 1:number_of_drugs +hold on +xpos = ii*gap+0.32; +hd1(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 rate_gain_res_rec2(1,ii)*100 rate_gain_res_rec2(1,ii)*100],'w','EdgeColor','k', 'FaceColor', [0 0.6 0.07]); % using MATLAB "patch" to establish the border +errorbar(xpos, rate_gain_res_rec2(1,ii)*100,rate_gain_res_rec2_error(1,ii)*100,'k', 'LineStyle','none') + +end +xlim([0.5 number_of_drugs*gap+1]) +ylabel('% of patients who acquired post-treatment resistance ') +xlabel('treatment drug') +set(gca,'XTick',gap:gap:gap*7); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:7)); +xtickangle(45); + +hold on +y = rate_gain_res_notrec*100; +for ii = 1:length(y) + xpos = ii*gap; + if p(ii)< 0.05 && p(ii)> 0.005 + plot(xpos, y(ii)*1.1, '*k', 'MarkerSize',4) + elseif p(ii) <= 0.005 && p(ii)> 0.0005 + plot([xpos-0.1 xpos+0.1] , [y(ii)*1.1 y(ii)*1.1], '*k', 'MarkerSize',4) + elseif p(ii) <= 0.0005 + plot([xpos-0.2 xpos xpos+0.2] , [ y(ii)*1.1 y(ii)*1.1 y(ii)*1.1], '*k', 'MarkerSize',4) + end +end + +%% number of each antibiotic prescribed in test period for +% different prescription methods + +number_prescribed_reccomended = zeros(3,size(real_prch,2)); +number_prescribed_reccomended(1,:) = sum(real_prch); +number_prescribed_reccomended(2,:) = sum(best_drug_costadjust); +number_prescribed_reccomended(3,:) = sum(best_drug); + + +figure; +set(gcf,'color','w', 'name','Fig. S14', 'units','centimeters','Position',[1 1 15 10]); +bar(number_prescribed_reccomended') +legend({'physician prescribed drugs' ; 'ML, recommended cost adjusted' ; 'ML, recommended'}) +xticklabels(UTI_cases.SMP_Res_drug_names) +xtickangle(45) +ylabel('number of prescriptions/ reccomendations') + + +%% Look at recommendatoins in antibiotic sensitive cases where there was past reisitance to that antibitoc +real_prch = UTI_cases.PCR_sameday(withPdata_index, 1:number_of_drugs); +figure; +set(gcf,'color','w', 'name','Fig. S15', 'units','centimeters','Position',[1 1 12 25]); + +for drug = 1:7 +any_previous_cipr = num_of_previous_R(withPdata_index ,drug)>0 ; +cip_sensitve = ismember(UTI_cases.SMP_Res(withPdata_index,drug),params.sensitive_group); +only_cip = any_previous_cipr & cip_sensitve; + + +number_prescribed_reccomended = zeros(3,size(real_prch(only_cip,:),2)); +number_prescribed_reccomended(1,:) = sum(real_prch(only_cip,:)); +number_prescribed_reccomended(2,:) = sum(best_drug_costadjust(only_cip,:)); +number_prescribed_reccomended(3,:) = sum(best_drug(only_cip,:)); +diff_recc(1,:) = -number_prescribed_reccomended(1,:)+number_prescribed_reccomended(2,:); +diff_recc(2,:) = -number_prescribed_reccomended(1,:)+number_prescribed_reccomended(3,:); +subplot(4,2,drug) +bar(diff_recc'); +ylim([-450 450]); +%set(gca,'YScale','log') +xticklabels(UTI_cases.SMP_Res_drug_names); +xtickangle(45); +ylabel({'difference between number of antibiotic'; 'prescribed by physicans and'; 'reccomended by ML models'}) +title(UTI_cases.SMP_Res_drug_names{drug}) +end + +%% +%% was the treatment reccomended or not for differnt tresholds +%bins =0:0.001:0.3; +figure; +set(gcf,'color','w', 'name','Fig. S13', 'units','centimeters','Position',[1 1 40 10]); +thresholds = [90 70 50]; % binarize using 3 different thresholds + +for mm = 1:length(thresholds) +clear x +below_thresh = zeros(size(P_nonans)); +for drug = 1:number_of_drugs +threshold(drug) = prctile(P_nonans(P_nonans(:,drug)<1,drug),thresholds(mm)); +below_thresh(:,drug) = P_nonans(:,drug) < threshold(drug); +below_thresh(P_nonans(:,drug) > 1,drug) = NaN; +end + +above_thresh = below_thresh == 0; +below_thresh = below_thresh == 1; + +was_reccomended = logical(real_prch) & ismember(real_res, [ 1 2]) & below_thresh; +was_not_reccomended = logical(real_prch) & ismember(real_res, [ 1 2]) & above_thresh; + +p = zeros(1,number_of_drugs); +for drug = 1:number_of_drugs + x(1,1,drug) = nnz(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + x(2,1,drug) = nnz(~real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + x(1,2,drug) = nnz(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + x(2,2,drug) = nnz(~real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + + rate_gain_res_rec2(drug) = nnz(real_treatfails_gainedres_toprch(was_reccomended(:,drug)))/length(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + total_number_rec2 = length(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + + rate_gain_res_rec2_error(drug) = sqrt((rate_gain_res_rec2(drug)*(1-rate_gain_res_rec2(drug)))/total_number_rec2); + + rate_gain_res_notrec(drug) = nnz(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug)))/length(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + total_number_notrec = length(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + rate_gain_res_notrec_error(drug) = sqrt((rate_gain_res_notrec(drug)*(1-rate_gain_res_notrec(drug)))/total_number_notrec); + + [h1,p1] = fishertest(x(:,:,drug)); + p_fisher(drug) = p1; + + n1 = x(1,1,drug); N1 = sum(x(1:2,1,drug)); + n2 = x(1,2,drug); N2 = sum(x(1:2,2,drug)); + % Pooled estimate of proportion + p0 = (n1+n2) / (N1+N2); + % Expected counts under H0 (null hypothesis) + n10 = N1 * p0; + n20 = N2 * p0; + % Chi-square test + observed = [n1 N1-n1 n2 N2-n2]; + expected = [n10 N1-n10 n20 N2-n20]; + chi2stat = sum((observed-expected).^2 ./ expected); + p(drug) = 1 - chi2cdf(chi2stat,1); + + + +end + + +% +subplot(1,3,mm) +width = 0.5; +gap = 1.8; +plot([0 7*gap+3], [0 0],'k') + +for ii = 1:number_of_drugs +hold on +xpos = ii*gap-0.32; +hd3(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 rate_gain_res_notrec(1,ii)*100 rate_gain_res_notrec(1,ii)*100],'w','EdgeColor','k', 'FaceColor', [0.78 0.13 0.13]); % using MATLAB "patch" to establish the border +errorbar(xpos, rate_gain_res_notrec(1,ii)*100,rate_gain_res_notrec_error(1,ii)*100,'k', 'LineStyle','none') + +%errorbar(xpos,(fail_split_noprch(1,ii)+fail_split_noprch(2,ii)),ratio_noprch_error(ii), 'k', 'LineStyle','none') + +end + +for ii = 1:number_of_drugs +hold on +xpos = ii*gap+0.32; +hd1(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 rate_gain_res_rec2(1,ii)*100 rate_gain_res_rec2(1,ii)*100],'w','EdgeColor','k', 'FaceColor', [0 0.6 0.07]); % using MATLAB "patch" to establish the border +errorbar(xpos, rate_gain_res_rec2(1,ii)*100,rate_gain_res_rec2_error(1,ii)*100,'k', 'LineStyle','none') + +end +xlim([0.5 number_of_drugs*gap+1]) +title(['threshold' num2str(100-thresholds(mm))]); +ylabel('% of patients who acquired post-treatment resistance ') +xlabel('treatment drug') +set(gca,'XTick',gap:gap:gap*7); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:7)); +xtickangle(45); + +hold on +y = rate_gain_res_notrec*100; +for ii = 1:length(y) + xpos = ii*gap; + if p(ii)< 0.05 && p(ii)> 0.005 + plot(xpos, y(ii)*1.1, '*k', 'MarkerSize',4) + elseif p(ii) <= 0.005 && p(ii)> 0.0005 + plot([xpos-0.1 xpos+0.1] , [y(ii)*1.1 y(ii)*1.1], '*k', 'MarkerSize',4) + elseif p(ii) <= 0.0005 + plot([xpos-0.2 xpos xpos+0.2] , [ y(ii)*1.1 y(ii)*1.1 y(ii)*1.1], '*k', 'MarkerSize',4) + end +end + +end + +%% Do regression for any failure (S-S & S-R) and look at the predicted risk for the +% antibiotic recomendations trained to miniize StoR failures +sen_res = [ 1 2 3]; +clear coef + +for drug = 1:7 + +SMP_to_use = find((UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & ~test_data & UTI_cases.hasdiag); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); + +X = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial','logit') ; +coef(:,drug) = glm.B; + +end +%% test data: +clear P +P = nan(height(UTI_cases.Demog),number_of_drugs); +treatfails_gainedres_toprch = zeros(height(UTI_cases.Demog),number_of_drugs); +%patient was correctly prescribed a drug from the used drugs +was_correctly_prescribed = sum(UTI_cases.PCR_sameday(:,1:number_of_drugs) & ismember(UTI_cases.SMP_Res(:,1:number_of_drugs), params.sensitive_group),2) > 0; + +for drug = 1:number_of_drugs + +SMP_to_use = find(was_correctly_prescribed & test_data & UTI_cases.hasdiag); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use, num_previous_R num_previous_S]; +P(SMP_to_use, drug) = glmval(coef(:,drug),X,'logit') ; + +%% +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfails = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +treatfails_gainedres_toprch(SMP_to_use, drug) = treatfails ;%;& drug_prch_temp; + +%% reassign any mismatched (or unknown Res) probabilities to 1 +index = find(ismember(UTI_cases.SMP_Res(SMP_to_use,drug), [0 3])); +P(SMP_to_use(index), drug) = 1.1; % mismatched treatments are not used + +end + +% +withPdata_index_SS = find(sum(isnan(P),2)== 0); +P_nonans_SS = P(withPdata_index_SS,:); + +%using the best_drug etc from the gain of resistance S-R model +%on the P values from the S-any model +best_cost_SS_boot = bootstrp(num_bootstraps,@mean,P_nonans_SS(best_drug_costadjust ==1)); +best_SS_boot = bootstrp(num_bootstraps,@mean,P_nonans_SS(best_drug ==1)); +real_SS_boot = bootstrp(num_bootstraps,@mean,P_nonans_SS(real_prch ==1)); + + +figure; +set(gcf,'color','w', 'name','Fig. S17 Overall risk of recurrence', 'units','centimeters','Position',[1 1 10 10]); +b1= bar([mean(real_SS_boot) mean(best_SS_boot) mean(best_cost_SS_boot) ]); +hold on +errorbar(b1(1).XData,b1(1).YData,[std(real_SS_boot) std(best_SS_boot) std(best_cost_SS_boot) ],'k', 'LineStyle','none') +xticklabels({'All rec real','All rec best','All rec cost'}) +xtickangle( 45 ) +ylabel('predicted probability of recurrence') \ No newline at end of file diff --git a/UTI_analysis/correct_treatment_fails_reccomend_drug_S_IR.m b/UTI_analysis/correct_treatment_fails_reccomend_drug_S_IR.m new file mode 100644 index 0000000..6398741 --- /dev/null +++ b/UTI_analysis/correct_treatment_fails_reccomend_drug_S_IR.m @@ -0,0 +1,174 @@ +function [] = correct_treatment_fails_reccomend_drug_S_IR(UTI_cases,params) +% function takes the UTI_case structure and optional params and treains and tests +% regressoin model to predict risk of gain of resistance for all susceptibility-matched treated cases cases +% with the intermediate grouped with resistant +X_age = UTI_cases.Demog.Age; +X_age(:,6) = []; % reference age +X_demog = [X_age, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg UTI_cases.Demog.any_prev_cath]; +number_of_drugs = 7; % not including orflox as not measured in test period + +%% seperate training data and test data +test_date_start = datenum('2018-05-01') ; +test_date_end = datenum('2019-07-01') ; +test_date_range = test_date_start:test_date_end; +test_data = ismember(UTI_cases.SamplingDate, test_date_range); +fprintf('Testing using %.2f percent of the data\n' ,nnz(test_data)/length(test_data)*100) + +%% Regression for StoR failure given any previous resistance to drug +clear coef +num_of_previous_R = UTI_cases.num_of_previous_R; +num_of_previous_S = UTI_cases.num_of_previous_S; +sen_res = [ 2 3]; % intermediate grouped with resistant + +for drug = 1:number_of_drugs + +SMP_to_use = find( ismember(UTI_cases.SMP_Res(:,drug), 1) & ~test_data & UTI_cases.hasdiag); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial','logit') ; +coef(:,drug) = glm.B; + +end + +%% test data: +clear P +P = nan(height(UTI_cases.Demog),number_of_drugs); +treatfails_gainedres_toprch = zeros(height(UTI_cases.Demog),number_of_drugs); +%patient was correctly prescribed a drug from the used drugs +was_correctly_prescribed = sum(UTI_cases.PCR_sameday(:,1:number_of_drugs) & ismember(UTI_cases.SMP_Res(:,1:number_of_drugs), [1]),2) > 0; + +for drug = 1:number_of_drugs + +SMP_to_use = find(was_correctly_prescribed & test_data & UTI_cases.hasdiag); + +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use, num_previous_R num_previous_S]; +P(SMP_to_use, drug) = glmval(coef(:,drug),X,'logit') ; + +%% +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfails = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +treatfails_gainedres_toprch(SMP_to_use, drug) = treatfails & drug_prch_temp; + +%% reassign any mismatched (or unknown Res) probabilities to 1 +index = find(ismember(UTI_cases.SMP_Res(SMP_to_use,drug), [0 3])); +P(SMP_to_use(index), drug) = 1.1; + +end + +treatfails_gainedres_toprch = logical(sum(treatfails_gainedres_toprch,2)); + + +%% pick lowest P +clear M best_drug + +withPdata_index = find(sum(isnan(P),2)== 0); +P_nonans = P(withPdata_index,:); +real_prch = UTI_cases.PCR_sameday(withPdata_index, 1:number_of_drugs); +real_treatfails_gainedres_toprch = treatfails_gainedres_toprch(withPdata_index); +real_res = UTI_cases.SMP_Res(withPdata_index, 1:number_of_drugs); + +[M,best_drug_temp] = min(P_nonans,[],2); + +best_drug = zeros(size(P_nonans,1),number_of_drugs); +for ii = 1:number_of_drugs +best_drug(best_drug_temp == ii,ii) = 1; +end + +%% was the treatment reccomended or not +clear x +below_thresh = zeros(size(P_nonans)); +for drug = 1:number_of_drugs +threshold(drug) = prctile(P_nonans(P_nonans(:,drug)<1,drug),85); +below_thresh(:,drug) = P_nonans(:,drug) < threshold(drug); +below_thresh(P_nonans(:,drug) > 1,drug) = NaN; +end + +above_thresh = below_thresh == 0; +below_thresh = below_thresh == 1; + +was_reccomended = logical(real_prch) & ismember(real_res, [ 1 2]) & below_thresh; +was_not_reccomended = logical(real_prch) & ismember(real_res, [ 1 2]) & above_thresh; + +p = zeros(1,number_of_drugs); +for drug = 1:number_of_drugs + x(1,1,drug) = nnz(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + x(2,1,drug) = nnz(~real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + x(1,2,drug) = nnz(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + x(2,2,drug) = nnz(~real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + + rate_gain_res_rec2(drug) = nnz(real_treatfails_gainedres_toprch(was_reccomended(:,drug)))/length(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + total_number_rec2 = length(real_treatfails_gainedres_toprch(was_reccomended(:,drug))); + + rate_gain_res_rec2_error(drug) = sqrt((rate_gain_res_rec2(drug)*(1-rate_gain_res_rec2(drug)))/total_number_rec2); + + rate_gain_res_notrec(drug) = nnz(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug)))/length(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + total_number_notrec = length(real_treatfails_gainedres_toprch(was_not_reccomended(:,drug))); + rate_gain_res_notrec_error(drug) = sqrt((rate_gain_res_notrec(drug)*(1-rate_gain_res_notrec(drug)))/total_number_notrec); + + [h1,p1] = fishertest(x(:,:,drug)); + p_fisher(drug) = p1; + + n1 = x(1,1,drug); N1 = sum(x(1:2,1,drug)); + n2 = x(1,2,drug); N2 = sum(x(1:2,2,drug)); + % Pooled estimate of proportion + p0 = (n1+n2) / (N1+N2); + % Expected counts under H0 (null hypothesis) + n10 = N1 * p0; + n20 = N2 * p0; + % Chi-square test + observed = [n1 N1-n1 n2 N2-n2]; + expected = [n10 N1-n10 n20 N2-n20]; + chi2stat = sum((observed-expected).^2 ./ expected); + p(drug) = 1 - chi2cdf(chi2stat,1); + + +end + +subplot(1,2,2) +width = 0.5; +gap = 1.8; +plot([0 7*gap+3], [0 0],'k') + +for ii = 1:number_of_drugs +hold on +xpos = ii*gap-0.32; +hd3(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 rate_gain_res_notrec(1,ii)*100 rate_gain_res_notrec(1,ii)*100],'w','EdgeColor','k', 'FaceColor', [0.78 0.13 0.13]); % using MATLAB "patch" to establish the border +errorbar(xpos, rate_gain_res_notrec(1,ii)*100,rate_gain_res_notrec_error(1,ii)*100,'k', 'LineStyle','none') +end + +for ii = 1:number_of_drugs +hold on +xpos = ii*gap+0.32; +hd1(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 rate_gain_res_rec2(1,ii)*100 rate_gain_res_rec2(1,ii)*100],'w','EdgeColor','k', 'FaceColor', [0 0.6 0.07]); % using MATLAB "patch" to establish the border +errorbar(xpos, rate_gain_res_rec2(1,ii)*100,rate_gain_res_rec2_error(1,ii)*100,'k', 'LineStyle','none') + +end +xlim([0.5 number_of_drugs*gap+1]) +%ylim([0 23]) +ylabel('% of patients who acquired post-treatment resistance ') +xlabel('treatment drug') +% set(gca,'XTick',2:2:16); +set(gca,'XTick',gap:gap:gap*7); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(1:7)); +xtickangle(45); + +hold on +y = rate_gain_res_notrec*100; +for ii = 1:length(y) + xpos = ii*gap; + if p(ii)< 0.05 && p(ii)> 0.005 + plot(xpos, y(ii)*1.1, '*k', 'MarkerSize',4) + elseif p(ii) <= 0.005 && p(ii)> 0.0005 + plot([xpos-0.1 xpos+0.1] , [y(ii)*1.1 y(ii)*1.1], '*k', 'MarkerSize',4) + elseif p(ii) <= 0.0005 + plot([xpos-0.2 xpos xpos+0.2] , [ y(ii)*1.1 y(ii)*1.1 y(ii)*1.1], '*k', 'MarkerSize',4) + end +end diff --git a/UTI_analysis/correct_treatment_fails_reccomend_drug_v9_2testperiods.m b/UTI_analysis/correct_treatment_fails_reccomend_drug_v9_2testperiods.m new file mode 100644 index 0000000..a7acd04 --- /dev/null +++ b/UTI_analysis/correct_treatment_fails_reccomend_drug_v9_2testperiods.m @@ -0,0 +1,373 @@ +function [] = correct_treatment_fails_reccomend_drug_v9_2testperiods(UTI_cases,params) +% function takes the UTI_case structure and optional params and treains and tests +% regression to predict risk of gain of resistance for all susceptiblty-matched treated cases cases +% model is trained in temporally seperated period, the cost adjusted in +% another, then tested in a third + +figure +set(gcf,'color','w') +clf; set(gcf,'name','Fig. S14C seperate constrain vs test periods'); +set(gcf,'units','centimeters','Position',[2 2 25 10]); + +%demogs included +X_age = UTI_cases.Demog.Age; +X_age(:,6) = [];% reference age +zeroto39 = sum(X_age(:,1:4),2); % larger bin for younger ages since less data +eightyplus = sum(X_age(:,end-1:end),2); +X_demog = [zeroto39 X_age(:,5:end-2) eightyplus, UTI_cases.Demog.Gender, UTI_cases.Demog.Preg]; +number_of_drugs = 7; % not including orflox as not measured in test period + +sen_res = params.resistant_group; % gained resistance + +%% seperate training data and test data with seperate cost_ajust and test period +test2_date_start = datenum('2017-08-01') ; +test2_date_end = datenum('2018-05-01') ; + +test_date_start = datenum('2018-05-01') ; +test_date_end = datenum('2019-07-01'); + +test_date_range = test_date_start:test_date_end; +test_data = ismember(UTI_cases.SamplingDate, test_date_range); +test_data2 = ismember(UTI_cases.SamplingDate, test2_date_start:test2_date_end); +fprintf('Testing using %.2f percent of the data\n' ,nnz(test_data)/length(test_data)*100) + +%% Regression for StoR failure given any previous resistance to drug +clear coef + +num_of_previous_R = UTI_cases.num_of_previous_R; +num_of_previous_S = UTI_cases.num_of_previous_S; + +for drug = 1:number_of_drugs +SMP_to_use = find((UTI_cases.SMP_Res(:,drug)== 1 | UTI_cases.SMP_Res(:,drug)== 2) & ~test_data & ~test_data2 & UTI_cases.hasdiag); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +treatfailure = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial','logit') ; +coef(:,drug) = glm.B; +%nums(drug) = length(X); + +end + + +%% test data: +clear P +P = nan(height(UTI_cases.Demog),number_of_drugs); +treatfails_gainedres_toprch = zeros(height(UTI_cases.Demog),number_of_drugs); +%patient was correctly prescribed a drug from the used drugs +was_correctly_prescribed = sum(UTI_cases.PCR_sameday(:,1:number_of_drugs) & ismember(UTI_cases.SMP_Res(:,1:number_of_drugs), [1 2]),2) > 0; +had_prev_resistance = nan(height(UTI_cases.Demog),number_of_drugs); + +for drug = 1:number_of_drugs + +SMP_to_use = find(was_correctly_prescribed & test_data2 & UTI_cases.hasdiag); + +had_prev_resistance(was_correctly_prescribed & test_data2 & UTI_cases.hasdiag & num_of_previous_R(:,drug) >0 ) = 1; +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use, num_previous_R num_previous_S]; +P(SMP_to_use, drug) = glmval(coef(:,drug),X,'logit') ; + +%% +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfails = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +treatfails_gainedres_toprch(SMP_to_use, drug) = treatfails & drug_prch_temp; + +%% reassign any mismatched (or unknown Res) probabilities to 1 +index = find(ismember(UTI_cases.SMP_Res(SMP_to_use,drug), [0 3])); +P(SMP_to_use(index), drug) = 1.1; + +end + +treatfails_gainedres_toprch = logical(sum(treatfails_gainedres_toprch,2)); + +%% Test that reccomended which are incorectly prescribed are set to 1 +fprintf('There minimum P for mismatched reccomendations is %.1f \n' ,min(P(UTI_cases.SMP_Res(:,1:number_of_drugs) == 3))) + + +%% pick lowest P +clear M best_drug + +withPdata_index = find(sum(isnan(P),2)== 0); +P_nonans = P(withPdata_index,:); +real_prch = UTI_cases.PCR_sameday(withPdata_index, 1:number_of_drugs); +real_treatfails_gainedres_toprch = treatfails_gainedres_toprch(withPdata_index); +real_res = UTI_cases.SMP_Res(withPdata_index, 1:number_of_drugs); + +[M,best_drug_temp] = min(P_nonans,[],2); + +best_drug = zeros(size(P_nonans,1),number_of_drugs); +for ii = 1:number_of_drugs +best_drug(best_drug_temp == ii,ii) = 1; +end + + +%% Test that data all have a prch amoung the chosen drugs +fprintf('There are %.0f samples without a PRCH (should be zero)\n' ,(length(real_prch) - nnz(sum(real_prch,2)>0))) + +% Test that there are no actually inccorectly prescribed samples +incorrectly_presribed = nnz(sum(ismember(real_res, 3) & real_prch,2)); +fprintf('There are %.0f samples incorrectly prescribed (should be zero)\n' ,incorrectly_presribed) + +correctly_presribed = nnz(sum(ismember(real_res, [1 2]) & real_prch,2)); +fprintf('%.0f out of %.0f samples are actuall correctly prescribed (should be all)\n' ,correctly_presribed, length(real_res)) + +reccomended_correctly_presribed = logical(sum(ismember(real_res, [1 2]) & best_drug,2)); +fprintf('%.0f out of %.0f BEST RECCOMENDED samples are correctly prescribed (should be all)\n' ,nnz(reccomended_correctly_presribed), length(reccomended_correctly_presribed)) + + +%% are the NON COST ADJUSTED prescribed and best reccomended the same? +prescribed_pred_matched = logical(sum(best_drug & real_prch,2)); + +fprintf('Mean rate of S->R fail for pysician/recommended (no cost adj) MATCHED is: %.2f %%\n' ,mean(real_treatfails_gainedres_toprch(prescribed_pred_matched))*100) +fprintf('Mean rate of S->R fail for pysician/recommended (no cost adj) NOT MATCHED is: %.2f %%\n' ,mean(real_treatfails_gainedres_toprch(~prescribed_pred_matched))*100) + +mean(real_treatfails_gainedres_toprch) +%mean(real_fails2(~prescribed_pred_matched)) + +%% was there alternative available +num_w_alternative = nnz(best_drug & ~real_prch)/ (nnz(best_drug & real_prch) + nnz(best_drug & ~real_prch))*100; +disp(['in ' num2str(num_w_alternative) ' of cases an alternative (non cost adj) drug w/ lower P was avavilable']); +%% cost adjusted to give equal numbers of reccomended drugs to actual purchased drugs +rng('default'); rng(1); +P_nonans = P_nonans+rand(size(P_nonans))/100000; % to help with the cost adjusting + +Fr0= zeros(1, number_of_drugs); +for ii = 1:number_of_drugs +Fr0(ii) = nnz(real_prch(:,ii)); +end +Fr0 = Fr0./size(real_prch,1); + +iter_params = [1 0.9 0.9 1e4]; + % params = [0.1, 0.9, 0.95, 1e4] ; +d = size(P_nonans,2) ; +n = size(P_nonans,1) ; + +tol = iter_params(2) / n ; +relax = iter_params(3) ; +niter = iter_params(4) ; + +dcost = iter_params(1) * ones(1,d) ; +cost = zeros(1,d) ; +exitflag = 1 ; +Fr = Fr0 ; + +for i = 1:niter + cost = cost + dcost.*sign(Fr-Fr0) ; + cost = cost - mean(cost) ; + dcost = dcost*relax ; + + [p,treat] = min(P_nonans+cost,[],2) ; + treat(p>1) = 0 ; + Fr = histc(treat,1:d)' ./ n ; + err = max(abs(Fr-Fr0)) ; + %Fr + if err 0; + +had_prev_resistance = nan(height(UTI_cases.Demog),number_of_drugs); + +for drug = 1:number_of_drugs + +SMP_to_use = find(was_correctly_prescribed & test_data & UTI_cases.hasdiag); + +had_prev_resistance(was_correctly_prescribed & test_data & UTI_cases.hasdiag & num_of_previous_R(:,drug) >0 ) = 1; +any_previous_R = num_of_previous_R(SMP_to_use ,drug)>0 ; +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); + +X_demog_to_use = X_demog(SMP_to_use,:); + +X = [X_demog_to_use, num_previous_R num_previous_S]; + +P(SMP_to_use, drug) = glmval(coef(:,drug),X,'logit') ; + +%% +drug_prch_temp = UTI_cases.PCR_sameday(SMP_to_use ,drug); +treatfails = UTI_cases.treatfailure(SMP_to_use) ==1 & ismember(UTI_cases.next_res(SMP_to_use, drug),sen_res) ; +treatfails_gainedres_toprch(SMP_to_use, drug) = treatfails & drug_prch_temp; + +%% reassign any mismatched (or unknown Res) probabilities to 1 +index = find(ismember(UTI_cases.SMP_Res(SMP_to_use,drug), [0 3])); +P(SMP_to_use(index), drug) = 1.1; + +end + +treatfails_gainedres_toprch = logical(sum(treatfails_gainedres_toprch,2)); + +%% Test that reccomended which are incorectly prescribed are set to 1 +fprintf('There minimum P for mismatched reccomendations is %.1f \n' ,min(P(UTI_cases.SMP_Res(:,1:number_of_drugs) == 3))) + + +%% pick lowest P +clear M best_drug + +withPdata_index = find(sum(isnan(P),2)== 0); +P_nonans = P(withPdata_index,:); +real_prch = UTI_cases.PCR_sameday(withPdata_index, 1:number_of_drugs); +real_treatfails_gainedres_toprch = treatfails_gainedres_toprch(withPdata_index); +real_res = UTI_cases.SMP_Res(withPdata_index, 1:number_of_drugs); + +[M,best_drug_temp] = min(P_nonans,[],2); + +best_drug = zeros(size(P_nonans,1),number_of_drugs); +for ii = 1:number_of_drugs +best_drug(best_drug_temp == ii,ii) = 1; +end + + +%% Test that data all have a prch amoung the chosen drugs +fprintf('There are %.0f samples without a PRCH (should be zero)\n' ,(length(real_prch) - nnz(sum(real_prch,2)>0))) + +% Test that there are no actually inccorectly prescribed samples +incorrectly_presribed = nnz(sum(ismember(real_res, 3) & real_prch,2)); +fprintf('There are %.0f samples incorrectly prescribed (should be zero)\n' ,incorrectly_presribed) + +correctly_presribed = nnz(sum(ismember(real_res, [1 2]) & real_prch,2)); +fprintf('%.0f out of %.0f samples are actuall correctly prescribed (should be all)\n' ,correctly_presribed, length(real_res)) + +reccomended_correctly_presribed = logical(sum(ismember(real_res, [1 2]) & best_drug,2)); +fprintf('%.0f out of %.0f BEST RECCOMENDED samples are correctly prescribed (should be all)\n' ,nnz(reccomended_correctly_presribed), length(reccomended_correctly_presribed)) + + +%% are the NON COST ADJUSTED prescribed and best reccomended the same? +prescribed_pred_matched = logical(sum(best_drug & real_prch,2)); + +fprintf('Mean rate of S->R fail for pysician/recommended (no cost adj) MATCHED is: %.2f %%\n' ,mean(real_treatfails_gainedres_toprch(prescribed_pred_matched))*100) +fprintf('Mean rate of S->R fail for pysician/recommended (no cost adj) NOT MATCHED is: %.2f %%\n' ,mean(real_treatfails_gainedres_toprch(~prescribed_pred_matched))*100) + +mean(real_treatfails_gainedres_toprch) +%mean(real_fails2(~prescribed_pred_matched)) + +%% was there alternative available +num_w_alternative = nnz(best_drug & ~real_prch)/ (nnz(best_drug & real_prch) + nnz(best_drug & ~real_prch))*100; +disp(['in ' num2str(num_w_alternative) ' of cases an alternative (non cost adj) drug w/ lower P was avavilable']); + + %% + %add previous cost to the new Ps +[p,treat] = min(P_nonans+cost,[],2) ; + +%check how good the prev cost on the new data is +Fr0= zeros(1, number_of_drugs); +for ii = 1:number_of_drugs +Fr0(ii) = nnz(real_prch(:,ii)); +end +Fr0 = Fr0./size(real_prch,1); +d = size(P_nonans,2) ; +n = size(P_nonans,1) +Fr = histc(treat,1:d)' ./ n ; +fprintf('error in number of samples=\n') + disp((Fr-Fr0)*100) ; + mean(abs((Fr-Fr0)*100)) +best_drug_costadjust = zeros(size(treat,1),number_of_drugs); +for ii = 1:number_of_drugs +best_drug_costadjust(treat == ii,ii) = 1; + +end + +%random but correctly prescribed +random_drug = zeros(size(treat,1),number_of_drugs); +num = 1:7; +aa = 0; +for ii = 1:size(treat,1) +numstemp = num(P_nonans(ii,:) < 1); +if ~isempty(numstemp) +random_drug(ii,numstemp(randi(length(numstemp)))) = 1; +else + numstemp = 1:7; + random_drug(ii,numstemp(randi(length(numstemp)))) = 0; + aa =aa+1; +end +end + +had_prev_resistance_nonans = num_of_previous_R(withPdata_index,1:7); +incorrectly_prescribed = find(sum(had_prev_resistance_nonans & real_prch,2)>0); +% size(had_prev_resistance_nonans) +% size(real_prch) +random_drug_noprev = real_prch; +num = 1:7; +for ii = 1:length(incorrectly_prescribed) + random_drug_noprev(incorrectly_prescribed(ii),1:7)= zeros(1,7); +numstemp = num(had_prev_resistance_nonans(incorrectly_prescribed(ii),1:7) == 0 & ismember(real_res(incorrectly_prescribed(ii),1:7), [1 2])); +if ~isempty(numstemp) +random_drug_noprev(incorrectly_prescribed(ii),numstemp(randi(length(numstemp)))) = 1; +end +end + +%% +numprch = zeros(1,number_of_drugs); +numreccost = zeros(1,number_of_drugs); +numrec = zeros(1,number_of_drugs); +for ii = 1:number_of_drugs +numprch(ii)= nnz(real_prch(:,ii)); +numreccost(ii)= nnz(best_drug_costadjust(:,ii)); +numrec(ii)= nnz(best_drug(:,ii)); +end + +%% cost adjusted reccomended only correctly prescribed + +real = mean(P_nonans(real_prch ==1)); +best_cost = mean(P_nonans(best_drug_costadjust ==1)); +best = mean(P_nonans(best_drug ==1)); +random_noprev = mean(P_nonans(random_drug_noprev ==1)); + +realPs = P_nonans(real_prch ==1); +best_costPs = P_nonans(best_drug_costadjust ==1); +bestPs = P_nonans(best_drug ==1); +random_noprevPs = P_nonans(random_drug_noprev ==1); +num_bootstraps = 1000; + +real_boot = bootstrp(num_bootstraps,@mean,realPs); +best_cost_boot = bootstrp(num_bootstraps,@mean,best_costPs); +best_boot = bootstrp(num_bootstraps,@mean,bestPs); +random_noprev_boot = bootstrp(num_bootstraps,@mean,random_noprevPs); + +random_noprev_CI = prctile(random_noprev_boot,[2.5 97.5]) ; +real_CI = prctile(real_boot,[2.5 97.5]) ; +best_CI = prctile(best_boot,[2.5 97.5]) ; +best_cost_CI = prctile(best_cost_boot,[2.5 97.5]) ; + +subplot(1,2,2) +b1= bar([mean(real_boot) mean(random_noprev_boot) mean(best_cost_boot) mean(best_boot)]); +hold on +%errorbar(b1(1).XData,b1(1).YData,[std(random_boot) std(real_boot) std(best_cost_boot) std(best_boot)],'k', 'LineStyle','none') +errorbar(b1(1).XData,b1(1).YData,[ mean(real_boot)-real_CI(1) mean(random_noprev_boot)-random_noprev_CI(1) mean(best_cost_boot)-best_cost_CI(1) mean(best_boot)-best_CI(1) ],... + [ -mean(real_boot)+real_CI(2) -mean(random_noprev_boot)+random_noprev_CI(1) -mean(best_cost_boot)+best_cost_CI(2) -mean(best_boot)+best_CI(2) ],'k', 'LineStyle','none') +xticklabels({'Physician','Random no prevR','Recomended cost adj','Recommended'}) +xtickangle( 45 ) +ylabel('predicted probability of aquiring resistance') +plot(1:4,mean(real_treatfails_gainedres_toprch)*ones(1,4),'k--'); + +%% which drug best vs physician prescibed + +number_prescribed_reccomended = zeros(3,size(real_prch,2)); +number_prescribed_reccomended(1,:) = sum(real_prch); +number_prescribed_reccomended(2,:) = sum(best_drug_costadjust); +number_prescribed_reccomended(3,:) = sum(best_drug); + + +subplot(1,2,1) +bar(number_prescribed_reccomended') +legend({'physician prescribed drugs' ; 'ML, recommended cost adjusted' ; 'ML, recommended'}) +xticklabels(UTI_cases.SMP_Res_drug_names) +xtickangle(45) +ylabel('number of prescriptions/ reccomendations') + +end \ No newline at end of file diff --git a/UTI_analysis/hatch.m b/UTI_analysis/hatch.m new file mode 100644 index 0000000..11eaa3a --- /dev/null +++ b/UTI_analysis/hatch.m @@ -0,0 +1,286 @@ +function hatch(obj,angle,color,style,step,width) +% HATCH Hatches a two-dimensional domain. +% Somewhat similar to the FILL command but fills the closed +% contour with hatched lines instead of uniform color. +% The boundary line(s) must be created prior to this command +% and its handle(s) specified by OBJ argument. +% HATCH(OBJ) Hatchs the domain bounded by the Xdata and Ydata +% properties of the OBJ (can be line or patch type). +% HATCH by itself takes as OBJ the last object created in the +% current axes. +% HATCH(OBJ,ANGLE,COLOR,STYLE,STEP,WIDTH) Specifies additional +% parameters: slope of the hatches (in degrees), +% their color ([red green blue], or 'r','g','b','w','y','c','m') +% the linestyle ('-','--','-.',':') and also the steps +% (distances between hatches) and the linewidth (thickness) +% of the hatch lines (the last two in points). +% All arguments are optional but must be in the given order. +% They also can be grouped in two vectors for convenience: +% HATCH(OBJ,[ANGLE STEP WIDTH],[COLOR STYLE]), where the last +% argument is a string: 'w--', '-.y' are both legal notations. +% LH = HATCH(OBJ) also returns the handle of a hatch line. +% OBJ can be a vector of several handles, in which case the +% composite boundary is hatched. If one contour lies within +% another, then the first one will appear as a "hole" in the +% outer contour. +% +% Examples: +% HATCH(L,30,[1 0 0],'--',8,2) or +% HATCH(L,[30 8 2],'r--') Hatchs a domain +% bounded by the contour L with red dashed lines of 2-point +% thickness and 8-point steps, inclined at 30 degrees +% to the x-axis. +% HATCH([L1 L2],'CROSS') Hatches the domain with composite +% boundary [L1 L2] with hatch parameters specified by the +% "macro" 'CROSS' (in this case two crossed hatches). +% +% Type HATCH('demo') to see all the macro effects available +% +% See also FILL, LINE, PATCH + +% Kirill K. Pankratov, kirill@plume.mit.edu +% April 27 1994 +% +% Modified for Matlab 5+, Iram Weinstein weinsteini@saic.com +% May 10, 2001 + + + +% Defaults ............ +angledflt = 45; % Angle in degrees +colordflt = [1 1 1]; % Color +styledflt = '-'; % Linestyle +widthdflt = 1; % Thickness of the lines +stepdflt = 10; % Distance between hatches +widthdflt = 1; % Thickness of the lines + +%macros ..................... +macros={ 'hor' '0.1 ,''w'''; + 'ver' '90.1,''w'''; + 'thick' '[45 10 2],''w'''; % Thicker hatch lines + 'thicky' '[45 10 2],''y'''; + 'Thick' '[45 10 2],''w'''; + 'dense' '[45 5]'; % Denser lines + 'Dense' '[45 3]'; + 'fill' '[45 1 1]'; % Fills almost uniformly + 'filly' '[45 1 1],''y'''; + 'rare' '[45 15]'; + 'Rare' '[45 20]'; + 'rarethick' '[45 15 2]'; + 'cross' '45 135'; % Two crossed hatches + 'plus' '1 90.1'}; +argcount=nargin; +% Handle input :::::::::::::::::::::::::::::::::::::::::::::::::: +% Check for macros ................ +ismacro = 0; +if argcount==2 + if isstr(angle) + macro = angle; ismacro = 1; angle = angledflt; + end +elseif argcount == 1 + if isstr(obj), + if strcmp(obj,'demo'), + demo; + return + else + macro = obj; ismacro = 1; argcount = 0; + end + end +end + +if argcount==0 % Find the object on figure + ch = get(gca,'child'); + if ~isempty(ch), obj = ch(1); + else + disp([10 ' Error: no object to hatch is found ' 10]) + return + end +end + +% Hatch with macros .......................................... +if ismacro + match=strcmp(macros(:,1),macro); + if ~any(match), + disp([10 ' Macro is not found' 10]), return + end + call=macros(match,:); + call=call{2}; + isbr = cumsum((call=='[')-(call==']')); + lc = length(call); + n0 = [0 find(call==' '&isbr==0) lc]; + for jf = 2:length(n0) + if nargout == 0, out = ''; + elseif nargout==1, out = ['lh(' num2str(jf-1) ')=']; + end + str = [out 'hatch(obj,' call(n0(jf-1)+1:n0(jf)) ');']; + eval(str) + end + return +end + +if argcount<6, width = widthdflt; end +if argcount<5, step = stepdflt; end +if argcount<4, style = styledflt; end +if argcount<3, color = colordflt; end +if argcount<2, angle = angledflt; end + +% Check for step and width in one vector +if length(angle)>1 + step = angle(2); + if length(angle)>2, width = angle(3); end + angle = angle(1); +end +% Check for color and style in one string +if isstr(color) + A = color(ones(8,1),:)==setstr(ones(length(color),1)*'wyrgbcmk')'; + n0 = find(any(A)); + str = color(any(A)==0); + if ~isempty(n0), color = color(n0); end + if ~isempty(str) + iss = strcmp(str,'-')|strcmp(str,'--')|strcmp(str,'-.'); + if iss|strcmp(str,':'), style = str; end + end +end + +% Check for the object to be line or patch +typ = get(obj(1),'type'); +if ~(strcmp(typ,'line')|strcmp(typ,'patch')) + disp([10 ' Error: object must be either line or patch ' 10]) + return +end + +angle = angle*pi/180; % Degrees to radians +% Combine all objects into a single contour +x = []; y = []; +for jo = 1:length(obj)% Get x,y + xx=get(obj(jo),'xdata'); + x = [x xx(:).']; + yy=get(obj(jo),'ydata'); + y = [y yy(:).']; + if jo == 1, + yi = find(~isnan(x)&~isnan(y)); + if ~isempty(yi), n0 = yi(1); x0 = x(n0); y0 = y(n0); + else, x0 = 0; y0 = 0; + end + end + x = [x x0]; y = [y y0]; % Close loop +end +yi = find(~isnan(x)&~isnan(y)); +x = x(yi); y = y(yi); % Remove NaN's +ll = length(x); + +% Transform the coordinates ............................. +oldu = get(gca,'units'); +set(gca,'units','points') +sza = get(gca,'pos'); sza = sza(3:4); +xlim = get(gca,'xlim'); +ylim = get(gca,'ylim'); +islx = strcmp(get(gca,'xscale'),'log'); +isly = strcmp(get(gca,'yscale'),'log'); +if islx % If log scale in x + xlim = log10(xlim); + x = log10(x); +end +if isly % If log scale in y + ylim = log10(ylim); + y = log10(y); +end +xsc = sza(1)/(xlim(2)-xlim(1)+eps); +ysc = sza(2)/(ylim(2)-ylim(1)+eps); + +ca = cos(angle); sa = sin(angle); +x0 = mean(x); y0 = mean(y); % Central point +x = (x-x0)*xsc; y = (y-y0)*ysc; +yi = x*ca+y*sa; % Rotation +y = -x*sa+y*ca; +x = yi; +y = y/step; % Make steps equal to one + +% Compute the coordinates of the hatch line ............... +yi = ceil(y); +ll = length(y); +yd = [yi(2:ll)-yi(1:ll-1) 0]; +dm = max(abs(yd)); +fnd = find(yd); +lfnd = length(fnd); +A = sign(yd(fnd)); +edm = ones(dm,1); +A = A(edm,:); +if size(A,1)>1, A = cumsum(A); end +fnd1 = find(abs(A)<=abs(yd(edm,fnd))); +A = A+yi(edm,fnd)-(A>0); +xy = (x(fnd+1)-x(fnd))./(y(fnd+1)-y(fnd)); +xi = x(edm,fnd)+(A-y(edm,fnd)).*xy(edm,:); +yi = A(fnd1); +xi = xi(fnd1); + +% Sorting points of the hatch line ........................ +li = length(xi); +xi0 = min(xi); xi1 = max(xi); +yi0 = min(yi); yi1 = max(yi); +ci = yi*(xi1-xi0)+xi; +[ci,num] = sort(ci); +xi = xi(num); yi = yi(num); +if floor(li/2)~=li/2 + xi = [xi xi(li)]; + yi = [yi yi(li)]; +end + +% Organize to pairs and separate by NaN's ................ +li = length(xi); +xi = reshape(xi,2,li/2); +yi = reshape(yi,2,li/2); +xi = [xi; ones(1,li/2)*nan]; +yi = [yi; ones(1,li/2)*nan]; +xi = xi(:)'; yi = yi(:)'; + +% Transform to the original coordinates ................... +yi = yi*step; +xy = xi*ca-yi*sa; +yi = xi*sa+yi*ca; +xi = xy/xsc+x0; +yi = yi/ysc+y0; +if islx, xi = 10.^xi; end +if isly, yi = 10.^yi; end + +% Now create a line to hatch .............................. +ax=axis; +lh = line('xdata',xi,'ydata',yi); +set(lh,'linewidth',width); +set(lh,'color',color) +set(lh,'linestyle',style) +set(gca,'units',oldu) % Set axes units back +axis(ax); +%------------------------ +function demo +figure +subplot 211 +h=bar(ones(2,7)) +axis([0.6 1.4 0 1.3]) +set(gca,'color',[1 1 1]*0.9,'XTickLabel','','YTickLabel','') +hatch(h(1),'hor') +hatch(h(2),'ver') +hatch(h(3),'thick') +hatch(h(4),'thicky') +hatch(h(5),'Thick') +hatch(h(6),'dense') +hatch(h(7),'Dense') + +x=0.65+[0 1 2 3 4 5 6]*.11; +y=1.1*ones(size(x)); +string=char({'hor', 'ver', 'thick','thicky','Thick','dense','Dense'}); +text(x,y,string); + +subplot 212 +h=bar(ones(2,7)) +axis([0.6 1.4 0 1.3]) +set(gca,'color',[1 1 1]*0.9,'XTickLabel','','YTickLabel','') +hatch(h(1),'fill') +hatch(h(2),'filly') +hatch(h(3),'rare') +hatch(h(4),'Rare') +hatch(h(5),'rarethick') +hatch(h(6),'cross') +hatch(h(7),'plus') +string=char({'fill','filly','rare','Rare','rarethick','cross','plus'}); +text(x,y,string); \ No newline at end of file diff --git a/UTI_analysis/initally_ecoli_gained_res_changed_bac.m b/UTI_analysis/initally_ecoli_gained_res_changed_bac.m new file mode 100644 index 0000000..833017f --- /dev/null +++ b/UTI_analysis/initally_ecoli_gained_res_changed_bac.m @@ -0,0 +1,113 @@ +function [] = initally_ecoli_gained_res_changed_bac(UTI_cases,params) +%all recurrent cases of initially E coli +% function takes UTI_case structure and optional params and calcuates the +% rate of change of species for initially E coli susceptibiltiy-matched treated cases which result in +% early recurrence, either S-S, or S-R. + +%% +% use periods for which relevant drug was routeenly measured +dates_to_use_start([1:4 6 8]) = min(UTI_cases.SamplingDate); +dates_to_use_start(5) = min(UTI_cases.SamplingDate)+7*321; +dates_to_use_start(7) = min(UTI_cases.SamplingDate)+7*293; +dates_to_use_end(1:7) = max(UTI_cases.SamplingDate); +dates_to_use_end(8) = min(UTI_cases.SamplingDate)+7*293; + +% for gained resistance cases +%for all antibiotics +for drug = 1:params.number_drugs + dates_index = find(UTI_cases.SamplingDate >= dates_to_use_start(drug) & UTI_cases.SamplingDate <= dates_to_use_end(drug)); + all_sensitive = (UTI_cases.SMP_Res(dates_index,drug) == 1 | UTI_cases.SMP_Res(dates_index,drug) == 2) & UTI_cases.hasdiag(dates_index) & UTI_cases.bug(dates_index) == 179 & UTI_cases.nBac(dates_index) == 1; % code 179 = E. coli + all_resistant_nextres = ismember(UTI_cases.next_res(dates_index,drug), params.resistant_group) ; + sensitive_purchased_fails = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_resistant_nextres); + + % for the most common species + sensitive_purchased_fails_stayedEcoli = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_resistant_nextres & UTI_cases.changed_bac(dates_index)==0); + sensitive_purchased_fails_changed_kleb = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_resistant_nextres & UTI_cases.changed_bac(dates_index)==1 & UTI_cases.new_bac(dates_index)==225); + sensitive_purchased_fails_changed_prot = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_resistant_nextres & UTI_cases.changed_bac(dates_index)==1 & UTI_cases.new_bac(dates_index)==280); + sensitive_purchased_fails_changed_other = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_resistant_nextres & UTI_cases.changed_bac(dates_index)==1 & UTI_cases.new_bac(dates_index)~=280 & UTI_cases.new_bac(dates_index)~=225 & floor(UTI_cases.new_bac(dates_index))~=179 & UTI_cases.new_bac(dates_index)>0); + + ratio_stayed(drug) = sensitive_purchased_fails_stayedEcoli/sensitive_purchased_fails*100; + ratio_kleb(drug) = sensitive_purchased_fails_changed_kleb/sensitive_purchased_fails*100; + ratio_prot(drug) = sensitive_purchased_fails_changed_prot/sensitive_purchased_fails*100; + ratio_other(drug) = sensitive_purchased_fails_changed_other/sensitive_purchased_fails*100; + ratio_changed(drug) = ratio_kleb(drug) + ratio_prot(drug) + ratio_other(drug); + ratio_error(drug) = sqrt((ratio_changed(drug)/100).*(1-(ratio_changed(drug)/100))./(sensitive_purchased_fails))*100; +end + +%% +total = sum([ratio_stayed; ratio_kleb; ratio_prot; ratio_other]); +ratio_stayed = ratio_stayed./total*100; +ratio_kleb = ratio_kleb./total*100; +ratio_prot = ratio_prot./total*100; +ratio_other = ratio_other./total*100; +gainedR = [ratio_other; ratio_prot; ratio_kleb]; + +%% remained sensitve +for drug = 1:params.number_drugs + dates_index = find(UTI_cases.SamplingDate >= dates_to_use_start(drug) & UTI_cases.SamplingDate <= dates_to_use_end(drug)); + all_sensitive = (UTI_cases.SMP_Res(dates_index,drug) == 1 | UTI_cases.SMP_Res(dates_index,drug) == 2) & UTI_cases.hasdiag(dates_index) & UTI_cases.bug(dates_index) == 179 & UTI_cases.nBac(dates_index) == 1; + all_sensitive_nextres = ismember(UTI_cases.next_res(dates_index,drug), params.sensitive_group) ; + sensitive_purchased_fails = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_sensitive_nextres); + sensitive_purchased_fails_stayedEcoli = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_sensitive_nextres & UTI_cases.changed_bac(dates_index)==0); + sensitive_purchased_fails_changed_kleb = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_sensitive_nextres & UTI_cases.changed_bac(dates_index)==1 & UTI_cases.new_bac(dates_index)==225); + sensitive_purchased_fails_changed_prot = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_sensitive_nextres & UTI_cases.changed_bac(dates_index)==1 & UTI_cases.new_bac(dates_index)==280); + sensitive_purchased_fails_changed_other = nnz(all_sensitive & UTI_cases.PCR_sameday(dates_index,drug) & UTI_cases.treatfailure(dates_index) & all_sensitive_nextres & UTI_cases.changed_bac(dates_index)==1 & UTI_cases.new_bac(dates_index)~=280 & UTI_cases.new_bac(dates_index)~=225 & floor(UTI_cases.new_bac(dates_index))~=179 & UTI_cases.new_bac(dates_index)>0); + + ratio_stayed(drug) = sensitive_purchased_fails_stayedEcoli/sensitive_purchased_fails*100; + ratio_kleb(drug) = sensitive_purchased_fails_changed_kleb/sensitive_purchased_fails*100; + ratio_prot(drug) = sensitive_purchased_fails_changed_prot/sensitive_purchased_fails*100; + ratio_other(drug) = sensitive_purchased_fails_changed_other/sensitive_purchased_fails*100; + ratio_changed(drug) = ratio_kleb(drug) + ratio_prot(drug) + ratio_other(drug); + ratio_error2(drug) = sqrt((ratio_changed(drug)/100).*(1-(ratio_changed(drug)/100))./(sensitive_purchased_fails))*100; + +end +%% +total = sum([ratio_stayed; ratio_kleb; ratio_prot; ratio_other]); +ratio_stayed = ratio_stayed./total*100; +ratio_kleb = ratio_kleb./total*100; +ratio_prot = ratio_prot./total*100; +ratio_other = ratio_other./total*100; +remainedS = [ratio_other; ratio_prot; ratio_kleb]; + +%% plot the fig +%reorder for fig +gainedR = gainedR(:,params.new_order); +remainedS =remainedS(:,params.new_order); + +width = 0.5; +gap = 1.8; +plot([0 7*gap+3], [0 0],'k') +new_kleb_col = [0.5, 0.5, 0.5]; +new_prot_col = [0.8, 0.8, 0.8]; +new_other_col = [0.2, 0.2, 0.2]; +for ii = 1:8 +hold on +xpos = ii*gap-0.32; +hd1(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 remainedS(1,ii) remainedS(1,ii)],'w','EdgeColor','k', 'FaceColor', new_other_col); % using MATLAB "patch" to establish the border +hd2(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[remainedS(1,ii) remainedS(1,ii) (remainedS(1,ii)+remainedS(2,ii)) (remainedS(1,ii)+remainedS(2,ii))],'w','EdgeColor','k', 'FaceColor', new_prot_col); % using MATLAB "patch" to establish the border +hd3(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[sum(remainedS(1:2,ii)) sum(remainedS(1:2,ii)) sum(remainedS(1:3,ii)) sum(remainedS(1:3,ii))],'w','EdgeColor','k', 'FaceColor', new_kleb_col ); % using MATLAB "patch" to establish the border +errorbar(xpos,sum(remainedS(1:3,ii))',ratio_error2(ii), 'k', 'LineStyle','none') + +end +for ii = 1:8 +hold on +xpos = ii*gap+0.32; +hd1(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 gainedR(1,ii) gainedR(1,ii)],'w','EdgeColor','k', 'FaceColor', new_other_col); % using MATLAB "patch" to establish the border +hd2(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[gainedR(1,ii) gainedR(1,ii) (gainedR(1,ii)+gainedR(2,ii)) (gainedR(1,ii)+gainedR(2,ii))],'w','EdgeColor','k', 'FaceColor', new_prot_col); % using MATLAB "patch" to establish the border +hd3(ii) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[sum(gainedR(1:2,ii)) sum(gainedR(1:2,ii)) sum(gainedR(1:3,ii)) sum(gainedR(1:3,ii))],'w','EdgeColor','k', 'FaceColor', new_kleb_col ); % using MATLAB "patch" to establish the border +errorbar(xpos,sum(gainedR(1:3,ii))',ratio_error(ii), 'k', 'LineStyle','none') + +end + +xlim([0.5 7*gap+3]) +ylim([0 80]) +% xlim([0 8.5]) +% ylim([0 80]) +ylabel({'% of initially {\it E. coli} infections which'; ... + 'gained resistance that were caused by';... + 'reinfection different species'}) +xlabel('treatment antibiotic') +set(gca,'XTick',width:gap:gap*8); +set(gca,'xticklabel', UTI_cases.SMP_Res_drug_names([1 2 8 3:7])); +xtickangle(45); +legend('Other species','{\it P. mirabilis}','{\it K. pneumoniae}') diff --git a/UTI_analysis/mismatched_vs_matched_recurrence_rate.m b/UTI_analysis/mismatched_vs_matched_recurrence_rate.m new file mode 100644 index 0000000..4f210fa --- /dev/null +++ b/UTI_analysis/mismatched_vs_matched_recurrence_rate.m @@ -0,0 +1,93 @@ +function []= mismatched_vs_matched_recurrence_rate(UTI_cases,params) +% function takes UTI_case struc and optional params and makes bar chart of +% the % of early recurrences for sensitivity matched and mismatched antibiotic +% treated cases. + +% pre-allocate +total_prch = zeros(1,params.number_drugs); +all_sensitive_purchased = zeros(1,params.number_drugs); +sensitive_purchased_fails = zeros(1,params.number_drugs); +sensitive_purchased_nextresfails = zeros(1,params.number_drugs); +sensitive_purchased_fails_SS = zeros(1,params.number_drugs); +sensitive_purchased_fails_SR = zeros(1,params.number_drugs); +all_resistant_purchased = zeros(1,params.number_drugs); +resistant_purchased_fails = zeros(1,params.number_drugs); +resistant_purchased_nextresfails = zeros(1,params.number_drugs); +resistant_purchased_fails_RS = zeros(1,params.number_drugs); +resistant_purchased_fails_RR = zeros(1,params.number_drugs); + +% loop over all antibiotics +for drug = 1:params.number_drugs + total_prch(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & UTI_cases.hasdiag ); + all_sensitive = (ismember(UTI_cases.SMP_Res(:,drug), params.sensitive_group)) & UTI_cases.hasdiag ; + all_reistant = (ismember(UTI_cases.SMP_Res(:,drug), params.resistant_group)) & UTI_cases.hasdiag ; + + all_sensitive_nextres = ismember(UTI_cases.next_res(:,drug),params.sensitive_group); + all_resistant_nextres = ismember(UTI_cases.next_res(:,drug),params.resistant_group); + all_nextres = ismember(UTI_cases.next_res(:,drug),[1 2 3]); + + all_sensitive_purchased(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure); + sensitive_purchased_nextresfails(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_nextres); + + sensitive_purchased_fails_SS(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_sensitive_nextres); + sensitive_purchased_fails_SR(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_resistant_nextres); + + all_resistant_purchased(drug) = nnz(all_reistant & UTI_cases.PCR_sameday(:,drug)); + resistant_purchased_fails(drug) = nnz(all_reistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure); + resistant_purchased_nextresfails(drug) = nnz(all_reistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_nextres); + + resistant_purchased_fails_RS(drug) = nnz(all_reistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_sensitive_nextres); + resistant_purchased_fails_RR(drug) = nnz(all_reistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_resistant_nextres); +end + +% sum the numbers from all antibiotics +all_ratio = sum(sensitive_purchased_fails)/sum(all_sensitive_purchased)*100; +all_fail_split = [sum(sensitive_purchased_fails_SS)/sum(sensitive_purchased_nextresfails) ; sum(sensitive_purchased_fails_SR)/sum(sensitive_purchased_nextresfails)]*all_ratio; +all_fail_split_error = sqrt((all_ratio/100).*(1-(all_ratio/100))./(sum(all_sensitive_purchased)))*100; + +all_resistant_ratio = sum(resistant_purchased_fails)/sum(all_resistant_purchased)*100; +all_resistant_fail_split = [sum(resistant_purchased_fails_RS)/sum(resistant_purchased_nextresfails) ; sum(resistant_purchased_fails_RR)/sum(resistant_purchased_nextresfails)]*all_resistant_ratio; +all_resistant_fail_split_error = sqrt((all_resistant_ratio/100).*(1-(all_resistant_ratio/100))./(sum(all_resistant_purchased)))*100; + +%% print bar chart +figure +HW = [3 2]; +set(gcf,'color','w') +clf; set(gcf,'name','Fig. 1B'); +set(gcf,'units','centimeters','Position',[2 2 7 10]); + +width = 0.5; + +ii = 1; + hold on +xpos = 2;%gap+0.32; +hd1 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [0 0 all_fail_split(2,ii) all_fail_split(2,ii)],... + 'w','EdgeColor','k', 'FaceColor', params.SR_color); +hd2 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [all_fail_split(2,ii) all_fail_split(2,ii) ... + (all_fail_split(1,ii)+all_fail_split(2,ii)) ... + (all_fail_split(1,ii)+all_fail_split(2,ii))],... + 'w','EdgeColor','k', 'FaceColor', params.SS_color); +errorbar(xpos,(all_fail_split(1,ii)+all_fail_split(2,ii)),all_fail_split_error(ii), 'k', 'LineStyle','none') + +hold on +xpos = 1;%gap-0.32; +hd1 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [0 0 all_resistant_fail_split(2,ii) all_resistant_fail_split(2,ii)],... + 'w','EdgeColor','k', 'FaceColor', params.RR_color); +hd2 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [all_resistant_fail_split(2,ii) all_resistant_fail_split(2,ii) ... + (all_resistant_fail_split(1,ii)+all_resistant_fail_split(2,ii)) ... + (all_resistant_fail_split(1,ii)+all_resistant_fail_split(2,ii))],... + 'w','EdgeColor','k', 'FaceColor', params.RS_color); +errorbar(xpos,(all_resistant_fail_split(1,ii)+all_resistant_fail_split(2,ii)),all_resistant_fail_split_error(ii), 'k', 'LineStyle','none') + +ylabel({'percentage of UTIs' ; 'resulting in early recurrence'}) +set(gca,'XTick',[1 2]); +set(gca,'xticklabel',{'mismatched','mathced'}); +xtickangle(45); + +ylim([0 25]) +end \ No newline at end of file diff --git a/UTI_analysis/mode_of_reccurence_pie_charts.m b/UTI_analysis/mode_of_reccurence_pie_charts.m new file mode 100644 index 0000000..ae41ad6 --- /dev/null +++ b/UTI_analysis/mode_of_reccurence_pie_charts.m @@ -0,0 +1,108 @@ +function [] = mode_of_reccurence_pie_charts(UTI_cases, params) +% function takes UTI_case strcut and optional params and makes pie charts of +% the % of early recurrences and their mode of recurrence for all antibiotic +% treated cases. + +%define fig properties +figure +Names = UTI_cases.SMP_Res_drug_names; +set(gcf,'color','w') +clf; set(gcf,'name','Fig. 1C'); +left_val = 5; +bottom_val = 5; +width_val = 25; +height_val = 8; +set(gcf,'units','centimeters','Position',[left_val bottom_val width_val height_val]); + +%% loop over all antibtioics +treatfailure= UTI_cases.treatfailure; +for drug = 1:params.number_drugs + total_prch1(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & UTI_cases.hasdiag); + num_fails(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & treatfailure & UTI_cases.hasdiag); + + total_prch_matched(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & UTI_cases.hasdiag & ismember(UTI_cases.SMP_Res(:,drug),params.sensitive_group)); + total_prch_mismatched(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & UTI_cases.hasdiag & ismember(UTI_cases.SMP_Res(:,drug),params.resistant_group)); + + total_prch_matched_fails(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & UTI_cases.hasdiag & ismember(UTI_cases.SMP_Res(:,drug),params.sensitive_group) & treatfailure); + total_prch_mismatched_fails(drug) = nnz(UTI_cases.PCR_sameday(:,drug)& UTI_cases.hasdiag & ismember(UTI_cases.SMP_Res(:,drug),params.resistant_group) & treatfailure); + + total_prch_matched_clear(drug) = nnz(UTI_cases.PCR_sameday(:,drug)& UTI_cases.hasdiag & ismember(UTI_cases.SMP_Res(:,drug),params.sensitive_group) & ~treatfailure); + total_prch_mismatched_clear(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & UTI_cases.hasdiag & ismember(UTI_cases.SMP_Res(:,drug),params.resistant_group) & ~treatfailure); +end + +num_total_prch = sum(total_prch_matched) + sum(total_prch_mismatched); +num_early_rec = sum(num_fails)/sum(total_prch1); +fprintf('The total number of treated infections is %i\n',num_total_prch); +fprintf('The percentage number of early recurrences is %2.1f\n',num_early_rec*100); + +num_early_rec = (sum(total_prch_mismatched_fails)+sum(total_prch_matched_fails)); +num_prch_matched_clear = sum(total_prch_matched_clear); +num_prch_mismatched_clear = sum(total_prch_mismatched_clear); + +per_early_rec = num_early_rec/(sum(total_prch_mismatched)+sum(total_prch_matched)); +per_prch_matched_clear = num_prch_matched_clear/(sum(total_prch_mismatched)+sum(total_prch_matched)); +per_prch_mismatched_clear = num_prch_mismatched_clear/(sum(total_prch_mismatched)+sum(total_prch_matched)); + +t = tiledlayout(2,8, 'Padding','tight'); +nexttile(1,[2 2]); +pie([per_early_rec per_prch_matched_clear per_prch_mismatched_clear ], ... + {sprintf('early reccurrence \n %d',num_early_rec),... + sprintf('S->0 \n %d',num_prch_matched_clear),... + sprintf('R->0 \n %d',num_prch_mismatched_clear)}); +ax = gca(); +ax.Colormap = [[0.32 0.32 0.32]; [0.74, 0.74, 0.98]; [0.98, 0.79, 0.79]]; +title('all treated UTIs') +% +no_measurement = UTI_cases.SMP_Res == 0; +no_next_measurement = UTI_cases.next_res == 0 | isnan(UTI_cases.next_res); +no_measurement_either_all = no_measurement | no_next_measurement; +no_measurement_either = no_measurement_either_all(UTI_cases.treatfailure == 1 & UTI_cases.hasdiag,:); +CurrentRes = UTI_cases.SMP_Res(UTI_cases.treatfailure == 1 & UTI_cases.hasdiag,:) ; +CurrentRes = ismember(CurrentRes,params.resistant_group); +NextRes = UTI_cases.next_res(UTI_cases.treatfailure == 1 & UTI_cases.hasdiag,:); +NextRes = ismember(NextRes,params.resistant_group); +SS = ~CurrentRes & ~NextRes & ~no_measurement_either; +SR = ~CurrentRes & NextRes & ~no_measurement_either; +RS = CurrentRes & ~NextRes & ~no_measurement_either; +RR = CurrentRes & NextRes & ~no_measurement_either; +drug_prch_fails = UTI_cases.PCR_sameday(UTI_cases.treatfailure & UTI_cases.hasdiag,:); + +for ii = 1:params.number_drugs +SS_drugprch = SS(drug_prch_fails(:,ii),ii); +SR_drugprch = SR(drug_prch_fails(:,ii),ii); +RS_drugprch = RS(drug_prch_fails(:,ii),ii); +RR_drugprch = RR(drug_prch_fails(:,ii),ii); + +SSnum(ii) = length(SS_drugprch(SS_drugprch)); +SRnum(ii) = length(SR_drugprch(SR_drugprch)); +RSnum(ii) = length(RS_drugprch(RS_drugprch)); +RRnum(ii) = length(RR_drugprch(RR_drugprch)); +total(ii) = SSnum(ii) + SRnum(ii) + RSnum(ii) + RRnum(ii) ; +fraction = [ RRnum(ii) RSnum(ii) SRnum(ii) SSnum(ii)]./total(ii); + +if ismember(ii,[1 2]) +ax = nexttile(4+ii); +elseif ismember(ii,3) +ax = nexttile(5+ii); +elseif ismember(ii,8) %rearrange order for figures +ax = nexttile(4+3); +else +ax = nexttile(9+ii); +end + +pie(fraction); +ax.Colormap = [params.RR_color; params.RS_color; params.SR_color; params.SS_color]; +TextChildren = findobj(ax,'Type','text'); +set(TextChildren,'visible','off') +title(Names{ii}) +savefraction(:,ii) = fraction; + +clear fraction SS_drugprch SR_drugprch RS_drugprch RR_drugprch +end + +fraction = [sum(RRnum) sum(RSnum) sum(SRnum) sum(SSnum) ]./(sum(SSnum) + sum(SRnum) + sum(RSnum) + sum(RRnum)); +nexttile(3,[2 2]) +pie(fraction); +ax = gca(); +ax.Colormap = [params.RR_color; params.RS_color; params.SR_color; params.SS_color]; +end diff --git a/UTI_analysis/mode_of_recurrence_treated_untreated.m b/UTI_analysis/mode_of_recurrence_treated_untreated.m new file mode 100644 index 0000000..6af1481 --- /dev/null +++ b/UTI_analysis/mode_of_recurrence_treated_untreated.m @@ -0,0 +1,108 @@ +function [] = mode_of_recurrence_treated_untreated(UTI_cases,params) +% function takes UTI_case structure and optional params and makes plots of +% the 7-day moving avaerage mode of early recurrences (S-R, S-S, R-R, R-S) +% for all antibtioics both for cases treated with the specified antibiotic and untreated cases + +av_window = 7; +days = 4:1:60; +for kk = 1:length(days)-1 +clear treatfailure +treatfailure = UTI_cases.date_diff >= days(kk) & UTI_cases.date_diff < days(kk)+av_window; + + +for drug = 1:params.number_drugs + + all_sensitive1 = (UTI_cases.SMP_Res(:,drug) == 1 | UTI_cases.SMP_Res(:,drug) == 2) & UTI_cases.hasdiag ; + all_resistant1 = (UTI_cases.SMP_Res(:,drug) == 3) & UTI_cases.hasdiag ; + all_sensitive_nextres1 = UTI_cases.next_res(:,drug) == 1 | UTI_cases.SMP_Res(:,drug) == 2 ; + all_resistant_nextres1 = UTI_cases.next_res(:,drug) == 3 ; + all_nextres = ismember(UTI_cases.next_res(:,drug),[1 2 3]); + + all_sensitive_purchased1 = nnz((all_sensitive1 | all_resistant1) & UTI_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails1 = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure); + sensitive_purchased_nextresfails1 = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + sensitive_purchased_fails_SS = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + sensitive_purchased_fails_SR = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + ratio1(drug,kk) = sensitive_purchased_fails1/all_sensitive_purchased1*100; + number_prch1(drug) = all_sensitive_purchased1; + ratio_error1(drug ,kk) = sqrt((ratio1(drug,kk)/100).*(1-(ratio1(drug,kk)/100))./(all_sensitive_purchased1))*100; + fail_split1(1:2,kk, drug) = [sensitive_purchased_fails_SS/sensitive_purchased_nextresfails1 ; sensitive_purchased_fails_SR/sensitive_purchased_nextresfails1]*ratio1(drug,kk); + + all_resistant_purchased = nnz((all_sensitive1 | all_resistant1) & UTI_cases.PCR_sameday(:,drug)); + resistant_purchased_fails = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure); + resistant_purchased_nextresfails = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + resistant_purchased_fails_RS = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + resistant_purchased_fails_RR = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + ratio_res1(drug,kk) = resistant_purchased_fails/all_resistant_purchased*100; + number_prch_res1(drug) = all_resistant_purchased; + ratio_error_res1(drug,kk) = sqrt((ratio_res1(drug,kk)/100).*(1-(ratio_res1(drug,kk)/100))./(all_resistant_purchased))*100; + fail_split_res1(1:2,kk, drug) = [resistant_purchased_fails_RR/resistant_purchased_nextresfails ; resistant_purchased_fails_RS/resistant_purchased_nextresfails]*ratio_res1(drug,kk); + + all_sensitive_noprch1 = nnz((all_sensitive1 | all_resistant1) & UTI_cases.PCR_sameday(:,10)); + sensitive_noprch_fails1 = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,10) & treatfailure ); + sensitive_noprch_nextresfails1 = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,10) & treatfailure & all_nextres); + sensitive_noprch_fails_SS = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,10) & treatfailure & all_sensitive_nextres1); + sensitive_noprch_fails_SR = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,10) & treatfailure & all_resistant_nextres1); + ratio_noprch1(drug,kk) = sensitive_noprch_fails1/all_sensitive_noprch1*100; + number_noprch1(drug) = all_sensitive_noprch1; + ratio_noprch_error1(drug,kk) = sqrt((ratio_noprch1(drug,kk)/100).*(1-(ratio_noprch1(drug,kk)/100))./(all_sensitive_noprch1))*100; + fail_split_noprch1(1:2,kk, drug) = [sensitive_noprch_fails_SS/sensitive_noprch_nextresfails1 ; sensitive_noprch_fails_SR/sensitive_noprch_nextresfails1]*ratio_noprch1(drug,kk); + + all_resistant_noprch1 = nnz((all_sensitive1 | all_resistant1) & UTI_cases.PCR_sameday(:,10)); + resistant_noprch_fails1 = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,10) & treatfailure); + resistant_noprch_nextresfails1 = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,10) & treatfailure & all_nextres); + resistant_noprch_fails_RS = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,10) & treatfailure & all_sensitive_nextres1); + resistant_noprch_fails_RR = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,10) & treatfailure & all_resistant_nextres1); + ratio_noprch_res1(drug,kk) = resistant_noprch_fails1/all_resistant_noprch1*100; + number_noprch_res1(drug) = all_resistant_noprch1; + ratio_error_res1(drug,kk) = sqrt((ratio_noprch_res1(drug,kk)/100).*(1-(ratio_noprch_res1(drug,kk)/100))./(all_resistant_noprch1))*100; + fail_split_noprch_res1(1:2,kk, drug) = [resistant_noprch_fails_RR/resistant_noprch_nextresfails1 ; resistant_noprch_fails_RS/resistant_noprch_nextresfails1]*ratio_noprch_res1(drug,kk); + + +end + +end + +%% plot the fig +set(0, 'DefaultFigureRenderer', 'painters'); +first_set = [1 2 5 6 9 10 13 14]; +for drug = 1:params.number_drugs +subplot(8,2,first_set(drug)) +tots = [fail_split1(:,:,drug)',fail_split_res1(:,:,drug)']; +tots(isnan(tots))= 0; +total_vals = sum(tots,2); +b1 = bar(1:length(days)-1,[fail_split1(:,:,drug)',fail_split_res1(:,:,drug)']./total_vals, 'stacked' , 'FaceColor','flat', 'EdgeColor', 'none', 'BarWidth', 1); +b1(1).CData(:,:) = ones(length(days)-1,1)*params.SS_color; +b1(2).CData(:,:) = ones(length(days)-1,1)*params.SR_color; +b1(3).CData(:,:) = ones(length(days)-1,1)*params.RR_color; +b1(4).CData(:,:) = ones(length(days)-1,1)*params.RS_color; +ylabel('% of early recurrences'); +set(gca,'XTick',1:8:length(days)); +set(gca, 'XTickLabel', []) +xlim([0.5 length(days)-0.5]) +ylim([0 1]) +set(gca,'YTick',0:0.5:1); +nums_string = num2str(((0:0.5:1)*100)'); +set(gca,'yticklabel',nums_string); +title(UTI_cases.SMP_Res_drug_names(drug)); +end + +% +for drug = 1:params.number_drugs +subplot(8,2,first_set(drug)+2) +total_vals = sum([fail_split_noprch1(:,:,drug)',fail_split_noprch_res1(:,:,drug)'],2); +b1 = bar(1:length(days)-1,[fail_split_noprch1(:,:,drug)',fail_split_noprch_res1(:,:,drug)']./total_vals, 'stacked' , 'FaceColor','flat', 'EdgeColor', 'none', 'BarWidth', 1); +b1(1).CData(:,:) = ones(length(days)-1,1)*params.SS_color; +b1(2).CData(:,:) = ones(length(days)-1,1)*params.SR_color; +b1(3).CData(:,:) = ones(length(days)-1,1)*params.RR_color; +b1(4).CData(:,:) = ones(length(days)-1,1)*params.RS_color; +set(gca,'XTick',1:8:length(days)); +days_string = num2str((days(1:8:length(days)))'); +set(gca,'xticklabel',days_string); +xlabel('number of days between first and second sample'); +xlim([0.5 length(days)-0.5]) +ylim([0 1]) +set(gca,'YTick',0:0.5:1); +set(gca,'yticklabel',nums_string); +end +end \ No newline at end of file diff --git a/UTI_analysis/my_fit.m b/UTI_analysis/my_fit.m new file mode 100644 index 0000000..dd367a8 --- /dev/null +++ b/UTI_analysis/my_fit.m @@ -0,0 +1,55 @@ +function c = my_fit(X,Y,n0,link) + +if nargin<3 + n0 = 0 ; % minimal number of zeros and ones +end +if nargin<4 + link = 'logit' ; +end +sumX0 = sum(Xmin(X)) ; +kv = sumX0>=n0 & sumX1>=n0 ; % variables to include +X = X(:,kv) ; + +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial',link) ; +c.coef = glm.stats.beta ; +c.se = glm.stats.se ; +c.p = glm.stats.p ; +c.t = glm.stats.t ; +c.dfe = glm.stats.dfe ; +c.covb = glm.stats.covb ; +c.rmse = glm.stats.sfit ; +c.coeffcorr = glm.stats.coeffcorr ; + +kv = [true, kv] ; +c.coef = addnans(c.coef,kv,1) ; +c.se = addnans(c.se ,kv,1) ; +c.p = addnans(c.p ,kv,1) ; +c.t = addnans(c.t ,kv,1) ; +c.covb = addnans(c.covb,kv,3) ; +c.coeffcorr = addnans(c.coeffcorr,kv,3) ; + +c.sumX0 = sumX0 ; +c.sumX1 = sumX1 ; +c.sumY0 = sum(Y==0) ; +c.sumY1 = sum(Y>0) ; +c.totallines = size(X,1) ; +c.remove = ~kv ; + +end + +function xn = addnans(x,k,dim) +switch dim + case 1 + xn(k,:) = x ; + xn(~k,:) = nan ; + case 2 + xn(:,k) = x ; + xn(:,~k) = nan ; + case 3 + xn(k,k) = x ; + xn(:,~k) = nan ; + xn(~k,:) = nan ; +end +end + diff --git a/UTI_analysis/net_change_resistance.m b/UTI_analysis/net_change_resistance.m new file mode 100644 index 0000000..339afd7 --- /dev/null +++ b/UTI_analysis/net_change_resistance.m @@ -0,0 +1,114 @@ +function []= net_change_resistance(UTI_cases,params) +% function takes UTI_case stuc and optional params and makes bar chart of +% the % of early recurrences which changed susceptibiltiy to specific antiboitic, for all untreated cases and +% all cases treated the the specific antibtioicu + +%for all the antibiotics +for drug = 1:params.number_drugs + + % initially sensitive or resistant + all_sensitive = ismember(UTI_cases.SMP_Res(:,drug),params.sensitive_group) & UTI_cases.hasdiag ; + all_resistant = ismember(UTI_cases.SMP_Res(:,drug),params.resistant_group) & UTI_cases.hasdiag ; + + % susceptibilty of recurrent infection + all_sensitive_nextres = UTI_cases.next_res(:,drug) == 1 | UTI_cases.SMP_Res(:,drug) == 2 ; + all_resistant_nextres = UTI_cases.next_res(:,drug) == 3 ; + all_nextres = ismember(UTI_cases.next_res(:,drug),[1 2 3]); + + %num treated with the antibitoic + all_sensitive_purchased2 = nnz((all_sensitive | all_resistant) & UTI_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails2 = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure); + sensitive_purchased_nextresfails2 = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_nextres); + + sensitive_purchased_fails_SS = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_sensitive_nextres); + sensitive_purchased_fails_SR = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_resistant_nextres); + + %rate of failure for suscptibitiy-matched + ratio2(drug) = sensitive_purchased_fails2/all_sensitive_purchased2*100; + number_prch(drug) = all_sensitive_purchased2; + ratio_error2(drug) = sqrt((ratio2(drug)/100).*(1-(ratio2(drug)/100))./(all_sensitive_purchased2))*100; + %split rate of failure by mode + fail_split2(1:2,drug) = [sensitive_purchased_fails_SS/sensitive_purchased_nextresfails2 ; sensitive_purchased_fails_SR/sensitive_purchased_nextresfails2]*ratio2(drug); + SR_error2(drug) = sqrt((fail_split2(2,drug)/100).*(1-(fail_split2(2,drug)/100))./(all_sensitive_purchased2))*100; + + %rate of failure for suscptibitiy-mismatched + all_resistant_purchased2 = nnz((all_sensitive | all_resistant) & UTI_cases.PCR_sameday(:,drug)); + resistant_purchased_fails2 = nnz(all_resistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure); + resistant_purchased_nextresfails2 = nnz(all_resistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_nextres); + resistant_purchased_fails_RS = nnz(all_resistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_sensitive_nextres); + resistant_purchased_fails_RR = nnz(all_resistant & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_resistant_nextres); + + ratio_res(drug) = resistant_purchased_fails2/all_resistant_purchased2*100; + number_prch_res(drug) = all_resistant_purchased2; + ratio_error_res(drug) = sqrt((ratio_res(drug)/100).*(1-(ratio_res(drug)/100))./(all_resistant_purchased2))*100; + fail_split_res2(1:2,drug) = [resistant_purchased_fails_RR/resistant_purchased_nextresfails2 ; resistant_purchased_fails_RS/resistant_purchased_nextresfails2]*ratio_res(drug); + SR_error_res2(drug) = sqrt((fail_split_res2(2,drug)/100).*(1-(fail_split_res2(2,drug)/100))./(all_resistant_purchased2))*100; + + %same for untreated + all_sensitive_noprch2 = nnz((all_sensitive | all_resistant) & UTI_cases.PCR_sameday(:,10)); + sensitive_noprch_fails2 = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure ); + sensitive_noprch_nextresfails2 = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_nextres); + + sensitive_noprch_fails_SS = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_sensitive_nextres); + sensitive_noprch_fails_SR = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_resistant_nextres); + + ratio_noprch2(drug) = sensitive_noprch_fails2/all_sensitive_noprch2*100; + number_noprch(drug) = all_sensitive_noprch2; + ratio_noprch_error(drug) = sqrt((ratio_noprch2(drug)/100).*(1-(ratio_noprch2(drug)/100))./(all_sensitive_noprch2))*100; + fail_split_noprch2(1:2,drug) = [sensitive_noprch_fails_SS/sensitive_noprch_nextresfails2 ; sensitive_noprch_fails_SR/sensitive_noprch_nextresfails2]*ratio_noprch2(drug); + SR_noprch_error2(drug) = sqrt((fail_split_noprch2(2,drug)/100).*(1-(fail_split_noprch2(2,drug)/100))./(all_sensitive_noprch2))*100; + + + %all_resistant_noprch = nnz(all_resistant & UTI_cases.PCR_sameday(:,10)); + all_resistant_noprch2 = nnz((all_sensitive | all_resistant) & UTI_cases.PCR_sameday(:,10)); + resistant_noprch_fails2 = nnz(all_resistant & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure); + resistant_noprch_nextresfails2 = nnz(all_resistant & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_nextres); + resistant_noprch_fails_RS = nnz(all_resistant & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_sensitive_nextres); + resistant_noprch_fails_RR = nnz(all_resistant & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_resistant_nextres); + + ratio_noprch_res2(drug) = resistant_noprch_fails2/all_resistant_noprch2*100; + number_noprch_res(drug) = all_resistant_noprch2; + ratio_error_res(drug) = sqrt((ratio_noprch_res2(drug)/100).*(1-(ratio_noprch_res2(drug)/100))./(all_resistant_noprch2))*100; + fail_split_noprch_res2(1:2,drug) = [resistant_noprch_fails_RR/resistant_noprch_nextresfails2 ; resistant_noprch_fails_RS/resistant_noprch_nextresfails2]*ratio_noprch_res2(drug); + SR_error_noprch_res2(drug) = sqrt((fail_split_noprch_res2(2,drug)/100).*(1-(fail_split_noprch_res2(2,drug)/100))./(all_resistant_noprch2))*100; + + clear all_sensitive all_sensitive_purchased sensitive_purchased_fails +end + +%% plot the figure + +width = 0.5; +gap = 1.8; +plot([0 7*gap+3], [0 0],'k') + +for jj = 1:params.number_drugs + ii = params.new_order(jj); +hold on +xpos = jj*gap-0.32; +hd3(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 fail_split_noprch2(2,ii) fail_split_noprch2(2,ii)],'w','EdgeColor','k', 'FaceColor', params.SR_color); % using MATLAB "patch" to establish the border +errorbar(xpos,fail_split_noprch2(2,ii)',SR_noprch_error2(ii), 'k', 'LineStyle','none') +%hatch(hda(ii),[45,4,1],'w') +hd4(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 -fail_split_noprch_res2(2,ii) -fail_split_noprch_res2(2,ii)],'w','EdgeColor','k', 'FaceColor', params.RS_color); % using MATLAB "patch" to establish the border +errorbar(xpos,-fail_split_noprch_res2(2,ii)',SR_error_noprch_res2(ii), 'k', 'LineStyle','none') +end + +for jj = 1:params.number_drugs + ii = params.new_order(jj); +hold on +xpos = jj*gap+0.32; +hd1(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 fail_split2(2,ii) fail_split2(2,ii)],'w','EdgeColor','k', 'FaceColor', params.SR_color); % using MATLAB "patch" to establish the border +errorbar(xpos,fail_split2(2,ii)',SR_error2(ii), 'k', 'LineStyle','none') +hd2(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 -fail_split_res2(2,ii) -fail_split_res2(2,ii)],'w','EdgeColor','k', 'FaceColor', params.RS_color); % using MATLAB "patch" to establish the border +errorbar(xpos,-fail_split_res2(2,ii)',SR_error_res2(ii), 'k', 'LineStyle','none'); +hatch(hd3(jj),[45,2.5,0.8],'k') +hatch(hd4(jj),[45,2.5,0.8],'k') +end +xlim([0.5 7*gap+3]) +ylim([-1.5 7.5]) +ylabel('% of patients who have an infection which changes resistance') + +set(gca,'XTick',gap:gap:gap*8); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(params.new_order)); +xtickangle(45); + +end diff --git a/UTI_analysis/rate_res_by_species.m b/UTI_analysis/rate_res_by_species.m new file mode 100644 index 0000000..a79935d --- /dev/null +++ b/UTI_analysis/rate_res_by_species.m @@ -0,0 +1,60 @@ +function [] = rate_res_by_species(UTI_cases, params) +% function takes UTI_case structure and optional params and plots pie charts of the +% rate of resistance for each of most commmon species + +all_bugs = cell2mat(UTI_cases.bug_all); +all_res= cell2mat(UTI_cases.RES); + +%% by species +bug = cell2mat(UTI_cases.bug_all); +SMP_Res = cell2mat(UTI_cases.RES); +frac_ecoli = nnz(bug == 179)/length(bug)*100; %most common species codes +frac_kleb = nnz(bug == 225)/length(bug)*100; +frac_prot= nnz(bug == 280)/length(bug)*100; +frac_cit = nnz(bug == 110 )/length(bug)*100; +Names = UTI_cases.SMP_Res_drug_names; +pos2 = [0 0.05 0.1 0.1] ;%[left bottom width height] +for kk = [110 280 225 179 ] % codes for 4 most common species +for drug = 1:params.number_drugs +pos2(1) = pos2(1)+0.1; +subplot('Position',pos2) +yes_measurement = SMP_Res(:,drug)>0 & bug == kk; +number_resistant(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),3)); +number_intermediate(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[2])); +number_sensitive(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[1])); + +fractionR(drug) = (number_resistant(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionI(drug) = (number_intermediate(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionS(drug) = (number_sensitive(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); + +pie([fractionS(drug),fractionI(drug), fractionR(drug)]); +set(findobj(gca,'type','text'),'fontsize',7.5); +%labels = repmat({''},size(fractionS)); +%title(Names{drug}) +cmap = [150 150 150 ; 75 75 75 ; 0 0 0]./255; +colormap(gca, cmap) +end +text(0, pos2(2), UTI_cases.Bugs.Name(find(UTI_cases.Bugs.Code == kk))); +pos2 = [0 pos2(2) 0.1 0.1]; +pos2(2) = pos2(2)+0.2; +end + +%% plot the data +for drug = 1:params.number_drugs +pos2(1) = pos2(1)+0.1; +subplot('Position',pos2); +yes_measurement = SMP_Res(:,drug)>0; +number_resistant(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),3)); +number_intermediate(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[2])); +number_sensitive(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[1])); +fractionR(drug) = (number_resistant(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionI(drug) = (number_intermediate(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionS(drug) = (number_sensitive(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +pie([fractionS(drug),fractionI(drug), fractionR(drug)]); +set(findobj(gca,'type','text'),'fontsize',7.5); +title(Names{drug}) +cmap = [150 150 150 ; 75 75 75 ; 0 0 0]./255; +colormap(gca, cmap) +end +text(0, pos2(2), 'All species'); +end \ No newline at end of file diff --git a/UTI_analysis/risk_reccurence_correctly_prescribed_treat_v_untreat.m b/UTI_analysis/risk_reccurence_correctly_prescribed_treat_v_untreat.m new file mode 100644 index 0000000..ed6f033 --- /dev/null +++ b/UTI_analysis/risk_reccurence_correctly_prescribed_treat_v_untreat.m @@ -0,0 +1,79 @@ +function []= risk_reccurence_correctly_prescribed_treat_v_untreat(UTI_cases,params) +% function takes UTI_case structure and optional params and makes bar charts of +% the % of early recurrences sensitive to specific antiboitic, for untreated cases and +% cases treated the the specific antibtioic + +%loop all antibiotics +for drug = 1:params.number_drugs + + total_prch(drug) = nnz(UTI_cases.PCR_sameday(:,drug) & UTI_cases.hasdiag); + all_sensitive = (ismember(UTI_cases.SMP_Res(:,drug), params.sensitive_group)) & UTI_cases.hasdiag ; + all_sensitive_nextres = ismember(UTI_cases.next_res(:,drug),params.sensitive_group); + all_resistant_nextres = ismember(UTI_cases.next_res(:,drug),params.resistant_group); + all_nextres = ismember(UTI_cases.next_res(:,drug),[1 2 3]); + + all_sensitive_purchased(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure); + sensitive_purchased_nextresfails(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_nextres); + + sensitive_purchased_fails_SS(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_sensitive_nextres); + sensitive_purchased_fails_SR(drug) = nnz(all_sensitive & UTI_cases.PCR_sameday(:,drug) & UTI_cases.treatfailure & all_resistant_nextres); + + %first calulate rate of failure + ratio(drug) = sensitive_purchased_fails(drug)/all_sensitive_purchased(drug)*100; + number_prch(drug) = all_sensitive_purchased(drug); + ratio_error(drug) = sqrt((ratio(drug)/100).*(1-(ratio(drug)/100))./(all_sensitive_purchased(drug)))*100; + % slit the overall rate of faliure into 2 modes based on ratio of gained + % res to remained sen + fail_split(1:2,drug) = [sensitive_purchased_fails_SS(drug)/sensitive_purchased_nextresfails(drug) ; sensitive_purchased_fails_SR(drug)/sensitive_purchased_nextresfails(drug)]*ratio(drug); + + %same for untreated cases + all_sensitive_noprch = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10)); + sensitive_noprch_fails = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure ); + sensitive_noprch_nextresfails = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_nextres); + sensitive_noprch_fails_SS = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_sensitive_nextres); + sensitive_noprch_fails_SR = nnz(all_sensitive & UTI_cases.PCR_sameday(:,10) & UTI_cases.treatfailure & all_resistant_nextres); + + ratio_noprch(drug) = sensitive_noprch_fails/all_sensitive_noprch*100; + number_noprch(drug) = all_sensitive_noprch; + ratio_noprch_error(drug) = sqrt((ratio_noprch(drug)/100).*(1-(ratio_noprch(drug)/100))./(all_sensitive_noprch))*100; + + fail_split_noprch(1:2,drug) = [sensitive_noprch_fails_SS/sensitive_noprch_nextresfails ; sensitive_noprch_fails_SR/sensitive_noprch_nextresfails]*ratio_noprch(drug); + +end + +%% plot figure + +width = 0.5; +gap = 1.8; +plot([0 7*gap+3], [0 0],'k') + +for jj = 1:params.number_drugs + ii = params.new_order(jj); + hold on +xpos = jj*gap-0.32; +hd3(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 fail_split_noprch(2,ii) fail_split_noprch(2,ii)],'w','EdgeColor','k', 'FaceColor', params.SR_color); % using MATLAB "patch" to establish the border +hd4(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[fail_split_noprch(2,ii) fail_split_noprch(2,ii) (fail_split_noprch(1,ii)+fail_split_noprch(2,ii)) (fail_split_noprch(1,ii)+fail_split_noprch(2,ii))],'w','EdgeColor','k', 'FaceColor', params.SS_color); % using MATLAB "patch" to establish the border +errorbar(xpos,(fail_split_noprch(1,ii)+fail_split_noprch(2,ii)),ratio_noprch_error(ii), 'k', 'LineStyle','none') +end + +for jj = 1:params.number_drugs + ii = params.new_order(jj); +hold on +xpos = jj*gap+0.32; +hd1(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[0 0 fail_split(2,ii) fail_split(2,ii)],'w','EdgeColor','k', 'FaceColor', params.SR_color); % using MATLAB "patch" to establish the border +hd2(jj) = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],[fail_split(2,ii) fail_split(2,ii) (fail_split(1,ii)+fail_split(2,ii)) (fail_split(1,ii)+fail_split(2,ii))],'w','EdgeColor','k', 'FaceColor', params.SS_color); % using MATLAB "patch" to establish the border +hatch(hd3(jj),[45,2.5,0.8],'k') +hatch(hd4(jj),[45,2.5,0.8],'w') +errorbar(xpos,(fail_split(1,ii)+fail_split(2,ii)),ratio_error(ii), 'k', 'LineStyle','none') +temp_text = {'n = '; [num2str(round(number_prch(ii)/1000)) 'k']}; +text(xpos-width/2, (fail_split(1,ii)+fail_split(2,ii))+3, temp_text); +end +xlim([0.5 7*gap+3]) +ylim([0 20]) +ylabel('% of treatment failures ') +set(gca,'XTick',gap:gap:gap*8); +set(gca,'xticklabel',UTI_cases.SMP_Res_drug_names(params.new_order)); +xtickangle(45); + +end \ No newline at end of file diff --git a/UTI_analysis/risk_recurrence_by_day.m b/UTI_analysis/risk_recurrence_by_day.m new file mode 100644 index 0000000..8f246b6 --- /dev/null +++ b/UTI_analysis/risk_recurrence_by_day.m @@ -0,0 +1,63 @@ +function [] = risk_recurrence_by_day(UTI_cases,params) +% function takes UTI_case structure and optional params and makes plot of +% the 7-day moving avaerage % of early recurrences for all antibtioic treated cases + +av_window = 7; +days = 4:1:50; +%for all days +for kk = 1:length(days)-1 +clear treatfailure +treatfailure = UTI_cases.date_diff >= days(kk) & UTI_cases.date_diff < days(kk)+av_window; +%for all antibioitcs +for drug = 1:params.number_drugs + + all_sensitive1 = ismember(UTI_cases.SMP_Res(:,drug), params.sensitive_group) & UTI_cases.hasdiag; + all_resistant1 = ismember(UTI_cases.SMP_Res(:,drug), params.resistant_group) & UTI_cases.hasdiag; + all_sensitive_nextres1 = ismember(UTI_cases.next_res(:,drug), params.sensitive_group) ; + all_resistant_nextres1 = ismember(UTI_cases.next_res(:,drug), params.resistant_group) ; + all_nextres = ismember(UTI_cases.next_res(:,drug),[1 2 3]); + + all_sensitive_purchased1(drug ,kk) = nnz((all_sensitive1 | all_resistant1) & UTI_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails1(drug ,kk) = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure); + sensitive_purchased_nextresfails1(drug ,kk) = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + sensitive_purchased_fails_SS(drug ,kk) = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + sensitive_purchased_fails_SR(drug ,kk) = nnz(all_sensitive1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + + all_resistant_purchased(drug ,kk) = nnz((all_sensitive1 | all_resistant1) & UTI_cases.PCR_sameday(:,drug)); + resistant_purchased_fails(drug ,kk) = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure); + resistant_purchased_nextresfails(drug ,kk) = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + resistant_purchased_fails_RS(drug ,kk) = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + resistant_purchased_fails_RR(drug ,kk) = nnz(all_resistant1 & UTI_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + + +end + +% sum the numbers from all the drugs for each day +fail_split1_all(1:2,kk, 1) = [sum(sensitive_purchased_fails_SS(1:params.number_drugs ,kk))/sum(sensitive_purchased_nextresfails1(1:params.number_drugs ,kk)) ; sum(sensitive_purchased_fails_SR(1:params.number_drugs ,kk))/sum(sensitive_purchased_nextresfails1(1:params.number_drugs ,kk))]*(sum(sensitive_purchased_fails1(1:params.number_drugs ,kk))/sum(all_sensitive_purchased1(1:params.number_drugs))*100); +fail_split_res1_all(1:2,kk, 1) = [sum(resistant_purchased_fails_RR(1:params.number_drugs ,kk))/sum(resistant_purchased_nextresfails(1:params.number_drugs ,kk)) ; sum(resistant_purchased_fails_RS(1:params.number_drugs ,kk))/sum(resistant_purchased_nextresfails(1:params.number_drugs ,kk))]*(sum(resistant_purchased_fails(1:params.number_drugs ,kk))/sum(all_resistant_purchased(1:params.number_drugs))*100); + + +end + +%% plot the fig +fail_split2(:,:,1) = fail_split1_all(:,:,1); +fail_split_res2(:,:,1) = fail_split_res1_all(:,:,1); + +b1 = bar(1:length(days)-1,[fail_split2(:,:,1)',fail_split_res2(:,:,1)']./av_window, 'stacked' , 'FaceColor','flat', 'EdgeColor', 'none', 'BarWidth', 1); + +b1(1).CData(:,:) = ones(length(days)-1,1)*params.SS_color; +b1(2).CData(:,:) = ones(length(days)-1,1)*params.SR_color; +b1(3).CData(:,:) = ones(length(days)-1,1)*params.RR_color; +b1(4).CData(:,:) = ones(length(days)-1,1)*params.RS_color; + +ylabel('% of patients'); +set(gca,'XTick',1:8:length(days)); +days_string = num2str((days(1:8:length(days)))'); +set(gca,'xticklabel',days_string); +xlabel('# of days between first and second sample'); +xlim([0.5 length(days)-0.5]) +hold on +ylim([0 0.6]); +yl = ylim; +plot([28-days(1)+1 28-days(1)+1],yl, 'k--'); +end \ No newline at end of file diff --git a/UTI_analysis/species_change_matrix_gained_res.m b/UTI_analysis/species_change_matrix_gained_res.m new file mode 100644 index 0000000..e862ad2 --- /dev/null +++ b/UTI_analysis/species_change_matrix_gained_res.m @@ -0,0 +1,143 @@ +function [] = species_change_matrix_gained_res(UTI_cases,params) +%function takes the UTI_case structure and optional params and calulates +% matrix of the rate of change of species in gained-resistance early recurrences + +%% matrix UTI gained res + +bugs_order = [1 381 292 110 280 225 179]; % most common UTI species, 1 = other +clear names +for ii = 1:length(bugs_order) + names(ii) = UTI_cases.Bugs.Name(find(UTI_cases.Bugs.Code == bugs_order(ii))); +end +names(1) = {'other'}; +not_members = 1:1000; +not_members(bugs_order) = []; +clear mat_changed +treatfailure = UTI_cases.treatfailure;% +mat_changed = zeros(length(bugs_order),length(bugs_order),params.number_drugs ); + +for drug = 1:params.number_drugs + +%next res is resistant +index = cellfun(@(x) ismember(x,params.resistant_group), UTI_cases.new_RES(:,drug),'UniformOutput',false); +%only resistant next bugs +resistant_nextres_bugs = cellfun(@(v,x)v(x),UTI_cases.new_bug,index,'UniformOutput',false); + +initially_sensitive = (UTI_cases.SMP_Res(:,drug) == 1 | UTI_cases.SMP_Res(:,drug) == 2); +to_use = find(initially_sensitive & treatfailure & UTI_cases.PCR_sameday(:,drug)); + +for inital_bug = 1:length(bugs_order) + if inital_bug == 1 %all other species + initial_true = cellfun(@(x) ismember(x,not_members),UTI_cases.bug_all,'UniformOutput',false); + initial_true = cellfun(@sum,initial_true)>0; + else + initial_true = (cellfun(@(x) x==bugs_order(inital_bug),UTI_cases.bug_all,'UniformOutput',false)); + initial_true = cellfun(@sum,initial_true)>0; + end + for new_bug = 1:length(bugs_order) + if new_bug == 1 + recurrent_true = cellfun(@(x) ismember(x,not_members),resistant_nextres_bugs,'UniformOutput',false); + recurrent_true = cellfun(@sum,recurrent_true)>0; + else + recurrent_true = (cellfun(@(x) x==bugs_order(new_bug),resistant_nextres_bugs,'UniformOutput',false)); + recurrent_true = cellfun(@sum,recurrent_true)>0; + end + mat_changed(inital_bug,new_bug,drug) = nnz(initial_true(to_use) & recurrent_true(to_use)); + end +end + +end + +%% +figure; +set(gcf,'color','w', 'name','Fig. S9 UTIs drugs', 'units','centimeters','Position',[1 1 18 10]); +tiledlayout(2,4, 'TileSpacing','Compact', 'Padding', 'none'); + +for drug = 1:params.number_drugs +nexttile +temp = mat_changed(:,:,drug); +for ii = 1:length(bugs_order) +temp(ii,:) = temp(ii,:)./sum(temp(ii,:)); +end +image(fliplr(temp*256)) +title( UTI_cases.SMP_Res_drug_names(drug)); +yticklabels([]) +xticklabels([]) +axis image + +end + +figure; +set(gcf,'color','w', 'name','Fig. S9 UTIs', 'units','centimeters','Position',[1 1 25 10]); +tiledlayout(1,2, 'TileSpacing','Compact', 'Padding', 'none'); +nexttile +mat_changed_all = sum(mat_changed, 3); +temp = mat_changed_all; +for ii = 1:length(bugs_order) +temp(ii,:) = temp(ii,:)./sum(temp(ii,:)); +end +image(fliplr(temp*256)) +title('all antibiotics') +xticks(1:length(bugs_order)) +yticklabels(names) +xtickangle(45) +yticks(1:length(bugs_order)) +xticklabels(fliplr(names)) +axis image +ylabel('Initial species') +xlabel('Gained resistance species') +%colorbar + +%% matrix UTI remained sensitive +mat_changedSS = zeros(length(bugs_order),length(bugs_order),params.number_drugs ); + +for drug = 1:params.number_drugs + +index = cellfun(@(x) ismember(x,params.sensitive_group), UTI_cases.new_RES(:,drug),'UniformOutput',false); +%only sensitive next bugs +resistant_nextres_bugs = cellfun(@(v,x)v(x),UTI_cases.new_bug,index,'UniformOutput',false); + +initially_sensitive = (UTI_cases.SMP_Res(:,drug) == 1 | UTI_cases.SMP_Res(:,drug) == 2); +to_use = find(initially_sensitive & treatfailure & UTI_cases.PCR_sameday(:,drug)); + +for inital_bug = 1:length(bugs_order) + if inital_bug == 1 + initial_true = cellfun(@(x) ismember(x,not_members),UTI_cases.bug_all,'UniformOutput',false); + initial_true = cellfun(@sum,initial_true)>0; + else + initial_true = (cellfun(@(x) x==bugs_order(inital_bug),UTI_cases.bug_all,'UniformOutput',false)); + initial_true = cellfun(@sum,initial_true)>0; + end + for new_bug = 1:length(bugs_order) + if new_bug == 1 + recurrent_true = cellfun(@(x) ismember(x,not_members),resistant_nextres_bugs,'UniformOutput',false); + recurrent_true = cellfun(@sum,recurrent_true)>0; + else + recurrent_true = (cellfun(@(x) x==bugs_order(new_bug),resistant_nextres_bugs,'UniformOutput',false)); + recurrent_true = cellfun(@sum,recurrent_true)>0; + end + mat_changedSS(inital_bug,new_bug,drug) = nnz(initial_true(to_use) & recurrent_true(to_use)); + end +end + + +end + +nexttile +mat_changed_all = sum(mat_changedSS, 3); +temp = mat_changed_all; +for ii = 1:length(bugs_order) +temp(ii,:) = temp(ii,:)./sum(temp(ii,:)); +end +image(fliplr(temp*256)) +title('all antibiotics') +xticks(1:length(bugs_order)) +yticklabels(names) +xtickangle(45) +yticks(1:length(bugs_order)) +xticklabels(fliplr(names)) +axis image +ylabel('Initial species') +xlabel('Remained sensitive species') +%colorbar +end \ No newline at end of file diff --git a/UTI_analysis/species_prevalence_table.m b/UTI_analysis/species_prevalence_table.m new file mode 100644 index 0000000..6a80fe6 --- /dev/null +++ b/UTI_analysis/species_prevalence_table.m @@ -0,0 +1,16 @@ +function [] = species_prevalence_table(UTI_cases) +%function makes table of the species prevelance for all UTI cases +A = cell2mat(UTI_cases.bug_all); +[counts,bugs] = groupcounts(A); +species_prevalence_table = table(bugs,counts); +total = sum(counts); +for ii = 1:height(species_prevalence_table) + names(ii,1) = UTI_cases.Bugs.Name( UTI_cases.Bugs.Code == species_prevalence_table.bugs(ii)); + percent(ii,1) = counts(ii)/total*100; +end +species_prevalence_table.Names = names; +species_prevalence_table.percent = round(percent); +species_prevalence_table_wounds = sortrows(species_prevalence_table,'counts','descend'); +species_prevalence_table_wounds = species_prevalence_table_wounds(1:10,:); +filename = 'Tables/TableS4_species_prevalence_table_UTIs.xlsx'; +writetable(species_prevalence_table_wounds,filename); \ No newline at end of file diff --git a/UTI_analysis/susceptibiltiy_change_matrix2.m b/UTI_analysis/susceptibiltiy_change_matrix2.m new file mode 100644 index 0000000..0d2a3dc --- /dev/null +++ b/UTI_analysis/susceptibiltiy_change_matrix2.m @@ -0,0 +1,112 @@ +function [] = susceptibiltiy_change_matrix(UTI_cases,params) +% function takes UTI_case structure and optional params and makes matric plot of +% rate of change resistance for each antiboitic suceptibiltiy and each +% antiboitic treatment + +%% sensitive chance of failure +% use periods for which relevant drug was routeenly measured +dates_to_use_start([1:4 6 8]) = min(UTI_cases.SamplingDate); +dates_to_use_start(5) = min(UTI_cases.SamplingDate)+7*321; +dates_to_use_start(7) = min(UTI_cases.SamplingDate)+7*293; +dates_to_use_end(1:7) = max(UTI_cases.SamplingDate); +dates_to_use_end(8) = min(UTI_cases.SamplingDate)+7*293; + +%preallocate +num_gained_resistance_to_test = zeros(params.number_drugs); +total_num_treated = zeros(params.number_drugs); +num_lost_resistance_to_test = zeros(params.number_drugs); + +%for each antibiotic treated +for drug = 1:params.number_drugs + total_prch(drug) = nnz(UTI_cases.PCR_sameday(:,drug)); + dates_index_drug = find(UTI_cases.SamplingDate >= dates_to_use_start(drug) & UTI_cases.SamplingDate <= dates_to_use_end(drug)); + + %for each antibiotic suceptiblitly meased + for drug_to_test = 1:params.number_drugs + dates_index_test = find(UTI_cases.SamplingDate >= dates_to_use_start(drug_to_test) & UTI_cases.SamplingDate <= dates_to_use_end(drug_to_test)); + dates_index = intersect(dates_index_test , dates_index_drug); + all_sensitive_test = (UTI_cases.SMP_Res(dates_index,drug_to_test) == 1 | UTI_cases.SMP_Res(dates_index,drug_to_test) == 2) & UTI_cases.hasdiag(dates_index) ; + all_resistant_test = UTI_cases.SMP_Res(dates_index,drug_to_test) == 3 & UTI_cases.hasdiag(dates_index) ; + all_currentres = ismember(UTI_cases.SMP_Res(dates_index,drug),[1 2]) & ismember(UTI_cases.SMP_Res(dates_index,drug_to_test),[1 2 3]); + all_sensitive_nexttestres = UTI_cases.next_res(dates_index,drug_to_test) == 1 | UTI_cases.SMP_Res(dates_index,drug_to_test) == 2 ; + all_resistant_nexttestres = UTI_cases.next_res(dates_index,drug_to_test) == 3 ; + all_nextres = ismember(UTI_cases.next_res(dates_index,drug),[1 2 3]) & ismember(UTI_cases.next_res(dates_index,drug_to_test),[1 2 3]); + gained_resistance_to_test = all_sensitive_test & all_resistant_nexttestres & UTI_cases.PCR_sameday(dates_index,drug); + lost_resistance_to_test = all_resistant_test & all_sensitive_nexttestres & UTI_cases.PCR_sameday(dates_index,drug); + total_num_treated(drug,drug_to_test) = nnz(UTI_cases.PCR_sameday(dates_index,drug) & all_nextres & all_currentres); + num_gained_resistance_to_test(drug,drug_to_test) = nnz(gained_resistance_to_test & UTI_cases.treatfailure(dates_index) & all_nextres & all_currentres); + num_lost_resistance_to_test(drug,drug_to_test) = nnz(lost_resistance_to_test & UTI_cases.treatfailure(dates_index) & all_nextres & all_currentres); + end +end + +%% net change in resistance +rate_gained_resistance_to_test = num_gained_resistance_to_test./total_num_treated*100; +rate_lost_resistance_to_test = num_lost_resistance_to_test./total_num_treated*100; +rate_gained_resistance_to_test(rate_gained_resistance_to_test == Inf) = 0; +rate_lost_resistance_to_test(rate_lost_resistance_to_test == Inf) = 0; +net_change_res = rate_gained_resistance_to_test-rate_lost_resistance_to_test; +net_change_res(isnan(rate_lost_resistance_to_test)) = 0; +net_change_res = net_change_res(params.new_order, params.new_order); + +n = 10; +lost_res_num = 15; % for colormap +gained_res_num = 55; % for colormap +total_num = gained_res_num + lost_res_num; +%make colormap +cyan = [ linspace(0, 1, gained_res_num)' ones(gained_res_num,1) ones(gained_res_num,1)]; +magenta = [ ones(gained_res_num,1) linspace(0, 1, gained_res_num)' ones(gained_res_num,1)]; +magenta = flipud(magenta); +cyan_white_magenta = [cyan; magenta(1:lost_res_num,:)]; +colormap(flipud(cyan_white_magenta)) + + + +%% chance of failure untreated +num_gained_resistance_to_test = zeros(params.number_drugs, 1); +total_num_treated = zeros(params.number_drugs,1); +num_lost_resistance_to_test = zeros(params.number_drugs,1); + +for drug = 1:params.number_drugs + total_prch(drug) = nnz(UTI_cases.PCR_sameday(:,10)); + dates_index = find(UTI_cases.SamplingDate >= dates_to_use_start(drug) & UTI_cases.SamplingDate <= dates_to_use_end(drug)); + all_sensitive_test = (UTI_cases.SMP_Res(dates_index,drug) == 1 | UTI_cases.SMP_Res(dates_index,drug) == 2) & UTI_cases.hasdiag(dates_index) ; + all_resistant_test = UTI_cases.SMP_Res(dates_index,drug) == 3 & UTI_cases.hasdiag(dates_index) ; + all_currentres = ismember(UTI_cases.SMP_Res(dates_index,drug),[1 2 3]); + all_sensitive_nexttestres = UTI_cases.next_res(dates_index,drug) == 1 | UTI_cases.SMP_Res(dates_index,drug) == 2 ; + all_resistant_nexttestres = UTI_cases.next_res(dates_index,drug) == 3 ; + all_nextres = ismember(UTI_cases.next_res(dates_index,drug),[1 2 3]) & ismember(UTI_cases.next_res(dates_index,drug),[1 2 3]); + gained_resistance_to_test = all_sensitive_test & all_resistant_nexttestres & UTI_cases.PCR_sameday(dates_index,10); + lost_resistance_to_test = all_resistant_test & all_sensitive_nexttestres & UTI_cases.PCR_sameday(dates_index,10); + total_num_treated(drug) = nnz(UTI_cases.PCR_sameday(dates_index,10) & all_nextres & all_currentres); + num_gained_resistance_to_test(drug) = nnz(gained_resistance_to_test & UTI_cases.treatfailure(dates_index) & all_nextres & all_currentres); + num_lost_resistance_to_test(drug) = nnz(lost_resistance_to_test & UTI_cases.treatfailure(dates_index) & all_nextres & all_currentres); + +end +%% net change in resistance +rate_gained_resistance_to_test = num_gained_resistance_to_test./total_num_treated*100; +rate_lost_resistance_to_test = num_lost_resistance_to_test./total_num_treated*100; +rate_gained_resistance_to_test(rate_gained_resistance_to_test == Inf) = 0; +rate_lost_resistance_to_test(rate_lost_resistance_to_test == Inf) = 0; +D3 = rate_gained_resistance_to_test-rate_lost_resistance_to_test; + +%% make the plot + +image([rot90(net_change_res) flipud(D3)]*n+lost_res_num ) +xlabel('treatment antibiotic') +ylabel('susceptibiltiy of reccurent UTI') +colormap(flipud(cyan_white_magenta)) +xticks([1:1:params.number_drugs+1]) +set(gca,'xticklabel',[UTI_cases.SMP_Res_drug_names(params.new_order); 'Untreated']) +xtickangle(45); +yticks([1:1:params.number_drugs]) +set(gca,'yticklabel',flipud(UTI_cases.SMP_Res_drug_names(params.new_order))) +cbh = colorbar ; %Create Colorbar +x=5; +cbh.Ticks = linspace(0, length(colormap), 8)+x ; +ticknums = (linspace(-lost_res_num, gained_res_num, 8))/n+x/n; +cbh.TickLabels = num2cell(ticknums) ; +set(get(cbh,'label'),'string',{'net % of treated cases which changed';... + 'resistance to focal drug'}); +axis image + +end diff --git a/Wound_analysis/OR_wounds.m b/Wound_analysis/OR_wounds.m new file mode 100644 index 0000000..d44a616 --- /dev/null +++ b/Wound_analysis/OR_wounds.m @@ -0,0 +1,197 @@ +function [] = OR_wounds(wound_cases, params) +% function takes the wound_cases structure and params and performs +% regresion for all susceptibitlyi-matched treated cases which gained resistance +% and remained sensitive. Fuction writes table of regressoin coefficients +% to the Tables directory. + +any_previous_measurement = wound_cases.any_SRmeasurement; +previous_resistance = wound_cases.num_of_previous_R; +treatment_failures = wound_cases.treatfailure; +next_resistance_measurement = wound_cases.next_res; + +%Adjusted for following demographics: +X_age = wound_cases.Demog.Age; X_age(:,6) = []; % reference age +zeroto39 = sum(X_age(:,1:4),2); %binned to larger bin for lower age groups since less data +eightyplus = sum(X_age(:,end-1:end),2); +X_demog = [zeroto39 X_age(:,5:end-2) eightyplus, wound_cases.Demog.Gender, wound_cases.Demog.Preg]; +features = {'Age 0-39', 'Age 40-49', 'Age 60-69', 'Age 70-79', 'Age 80+', 'Gender', 'Pregnancy','Prev Resistance'}; + + +min_1 = 5; +clear y_SSR p_SSR ciu_SSR cil_SSR se_SSR +sen_res = params.resistant_group; % gain of resistance + +X_all_to_use = zeros(size(any_previous_measurement(:,params.number_drugs))); +Y_all_to_use = zeros(size(any_previous_measurement(:,params.number_drugs))); +Y_all = zeros(size(any_previous_measurement(:,params.number_drugs))); +X_all = zeros(size(X_demog,1),size(X_demog,2)+1); + + +for drug = 1:params.number_drugs +SMP_to_use = find(any_previous_measurement(:,drug)>0 & (wound_cases.SMP_Res(:,drug)== 1 | wound_cases.SMP_Res(:,drug)== 2) & next_resistance_measurement(:, drug) ~=0 ); +any_previous_R = previous_resistance(SMP_to_use ,drug)>0 ; +treatfailure = treatment_failures(SMP_to_use) ==1 & ismember(next_resistance_measurement(SMP_to_use, drug),sen_res) ; +drug_prch_temp = wound_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +X_all(SMP_to_use(drug_prch_temp==1,:),:) = X; +X_all_to_use(SMP_to_use(drug_prch_temp==1,:)) = 1; +Y_all(SMP_to_use(drug_prch_temp==1)) =Y; +Y_all_to_use(SMP_to_use(drug_prch_temp==1,:)) = 1; +end + +X_all(X_all_to_use == 0,:) = []; +Y_all(X_all_to_use == 0) = []; +c = my_fit(X_all, Y_all, min_1); +y_SSR(1) = exp(c.coef(end)); +p_SSR(1) = c.p(end); +se_SSR(1) = c.se(end); +cil_SSR(1) = exp(c.coef(end) - c.se(end)); +ciu_SSR(1) = exp(c.coef(end) + c.se(end)); + +%% print to table +features = pad(features); +yall = (c.coef(2:end)); +pall = c.p(2:end); +seall = c.se(2:end); +CIL = (c.coef(2:end) - c.se(2:end)); +CIU = (c.coef(2:end) + c.se(2:end)); +pstrs = cell(size(pall)) ; +for i = 1:size(pall,1) + for j = 1:size(pall,2) + pstrs{i,j} = '' ; + if pall(i,j)<0.01 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.001 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.0001, pstrs{i,j} = [pstrs{i,j}, '*']; end + end +end +fid = fopen('Tables/Table_AdgustedOR_SR_wounds.txt', 'w'); + + +fprintf(fid,'%-12s',''); +fprintf(fid,'\n') ; +for ii = 1:size(yall,1) + fprintf(fid,[features{ii} ' ']); + coefs_tmp = [yall(ii) CIL(ii) CIU(ii) pstrs(ii)]; + fprintf(fid,'%5.2f [%5.2f,%5.2f]%-3s ',coefs_tmp{:}) ; + fprintf(fid,'%-7s',''); +fprintf(fid,'\n') ; +end +fprintf(fid,'\n') ; +fprintf(fid,'* P<0.01 ** P<0.0001 *** P<0.000001\n\n\n'); +fclose(fid) ; +%% +sen_res = params.sensitive_group; % remain sensitive + +X_all_to_use = zeros(size(any_previous_measurement(:,drug))); +Y_all_to_use = zeros(size(any_previous_measurement(:,drug))); +Y_all = zeros(size(any_previous_measurement(:,drug))); +X_all = zeros(size(X_demog,1),size(X_demog,2)+1); + +seall = zeros(size(X_demog,2) +2, params.number_drugs); +yall = zeros(size(X_demog,2) +2, params.number_drugs); +pall = zeros(size(X_demog,2) +2, params.number_drugs); + +for drug = 1:params.number_drugs +SMP_to_use = find(any_previous_measurement(:,drug)>0 & (wound_cases.SMP_Res(:,drug)== 1 | wound_cases.SMP_Res(:,drug)== 2) & next_resistance_measurement(:, drug) ~=0 ); +any_previous_R = previous_resistance(SMP_to_use ,drug)>0 ; +treatfailure = treatment_failures(SMP_to_use) ==1 & ismember(next_resistance_measurement(SMP_to_use, drug),sen_res) ; +drug_prch_temp = wound_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +X_all(SMP_to_use(drug_prch_temp==1,:),:) = X; +X_all_to_use(SMP_to_use(drug_prch_temp==1,:)) = 1; +Y_all(SMP_to_use(drug_prch_temp==1)) =Y; +Y_all_to_use(SMP_to_use(drug_prch_temp==1,:)) = 1; +end +X_all(X_all_to_use == 0,:) = []; +Y_all(X_all_to_use == 0) = []; +c = my_fit(X_all, Y_all, min_1); +y_SSR(2) = exp(c.coef(end)); +p_SSR(2) = c.p(end); +se_SSR(2) = c.se(end); +cil_SSR(2) = exp(c.coef(end) - c.se(end)); +ciu_SSR(2) = exp(c.coef(end) + c.se(end)); + +%% plot figure +b1 = bar(y_SSR, 'FaceColor','flat', 'BarWidth', 0.8); +hold on + +b1(1).CData(1,:) = ones(1,1)*params.SR_color; +b1.CData(2,:) = ones(1,1)*params.SS_color; +%plot(b1.XData,cil_SSR,'kx'); +%plot(b1.XData,ciu_SSR,'kx'); +errneg = y_SSR - cil_SSR; +errpos = ciu_SSR -y_SSR; + +errorbar(b1.XData,y_SSR,errneg,errpos,'k', 'LineStyle','none'); + +hold on +for ii = 1:length(y_SSR) + if p_SSR(ii)< 0.05 && p_SSR(ii)> 0.005 + plot(b1.XData(ii), y_SSR(ii)+1, '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.005 && p_SSR(ii)> 0.0005 + plot([b1.XData(ii)-0.1 b1.XData(ii)+0.1] , [y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + elseif p_SSR(ii) <= 0.0005 + plot([b1.XData(ii)-0.2 b1.XData(ii) b1.XData(ii)+0.2] , [ y_SSR(ii)+1 y_SSR(ii)+1 y_SSR(ii)+1], '*k', 'MarkerSize',4) + end +end +% c.se(c.p> 0.05) = 0; +% hold on +% errorbar(c.coef(2:end),c.se(2:end),'.') +xticks((1:2:params.number_drugs*2)+0.5); +set(gca,'xticklabel','Wounds'); +xtickangle(45); + +ylabel({'Adjusted odds ratio of S-R failure for patients with';... + 'any previous resistance to the drug compared to sensitive'}); + +text(0,6.5,'{\it * P<0.05}'); +text(0,6,'{\it** P<0.005}'); +text(0,5.5,'{\it*** P<0.0005}'); + +set(gca, 'YScale', 'log'); +%ylim([0.2 10]) + +%% print to table +features = pad(features); + +yall = c.coef(2:end); +pall = c.p(2:end); +seall = c.se(2:end); +CIL = (c.coef(2:end) - c.se(2:end)); +CIU = (c.coef(2:end) + c.se(2:end)); + +% yall = y_SSR(2:end,:); +% pall = p_SSR(2:end,:); +% seall= se_SSR(2:end,:); +% CIL = cil_SSR; +% CIU = ciu_SSR; + +pstrs = cell(size(pall)) ; +for i = 1:size(pall,1) + for j = 1:size(pall,2) + pstrs{i,j} = '' ; + if pall(i,j)<0.01 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.001 , pstrs{i,j} = [pstrs{i,j}, '*']; end + if pall(i,j)<0.0001, pstrs{i,j} = [pstrs{i,j}, '*']; end + end +end + +fid = fopen('Tables/Table_AdgustedOR_SS_wounds.txt', 'w'); + + +fprintf(fid,'%-12s',''); +fprintf(fid,'\n') ; +for ii = 1:size(yall,1) + fprintf(fid,[features{ii} ' ']); + coefs_tmp = [yall(ii) CIL(ii) CIU(ii) pstrs(ii)]; + fprintf(fid,'%5.2f [%5.2f,%5.2f]%-3s ',coefs_tmp{:}) ; + fprintf(fid,'%-7s',''); +fprintf(fid,'\n') ; +end +fprintf(fid,'\n') ; +fprintf(fid,'* P<0.01 ** P<0.0001 *** P<0.000001\n\n\n'); +fclose(fid) ; diff --git a/Wound_analysis/Patient_demographics_table_wounds2.m b/Wound_analysis/Patient_demographics_table_wounds2.m new file mode 100644 index 0000000..bf10036 --- /dev/null +++ b/Wound_analysis/Patient_demographics_table_wounds2.m @@ -0,0 +1,95 @@ +function [] = Patient_demographics_table_wounds2(wound_cases, params) +% funtion takes wound_cases struc and makes a table of patient demographics numbers and % +% for all antibiotic treated cases. Writes table to the Tables directory. Table +% lists the following demographics: +names ={'Female'; 'Male';'Pregnant';'Age 0-9';'Age 10-19';... + 'Age 20-29';'Age 30-39';'Age 40-49';'Age 50-59';'Age 60-69';'Age 70-79';'Age 80-89';'Age >90';... + 'Prev SMPs 0-1'; 'Prev SMPs 2-4';'Prev SMPs 5+';}; + +%% only susceptibiltiy measured + +for drug= 1:params.number_drugs + relavant_suceptib_measured(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & wound_cases.SMP_Res(:, drug) ~= 0; + relavant_suceptib_notmeasured(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & wound_cases.SMP_Res(:, drug) == 0; + suceptib_matched(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & ismember(wound_cases.SMP_Res(:, drug), [1 2]); + suceptib_mismatched(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & ismember(wound_cases.SMP_Res(:, drug), 3); + treat_fail(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & wound_cases.treatfailure; +end + +relavant_suceptib_measured_any = (sum(relavant_suceptib_measured,2)); + +for drug = 1:params.number_drugs +val1(drug) = nnz(relavant_suceptib_notmeasured(:,drug)); +end + +wound_cases.hasdiag = relavant_suceptib_measured_any; % just the susceptibiltiy measured cases +Demog_treated = wound_cases.Demog(wound_cases.hasdiag & wound_cases.PCR_sameday_any ,:); +any_SRmeasurement_treated = wound_cases.any_SRmeasurement( wound_cases.PCR_sameday_any,:,1); %+ ... + +%% + +predictive_numbers(1) = nnz(Demog_treated.Gender); +predictive_numbers(2) = nnz(~Demog_treated.Gender); +predictive_numbers(3) = nnz(Demog_treated.Preg); + + +for ii = 1:10 +predictive_numbers(ii+3) = nnz(Demog_treated.Age(:,ii)); +end + +prev_smp_range = [0 1 4 ]; +any_SRmeasurement = max(any_SRmeasurement_treated,[],2); +predictive_numbers(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2))); +predictive_numbers(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3))); +predictive_numbers(16) = nnz(any_SRmeasurement > prev_smp_range(3)); + +predictive_per(1) = nnz(Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per(2) = nnz(~Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per(3) = nnz(Demog_treated.Preg)/length(Demog_treated.Gender); + +for ii = 1:10 +predictive_per(ii+3) = nnz(Demog_treated.Age(:,ii))/length(Demog_treated.Age(:,1)); +end + +predictive_per(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2)))/length(any_SRmeasurement); +predictive_per(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3)))/length(any_SRmeasurement); +predictive_per(16) = nnz(any_SRmeasurement > prev_smp_range(3))/length(any_SRmeasurement); +%% treatment failures +Demog_treated = wound_cases.Demog(wound_cases.hasdiag & wound_cases.PCR_sameday_any & wound_cases.treatfailure,:); +any_SRmeasurement_treated = wound_cases.any_SRmeasurement(wound_cases.hasdiag & wound_cases.PCR_sameday_any & wound_cases.treatfailure,:); + +predictive_numbers_fails(1) = nnz(Demog_treated.Gender); +predictive_numbers_fails(2) = nnz(~Demog_treated.Gender); +predictive_numbers_fails(3) = nnz(Demog_treated.Preg); + +for ii = 1:10 % age groups +predictive_numbers_fails(ii+3) = nnz(Demog_treated.Age(:,ii)); +end + +any_SRmeasurement = max(any_SRmeasurement_treated,[],2); +predictive_numbers_fails(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2))); +predictive_numbers_fails(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3))); +predictive_numbers_fails(16) = nnz(any_SRmeasurement > prev_smp_range(3)); +predictive_per_fails(1) = nnz(Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per_fails(2) = nnz(~Demog_treated.Gender)/length(Demog_treated.Gender); +predictive_per_fails(3) = nnz(Demog_treated.Preg)/length(Demog_treated.Gender); + +for ii = 1:10 +predictive_per_fails(ii+3) = nnz(Demog_treated.Age(:,ii))/length(Demog_treated.Age(:,1)); +end + +predictive_per_fails(14) = nnz(ismember(any_SRmeasurement ,prev_smp_range(1):prev_smp_range(2)))/length(any_SRmeasurement); +predictive_per_fails(15) = nnz(ismember(any_SRmeasurement ,prev_smp_range(2)+1:prev_smp_range(3)))/length(any_SRmeasurement); +predictive_per_fails(16) = nnz(any_SRmeasurement > prev_smp_range(3))/length(any_SRmeasurement); + +%% make table + + Demographics_table_cases = table(names,predictive_numbers',round(predictive_per*100)'... + ,predictive_numbers_fails',round(predictive_per_fails*100)'); + +filename = 'Tables/Patient_demographics_table_wounds.xlsx'; +writetable(Demographics_table_cases,filename); + +% sum(Demographics_table_cases.Var2(1:2)) +% sum(Demographics_table_cases.Var2(5:14)) +end \ No newline at end of file diff --git a/Wound_analysis/README.txt b/Wound_analysis/README.txt new file mode 100644 index 0000000..03970ec --- /dev/null +++ b/Wound_analysis/README.txt @@ -0,0 +1,25 @@ +Run the main script wound_analysis_and_figures.m to perform the analysis and generate the figures. +The code requires the wound_cases structure, which contains the following data: + + SMP_Res_drug_names: {5×1 cell} % cell array of names of each antibiotic susceptibiltiy measured. + RandomID: [7365×1 double] % array of unique patient identifier for each case + SMP_Res: [7365×5 double] % array of current infection susceptibiltiy to each antibiotic. S = 1, I = 2, R = 3, 0 = unmeasured. If multiple isolates, maximal resistance is used. + num_of_previous_R: [7365×5 double] % array of number of previous infections patient has had which were resistant to each antibiotic. + num_of_previous_S: [7365×5 double] % array of number of previous infections patient has had which were sensitive to each antibiotic. + any_SRmeasurement: [7365×5 double] % array of number of previous infections patient has had with any susceptibiltiy measured to each antibiotic + num_of_previous_SMPs: [7365×1 double] % array of number of previous infections patient has had. + SamplingDate: [7365×1 double] % array of date of current sample + bug_all: {7365×1 cell} % cell array of species code for all isolates in current infection. + new_bug: {7365×1 cell} % cell array of species code for all isolates in future recurrent infection. NaN if no recurrence. + nBac: [7365×1 double] % number of isolated in current infection. + RES: {7365×5 cell} % suceptibilty of each isolate in current infection. + new_RES: {7365×5 cell} % suceptibilty of each isolate in future recurrent infection. NaN if no recurrence. + next_res: [7365×5 double] % array of future recurrent infection maximal resistance to each antibiotic. NaN if no recurrence. + date_diff: [7365×1 double] % number of days between current and future recurrent infection. NaN if no recurrence. + treatfailure: [7365×1 logical] % logical array id case resulted in early recurrence within 28 days. + PCR_sameday_any: [7365×1 logical] % logical vector if any of the 5 antibiotics were prescribed + PCR_sameday: [7365×5 logical] % logical array of which antibitoic was prescribed. + PCR_sameday_names: {1×5 cell} % names of each prescribed antibitoics. + Demog: [7365×4 table] % table of demographics of each wound case, including age bracket, gender, pregnancy. + agem: [10×1 double] % midpoint of each age bracket in demograhics. + Bugs: [609×2 table] % table of species names and codes. \ No newline at end of file diff --git a/Wound_analysis/changed_res_bac_alldrugs_wounds.m b/Wound_analysis/changed_res_bac_alldrugs_wounds.m new file mode 100644 index 0000000..bb9bf96 --- /dev/null +++ b/Wound_analysis/changed_res_bac_alldrugs_wounds.m @@ -0,0 +1,52 @@ +function [] = changed_res_bac_alldrugs_wounds(wound_cases,params) +%function takes the wound_cases structure and optional params and calulates +% the rate of change of species in gained-resistance early recurrences + +treatfailure = wound_cases.treatfailure; +clear ratio_error +for drug = 1:params.number_drugs + +%next res is resistant +index = cellfun(@(x) x==3, wound_cases.new_RES(:,drug),'UniformOutput',false); +%only resistant next wound_cases.Bugs +resistant_nextres_wound_cases.Bugs = cellfun(@(v,x)v(x),wound_cases.new_bug,index,'UniformOutput',false); +%are any of the next resistant wound_cases.Bugs not those in original infection +[M2,X2] = cellfun(@ismember,resistant_nextres_wound_cases.Bugs,wound_cases.bug_all,'UniformOutput',false); + +resistant_nextres_wound_cases.Bugs_members = cellfun(@(v,x)v(x),wound_cases.new_bug,M2,'UniformOutput',false); +M3 = cellfun(@not,M2,'UniformOutput',false); +resistant_nextres_wound_cases.Bugs_notmembers = cellfun(@(v,x)v(x),wound_cases.new_bug,M3,'UniformOutput',false); + +initially_sensitive = (wound_cases.SMP_Res(:,drug) == 1 | wound_cases.SMP_Res(:,drug) == 2); + +to_use = find(initially_sensitive & treatfailure & wound_cases.PCR_sameday(:,drug)); + +changed_species = cell2mat( resistant_nextres_wound_cases.Bugs_notmembers(to_use)); +[GC,GR] = groupcounts(changed_species) ; +table(wound_cases.Bugs.Name(ismember(wound_cases.Bugs.Code, GR)),GC); + +same_species = cell2mat( resistant_nextres_wound_cases.Bugs_members(to_use)); +[GC,GR] = groupcounts(same_species) ; +table(wound_cases.Bugs.Name(ismember(wound_cases.Bugs.Code, GR)),GC); + +changed(drug) = length(changed_species); +stayed(drug) = length(same_species); + +ratio_changed(drug) = changed(drug)./(changed(drug) + stayed(drug)); +ratio_error(drug) = sqrt((ratio_changed(drug)).*(1-(ratio_changed(drug)))./(changed(drug)+stayed(drug))); + nums(drug) = (changed(drug) + stayed(drug)) ; + +end + +ratio_changed2 = sum(changed)./(sum(changed) + sum(stayed)); +ratio_error2 = sqrt((ratio_changed2).*(1-(ratio_changed2))./(sum(changed) + sum(stayed))); +% ratio_changed2(2) = 0.7466; +% ratio_error2(2) = 0.0253; +bar(ratio_changed2, 'FaceColor',params.SR_color) +xticklabels({'Wounds'}) +xtickangle(45) +hold on +errorbar(1:length(ratio_changed2),ratio_changed2,ratio_error2, 'k', 'LineStyle','none') +ylabel('% of SR caused by different species') +ylim([0 1]) + diff --git a/Wound_analysis/fail_split_by_week_SIR_all_wound.m b/Wound_analysis/fail_split_by_week_SIR_all_wound.m new file mode 100644 index 0000000..52cad56 --- /dev/null +++ b/Wound_analysis/fail_split_by_week_SIR_all_wound.m @@ -0,0 +1,125 @@ +function [] = fail_split_by_week_SIR_all_wound(wound_cases, params) + +clear ratio1 fail_split1 all_sensitive1 all_sensitive_purchased1 sensitive_purchased_fails1 sensitive_purchased_fails_SS sensitive_purchased_fails_SR +clear ratio_noprch1 fail_split_noprch1 fail_split_adjusted fail_split_noprch_adjusted1 ratio_error1 number_prch1 ratio_noprch_error1 number_noprch1 +clear ratio_res1 fail_split_res1 +clear ratio_noprch1 fail_split_noprch_res1 fail_split2 fail_split_res2 +wound_cases.hasdiag = true(size(wound_cases.RandomID)); + +av_window = 7; +days = 4:1:50; +for kk = 1:length(days)-1 +clear treatfailure +treatfailure = wound_cases.date_diff >= days(kk) & wound_cases.date_diff < days(kk)+av_window; + +for drug = 1:params.number_drugs + + total_prch1(drug) = nnz(wound_cases.PCR_sameday(:,drug)); + + %all_sensitive = wound_cases.SMP_Res(:,drug) == 1 | wound_cases.SMP_Res(:,drug) == 2 ; + all_sensitive1 = ismember(wound_cases.SMP_Res(:,drug), params.sensitive_group) & wound_cases.hasdiag; + all_resistant1 = ismember(wound_cases.SMP_Res(:,drug), params.resistant_group) & wound_cases.hasdiag; + + all_sensitive_nextres1 = ismember(wound_cases.next_res(:,drug), params.sensitive_group) ; + all_resistant_nextres1 = ismember(wound_cases.next_res(:,drug), params.resistant_group) ; + all_nextres = ismember(wound_cases.next_res(:,drug),[1 2 3]); + + all_sensitive_purchased1(drug ,kk) = nnz((all_sensitive1 | all_resistant1) & wound_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails1(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure); + sensitive_purchased_nextresfails1(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + + sensitive_purchased_fails_SS(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + sensitive_purchased_fails_SR(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + + ratio1(drug,kk) = sensitive_purchased_fails1(drug ,kk)/all_sensitive_purchased1(drug ,kk)*100; + number_prch1(drug) = all_sensitive_purchased1(drug ,kk); + ratio_error1(drug ,kk) = sqrt((ratio1(drug,kk)/100).*(1-(ratio1(drug,kk)/100))./(all_sensitive_purchased1(drug,kk)))*100; + fail_split1(1:2,kk, drug) = [sensitive_purchased_fails_SS(drug ,kk)/sensitive_purchased_nextresfails1(drug ,kk) ; sensitive_purchased_fails_SR(drug ,kk)/sensitive_purchased_nextresfails1(drug ,kk)]*ratio1(drug,kk); + SR_error1(drug,kk) = sqrt((fail_split1(2,kk, drug)/100).*(1-(fail_split1(2,kk, drug)/100))./(all_sensitive_purchased1(drug,kk)))*100; + + + %all_resistant_purchased = nnz(all_resistant & wound_cases.PCR_sameday(:,drug)); + all_resistant_purchased(drug ,kk) = nnz((all_sensitive1 | all_resistant1) & wound_cases.PCR_sameday(:,drug)); + resistant_purchased_fails(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure); + resistant_purchased_nextresfails(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + resistant_purchased_fails_RS(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + resistant_purchased_fails_RR(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + + ratio_res1(drug,kk) = resistant_purchased_fails(drug ,kk)/all_resistant_purchased(drug ,kk)*100; + number_prch_res1(drug) = all_resistant_purchased(drug ,kk); + ratio_error_res1(drug,kk) = sqrt((ratio_res1(drug,kk)/100).*(1-(ratio_res1(drug,kk)/100))./(all_resistant_purchased(drug,kk)))*100; + fail_split_res1(1:2,kk, drug) = [resistant_purchased_fails_RR(drug ,kk)/resistant_purchased_nextresfails(drug ,kk) ; resistant_purchased_fails_RS(drug ,kk)/resistant_purchased_nextresfails(drug ,kk)]*ratio_res1(drug,kk); + SR_error_res1(drug,kk) = sqrt((fail_split_res1(2,kk, drug)/100).*(1-(fail_split_res1(2,kk, drug)/100))./(all_resistant_purchased(drug,kk)))*100; + + + %just_cleared(drug) = (100 -ratio(drug)) +(sensitive_purchased_fails_SS/sensitive_purchased_nextresfails)*ratio(drug); + %fail_split_adjusted(1,drug) = ((sensitive_purchased_fails_SR/sensitive_purchased_nextresfails)*ratio(drug))/just_cleared(drug)*100; + + %all_sensitive_noprch = nnz(all_sensitive & wound_cases.PCR_sameday(:,10)); + all_sensitive_noprch1 = nnz((all_sensitive1 | all_resistant1) & wound_cases.PCR_sameday(:,10)); + sensitive_noprch_fails1 = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,10) & treatfailure ); + sensitive_noprch_nextresfails1 = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,10) & treatfailure & all_nextres); + + sensitive_noprch_fails_SS = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,10) & treatfailure & all_sensitive_nextres1); + sensitive_noprch_fails_SR = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,10) & treatfailure & all_resistant_nextres1); + + ratio_noprch1(drug,kk) = sensitive_noprch_fails1/all_sensitive_noprch1*100; + number_noprch1(drug) = all_sensitive_noprch1; + ratio_noprch_error1(drug,kk) = sqrt((ratio_noprch1(drug,kk)/100).*(1-(ratio_noprch1(drug,kk)/100))./(all_sensitive_noprch1))*100; + fail_split_noprch1(1:2,kk, drug) = [sensitive_noprch_fails_SS/sensitive_noprch_nextresfails1 ; sensitive_noprch_fails_SR/sensitive_noprch_nextresfails1]*ratio_noprch1(drug,kk); + SR_noprch_error1(drug,kk) = sqrt((fail_split_noprch1(2,kk, drug)/100).*(1-(fail_split_noprch1(2,kk, drug)/100))./(all_sensitive_noprch1))*100; + + + %all_resistant_noprch = nnz(all_resistant & wound_cases.PCR_sameday(:,10)); + all_resistant_noprch1 = nnz((all_sensitive1 | all_resistant1) & wound_cases.PCR_sameday(:,10)); + resistant_noprch_fails1 = nnz(all_resistant1 & wound_cases.PCR_sameday(:,10) & treatfailure); + resistant_noprch_nextresfails1 = nnz(all_resistant1 & wound_cases.PCR_sameday(:,10) & treatfailure & all_nextres); + resistant_noprch_fails_RS = nnz(all_resistant1 & wound_cases.PCR_sameday(:,10) & treatfailure & all_sensitive_nextres1); + resistant_noprch_fails_RR = nnz(all_resistant1 & wound_cases.PCR_sameday(:,10) & treatfailure & all_resistant_nextres1); + + ratio_noprch_res1(drug,kk) = resistant_noprch_fails1/all_resistant_noprch1*100; + number_noprch_res1(drug) = all_resistant_noprch1; + ratio_error_res1(drug,kk) = sqrt((ratio_noprch_res1(drug,kk)/100).*(1-(ratio_noprch_res1(drug,kk)/100))./(all_resistant_noprch1))*100; + fail_split_noprch_res1(1:2,kk, drug) = [resistant_noprch_fails_RR/resistant_noprch_nextresfails1 ; resistant_noprch_fails_RS/resistant_noprch_nextresfails1]*ratio_noprch_res1(drug,kk); + SR_error_noprch_res1(drug,kk) = sqrt((fail_split_noprch_res1(2,kk, drug)/100).*(1-(fail_split_noprch_res1(2,kk, drug)/100))./(all_resistant_noprch1))*100; + %just_cleared_noprch(drug) = (100 -ratio_noprch(drug)) +(sensitive_noprch_fails_SS/sensitive_noprch_nextresfails)*ratio_noprch(drug); + %fail_split_noprch_adjusted(1,drug) = ((sensitive_noprch_fails_SR/sensitive_noprch_nextresfails)*ratio_noprch(drug))/just_cleared_noprch(drug)*100; + + %total_error(drug) = sqrt(P.*(1-P)./(n)) + + +end + +fail_split1_all(1:2,kk, 1) = [sum(sensitive_purchased_fails_SS(1:params.number_drugs ,kk))/sum(sensitive_purchased_nextresfails1(1:params.number_drugs ,kk)) ; sum(sensitive_purchased_fails_SR(1:params.number_drugs ,kk))/sum(sensitive_purchased_nextresfails1(1:params.number_drugs ,kk))]*(sum(sensitive_purchased_fails1(1:params.number_drugs ,kk))/sum(all_sensitive_purchased1(1:params.number_drugs))*100); +fail_split_res1_all(1:2,kk, 1) = [sum(resistant_purchased_fails_RR(1:params.number_drugs ,kk))/sum(resistant_purchased_nextresfails(1:params.number_drugs ,kk)) ; sum(resistant_purchased_fails_RS(1:params.number_drugs ,kk))/sum(resistant_purchased_nextresfails(1:params.number_drugs ,kk))]*(sum(resistant_purchased_fails(1:params.number_drugs ,kk))/sum(all_resistant_purchased(1:params.number_drugs))*100); + + +end + +fail_split2(:,:,1) = fail_split1_all(:,:,1); +fail_split_res2(:,:,1) = fail_split_res1_all(:,:,1); +% fail_split2(:,:,1) = mean(fail_split1(:,:,1:params.number_drugs),3); +% fail_split_res2(:,:,1) = mean(fail_split_res1(:,:,1:params.number_drugs),3); +% + +%b1 = bar(1:length(days)-1,[fail_split1(:,:,drug)',fail_split_res1(:,:,drug)']./av_window, 'stacked' , 'FaceColor','flat', 'EdgeColor', 'none', 'BarWidth', 1); +b1 = bar(1:length(days)-1,[fail_split2(:,:,1)',fail_split_res2(:,:,1)']./av_window, 'stacked' , 'FaceColor','flat', 'EdgeColor', 'none', 'BarWidth', 1); + +b1(1).CData(:,:) = ones(length(days)-1,1)*fig_colors.SS_color; +b1(2).CData(:,:) = ones(length(days)-1,1)*fig_colors.SR_color; +b1(3).CData(:,:) = ones(length(days)-1,1)*fig_colors.RR_color; +b1(4).CData(:,:) = ones(length(days)-1,1)*fig_colors.RS_color; + +ylabel('% of patients'); +set(gca,'XTick',1:8:length(days)); +days_string = num2str((days(1:8:length(days)))'); +set(gca,'xticklabel',days_string); +xlabel('# of days between first and second sample'); +xlim([0.5 length(days)-0.5]) +hold on +yl = ylim; +plot([28-days(1)+1 28-days(1)+1],yl, 'k--'); + +%set(gca,'yticklabel',nums_string); +% xtickangle(45); + diff --git a/Wound_analysis/mismatched_vs_mathced_recurrence_rate_wounds.m b/Wound_analysis/mismatched_vs_mathced_recurrence_rate_wounds.m new file mode 100644 index 0000000..72f2006 --- /dev/null +++ b/Wound_analysis/mismatched_vs_mathced_recurrence_rate_wounds.m @@ -0,0 +1,87 @@ +function []= mismatched_vs_mathced_recurrence_rate_wounds(wound_cases,params) +% function takes UTI_case struc and optional params and makes bar chart of +% the % of early recurrences for sensitivity matched and mismatched antibiotic +% treated cases. + +% pre-allocate +total_prch = zeros(1,params.number_drugs); +all_sensitive_purchased = zeros(1,params.number_drugs); +sensitive_purchased_fails = zeros(1,params.number_drugs); +sensitive_purchased_nextresfails = zeros(1,params.number_drugs); +sensitive_purchased_fails_SS = zeros(1,params.number_drugs); +sensitive_purchased_fails_SR = zeros(1,params.number_drugs); +all_resistant_purchased = zeros(1,params.number_drugs); +resistant_purchased_fails = zeros(1,params.number_drugs); +resistant_purchased_nextresfails = zeros(1,params.number_drugs); +resistant_purchased_fails_RS = zeros(1,params.number_drugs); +resistant_purchased_fails_RR = zeros(1,params.number_drugs); + +% loop over all antibiotics +for drug = 1:params.number_drugs + total_prch(drug) = nnz(wound_cases.PCR_sameday(:,drug) ); + all_sensitive = (ismember(wound_cases.SMP_Res(:,drug), params.sensitive_group)) ; + all_reistant = (ismember(wound_cases.SMP_Res(:,drug), params.resistant_group)) ; + + all_sensitive_nextres = ismember(wound_cases.next_res(:,drug),params.sensitive_group); + all_resistant_nextres = ismember(wound_cases.next_res(:,drug),params.resistant_group); + all_nextres = ismember(wound_cases.next_res(:,drug),[1 2 3]); + + all_sensitive_purchased(drug) = nnz(all_sensitive & wound_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails(drug) = nnz(all_sensitive & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure); + sensitive_purchased_nextresfails(drug) = nnz(all_sensitive & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure & all_nextres); + + sensitive_purchased_fails_SS(drug) = nnz(all_sensitive & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure & all_sensitive_nextres); + sensitive_purchased_fails_SR(drug) = nnz(all_sensitive & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure & all_resistant_nextres); + + all_resistant_purchased(drug) = nnz(all_reistant & wound_cases.PCR_sameday(:,drug)); + resistant_purchased_fails(drug) = nnz(all_reistant & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure); + resistant_purchased_nextresfails(drug) = nnz(all_reistant & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure & all_nextres); + + resistant_purchased_fails_RS(drug) = nnz(all_reistant & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure & all_sensitive_nextres); + resistant_purchased_fails_RR(drug) = nnz(all_reistant & wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure & all_resistant_nextres); +end + +% sum the numbers from all antibiotics +all_ratio = sum(sensitive_purchased_fails)/sum(all_sensitive_purchased)*100; +all_fail_split = [sum(sensitive_purchased_fails_SS)/sum(sensitive_purchased_nextresfails) ; sum(sensitive_purchased_fails_SR)/sum(sensitive_purchased_nextresfails)]*all_ratio; +all_fail_split_error = sqrt((all_ratio/100).*(1-(all_ratio/100))./(sum(all_sensitive_purchased)))*100; + +all_resistant_ratio = sum(resistant_purchased_fails)/sum(all_resistant_purchased)*100; +all_resistant_fail_split = [sum(resistant_purchased_fails_RS)/sum(resistant_purchased_nextresfails) ; sum(resistant_purchased_fails_RR)/sum(resistant_purchased_nextresfails)]*all_resistant_ratio; +all_resistant_fail_split_error = sqrt((all_resistant_ratio/100).*(1-(all_resistant_ratio/100))./(sum(all_resistant_purchased)))*100; + + +%% print bar chart +width = 0.5; +ii = 1; + hold on +xpos = 2;%gap+0.32; +hd1 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [0 0 all_fail_split(2,ii) all_fail_split(2,ii)],... + 'w','EdgeColor','k', 'FaceColor', params.SR_color); +hd2 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [all_fail_split(2,ii) all_fail_split(2,ii) ... + (all_fail_split(1,ii)+all_fail_split(2,ii)) ... + (all_fail_split(1,ii)+all_fail_split(2,ii))],... + 'w','EdgeColor','k', 'FaceColor', params.SS_color); +errorbar(xpos,(all_fail_split(1,ii)+all_fail_split(2,ii)),all_fail_split_error(ii), 'k', 'LineStyle','none') + +hold on +xpos = 1;%gap-0.32; +hd1 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [0 0 all_resistant_fail_split(2,ii) all_resistant_fail_split(2,ii)],... + 'w','EdgeColor','k', 'FaceColor', params.RR_color); +hd2 = patch([xpos-width/2 xpos+width/2 xpos+width/2 xpos-width/2],... + [all_resistant_fail_split(2,ii) all_resistant_fail_split(2,ii) ... + (all_resistant_fail_split(1,ii)+all_resistant_fail_split(2,ii)) ... + (all_resistant_fail_split(1,ii)+all_resistant_fail_split(2,ii))],... + 'w','EdgeColor','k', 'FaceColor', params.RS_color); +errorbar(xpos,(all_resistant_fail_split(1,ii)+all_resistant_fail_split(2,ii)),all_resistant_fail_split_error(ii), 'k', 'LineStyle','none') + +ylabel({'percentage of wound infections' ; 'resulting in early recurrence'}) +set(gca,'XTick',[1 2]); +set(gca,'xticklabel',{'mismatched','mathced'}); +xtickangle(45); + +ylim([0 12]) +end \ No newline at end of file diff --git a/Wound_analysis/mode_of_reccurence_pie_charts_wounds.m b/Wound_analysis/mode_of_reccurence_pie_charts_wounds.m new file mode 100644 index 0000000..59194e9 --- /dev/null +++ b/Wound_analysis/mode_of_reccurence_pie_charts_wounds.m @@ -0,0 +1,102 @@ +function [] = mode_of_reccurence_pie_charts_wounds(wound_cases, params) +% function takes wound_cases strcut and optional params and makes pie charts of +% the % of early recurrences and their mode of recurrence for all antibiotic +% treated cases. + + +%define fig properties +figure +Names = wound_cases.SMP_Res_drug_names; +set(gcf,'color','w', 'name','Fig. 1H'); +left_val = 5; +bottom_val = 5; +width_val = 17; +height_val = 10; +set(gcf,'units','centimeters','Position',[left_val bottom_val width_val height_val]); + + +for drug = 1:params.number_drugs + total_prch1(drug) = nnz(wound_cases.PCR_sameday(:,drug)); + num_fails(drug) = nnz(wound_cases.PCR_sameday(:,drug) & wound_cases.treatfailure); + + total_prch_matched(drug) = nnz(wound_cases.PCR_sameday(:,drug) & ismember(wound_cases.SMP_Res(:,drug),[1 2])); + total_prch_mismatched(drug) = nnz(wound_cases.PCR_sameday(:,drug) & ismember(wound_cases.SMP_Res(:,drug),3)); + + total_prch_matched_fails(drug) = nnz(wound_cases.PCR_sameday(:,drug) & ismember(wound_cases.SMP_Res(:,drug),[1 2]) & wound_cases.treatfailure); + total_prch_mismatched_fails(drug) = nnz(wound_cases.PCR_sameday(:,drug) & ismember(wound_cases.SMP_Res(:,drug),3) & wound_cases.treatfailure); + + total_prch_matched_clear(drug) = nnz(wound_cases.PCR_sameday(:,drug) & ismember(wound_cases.SMP_Res(:,drug),[1 2]) & ~wound_cases.treatfailure); + total_prch_mismatched_clear(drug) = nnz(wound_cases.PCR_sameday(:,drug) & ismember(wound_cases.SMP_Res(:,drug),3) & ~wound_cases.treatfailure); +end + +num_total_prch = sum(total_prch_matched) + sum(total_prch_mismatched); +num_early_rec = sum(num_fails)/sum(total_prch1); +fprintf('The total number of treated infections is %i\n',num_total_prch); +fprintf('The percentage number of early recurrences is %2.1f\n',num_early_rec*100); + +num_early_rec = (sum(total_prch_mismatched_fails)+sum(total_prch_matched_fails)); +num_prch_matched_clear = sum(total_prch_matched_clear); +num_prch_mismatched_clear = sum(total_prch_mismatched_clear); + +per_early_rec = num_early_rec/(sum(total_prch_mismatched)+sum(total_prch_matched)); +per_prch_matched_clear = num_prch_matched_clear/(sum(total_prch_mismatched)+sum(total_prch_matched)); +per_prch_mismatched_clear = num_prch_mismatched_clear/(sum(total_prch_mismatched)+sum(total_prch_matched)); + +t = tiledlayout(3,5, 'Padding','tight'); +nexttile(1,[2 2]); +pie([per_early_rec per_prch_matched_clear per_prch_mismatched_clear ], ... + {sprintf('early reccurrence \n %d',num_early_rec),... + sprintf('S->0 \n %d',num_prch_matched_clear),... + sprintf('R->0 \n %d',num_prch_mismatched_clear)}); +ax = gca(); +ax.Colormap = [[0.32 0.32 0.32]; [0.74, 0.74, 0.98]; [0.98, 0.79, 0.79]]; +title('all treated UTIs') + + +% +no_measurement = wound_cases.SMP_Res == 0; +no_next_measurement = wound_cases.next_res == 0 | isnan(wound_cases.next_res); +no_measurement_either_all = no_measurement | no_next_measurement; +no_measurement_either = no_measurement_either_all(wound_cases.treatfailure == 1,:); +CurrentRes = wound_cases.SMP_Res(wound_cases.treatfailure == 1,:) ; +CurrentRes = ismember(CurrentRes,params.resistant_group); +NextRes = wound_cases.next_res(wound_cases.treatfailure == 1,:); +NextRes = ismember(NextRes,params.resistant_group); +SS = ~CurrentRes & ~NextRes & ~no_measurement_either; +SR = ~CurrentRes & NextRes & ~no_measurement_either; +RS = CurrentRes & ~NextRes & ~no_measurement_either; +RR = CurrentRes & NextRes & ~no_measurement_either; +drug_prch_fails = wound_cases.PCR_sameday(wound_cases.treatfailure,:); + +for ii = 1:params.number_drugs +SS_drugprch = SS(drug_prch_fails(:,ii),ii); +SR_drugprch = SR(drug_prch_fails(:,ii),ii); +RS_drugprch = RS(drug_prch_fails(:,ii),ii); +RR_drugprch = RR(drug_prch_fails(:,ii),ii); + +SSnum(ii) = length(SS_drugprch(SS_drugprch)); +SRnum(ii) = length(SR_drugprch(SR_drugprch)); +RSnum(ii) = length(RS_drugprch(RS_drugprch)); +RRnum(ii) = length(RR_drugprch(RR_drugprch)); +total(ii) = SSnum(ii) + SRnum(ii) + RSnum(ii) + RRnum(ii) ; +fraction = [ RRnum(ii) RSnum(ii) SRnum(ii) SSnum(ii)]./total(ii); + +ax = nexttile(10+ii); +pie(fraction); +ax.Colormap = [params.RR_color; params.RS_color; params.SR_color; params.SS_color]; +TextChildren = findobj(ax,'Type','text'); +set(TextChildren,'visible','off') + +title(Names{ii}) +savefraction(:,ii) = fraction; + +clear fraction SS_drugprch SR_drugprch RS_drugprch RR_drugprch +end + +fraction = [sum(RRnum) sum(RSnum) sum(SRnum) sum(SSnum) ]./(sum(SSnum) + sum(SRnum) + sum(RSnum) + sum(RRnum)); +nexttile(3,[2 2]) +pie(fraction); +ax = gca(); +ax.Colormap = [params.RR_color; params.RS_color; params.SR_color; params.SS_color]; + +end diff --git a/Wound_analysis/my_fit.m b/Wound_analysis/my_fit.m new file mode 100644 index 0000000..dd367a8 --- /dev/null +++ b/Wound_analysis/my_fit.m @@ -0,0 +1,55 @@ +function c = my_fit(X,Y,n0,link) + +if nargin<3 + n0 = 0 ; % minimal number of zeros and ones +end +if nargin<4 + link = 'logit' ; +end +sumX0 = sum(Xmin(X)) ; +kv = sumX0>=n0 & sumX1>=n0 ; % variables to include +X = X(:,kv) ; + +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial',link) ; +c.coef = glm.stats.beta ; +c.se = glm.stats.se ; +c.p = glm.stats.p ; +c.t = glm.stats.t ; +c.dfe = glm.stats.dfe ; +c.covb = glm.stats.covb ; +c.rmse = glm.stats.sfit ; +c.coeffcorr = glm.stats.coeffcorr ; + +kv = [true, kv] ; +c.coef = addnans(c.coef,kv,1) ; +c.se = addnans(c.se ,kv,1) ; +c.p = addnans(c.p ,kv,1) ; +c.t = addnans(c.t ,kv,1) ; +c.covb = addnans(c.covb,kv,3) ; +c.coeffcorr = addnans(c.coeffcorr,kv,3) ; + +c.sumX0 = sumX0 ; +c.sumX1 = sumX1 ; +c.sumY0 = sum(Y==0) ; +c.sumY1 = sum(Y>0) ; +c.totallines = size(X,1) ; +c.remove = ~kv ; + +end + +function xn = addnans(x,k,dim) +switch dim + case 1 + xn(k,:) = x ; + xn(~k,:) = nan ; + case 2 + xn(:,k) = x ; + xn(:,~k) = nan ; + case 3 + xn(k,k) = x ; + xn(:,~k) = nan ; + xn(~k,:) = nan ; +end +end + diff --git a/Wound_analysis/num_sucep_matched.m b/Wound_analysis/num_sucep_matched.m new file mode 100644 index 0000000..762e67c --- /dev/null +++ b/Wound_analysis/num_sucep_matched.m @@ -0,0 +1,13 @@ +for drug= 1:5 + relavant_suceptib_measured(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & wound_cases.SMP_Res(:, drug) ~= 0; + relavant_suceptib_notmeasured(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & wound_cases.SMP_Res(:, drug) == 0; + suceptib_matched(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & ismember(wound_cases.SMP_Res(:, drug), [1 2]); + suceptib_mismatched(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & ismember(wound_cases.SMP_Res(:, drug), 3); + treat_fail(:,drug) = wound_cases.PCR_sameday(:,drug) == 1 & wound_cases.treatfailure; +end + +relavant_suceptib_measured_any = (sum(relavant_suceptib_measured,2)); + +nnz(relavant_suceptib_measured) + +nnz(sum(suceptib_matched,2)) \ No newline at end of file diff --git a/Wound_analysis/rate_res_by_species_wounds.m b/Wound_analysis/rate_res_by_species_wounds.m new file mode 100644 index 0000000..6195f56 --- /dev/null +++ b/Wound_analysis/rate_res_by_species_wounds.m @@ -0,0 +1,60 @@ +function [] = rate_res_by_species_wounds(wound_cases, params) +% function takes UTI_case structure and optional params and plots pie charts of the +% rate of resistance for each of most commmon species + + +all_bugs = cell2mat(wound_cases.bug_all); +all_res= cell2mat(wound_cases.RES); + +bug = cell2mat(wound_cases.bug_all); +SMP_Res = cell2mat(wound_cases.RES); +Names = wound_cases.SMP_Res_drug_names; +pos2 = [0 0.05 0.1 0.1] ;%[left bottom width height] +for kk = [ 280 179 292 347] % codes for 4 most common species +for drug = 1:params.number_drugs +pos2(1) = pos2(1)+0.1; +subplot('Position',pos2) +yes_measurement = SMP_Res(:,drug)>0 & bug == kk; +number_resistant(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),3)); +number_intermediate(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[2])); +number_sensitive(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[1])); + +fractionR(drug) = (number_resistant(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionI(drug) = (number_intermediate(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionS(drug) = (number_sensitive(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); + +if ~isnan(fractionS(drug)*fractionI(drug)*fractionR(drug)) +pie([fractionS(drug),fractionI(drug), fractionR(drug)]); +set(findobj(gca,'type','text'),'fontsize',7.5); +%labels = repmat({''},size(fractionS)); +%title(Names{drug}) +cmap = [150 150 150 ; 75 75 75 ; 0 0 0]./255; +colormap(gca, cmap) +end +end +text(0, pos2(2), wound_cases.Bugs.Name(find(wound_cases.Bugs.Code == kk))); +pos2 = [0 pos2(2) 0.1 0.1]; +pos2(2) = pos2(2)+0.2; +end + +%% +for drug = 1:params.number_drugs +pos2(1) = pos2(1)+0.1; +subplot('Position',pos2); +yes_measurement = SMP_Res(:,drug)>0; +number_resistant(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),3)); +number_intermediate(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[2])); +number_sensitive(drug) = nnz(ismember(SMP_Res(yes_measurement,drug),[1])); +%fraction(drug) = (number_resistant(drug)/(number_resistant(drug) + number_sensitive(drug))); +fractionR(drug) = (number_resistant(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionI(drug) = (number_intermediate(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +fractionS(drug) = (number_sensitive(drug)/(number_resistant(drug) + number_intermediate(drug) + number_sensitive(drug))); +pie([fractionS(drug),fractionI(drug), fractionR(drug)]); +set(findobj(gca,'type','text'),'fontsize',7.5); +%labels = repmat({''},size(fractionS)); +title(Names{drug}) +cmap = [150 150 150 ; 75 75 75 ; 0 0 0]./255; +colormap(gca, cmap) +end +text(0, pos2(2), 'All species'); +end \ No newline at end of file diff --git a/Wound_analysis/reccomend_drugs.m b/Wound_analysis/reccomend_drugs.m new file mode 100644 index 0000000..fad8dbe --- /dev/null +++ b/Wound_analysis/reccomend_drugs.m @@ -0,0 +1,283 @@ +function [] = reccomend_drugs(wound_cases, params) +% function takes the UTI_case structure and optional params and treains and tests +% regressoin model to predict risk of gain of resistance for all susceptibility-matched treated cases cases + +X_age = wound_cases.Demog.Age; X_age(:,6) = []; % reference age +zeroto39 = sum(X_age(:,1:2),2); % larger bin for lower age groups with less data +eightyplus = sum(X_age(:,end-1:end),2); +X_demog = [zeroto39 X_age(:,3:end) , wound_cases.Demog.Gender ]; + +%% seperate training data and test data +test_data = ismember(wound_cases.SamplingDate, 736411:737382); +fprintf('Testing using %.2f percent of the data\n' ,nnz(test_data)/length(test_data)*100) + +%% Regression for StoR failure given any previous resistance to drug +clear coef +num_of_previous_R = wound_cases.num_of_previous_R; +num_of_previous_S = wound_cases.num_of_previous_S; +sen_res = params.resistant_group; % gain of resistance +warning('off','stats:glmfit:IterationLimit') + +for drug = 1:params.number_drugs +SMP_to_use = find((wound_cases.SMP_Res(:,drug)== 1 | wound_cases.SMP_Res(:,drug)== 2) & ~test_data ); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +treatfailure = wound_cases.treatfailure(SMP_to_use) ==1 & ismember(wound_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = wound_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial','logit') ; +coef(:,drug) = glm.B; +%AUC +scores = glmval(glm.B,X,'logit') ; +[X,Y,T,AUC] = perfcurve(Y,scores,1); +AUC_all(drug) = AUC; + subplot(4,2,drug) + plot(X,Y); + xlabel('False positive rate') ; + ylabel('True positive rate'); + title([wound_cases.SMP_Res_drug_names{drug} ' AUC:' num2str(AUC)]); +end + +%% test data +clear P +P = nan(height(wound_cases.Demog),params.number_drugs); +treatfails_gainedres_toprch = zeros(height(wound_cases.Demog),params.number_drugs); +to_use = false(height(wound_cases.Demog),params.number_drugs); +%patient was correctly prescribed a drug from the used drugs +was_correctly_prescribed = sum(wound_cases.PCR_sameday(:,1:params.number_drugs) & ismember(wound_cases.SMP_Res(:,1:params.number_drugs), [1 2]),2) > 0; + +had_prev_resistance = nan(height(wound_cases.Demog),params.number_drugs); + +for drug = 1:params.number_drugs +SMP_to_use = find(was_correctly_prescribed & test_data ); +had_prev_resistance(was_correctly_prescribed & test_data & num_of_previous_R(:,drug) >0 ) = 1; +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use, num_previous_R num_previous_S]; +P(SMP_to_use, drug) = glmval(coef(:,drug),X,'logit') ; +% +drug_prch_temp = wound_cases.PCR_sameday(SMP_to_use ,drug); +treatfails = wound_cases.treatfailure(SMP_to_use) ==1 & ismember(wound_cases.next_res(SMP_to_use, drug),sen_res) ; +treatfails_gainedres_toprch(SMP_to_use, drug) = treatfails & drug_prch_temp; +num_gained(drug) = nnz(treatfails(drug_prch_temp)); +num_treated(drug) = nnz(drug_prch_temp); +% reassign any mismatched (or unknown Res) probabilities to 1 +index = find(ismember(wound_cases.SMP_Res(SMP_to_use,drug), [0 3])); +P(SMP_to_use(index), drug) = 1.1; % mismatched treatments are not used + +X_test = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +treatfailure = wound_cases.treatfailure(SMP_to_use) ==1 & ismember(wound_cases.next_res(SMP_to_use, drug),sen_res) ; +Y = treatfailure(drug_prch_temp==1); + +scores = glmval(coef(:,drug),X_test,'logit') ; +[X_test,Y,T,AUC2] = perfcurve(Y,scores,1); +AUC_all2(drug) = AUC2; + subplot(4,2,drug) + hold on + plot(X_test,Y,'r'); + xlabel('False positive rate') ; + ylabel('True positive rate'); + title([wound_cases.SMP_Res_drug_names{drug} ' AUC train:' num2str(AUC_all(drug)) 'AUC test:' num2str(AUC_all2(drug))]); +end + +sum(num_gained)/sum(num_treated) +treatfails_gainedres_toprch = logical(sum(treatfails_gainedres_toprch,2)); + +%% pick antibiotic with lowest P +clear M best_drug + +withPdata_index = find(sum(isnan(P),2)== 0); +P_nonans = P(withPdata_index,:); +real_prch = wound_cases.PCR_sameday(withPdata_index, 1:params.number_drugs); +real_treatfails_gainedres_toprch = treatfails_gainedres_toprch(withPdata_index(1:end-100)); +real_res = wound_cases.SMP_Res(withPdata_index, 1:params.number_drugs); + +[M,best_drug_temp] = min(P_nonans,[],2); + +best_drug = zeros(size(P_nonans,1),params.number_drugs); +for ii = 1:params.number_drugs +best_drug(best_drug_temp == ii,ii) = 1; +end + +%% was there alternative available +num_w_alternative = nnz(best_drug & ~real_prch)/ (nnz(best_drug & real_prch) + nnz(best_drug & ~real_prch))*100; +disp(['in ' num2str(num_w_alternative) ' of cases an alternative (non cost adj) drug w/ lower P was avavilable']); +%% cost adjusted to give equal numbers of reccomended drugs to actual purchased drugs +rng('default'); rng(1); +P_nonans = P_nonans+rand(size(P_nonans))/100000; % to help with the cost adjusting +Fr0= zeros(1, params.number_drugs); +for ii = 1:params.number_drugs +Fr0(ii) = nnz(real_prch(:,ii)); +end +Fr0 = Fr0./size(real_prch,1); +iter_params = [1 0.9 0.9 1e4]; + % params = [0.1, 0.9, 0.95, 1e4] ; +d = size(P_nonans,2) ; +n = size(P_nonans,1) ; +tol = iter_params(2) / n ; +relax = iter_params(3) ; +niter = iter_params(4) ; +dcost = iter_params(1) * ones(1,d) ; +cost = zeros(1,d) ; +exitflag = 1 ; +Fr = Fr0 ; +for i = 1:niter + cost = cost + dcost.*sign(Fr-Fr0) ; + cost = cost - mean(cost) ; + dcost = dcost*relax ; + + [p,treat] = min(P_nonans+cost,[],2) ; + treat(p>1) = 0 ; + Fr = histc(treat,1:d)' ./ n ; + err = max(abs(Fr-Fr0)) ; + %Fr + if err0); +random_drug_noprev = real_prch; +num = 1:5; +for ii = 1:length(incorrectly_prescribed) + random_drug_noprev(incorrectly_prescribed(ii),1:5)= zeros(1,5); +numstemp = num(had_prev_resistance_nonans(incorrectly_prescribed(ii),1:5) == 0 & ismember(real_res(incorrectly_prescribed(ii),1:5), [1 2])); +if ~isempty(numstemp) +random_drug_noprev(incorrectly_prescribed(ii),numstemp(randi(length(numstemp)))) = 1; +end +end + +%% bootstrap data and plot predicted risk +reccomended_cost_correctly_presribed = logical(sum(ismember(real_res, [1 2]) & best_drug_costadjust,2)); +fprintf('%.0f out of %.0f COST ADJUSTED BEST RECCOMENDED samples are correctly prescribed (should be all)\n' ,nnz(reccomended_cost_correctly_presribed), length(reccomended_cost_correctly_presribed)) + +real = mean(P_nonans(real_prch ==1)); +best_cost = mean(P_nonans(best_drug_costadjust ==1)); +best = mean(P_nonans(best_drug ==1)); +random_noprev = mean(P_nonans(random_drug_noprev ==1)); + +realPs = P_nonans(real_prch ==1); +best_costPs = P_nonans(best_drug_costadjust ==1); +bestPs = P_nonans(best_drug ==1); +random_noprevPs = P_nonans(random_drug_noprev ==1); +num_bootstraps = 1000; + +real_boot = bootstrp(num_bootstraps,@mean,realPs); +best_cost_boot = bootstrp(num_bootstraps,@mean,best_costPs); +best_boot = bootstrp(num_bootstraps,@mean,bestPs); +random_noprev_boot = bootstrp(num_bootstraps,@mean,random_noprevPs); + +random_noprev_CI = prctile(random_noprev_boot,[2.5 97.5]) ; +real_CI = prctile(real_boot,[2.5 97.5]) ; +best_CI = prctile(best_boot,[2.5 97.5]) ; +best_cost_CI = prctile(best_cost_boot,[2.5 97.5]) ; + +figure; +set(gcf,'color','w', 'name','Fig. 4E', 'units','centimeters','Position',[1 1 10 10]); +b1= bar([mean(real_boot) mean(random_noprev_boot) mean(best_cost_boot) mean(best_boot)]); +hold on +errorbar(b1(1).XData,b1(1).YData,... + [ mean(real_boot)-real_CI(1) mean(random_noprev_boot)-random_noprev_CI(1) mean(best_cost_boot)-best_cost_CI(1) mean(best_boot)-best_CI(1) ],... + [ -mean(real_boot)+real_CI(2) -mean(random_noprev_boot)+random_noprev_CI(2) -mean(best_cost_boot)+best_cost_CI(2) -mean(best_boot)+best_CI(2) ],'k', 'LineStyle','none') +xticklabels({'Physician','Random no prevR','Recomended cost adj','Recommended'}) +xtickangle( 45 ) +ylabel('predicted probability of aquiring resistance') +plot(1:4,mean(real_treatfails_gainedres_toprch)*ones(1,4),'k--'); + +%% number of each antibiotic prescribed in test period for +% different prescription methods +number_prescribed_reccomended = zeros(3,size(real_prch,2)); +number_prescribed_reccomended(1,:) = sum(real_prch); +number_prescribed_reccomended(2,:) = sum(best_drug_costadjust); +number_prescribed_reccomended(3,:) = sum(best_drug); + +figure +set(gcf,'color','w') +clf; set(gcf,'name','Fig. S14 Number of prescribed and ML recommended antibiotics'); +bar(number_prescribed_reccomended') +legend({'physician prescribed drugs' ; 'ML, recommended cost adjusted' ; 'ML, recommended'}) +xticklabels(wound_cases.SMP_Res_drug_names) +xtickangle(45) +ylabel('number of prescriptions/ reccomendations') + +%% errors between models +dprb = real_boot-best_boot ; +sd = std(dprb) ; mn = mean(dprb) ; pval = 1-normcdf(mn/sd) +dprb = real_boot-best_cost_boot ; +sd = std(dprb) ; mn = mean(dprb) ; pval = 1-normcdf(mn/sd) +dprb = real_boot-random_noprev_boot ; +sd = std(dprb) ; mn = mean(dprb) ; pval = 1-normcdf(mn/sd) + +%% Do regression for any failure (S-S & S-R) and look at the predicted risk for the +% antibiotic recomendations trained to miniize StoR failures +clear coef +sen_res = [1 2 3]; +for drug = 1:params.number_drugs +SMP_to_use = find((wound_cases.SMP_Res(:,drug)== 1 | wound_cases.SMP_Res(:,drug)== 2) & ~test_data ); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +treatfailure = wound_cases.treatfailure(SMP_to_use) ==1 & ismember(wound_cases.next_res(SMP_to_use, drug),sen_res) ; +drug_prch_temp = wound_cases.PCR_sameday(SMP_to_use ,drug); +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use(drug_prch_temp==1,:), num_previous_R(drug_prch_temp==1), num_previous_S(drug_prch_temp==1)]; +%X = [X_demog_to_use(drug_prch_temp==1,:), any_previous_R(drug_prch_temp==1)]; +Y = treatfailure(drug_prch_temp==1); +[glm.B,glm.dev,glm.stats] = glmfit(X,Y,'binomial','logit') ; +coef(:,drug) = glm.B; +end + +%% test data: +clear P +P = nan(height(wound_cases.Demog),params.number_drugs); +treatfails_gainedres_toprch = zeros(height(wound_cases.Demog),params.number_drugs); +treatfails_all = zeros(height(wound_cases.Demog),params.number_drugs); +%patient was correctly prescribed a drug from the used drugs +was_correctly_prescribed = sum(wound_cases.PCR_sameday(:,1:params.number_drugs) & ismember(wound_cases.SMP_Res(:,1:params.number_drugs), [1 2]),2) > 0; + +for drug = 1:params.number_drugs + +SMP_to_use = find(was_correctly_prescribed & test_data ); +num_previous_R = num_of_previous_R(SMP_to_use ,drug); +num_previous_S = num_of_previous_S(SMP_to_use ,drug); +% treatfailure = SMP.treatfailure(SMP_to_use) ==1 & ismember(next_res(SMP_to_use, drug),sen_res) ; +X_demog_to_use = X_demog(SMP_to_use,:); +X = [X_demog_to_use, num_previous_R num_previous_S]; +P(SMP_to_use, drug) = glmval(coef(:,drug),X,'logit') ; +drug_prch_temp = wound_cases.PCR_sameday(SMP_to_use ,drug); +treatfails = wound_cases.treatfailure(SMP_to_use) ==1 & ismember(wound_cases.next_res(SMP_to_use, drug),sen_res) ; + +% reassign any mismatched (or unknown Res) probabilities to 1 +%index = find(SMP_Res(SMP_to_use,drug)== 3); +index = find(ismember(wound_cases.SMP_Res(SMP_to_use,drug), [0 3])); +P(SMP_to_use(index), drug) = 1.1; + +end + +withPdata_index_SS = find(sum(isnan(P),2)== 0); +P_nonans_SS = P(withPdata_index_SS,:); +best_cost_SS_boot = bootstrp(num_bootstraps,@mean,P_nonans_SS(best_drug_costadjust ==1)); +best_SS_boot = bootstrp(num_bootstraps,@mean,P_nonans_SS(best_drug ==1)); +real_SS_boot = bootstrp(num_bootstraps,@mean,P_nonans_SS(real_prch ==1)); +% +figure; +set(gcf,'color','w', 'name','Fig. S17', 'units','centimeters','Position',[1 1 10 10]); +b1= bar([mean(real_SS_boot) mean(best_SS_boot) mean(best_cost_SS_boot) ]); +hold on +errorbar(b1(1).XData,b1(1).YData,[std(real_SS_boot) std(best_SS_boot) std(best_cost_SS_boot) ],'k', 'LineStyle','none') +xticklabels({'All rec real','All rec best','All rec cost'}) +xtickangle( 45 ) +ylabel('predicted probability of aquiring resistance') \ No newline at end of file diff --git a/Wound_analysis/risk_recurrence_by_day_wounds.m b/Wound_analysis/risk_recurrence_by_day_wounds.m new file mode 100644 index 0000000..e4f713e --- /dev/null +++ b/Wound_analysis/risk_recurrence_by_day_wounds.m @@ -0,0 +1,65 @@ +function [] = risk_recurrence_by_day_wounds(wound_cases,params) +%% sensitive chance of failure +% function takes wound_cases structure and optional params and makes plot of +% the 7-day moving avaerage % of early recurrences for all antibtioic treated cases + +wound_cases.hasdiag = true(size(wound_cases.RandomID)); +av_window = 7; +days = 4:1:50; +%for all days +for kk = 1:length(days)-1 +clear treatfailure +treatfailure = wound_cases.date_diff >= days(kk) & wound_cases.date_diff < days(kk)+av_window; +%for all antibioitcs +for drug = 1:params.number_drugs + + all_sensitive1 = ismember(wound_cases.SMP_Res(:,drug), params.sensitive_group) & wound_cases.hasdiag; + all_resistant1 = ismember(wound_cases.SMP_Res(:,drug), params.resistant_group) & wound_cases.hasdiag; + all_sensitive_nextres1 = ismember(wound_cases.next_res(:,drug), params.sensitive_group) ; + all_resistant_nextres1 = ismember(wound_cases.next_res(:,drug), params.resistant_group) ; + all_nextres = ismember(wound_cases.next_res(:,drug),[1 2 3]); + + all_sensitive_purchased1(drug ,kk) = nnz((all_sensitive1 | all_resistant1) & wound_cases.PCR_sameday(:,drug)); + sensitive_purchased_fails1(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure); + sensitive_purchased_nextresfails1(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + sensitive_purchased_fails_SS(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + sensitive_purchased_fails_SR(drug ,kk) = nnz(all_sensitive1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + + all_resistant_purchased(drug ,kk) = nnz((all_sensitive1 | all_resistant1) & wound_cases.PCR_sameday(:,drug)); + resistant_purchased_fails(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure); + resistant_purchased_nextresfails(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_nextres); + resistant_purchased_fails_RS(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_sensitive_nextres1); + resistant_purchased_fails_RR(drug ,kk) = nnz(all_resistant1 & wound_cases.PCR_sameday(:,drug) & treatfailure & all_resistant_nextres1); + + +end + +% sum the numbers from all the drugs for each day +fail_split1_all(1:2,kk, 1) = [sum(sensitive_purchased_fails_SS(1:params.number_drugs ,kk))/sum(sensitive_purchased_nextresfails1(1:params.number_drugs ,kk)) ; sum(sensitive_purchased_fails_SR(1:params.number_drugs ,kk))/sum(sensitive_purchased_nextresfails1(1:params.number_drugs ,kk))]*(sum(sensitive_purchased_fails1(1:params.number_drugs ,kk))/sum(all_sensitive_purchased1(1:params.number_drugs))*100); +fail_split_res1_all(1:2,kk, 1) = [sum(resistant_purchased_fails_RR(1:params.number_drugs ,kk))/sum(resistant_purchased_nextresfails(1:params.number_drugs ,kk)) ; sum(resistant_purchased_fails_RS(1:params.number_drugs ,kk))/sum(resistant_purchased_nextresfails(1:params.number_drugs ,kk))]*(sum(resistant_purchased_fails(1:params.number_drugs ,kk))/sum(all_resistant_purchased(1:params.number_drugs))*100); + + +end + +%% plot the fig +fail_split2(:,:,1) = fail_split1_all(:,:,1); +fail_split_res2(:,:,1) = fail_split_res1_all(:,:,1); + +b1 = bar(1:length(days)-1,[fail_split2(:,:,1)',fail_split_res2(:,:,1)']./av_window, 'stacked' , 'FaceColor','flat', 'EdgeColor', 'none', 'BarWidth', 1); + +b1(1).CData(:,:) = ones(length(days)-1,1)*params.SS_color; +b1(2).CData(:,:) = ones(length(days)-1,1)*params.SR_color; +b1(3).CData(:,:) = ones(length(days)-1,1)*params.RR_color; +b1(4).CData(:,:) = ones(length(days)-1,1)*params.RS_color; + +ylabel('% of patients'); +set(gca,'XTick',1:8:length(days)); +days_string = num2str((days(1:8:length(days)))'); +set(gca,'xticklabel',days_string); +xlabel('# of days between first and second sample'); +xlim([0.5 length(days)-0.5]) +hold on +ylim([0 0.3]); +yl = ylim; +plot([28-days(1)+1 28-days(1)+1],yl, 'k--'); +end \ No newline at end of file diff --git a/Wound_analysis/species_change_matrix_gained_res_wound.m b/Wound_analysis/species_change_matrix_gained_res_wound.m new file mode 100644 index 0000000..673ba2d --- /dev/null +++ b/Wound_analysis/species_change_matrix_gained_res_wound.m @@ -0,0 +1,123 @@ +function [] = species_change_matrix_gained_res_wound(wound_cases,params) +%% matrix wound gained res + +bugs_order = [1 5 223 110 242 166 225 280 179 292 347]; %wounds +clear names +for ii = 1:length(bugs_order) + names(ii) = wound_cases.Bugs.Name(find(wound_cases.Bugs.Code == bugs_order(ii))); +end +names(1) = {'other'}; +not_members = 1:1000; +not_members(bugs_order) = []; +clear mat_changed +treatfailure = wound_cases.treatfailure;% wound_cases.next_SMP_days<29 & wound_cases.next_SMP_days>4; +mat_changed = zeros(length(bugs_order),length(bugs_order),params.number_drugs ); + +for drug = 1:params.number_drugs + +%next res is resistant +index = cellfun(@(x) ismember(x,params.resistant_group), wound_cases.new_RES(:,drug),'UniformOutput',false); + +%only resistant next bugs +resistant_nextres_bugs = cellfun(@(v,x)v(x),wound_cases.new_bug,index,'UniformOutput',false); + +initially_sensitive = (wound_cases.SMP_Res(:,drug) == 1 | wound_cases.SMP_Res(:,drug) == 2); +to_use = find(initially_sensitive & treatfailure & wound_cases.PCR_sameday(:,drug)); + +for inital_bug = 1:length(bugs_order) + if inital_bug == 1 + initial_true = cellfun(@(x) ismember(x,not_members),wound_cases.bug_all,'UniformOutput',false); + initial_true = cellfun(@sum,initial_true)>0; + else + initial_true = (cellfun(@(x) x==bugs_order(inital_bug),wound_cases.bug_all,'UniformOutput',false)); + initial_true = cellfun(@sum,initial_true)>0; + end + for new_bug = 1:length(bugs_order) + if new_bug == 1 + recurrent_true = cellfun(@(x) ismember(x,not_members),resistant_nextres_bugs,'UniformOutput',false); + recurrent_true = cellfun(@sum,recurrent_true)>0; + else + recurrent_true = (cellfun(@(x) x==bugs_order(new_bug),resistant_nextres_bugs,'UniformOutput',false)); + recurrent_true = cellfun(@sum,recurrent_true)>0; + end + mat_changed(inital_bug,new_bug,drug) = nnz(initial_true(to_use) & recurrent_true(to_use)); + end +end + + +end + +figure; +set(gcf,'color','w', 'name','Fig. S9 wounds', 'units','centimeters','Position',[1 1 25 10]); +tiledlayout(1,2, 'TileSpacing','Compact', 'Padding', 'none'); +nexttile +mat_changed_all = sum(mat_changed, 3); +temp = mat_changed_all; +for ii = 1:length(bugs_order) +temp(ii,:) = temp(ii,:)./sum(temp(ii,:)); +end +image(fliplr(temp*256)) +title('all antibiotics') +xticks(1:length(bugs_order)) +yticklabels(names) +xtickangle(45) +yticks(1:length(bugs_order)) +xticklabels(fliplr(names)) +axis image +ylabel('Initial species') +xlabel('Gained resistance species') +%colorbar + +%% +mat_changedSS = zeros(length(bugs_order),length(bugs_order),params.number_drugs ); + +for drug = 1:params.number_drugs + +index = cellfun(@(x) ismember(x,params.sensitive_group), wound_cases.new_RES(:,drug),'UniformOutput',false); +%only sensitive next bugs +resistant_nextres_bugs = cellfun(@(v,x)v(x),wound_cases.new_bug,index,'UniformOutput',false); + +initially_sensitive = (wound_cases.SMP_Res(:,drug) == 1 | wound_cases.SMP_Res(:,drug) == 2); +to_use = find(initially_sensitive & treatfailure & wound_cases.PCR_sameday(:,drug)); + +for inital_bug = 1:length(bugs_order) + if inital_bug == 1 + initial_true = cellfun(@(x) ismember(x,not_members),wound_cases.bug_all,'UniformOutput',false); + initial_true = cellfun(@sum,initial_true)>0; + else + initial_true = (cellfun(@(x) x==bugs_order(inital_bug),wound_cases.bug_all,'UniformOutput',false)); + initial_true = cellfun(@sum,initial_true)>0; + end + for new_bug = 1:length(bugs_order) + if new_bug == 1 + recurrent_true = cellfun(@(x) ismember(x,not_members),resistant_nextres_bugs,'UniformOutput',false); + recurrent_true = cellfun(@sum,recurrent_true)>0; + else + recurrent_true = (cellfun(@(x) x==bugs_order(new_bug),resistant_nextres_bugs,'UniformOutput',false)); + recurrent_true = cellfun(@sum,recurrent_true)>0; + end + mat_changedSS(inital_bug,new_bug,drug) = nnz(initial_true(to_use) & recurrent_true(to_use)); + end +end + + +end + +nexttile +mat_changed_all = sum(mat_changedSS, 3); +temp = mat_changed_all; +for ii = 1:length(bugs_order) +temp(ii,:) = temp(ii,:)./sum(temp(ii,:)); +end +image(fliplr(temp*256)) +title('all antibiotics') +xticks(1:length(bugs_order)) +yticklabels(names) +xtickangle(45) +yticks(1:length(bugs_order)) +xticklabels(fliplr(names)) +axis image +ylabel('Initial species') +xlabel('Remained sensitive species') +%colorbar +end \ No newline at end of file diff --git a/Wound_analysis/species_prevalence_table.m b/Wound_analysis/species_prevalence_table.m new file mode 100644 index 0000000..c3ace79 --- /dev/null +++ b/Wound_analysis/species_prevalence_table.m @@ -0,0 +1,16 @@ +function [] = species_prevalence_table(wound_cases) +%function makes table of the species prevelance for all wound_cases +A = cell2mat(wound_cases.bug_all); +[counts,bugs] = groupcounts(A); +species_prevalence_table = table(bugs,counts); +total = sum(counts); +for ii = 1:height(species_prevalence_table) + names(ii,1) = wound_cases.Bugs.Name( wound_cases.Bugs.Code == species_prevalence_table.bugs(ii)); + percent(ii,1) = counts(ii)/total*100; +end +species_prevalence_table.Names = names; +species_prevalence_table.percent = round(percent); +species_prevalence_table_wounds = sortrows(species_prevalence_table,'counts','descend'); +species_prevalence_table_wounds = species_prevalence_table_wounds(1:10,:); +filename = 'Tables/TableS4_species_prevalence_table_wounds.xlsx'; +writetable(species_prevalence_table_wounds,filename); \ No newline at end of file diff --git a/Wound_analysis/susceptibiltiy_change_matrix_wounds.m b/Wound_analysis/susceptibiltiy_change_matrix_wounds.m new file mode 100644 index 0000000..2899003 --- /dev/null +++ b/Wound_analysis/susceptibiltiy_change_matrix_wounds.m @@ -0,0 +1,79 @@ +function [] = susceptibiltiy_change_matrix_wounds(wound_cases, params) +% function takes UTI_case structure and optional params and makes matric plot of +% rate of change resistance for each antiboitic suceptibiltiy and each +% antiboitic treatment + +%% net change in resistance to test antibiotic for each treatement antibiotic +% use periods for which relevant drug was routeenly measured +dates_to_use_start([1:4 6 8]) = min(wound_cases.SamplingDate); +dates_to_use_start(5) = min(wound_cases.SamplingDate)+7*321; +dates_to_use_start(7) = min(wound_cases.SamplingDate)+7*293; +dates_to_use_end(1:7) = max(wound_cases.SamplingDate); +dates_to_use_end(8) = min(wound_cases.SamplingDate)+7*293; + + +num_gained_resistance_to_test = zeros(params.number_drugs); +total_num_treated = zeros(params.number_drugs); +num_lost_resistance_to_test = zeros(params.number_drugs); + + +for drug = 1:params.number_drugs + total_prch(drug) = nnz(wound_cases.PCR_sameday(:,drug)); + dates_index_drug = find(wound_cases.SamplingDate >= dates_to_use_start(drug) & wound_cases.SamplingDate <= dates_to_use_end(drug)); + for drug_to_test = 1:params.number_drugs + dates_index_test = find(wound_cases.SamplingDate >= dates_to_use_start(drug_to_test) & wound_cases.SamplingDate <= dates_to_use_end(drug_to_test)); + dates_index = intersect(dates_index_test , dates_index_drug); + all_sensitive_test = (wound_cases.SMP_Res(dates_index,drug_to_test) == 1 | wound_cases.SMP_Res(dates_index,drug_to_test) == 2) ; + all_resistant_test = wound_cases.SMP_Res(dates_index,drug_to_test) == 3 ; + all_currentres = ismember(wound_cases.SMP_Res(dates_index,drug),[1 2]) & ismember(wound_cases.SMP_Res(dates_index,drug_to_test),[1 2 3]); + all_sensitive_nexttestres = wound_cases.next_res(dates_index,drug_to_test) == 1 | wound_cases.SMP_Res(dates_index,drug_to_test) == 2 ; + all_resistant_nexttestres = wound_cases.next_res(dates_index,drug_to_test) == 3 ; + all_nextres = ismember(wound_cases.next_res(dates_index,drug),[1 2 3]) & ismember(wound_cases.next_res(dates_index,drug_to_test),[1 2 3]); + gained_resistance_to_test = all_sensitive_test & all_resistant_nexttestres & wound_cases.PCR_sameday(dates_index,drug); + lost_resistance_to_test = all_resistant_test & all_sensitive_nexttestres & wound_cases.PCR_sameday(dates_index,drug); + total_num_treated(drug,drug_to_test) = nnz(wound_cases.PCR_sameday(dates_index,drug) & all_currentres); + num_gained_resistance_to_test(drug,drug_to_test) = nnz(gained_resistance_to_test & wound_cases.treatfailure(dates_index) & all_nextres & all_currentres); + num_lost_resistance_to_test(drug,drug_to_test) = nnz(lost_resistance_to_test & wound_cases.treatfailure(dates_index) & all_nextres & all_currentres); + end +end + + + +% net change in resistance +rate_gained_resistance_to_test = num_gained_resistance_to_test./total_num_treated*100; +rate_lost_resistance_to_test = num_lost_resistance_to_test./total_num_treated*100; +rate_gained_resistance_to_test(rate_gained_resistance_to_test == Inf) = 0; +rate_lost_resistance_to_test(rate_lost_resistance_to_test == Inf) = 0; +net_change_res = rate_gained_resistance_to_test-rate_lost_resistance_to_test; +net_change_res(isnan(rate_lost_resistance_to_test)) = 0; + +%% +% for colormap +n = 20; +lost_res_num = 15; +gained_res_num = 55; +total_num = gained_res_num + lost_res_num; +cyan = [ linspace(0, 1, gained_res_num)' ones(gained_res_num,1) ones(gained_res_num,1)]; +magenta = [ ones(gained_res_num,1) linspace(0, 1, gained_res_num)' ones(gained_res_num,1)]; +magenta = flipud(magenta); +cyan_white_magenta = [cyan; magenta(1:lost_res_num,:)]; +colormap(flipud(cyan_white_magenta)); + +image([rot90(net_change_res)]*n+lost_res_num ) +xlabel('treatment drug') +ylabel('focal drug') +colormap(flipud(cyan_white_magenta)) +xticks([1:1:params.number_drugs+1]) +set(gca,'xticklabel',[wound_cases.SMP_Res_drug_names; 'Untreated']) +xtickangle(45); +yticks([1:1:params.number_drugs]) +set(gca,'yticklabel',flipud(wound_cases.SMP_Res_drug_names)) +cbh = colorbar ; %Create Colorbar +cbh.Ticks = linspace(0, length(colormap), 8) ; %Create 8 ticks from zero to 1 +ticknums = (linspace(-lost_res_num, gained_res_num, 8))/n; +cbh.TickLabels = num2cell(ticknums) ; +set(get(cbh,'label'),'string',{'net % of treated cases which changed';... + 'resistance to focal drug'}); +axis image + +end \ No newline at end of file diff --git a/Wound_analysis/wound_analysis_and_figures.m b/Wound_analysis/wound_analysis_and_figures.m new file mode 100644 index 0000000..fbbc14f --- /dev/null +++ b/Wound_analysis/wound_analysis_and_figures.m @@ -0,0 +1,82 @@ +%% perform wound infection analysis and makes figures for +% Minimizing antibiotic-induced emergence of antibiotic resistance in +% bacterial infections +% Mathew Stracy 2021 + +%% loads the wound_cases structure. Each line in the struct represents a wound infection case +clearvars -except wound_cases +if ~exist('wound_cases') % load the data + load('wound_cases.mat'); +end +if ~isfolder('Tables') + mkdir('Tables') +end + +%% parameters +params.number_drugs = 5; +% sensitivity grouping Sensitive = 1; Intermediate = 2; Resistant = 3; +params.sensitive_group = [1 2]; +SIR= 1:3; params.resistant_group = SIR(~ismember(SIR, params.sensitive_group)); +clear SIR +% figure colors +params.SS_color = [ 25, 32, 128]/255; params.SR_color = [ 0 0.95 0.95]; +params.RR_color = [ 128 0 128]/255; params.RS_color = [ 0.95 0 0.95]; + +%% generate Table S1 patient demographics +Patient_demographics_table_wounds2(wound_cases,params); + +%% Fig 1G +figure +set(gcf,'color','w','name','Fig. 1G', 'units','centimeters','Position',[2 2 7 10]); +mismatched_vs_mathced_recurrence_rate_wounds(wound_cases,params) + +%% Fig 1H +mode_of_reccurence_pie_charts_wounds(wound_cases,params) + +%% Table S4 +species_prevalence_table(wound_cases) + +%% Fig 1H +figure +set(gcf,'color','w', 'name','Fig. 1H', 'units','centimeters','Position',[1 1 10 10]); +susceptibiltiy_change_matrix_wounds(wound_cases,params) + +%% Fig S4 +figure +set(gcf,'color','w', 'name','Fig. S4', 'units','centimeters','Position',[1 1 12 9]); +risk_recurrence_by_day_wounds(wound_cases,params) + +%% Fig 2G +figure +set(gcf,'color','w', 'name','Fig. 2G wounds', 'units','centimeters','Position',[1 1 5 9]); +changed_res_bac_alldrugs_wounds(wound_cases,params) + +%% Fig S8 wounds +figure; +set(gcf,'color','w', 'name','Fig. S8B Rates of resistance by species wounds',... +'units','centimeters','Position',[1 1 25 18]); +rate_res_by_species_wounds(wound_cases, params); + +%% Fig 3C +figure; +set(gcf,'color','w', 'name','Fig. 4C',... +'units','centimeters','Position',[1 1 25 18]); +OR_wounds(wound_cases, params); + +%% Fig 3G +set(gcf,'color','w', 'name','Fig. S12 wounds',... +'units','centimeters','Position',[1 1 25 18]); +reccomend_drugs(wound_cases, params) + +%% +species_change_matrix_gained_res_wound(wound_cases,params) +%% +if ~isfolder('Figures') + mkdir('Figures') +end +FigList = findobj(allchild(0), 'flat', 'Type', 'figure'); +for iFig = 1:length(FigList) + FigHandle = FigList(iFig); + FigName = get(FigHandle, 'name'); + saveas(FigHandle,['Figures/' FigName '.fig']) +end \ No newline at end of file