simulation_pipeline.ml 14.2 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
5 6 7 8 9

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

10
type tree =
Philippe Veber's avatar
Philippe Veber committed
11
  | NHX of nhx file
12 13 14 15 16
  | Pair_tree of {
      npairs : int ;
      branch_length1 : float ;
      branch_length2 : float ;
    }
Philippe Veber's avatar
Philippe Veber committed
17

18
module type S = sig
19
  type query
20

21 22
  include Detection_pipeline.Query with type t := query
  include Detection_pipeline.S with type query := query
23

24
  val alignment_plot : query -> svg file
25 26
end

27 28 29 30 31 32 33
let tree_workflow = function
  | NHX w -> w
  | Pair_tree { branch_length1 ;
                branch_length2 ;
                npairs } ->
    Simulator.pair_tree ~branch_length1 ~branch_length2 ~npairs

34 35 36 37 38 39 40 41 42 43 44 45
module Make(Q : Detection_pipeline.Query) = struct
  include Detection_pipeline.Make(Q)

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

module Mutsel_query = struct
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
  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
    Simulator.simulation ~branch_scale ~n_ha ~n_h0 ~ne_s ~gBGC ~tree ~seed ~fitness_profiles ()

73 74 75
  let nucleotide_alignment p =
    simulation p
    |> Simulator.alignment_of_simulation
Philippe Veber's avatar
Philippe Veber committed
76

77 78
  let tree ~branch_length_unit:_ { tree ; _ } = tree_workflow tree
end
Philippe Veber's avatar
Philippe Veber committed
79

80

81 82 83 84
module Mutsel = struct
  type query = Mutsel_query.t
  let query = Mutsel_query.make
  let simulation = Mutsel_query.simulation
85

86
  include Make(Mutsel_query)
Philippe Veber's avatar
Philippe Veber committed
87

88

89 90 91 92 93 94 95 96
  type benchmark = {
    method_labels : string list ;
    method_outputs : float option array list ;
    average_precision : (float * (float * float)) list ;
    site_model : [`Convergent | `Non_convergent] array ;
    ancestral_counts : int Phylogenetics.Amino_acid.table array ;
    convergent_counts : int Phylogenetics.Amino_acid.table array ;
  }
97

98

99
  let%pworkflow benchmark_statistics simulation ~results =
100
    let open Phylogenetics in
101
    let open Codepitk in
102 103 104 105
    let open OCamlR_base in
    let open Codepitk.Simulator.Site_independent_mutsel in
    let module Codon = Codon.Universal_genetic_code.NS in
    let sim : simulation = [%eval simulation] in
106 107 108 109 110 111 112 113
    let result_paths = [%eval Bistro.Workflow.path_list results] 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 labels = List.map results ~f:fst in
114 115 116
    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
117
    let columns = List.map results ~f:(fun (l, r) ->
118 119 120 121 122 123 124 125 126
        l, `Numeric (Numeric.of_array_opt r)
      ) 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
            )
127 128
        )
    in
129 130 131 132 133 134 135
    let collect_profiles sel =
      Array.append sim.h0_params sim.ha_params
      |> Array.map ~f:(fun p ->
          sel p
          |> Mutsel.stationary_distribution
          |> amino_acid_vector_of_codon_vector
          |> Amino_acid.Vector.to_array
136
        )
137
      |> Numeric.Matrix.of_arrays
138
    in
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    let ancestral_profiles = collect_profiles fst in
    let convergent_profiles = collect_profiles snd in
    let counts seqs i =
      let t =
        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
      (t :> int array)
    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)
      |> Integer.Matrix.of_arrays
    in
    let ancestral_counts = collect_counts `Ancestral in
    let convergent_counts = collect_counts `Convergent in
    let make_classification_data x y =
      Prc.Classification_data (
        List.init (Array.length x) ~f:(fun i ->
            match x.(i), y.(i) with
            | Some x_i, Some y_i -> Some (x_i, y_i)
            | None, _ | _, None -> None
          )
        |> List.filter_opt
      )
    in
    let estimates, lower_bounds, upper_bounds =
      let oracle = Array.init nsites ~f:(fun i -> if i < n_h0 then Some false else Some true) in
181
      List.map results ~f:(fun (_, scores) ->
182 183 184 185 186
          let Prc.Classification_data xs as data = make_classification_data scores oracle in
          let n = List.count xs ~f:snd in
          let theta_hat = Prc.auc_trapezoidal_lt data in
          let lb, ub = Prc.logit_confidence_interval ~alpha:0.05 ~theta_hat ~n in
          theta_hat, lb, ub
187
        )
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
      |> List.unzip3
    in
    let open OCamlR_base in
    let auc_estimates = Dataframe.create [
        "method", `Character (Character.of_list 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.(
        append
          (map sim.h0_profiles ~f:(Fn.const false))
          (map sim.ha_profiles ~f:(Fn.const true))
203
      )
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      |> Logical.of_array
    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)

  (* 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 ;
229
    ]
230

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  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
258
  }
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  let%workflow record_of_simu s =
    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)]
    }

  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"
308 309 310


  (* let v = g.gc_stat.gc_variance_among_sequences in
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
     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