simulation_pipeline.ml 15.7 KB
Newer Older
1 2
open Base
open Printf
Philippe Veber's avatar
Philippe Veber committed
3
open Bistro
Philippe Veber's avatar
Philippe Veber committed
4
open File_formats
Philippe Veber's avatar
Philippe Veber committed
5
module U = Utils
6 7 8 9 10

let calc_fixed_seed ~(str:string) (seed:int) : int =
  let str_hash = Hashtbl.hash str in
  Hashtbl.hash (str_hash + seed)

11
type tree =
Philippe Veber's avatar
Philippe Veber committed
12
  | NHX of nhx file
13
  | Convergence_tree of Codepitk.Convergence_tree.t workflow
Philippe Veber's avatar
Philippe Veber committed
14

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
let nhx_of_convergence_tree tree =
  let f = fun%workflow dest ->
    let open Phylogenetics in
    let open Codepitk in
    let tree =
      [%eval tree]
      |> Tree.map
        ~node:(fun () -> { Newick_ast.name = None })
        ~leaf:(fun s  -> { Newick_ast.name = Some s })
        ~branch:Convergence_tree.(fun bi ->
            let tags = match bi.condition with
              | `Ancestral -> ["Condition", "0"]
              | `Convergent -> ["Condition", "1" ; "Transition", "1"]
            in
            { Newick_ast.length = Some bi.length ; tags }
          )
    in
    Newick.to_file (Tree tree) dest
  in
  Workflow.path_plugin ~descr:"nhx_of_convergence_tree" f

36 37 38 39 40 41 42 43 44 45 46 47 48
let pair_tree ~branch_length1 ~branch_length2 ~npairs =
  let leaf_info i c =
    sprintf "%c%d"
      (match c with `Convergent -> 'C' | `Ancestral -> 'A')
      i
  in
  Convergence_tree (
    Codepitk.Convergence_tree.pair_tree
      ~leaf_info ~node_info:()
      ~branch_length1 ~branch_length2 ~npairs
    |> Workflow.data
  )

49
module type S = sig
50
  type query
51

52 53
  include Detection_pipeline.Query with type t := query
  include Detection_pipeline.S with type query := query
54

55
  val alignment_plot : query -> svg file
56 57
end

58 59
let tree_workflow = function
  | NHX w -> w
60 61
  | Convergence_tree w ->
    nhx_of_convergence_tree w
62

63 64 65 66 67
module Make(Q : Detection_pipeline.Query) = struct
  include Detection_pipeline.Make(Q)
end

module Mutsel_query = struct
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  type t = {
    tree : tree ;
    branch_scale : float ;
    profiles : string ;
    n_h0 : int ;
    n_ha : int ;
    ne_s : float * float ;
    gBGC : float * float ;
    seed : int ;
  }

  let make ?(branch_scale = 1.) ?(ne_s = 1., 1.) ?(gBGC = 0., 0.) ?(seed = 0) ~tree ~profiles ~n_h0 ~n_ha () = {
    tree ;
    profiles ;
    n_h0 ;
    n_ha ;
    ne_s ;
    gBGC ;
    branch_scale ;
    seed : int ;
  }

  let simulation { n_h0 ; n_ha ; profiles ; ne_s ; gBGC ; branch_scale ; seed ; tree ; _ } =
    let tree = tree_workflow tree in
    let fitness_profiles = Workflow.input profiles in
Philippe Veber's avatar
Philippe Veber committed
93
    Mutsel_simulator.simulation ~branch_scale ~n_ha ~n_h0 ~ne_s ~gBGC ~tree ~seed ~fitness_profiles ()
94

95 96
  let nucleotide_alignment p =
    simulation p
Philippe Veber's avatar
Philippe Veber committed
97
    |> Mutsel_simulator.alignment_of_simulation
Philippe Veber's avatar
Philippe Veber committed
98

99 100
  let tree ~branch_length_unit:_ { tree ; _ } = tree_workflow tree
end
Philippe Veber's avatar
Philippe Veber committed
101

102

103
module Mutsel = struct
104 105
  open Phylogenetics

106 107 108
  type query = Mutsel_query.t
  let query = Mutsel_query.make
  let simulation = Mutsel_query.simulation
109

110
  include Make(Mutsel_query)
Philippe Veber's avatar
Philippe Veber committed
111

112

113
  type benchmark = {
114 115
    n_h0 : int ;
    n_ha : int ;
116 117 118
    method_labels : string list ;
    method_outputs : float option array list ;
    average_precision : (float * (float * float)) list ;
119 120 121
    profiles : (float array * float array) array ;
    ancestral_counts : int Amino_acid.table array ;
    convergent_counts : int Amino_acid.table array ;
122
  }
123

Philippe Veber's avatar
Philippe Veber committed
124 125 126 127
  let benchmark q methods =
    let f = fun%workflow () ->
      let open Phylogenetics in
      let open Codepitk in
Philippe Veber's avatar
Philippe Veber committed
128
      let open Codepitk.Mutsel_simulator.Site_independent in
Philippe Veber's avatar
Philippe Veber committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
      let module Codon = Codon.Universal_genetic_code.NS in
      let sim : simulation = [%eval simulation q] in
      let result_paths = [%eval Bistro.Workflow.path_list (List.map methods ~f:(fun f -> f q))] in
      let results =
        List.map result_paths ~f:Cpt.of_file
        |> Result.all
        |> Rresult.R.failwith_error_msg
        |> List.concat_map ~f:Cpt.columns
      in
      let method_labels, method_outputs = List.unzip results in
      let n_h0 = Array.length sim.h0_params in
      let n_ha = Array.length sim.ha_params in
      let nsites = n_h0 + n_ha in
      let amino_acid_vector_of_codon_vector xs =
        Amino_acid.Vector.init (fun aa ->
            List.fold Codon.all ~init:0. ~f:(fun acc c ->
                if Amino_acid.equal aa (Codon.aa_of_codon c) then
                  acc +. xs.Codon.%(c)
                else acc
              )
149 150
          )
      in
Philippe Veber's avatar
Philippe Veber committed
151 152 153 154 155 156 157 158 159
      let compute_profile p =
        Mutsel.stationary_distribution p
        |> amino_acid_vector_of_codon_vector
        |> Amino_acid.Vector.to_array
      in
      let profiles =
        Array.append sim.h0_params sim.ha_params
        |> Array.map ~f:(fun (p1, p2) ->
            compute_profile p1, compute_profile p2
160
          )
Philippe Veber's avatar
Philippe Veber committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
      in
      let counts seqs i =
        Amino_acid.Table.init (fun aa ->
            let aa = Amino_acid.to_char aa in
            List.count seqs ~f:(fun s ->
                let codon_str = String.sub (s : Dna.t :> string) ~pos:(i * 3) ~len:3 in
                let codon = match Codon.of_string codon_str with
                  | Some c -> c
                  | None -> assert false
                in
                Char.equal (Amino_acid.to_char (Codon.aa_of_codon codon)) aa)
          )
      in
      let collect_counts cond =
        let species = Convergence_tree.leaves sim.tree in
        let seqs =
          List.map2_exn sim.sequences species ~f:(fun s (_, cond_s) ->
              if Poly.equal cond cond_s then Some s else None
            )
          |> List.filter_opt
        in
        Array.init nsites ~f:(counts seqs)
      in
      let ancestral_counts = collect_counts `Ancestral in
      let convergent_counts = collect_counts `Convergent in
      let average_precision =
187
        let oracle = Array.init nsites ~f:(( <= ) n_h0) in
Philippe Veber's avatar
Philippe Veber committed
188
        let module PR = Prc.Precision_recall in
Philippe Veber's avatar
Philippe Veber committed
189
        List.map results ~f:(fun (_, scores) ->
Philippe Veber's avatar
Philippe Veber committed
190
            let Prc.Dataset xs as data = U.make_prc_dataset scores oracle in
Philippe Veber's avatar
Philippe Veber committed
191
            let n = List.count xs ~f:snd in
192
            let theta_hat = PR.auc_average_precision data in
Philippe Veber's avatar
Philippe Veber committed
193
            let lb, ub = PR.logit_confidence_interval ~alpha:0.05 ~theta_hat ~n in
Philippe Veber's avatar
Philippe Veber committed
194 195 196 197 198 199 200 201
            theta_hat, (lb, ub)
          )
      in
      {
        method_labels ; method_outputs ;
        ancestral_counts ; convergent_counts ;
        average_precision ; profiles ; n_h0 ; n_ha
      }
202
    in
203
    Workflow.plugin ~version:4 ~descr:"simulation_pipeline.benchmark" f
Philippe Veber's avatar
Philippe Veber committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

  let rds_of_benchmark b =
    let f = fun%workflow dest ->
      let { average_precision ; method_labels ;
            n_h0 ; n_ha ; method_outputs ; profiles ;
            ancestral_counts ; convergent_counts } = [%eval b] in
      let open OCamlR_base in
      let collect_profiles sel =
        Array.map profiles ~f:sel
        |> Numeric.Matrix.of_arrays
      in
      let ancestral_profiles = collect_profiles fst in
      let convergent_profiles = collect_profiles snd in
      let collect_counts c =
        Array.map c ~f:(fun c -> (c : int Amino_acid.table :> int array))
        |> Integer.Matrix.of_arrays
      in
      let ancestral_counts = collect_counts ancestral_counts in
      let convergent_counts = collect_counts convergent_counts in
      let auc_estimates =
        let estimates, bounds = List.unzip average_precision in
        let lower_bounds, upper_bounds = List.unzip bounds in
        Dataframe.create [
          "method", `Character (Character.of_list method_labels) ;
          "estimate", `Numeric (Numeric.of_list estimates) ;
          "lower_bound", `Numeric (Numeric.of_list lower_bounds) ;
          "upper_bound", `Numeric (Numeric.of_list upper_bounds) ;
        ]
      in
      let oracle =
        Array.init (n_h0 + n_ha) ~f:(fun i -> if i < n_h0 then false else true)
        |> Logical.of_array
      in
      let columns = List.map2_exn method_labels method_outputs ~f:(fun l r ->
          l, `Numeric (Numeric.of_array_opt r)
        ) in
      let results = Dataframe.create columns in
      let data = List_.create [
          Some "results", Dataframe.to_sexp results ;
          Some "oracle", Logical.to_sexp oracle ;
          Some "ancestral_profiles", Numeric.Matrix.to_sexp ancestral_profiles ;
          Some "convergent_profiles", Numeric.Matrix.to_sexp convergent_profiles ;
          Some "ancestral_counts", Integer.Matrix.to_sexp ancestral_counts ;
          Some "convergent_counts", Integer.Matrix.to_sexp convergent_counts ;
          Some "auc_estimates", Dataframe.to_sexp auc_estimates ;
        ]
      in
      saveRDS ~file:dest (List_.to_sexp data)
252
    in
Philippe Veber's avatar
Philippe Veber committed
253
    Workflow.path_plugin ~descr:"simulation_pipeline.rds_of_benchmark" f
254 255 256 257 258 259 260 261 262 263 264

  (* param exploration for SMBE paper *)
  (* type branch_scale_t = float *)
  let branch_scale_range = [ 1.; 3.; 6.; 9. ]

  type gBGC_t = Global of float | Convergent of float * float
  let gBGC_range =
    let range = [ 0.; 2.; 4.; 8.; 16.; 32.; 64.; ] in
    List.concat [
      (* List.map ~f:(fun x -> Global x) range ; *)
      List.map ~f:(fun x -> Convergent (0., x)) range ;
265
    ]
266

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  type param_t = float * gBGC_t

  let explore_params ~(f: param_t -> _) =
    List.map branch_scale_range ~f:(fun (bf:float) ->
        List.map gBGC_range ~f:(fun (gbgc:gBGC_t) -> ((bf, gbgc), f (bf, gbgc)))
      ) |> List.concat

  let simu_of_param ?n_h0:(n_h0=50) (p: param_t) =
    let bf, gbgc = p in
    Mutsel_query.make
      ~tree:(NHX (Workflow.input "example/trees_analyses/C4AmaranthaceaePolyroot.nhx"))
      ~profiles:"example/aa_fitness/263SelectedProfiles.tsv"
      ~branch_scale:bf
      ~gBGC:(match gbgc with
          | Convergent (a,c) -> (a, c)
          | Global g -> (g, g))
      ~ne_s:(4., 4.)
      ~n_ha:0
      ~n_h0
      ()

  let filter_results ~(f: _ -> bool) (results: (param_t * _) list) =
    List.filter results ~f:(fun (_, x) -> f x)

  type record_t = {
    gc_means_ancestral: ([`first | `second | `third] * float) list ;
    gc_means_convergent: ([`first | `second | `third] * float) list
294
  }
295

Philippe Veber's avatar
Philippe Veber committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
  let record_of_simu s =
    let f = fun%workflow () ->
      let tree = [%path tree ~branch_length_unit:`Nucleotide s] in
      let nucleotide_alignment = [%path nucleotide_alignment s] in
      let gc_mean_from_simu ~pos =
        Alistats.nucleotide_fasta_gc_ac ~pos tree nucleotide_alignment
      in let (m1_a, m1_c), (m2_a, m2_c), (m3_a, m3_c) =
           gc_mean_from_simu ~pos:`first,
           gc_mean_from_simu ~pos:`second,
           gc_mean_from_simu ~pos:`third
      in {
        gc_means_ancestral = [(`first, m1_a.gc_mean) ; (`second, m2_a.gc_mean) ; (`third, m3_a.gc_mean)] ;
        gc_means_convergent = [(`first, m1_c.gc_mean) ; (`second, m2_c.gc_mean) ; (`third, m3_c.gc_mean)]
      }
    in
    Workflow.plugin ~descr:"simulation_pipeline.record_of_simu" f
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

  let expected_gc = [
    (`first,  (0.3326, 0.5157, 0.5589, 0.6080, 0.8621)) ;
    (`second, (0.2102, 0.3784, 0.4160, 0.4626, 0.7499)) ;
    (`third,  (0.2242, 0.4852, 0.6274, 0.7358, 0.9575))
  ]

  let quartile (min_, fq_, mean_, tq_, max_) x =
    match Float.( x < min_, x < fq_, x < mean_, x < tq_, x < max_) with
    | true, _, _, _, _     -> `below_min
    | false, true, _, _, _ -> `first
    | _, false, true, _, _ -> `second
    | _, _, false, true, _ -> `third
    | _, _, _, false, true -> `fourth
    | _, _, _, _, false    -> `over_max

  let adjacent q1 q2 =
    match q1, q2 with
    | `first,  `first | `second, `second
    | `third,  `third | `fourth, `fourth
    | `first, `second | `second, `first
    | `second, `third | `third, `second
    | `third, `fourth | `fourth, `third -> true
    | _ -> false

  let quartile_of_record (r: record_t) =
    List.map r.gc_means_convergent ~f:(fun (q, x) ->
        let q_list = List.Assoc.find_exn expected_gc ~equal:(fun x y -> Caml.(x = y)) q in
        quartile q_list x
      )

  let realistic_result (r: record_t) =
    match quartile_of_record r with
    | [q1 ; q2 ; q3] -> adjacent q1 q2 && adjacent q2 q3 && adjacent q1 q3
    | _ -> failwith "oh no"
347 348 349


  (* let v = g.gc_stat.gc_variance_among_sequences in
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
     Float.(v >= 8.388e-05 && v <= 5.262e-02) *)
end

module Bppseqgen = struct
  type t =
    | Bppseqgen of {
        hypothesis : Convergence_hypothesis.t ;
        tree : tree ;
        profiles : string ;
        nb_sites : int ;
        seed : int ;
      }
    | Bppseqgen_mixed of {
        tree : tree ;
        profiles : string ;
        seed : int ;
        n_h0 : int ;
        n_ha : int ;
        ne_s : float ;
      }

  let bppseqgen_mixed ?(ne_s = 1.) ?(seed = 0) ~tree ~profiles ~n_h0 ~n_ha () =
    Bppseqgen_mixed {
      tree ;
      profiles ;
      seed ;
      n_ha ;
      n_h0 ;
      ne_s ;
    }

  let bppseqgen ~hyp ~tree ~profiles ~nb_sites ~seed =
    Bppseqgen {
      hypothesis = hyp ;
      tree ;
      profiles ;
      nb_sites ;
      seed ;
    }

  let tree ~branch_length_unit:_ = function
    | Bppseqgen { tree ; _ }
    | Bppseqgen_mixed { tree ; _ } ->
      tree_workflow tree

  let seed = function
    | Bppseqgen_mixed s -> s.seed
    | Bppseqgen s -> s.seed

  let profile ~nb_sites ~profiles ~seed =
    Profile.profile_l_of_splitted_profile
      ~nb_cat:All
      ~nb_sites
      profiles
      ~seed:(calc_fixed_seed ~str:profiles seed)

  let bppseqgen_simulation sim ~hypothesis ~nb_sites ~profiles =
    let model_prefix = Convergence_hypothesis.string_of_model hypothesis in
    let descr = sprintf ".%s" model_prefix in
    let profile = profile ~nb_sites ~profiles ~seed:(seed sim) in
    let profile_f = profile.profile_f in
    let profile_c = profile.profile_c in
    Bppsuite.Bppseqgen.multi_profiles
      ~descr
      ~input_tree:(tree ~branch_length_unit:`Nucleotide sim)
      ~hypothesis ~profile_f ~profile_c ~seed:(seed sim)

  let rec nucleotide_alignment = function
    | Bppseqgen { hypothesis ; nb_sites ; profiles ; _ } as sim ->
      bppseqgen_simulation sim ~hypothesis ~nb_sites ~profiles
      |> Bppsuite.Bppseqgen.alignment
    | Bppseqgen_mixed { profiles ; seed ; n_h0 ; n_ha ; ne_s ; tree } ->
      let h0 = nucleotide_alignment (Bppseqgen { hypothesis = H0 (Fixed ne_s) ; profiles ; seed ; nb_sites = n_h0 ; tree }) in
      let ha = nucleotide_alignment (Bppseqgen { hypothesis = HaPC (Fixed ne_s) ; profiles ; seed ; nb_sites = n_ha ; tree }) in
      Utils.fasta_cappend h0 ha

  include Detection_pipeline.Make(struct
      type nonrec t = t
      let tree = tree
      let nucleotide_alignment = nucleotide_alignment
    end)

  let alignment_plot d =
    Convergence_detection.plot_convergent_sites
      ~tree:(tree ~branch_length_unit:`Amino_acid d)
      ~alignment:(amino_acid_alignment d)
      ~detection_results:(multinomial_asymptotic_lrt d)
      ()

  let oracle d =
    let n_h0, n_ha =
      match d with
      | Bppseqgen { nb_sites ; hypothesis ; _ } -> (
          match hypothesis with
          | H0 _ -> nb_sites, 0
          | HaPC _ | HaPCOC _ -> 0, nb_sites
        )
      | Bppseqgen_mixed { n_h0 ; n_ha ; _ } ->
        n_h0, n_ha
    in
    Convergence_detection.oracle ~n_h0 ~n_ha

  let multinomial_benchmark d =
    Utils.recall_precision_curve
      ~oracle:(oracle d)
      ~labels:["LRT";"LRTsim";"sparse";"sparse_sim"]
      ~results:[
        multinomial_asymptotic_lrt d, 1 ;
        multinomial_simulation_lrt d, 1 ;
        multinomial_asymptotic_sparse d, 1 ;
        multinomial_simulation_sparse d, 1 ;
      ]


  let result_table ?(mode = `fast) d =
    Convergence_detection.merge_result_tables
      ~multinomial:(multinomial_asymptotic_lrt d)
      ~tdg09:(tdg09 d)
      ~identical:(identical d)
      ~topological:(topological d)
      ~pcoc:(
        match mode with
        | `fast -> pcoc ~gamma:false ~ncat:10 d
        | `full -> pcoc d
      )
      ?diffsel:(
        match mode with
        | `fast -> None
        | `full -> Some (diffsel d)
      )
      ~oracle:(oracle d)
      ()

  let benchmark ?mode d =
    result_table ?mode d
    |> Convergence_detection.recall_precision_curve

  let benchmark2 d =
    Utils.recall_precision_curve
      ~oracle:(oracle d)
      ~labels:["identical";"topological";"multinomial";"pcoc";"tdg09"]
      ~results:[
        identical d, 1 ;
        topological d, 1 ;
        multinomial_asymptotic_lrt d, 1 ;
        pcoc d, 3 ;
        tdg09 d, 1 ;
      ]
end