text
stringlengths
12
786k
module Add ( X : Exp with type t = private [ > num | ' a add ] as ' a ) = struct type t = X . t add let show ( ` Add ( e1 , e2 ) : t ) = " ( " ^ X . show e1 " " ^+^ X . show e2 " ) " ^ let eval ( ` Add ( e1 , e2 ) : t ) = let e1 = X . eval e1 and e2 = X . eval e2 in match e1 , e2 with ` Num n1 , ` Num n2 -> ` Num ( n1 + n2 ) | ` Num 0 , e | e , ` Num 0 -> e | e12 -> ` Add e12
type ' a mul = [ ` Mul of ' a * ' a ]
module Mul ( X : Exp with type t = private [ > num | ' a mul ] as ' a ) = struct type t = X . t mul let show ( ` Mul ( e1 , e2 ) : t ) = " ( " ^ X . show e1 " " ^*^ X . show e2 " ) " ^ let eval ( ` Mul ( e1 , e2 ) : t ) = let e1 = X . eval e1 and e2 = X . eval e2 in match e1 , e2 with ` Num n1 , ` Num n2 -> ` Num ( n1 * n2 ) | ` Num 0 , e | e , ` Num 0 -> ` Num 0 | ` Num 1 , e | e , ` Num 1 -> e | e12 -> ` Mul e12 end
module Ext ( X : sig type t = private [ > ] end ) ( Y : sig type t end ) = struct module type S = sig type t = private [ > ] ~ [ X . t ] val eval : t -> Y . t val show : t -> string end end
module Dummy = struct type t = [ ` Dummy ] end
module Mix ( E : Exp ) ( E1 : Ext ( Dummy ) ( E ) . S ) ( E2 : Ext ( E1 ) ( E ) . S ) = struct type t = [ E1 . t | E2 . t ] let eval = function # E1 . t as x -> E1 . eval x | # E2 . t as x -> E2 . eval x let show = function # E1 . t as x -> E1 . show x | # E2 . t as x -> E2 . show x end
module rec EAdd : ( Exp with type t = [ num | EAdd . t add ] ) = Mix ( EAdd ) ( Num ( EAdd ) ) ( Add ( EAdd ) )
module rec E : Exp with type t = [ num | E . t add | E . t mul ] = Mix ( E ) ( Mix ( E ) ( Num ( E ) ) ( Add ( E ) ) ) ( Mul ( E ) )
let e = E . eval ( ` Add ( ` Mul ( ` Num 2 , ` Num 3 ) , ` Num 1 ) )
module rec E : ( Exp with type t = [ num | E . t add | E . t mul ] ) = struct module E1 = Num ( E ) module E2 = Add ( E ) module E3 = Mul ( E ) type t = E . t let show = function | # num as x -> E1 . show x | # add as x -> E2 . show x | # mul as x -> E3 . show x let eval = function | # num as x -> E1 . eval x | # add as x -> E2 . eval x | # mul as x -> E3 . eval x end
module type T = sig type t = private [ > ] end
module type Tnum = sig type t = private [ > num ] end
module Ext ( E : Tnum ) = struct module type S = functor ( Y : Exp with type t = E . t ) -> sig type t = private [ > num ] val eval : t -> Y . t val show : t -> string end end
module Ext ' ( E : Tnum ) ( X : T ) = struct module type S = functor ( Y : Exp with type t = E . t ) -> sig type t = private [ > ] ~ [ X . t ] val eval : t -> Y . t val show : t -> string end end
module Mix ( E : Exp ) ( F1 : Ext ( E ) . S ) ( F2 : Ext ' ( E ) ( F1 ( E ) ) . S ) = struct module E1 = F1 ( E ) module E2 = F2 ( E ) type t = [ E1 . t | E2 . t ] let eval = function # E1 . t as x -> E1 . eval x | # E2 . t as x -> E2 . eval x let show = function # E1 . t as x -> E1 . show x | # E2 . t as x -> E2 . show x end
module Join ( E : Exp ) ( F1 : Ext ( E ) . S ) ( F2 : Ext ' ( E ) ( F1 ( E ) ) . S ) ( E ' : Exp with type t = E . t ) = Mix ( E ) ( F1 ) ( F2 )
module rec EAdd : ( Exp with type t = [ num | EAdd . t add ] ) = Mix ( EAdd ) ( Num ) ( Add )
module rec EMul : ( Exp with type t = [ num | EMul . t mul ] ) = Mix ( EMul ) ( Num ) ( Mul )
module rec E : ( Exp with type t = [ num | E . t add | E . t mul ] ) = Mix ( E ) ( Join ( E ) ( Num ) ( Add ) ) ( Mul )
module LExt ( X : T ) = struct module type S = sig type t val eval : t -> X . t val show : t -> string end end
module LNum ( E : Exp ) ( X : LExt ( E ) . S with type t = private [ > ] ~ [ num ] ) = struct type t = [ num | X . t ] let show = function ` Num n -> string_of_int n | # X . t as x -> X . show x let eval = function # num as x -> x | # X . t as x -> X . eval x end
module LAdd ( E : Exp with type t = private [ > num | ' a add ] as ' a ) ( X : LExt ( E ) . S with type t = private [ > ] ~ [ add ] ) = struct type t = [ E . t add | X . t ] let show = function ` Add ( e1 , e2 ) -> " ( " ^ E . show e1 " " ^+^ E . show e2 " ) " ^ | # X . t as x -> X . show x let eval = function ` Add ( e1 , e2 ) -> let e1 = E . eval e1 and e2 = E . eval e2 in begin match e1 , e2 with ` Num n1 , ` Num n2 -> ` Num ( n1 + n2 ) | ` Num 0 , e | e , ` Num 0 -> e | e12 -> ` Add e12 end | # X . t as x -> X . eval x end
module LEnd = struct type t = [ ` Dummy ] let show ` Dummy = " " let eval ` Dummy = ` Dummy end
module rec L : Exp with type t = [ num | L . t add | ` Dummy ] = LAdd ( L ) ( LNum ( L ) ( LEnd ) )
module Num ( X : Exp ) = struct type t = num let map f x = x let eval1 ( ` Num _ as x ) : X . t = x let show ( ` Num n ) = string_of_int n end
module Add ( X : Exp with type t = private [ > num | ' a add ] as ' a ) = struct type t = X . t add let show ( ` Add ( e1 , e2 ) : t ) = " ( " ^ X . show e1 " " ^+^ X . show e2 " ) " ^ let map f ( ` Add ( e1 , e2 ) : t ) = ` Add ( f e1 , f e2 ) let eval1 ( ` Add ( e1 , e2 ) as e : t ) = match e1 , e2 with ` Num n1 , ` Num n2 -> ` Num ( n1 + n2 ) | ` Num 0 , e | e , ` Num 0 -> e | _ -> e
module Mul ( X : Exp with type t = private [ > num | ' a mul ] as ' a ) = struct type t = X . t mul let show ( ` Mul ( e1 , e2 ) : t ) = " ( " ^ X . show e1 " " ^*^ X . show e2 " ) " ^ let map f ( ` Mul ( e1 , e2 ) : t ) = ` Mul ( f e1 , f e2 ) let eval1 ( ` Mul ( e1 , e2 ) as e : t ) = match e1 , e2 with ` Num n1 , ` Num n2 -> ` Num ( n1 * n2 ) | ` Num 0 , e | e , ` Num 0 -> ` Num 0 | ` Num 1 , e | e , ` Num 1 -> e | _ -> e end
module Ext ( X : sig type t = private [ > ] end ) ( Y : sig type t end ) = struct module type S = sig type t = private [ > ] ~ [ X . t ] val map : ( Y . t -> Y . t ) -> t -> t val eval1 : t -> Y . t val show : t -> string end end
module Mix ( E : Exp ) ( E1 : Ext ( Dummy ) ( E ) . S ) ( E2 : Ext ( E1 ) ( E ) . S ) = struct type t = [ E1 . t | E2 . t ] let map f = function # E1 . t as x -> ( E1 . map f x : E1 . t :> t ) | # E2 . t as x -> ( E2 . map f x : E2 . t :> t ) let eval1 = function # E1 . t as x -> E1 . eval1 x | # E2 . t as x -> E2 . eval1 x let show = function # E1 . t as x -> E1 . show x | # E2 . t as x -> E2 . show x end
module type ET = sig type t val map : ( t -> t ) -> t -> t val eval1 : t -> t val show : t -> string end
module Fin ( E : ET ) = struct include E let rec eval e = eval1 ( map eval e ) end
module rec EAdd : ( Exp with type t = [ num | EAdd . t add ] ) = Fin ( Mix ( EAdd ) ( Num ( EAdd ) ) ( Add ( EAdd ) ) )
module rec E : Exp with type t = [ num | E . t add | E . t mul ] = Fin ( Mix ( E ) ( Mix ( E ) ( Num ( E ) ) ( Add ( E ) ) ) ( Mul ( E ) ) )
let e = E . eval ( ` Add ( ` Mul ( ` Num 2 , ` Num 3 ) , ` Num 1 ) )
module type Wrap = sig type ' a t val ( <: ) : string -> ' a Value . Type . t -> ' a t include Value . Type . S end
module type Var = sig module type Wrap = Wrap type ' a t = { symbol : Symbol . t ; type_ : ' a Value . Type . t } [ @@ deriving fields , sexp_of ] type ' a var := ' a t val create : Symbol . t -> ' a Value . Type . t -> ' a t module Wrap : Wrap with type ' a t := ' a t module And_value : sig type t = T : ' a var * ' a -> t [ @@ deriving sexp_of ] end module And_value_option : sig type t = T : ' a var * ' a option -> t [ @@ deriving sexp_of ] end val symbol_as_value : _ t -> Value . t val default_value_exn : ' a t -> ' a val default_value_is_defined : _ t -> bool val set_default_value : ' a t -> ' a -> unit val make_buffer_local_always : _ t -> unit val is_buffer_local_always : _ t -> bool val is_buffer_local_if_set : _ t -> Buffer0 . t -> bool end
module Alphabet = struct type t = { c1 : string ; c1_len : int ; cn : string ; cn_len : int } let create ~ c1 ~ cn = { c1 ; c1_len = String . length c1 ; cn ; cn_len = String . length cn } let javascript = create ~ c1 " : abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_ " $ ~ cn " : abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ " $ let rec size t x acc = if x < t . c1_len then 1 + acc else size t ( ( x - t . c1_len ) / t . cn_len ) ( acc + 1 ) let to_string ( t : t ) ( x : int ) = let size = size t x 0 in let buf = Bytes . create size in let rec loop i x = match i with | 0 -> assert ( x < t . c1_len ) ; Bytes . set buf i t . c1 . [ x ] ; Bytes . unsafe_to_string buf | i -> let x = x - t . c1_len in Bytes . set buf i t . cn . [ x mod t . cn_len ] ; loop ( pred i ) ( x / t . cn_len ) in loop ( size - 1 ) x end
type t = { names : ( int , string ) Hashtbl . t ; known : ( int , string ) Hashtbl . t ; cache : ( int * int , string ) Hashtbl . t ; alphabet : Alphabet . t ; mutable last : int ; mutable pretty : bool ; mutable stable : bool }
let name_raw t v nm = Hashtbl . add t . names v nm
let propagate_name t v v ' = try let name = Hashtbl . find t . names v in name_raw t v ' name with Not_found -> ( )
let name t v nm_orig = let len = String . length nm_orig in if len > 0 then ( let buf = Buffer . create ( String . length nm_orig ) in let idx = ref 0 in while ! idx < len && not ( Char . is_alpha nm_orig . [ ! idx ] ) do incr idx done ; let pending = ref false in if ! idx >= len then ( pending := true ; idx := 0 ) ; for i = ! idx to len - 1 do if Char . is_alpha nm_orig . [ i ] || Char . is_num nm_orig . [ i ] then ( if ! pending then Buffer . add_char buf ' _ ' ; Buffer . add_char buf nm_orig . [ i ] ; pending := false ) else pending := true done ; let str = Buffer . contents buf in let str = match str , nm_orig with | " " , " " >>= -> " symbol_bind " | " " , " " >>| -> " symbol_map " | " " , _ -> " symbol " | str , _ -> str in let max_len = 30 in let str = if String . length str > max_len then String . sub str ~ pos : 0 ~ len : max_len else str in name_raw t v str )
let get_name t v = try Some ( Hashtbl . find t . names v ) with Not_found -> None
let format_var t i x = let s = Alphabet . to_string t . alphabet x in if t . stable then Format . sprintf " v % d " i else if t . pretty then Format . sprintf " _ % s_ " s else s
let reserved = ref StringSet . empty
let add_reserved s = reserved := List . fold_left s ~ init :! reserved ~ f ( : fun acc x -> StringSet . add x acc )
let _ = reserved := StringSet . union ! reserved Reserved . keyword
let get_reserved ( ) = ! reserved
let is_reserved s = StringSet . mem s ! reserved
let rec to_string t ? origin i = let origin = match origin with | Some i when t . pretty -> i | _ -> i in try Hashtbl . find t . cache ( i , origin ) with Not_found -> let name = try Hashtbl . find t . known i with Not_found -> t . last <- t . last + 1 ; let j = t . last in let s = format_var t i j in if is_reserved s then to_string t i else ( Hashtbl . add t . known i s ; s ) in let name = if t . pretty then try let nm = Hashtbl . find t . names origin in nm ^ name with Not_found -> name else name in Hashtbl . add t . cache ( i , origin ) name ; name
let set_pretty t b = t . pretty <- b
let set_stable t b = t . stable <- b
let reset t = Hashtbl . clear t . names ; Hashtbl . clear t . known ; Hashtbl . clear t . cache ; t . last <- - 1
let create ( ? pretty = false ) ( ? stable = false ) alphabet = let t = { names = Hashtbl . create 107 ; known = Hashtbl . create 1001 ; cache = Hashtbl . create 1001 ; alphabet ; last = - 1 ; pretty ; stable } in t
module Tensor_id : sig include Hashable . Key val create : unit -> t include Int let create = let current = ref 0 in fun ( ) -> Int . incr current ; ! current end
type t = { name : string ; trainable_tensors : ( Tensor_id . t , Tensor . t ) Hashtbl . t ; all_tensors_by_name : ( string , Tensor . t ) Hashtbl . t ; subs : ( string , t ) Hashtbl . t ; device : Device . t ; mutable frozen : bool }
let create ( ? frozen = false ) ( ? device = Device . Cpu ) ~ name ( ) = { name ; trainable_tensors = Hashtbl . create ( module Tensor_id ) ; subs = Hashtbl . create ( module String ) ; all_tensors_by_name = Hashtbl . create ( module String ) ; device ; frozen }
let first_free_name name table = if Hashtbl . mem table name then ( let rec loop idx = let name = Printf . sprintf " % s_ % d " name idx in if Hashtbl . mem table name then loop ( idx + 1 ) else name in loop 1 ) else name
let sub t sub_name = if String . contains sub_name ' . ' then Printf . failwithf " sub names cannot contain . , % s " sub_name ( ) ; Hashtbl . find_or_add t . subs sub_name ~ default ( : fun ( ) -> { name = t . name ; trainable_tensors = Hashtbl . create ( module Tensor_id ) ; subs = Hashtbl . create ( module String ) ; all_tensors_by_name = Hashtbl . create ( module String ) ; device = t . device ; frozen = t . frozen } )
let subi t i = sub t ( Int . to_string i )
let ( / ) = sub
let ( // ) = subi
let rec freeze t = t . frozen <- true ; Hashtbl . iter t . trainable_tensors ~ f ( : fun tensor -> ignore ( Tensor . set_requires_grad tensor ~ r : false : Tensor . t ) ) ; Hashtbl . iter t . subs ~ f : freeze
let rec unfreeze t = t . frozen <- false ; Hashtbl . iter t . trainable_tensors ~ f ( : fun tensor -> ignore ( Tensor . set_requires_grad tensor ~ r : true : Tensor . t ) ) ; Hashtbl . iter t . subs ~ f : unfreeze
let rec num_trainable_vars t = let sub_vars = Hashtbl . data t . subs |> List . fold ~ init : 0 ~ f ( : fun acc t -> acc + num_trainable_vars t ) in sub_vars + Hashtbl . length t . trainable_tensors
let iter_trainable_vars t ~ f = let f ~ key ~ data = f key data in let rec loop t = Hashtbl . iter t . subs ~ f : loop ; Hashtbl . iteri t . trainable_tensors ~ f in loop t
let all_vars t = let rec walk t ~ path = let sub_vars = Hashtbl . to_alist t . subs |> List . concat_map ~ f ( : fun ( key , t ) -> walk t ~ path ( : key :: path ) ) in let vars = Hashtbl . to_alist t . all_tensors_by_name |> List . map ~ f ( : fun ( key , tensor ) -> List . rev ( key :: path ) |> String . concat ~ sep " . " , : tensor ) in vars @ sub_vars in walk t ~ path [ ] :
let copy ~ src ~ dst = Tensor . no_grad ( fun ( ) -> let rec walk ~ src ~ dst path = Hashtbl . iteri dst . all_tensors_by_name ~ f ( : fun ~ key ~ data -> match Hashtbl . find src . all_tensors_by_name key with | Some src -> Tensor . copy_ data ~ src | None -> Printf . failwithf " cannot find var % s from var - store % s in % s " ( List . rev ( key :: path ) |> String . concat ~ sep " . " ) : dst . name src . name ( ) ) ; Hashtbl . iteri dst . subs ~ f ( : fun ~ key ~ data : dst -> match Hashtbl . find src . subs key with | Some src -> walk ~ src ~ dst ( key :: path ) | None -> Printf . failwithf " cannot find sub % s from var - store % s in % s " ( List . rev ( key :: path ) |> String . concat ~ sep " . " ) : dst . name src . name ( ) ) in walk ~ src ~ dst [ ] )
let name t = t . name
let device t = t . device
module Init = struct type t = | Zeros | Ones | Const of float | Normal of { mean : float ; stdev : float } | Uniform of float * float | Copy of Tensor . t end
let new_var ( ? trainable = true ) t ~ shape ~ init ~ name = let device = device t in let requires_grad = trainable && not t . frozen in let tensor = match ( init : Init . t ) with | Zeros -> Tensor . zeros shape ~ requires_grad ~ device | Ones -> Tensor . ones shape ~ requires_grad ~ device | Const scale -> Tensor . ones shape ~ requires_grad ~ device ~ scale | Normal { mean = 0 . ; stdev } -> Tensor . randn shape ~ scale : stdev ~ requires_grad ~ device | Normal { mean ; stdev } -> Tensor . ( + ) ( Tensor . randn shape ~ scale : stdev ~ requires_grad ~ device ) ( Tensor . f mean ) | Uniform ( from , to_ ) -> Tensor . zeros shape ~ device |> Tensor . uniform_ ~ from ~ to_ |> Tensor . set_requires_grad ~ r : requires_grad | Copy src -> Tensor . copy src |> Tensor . to_device ~ device |> Tensor . set_requires_grad ~ r : requires_grad in if String . contains name ' . ' then Printf . failwithf " tensor names cannot contain . , % s " name ( ) ; let name = first_free_name name t . all_tensors_by_name in Hashtbl . add_exn t . all_tensors_by_name ~ key : name ~ data : tensor ; if trainable then Hashtbl . add_exn t . trainable_tensors ~ key ( : Tensor_id . create ( ) ) ~ data : tensor ; tensor
let new_var_copy ? trainable t ~ src ~ name = new_var ? trainable t ~ shape ( : Tensor . shape src ) ~ init ( : Copy src ) ~ name
module Configuration = struct type t = { name : string ; vaccine_peptide_length : int ; padding_around_mutation : int ; max_vaccine_peptides_per_mutation : int ; max_mutations_in_report : int ; min_mapping_quality : int ; min_variant_sequence_coverage : int ; min_alt_rna_reads : int ; include_mismatches_after_variant : bool ; use_duplicate_reads : bool ; drop_secondary_alignments : bool ; mhc_epitope_lengths : int list ; reviewers : string list option ; final_reviewer : string option ; xlsx_report : bool ; pdf_report : bool ; ascii_report : bool ; debug_log : string ; parameters : ( string * string ) list ; } let to_json { name ; vaccine_peptide_length ; padding_around_mutation ; max_vaccine_peptides_per_mutation ; max_mutations_in_report ; min_mapping_quality ; min_variant_sequence_coverage ; min_alt_rna_reads ; include_mismatches_after_variant ; use_duplicate_reads ; drop_secondary_alignments ; mhc_epitope_lengths ; reviewers ; final_reviewer ; xlsx_report ; pdf_report ; ascii_report ; debug_log ; parameters } : Yojson . Basic . json = ` Assoc ( [ " name " , ` String name ; " vaccine_peptide_length " , ` Int vaccine_peptide_length ; " padding_around_mutation " , ` Int padding_around_mutation ; " max_vaccine_peptides_per_mutation " , ` Int max_vaccine_peptides_per_mutation ; " max_mutations_in_report " , ` Int max_mutations_in_report ; " min_mapping_quality " , ` Int min_mapping_quality ; " min_variant_sequence_coverage " , ` Int min_variant_sequence_coverage ; " min_alt_rna_reads " , ` Int min_alt_rna_reads ; " include_mismatches_after_variant " , ` Bool include_mismatches_after_variant ; " use_duplicate_reads " , ` Bool use_duplicate_reads ; " drop_secondary_alignments " , ` Bool drop_secondary_alignments ; " mhc_epitope_lengths " , ` List ( List . map mhc_epitope_lengths ~ f ( : fun i -> ` Int i ) ) ; " ascii_report " , ` Bool ascii_report ; " pdf_report " , ` Bool pdf_report ; " xlsx_report " , ` Bool xlsx_report ; " debug_log " , ` String debug_log ; " parameters " , ` Assoc ( List . map parameters ~ f ( : fun ( a , b ) -> a , ` String b ) ) ; ] @ Option . value_map reviewers ~ default [ ] : ~ f ( : fun r -> [ " reviewers " , ` List ( List . map ~ f ( : fun r -> ` String r ) r ) ] ) @ Option . value_map final_reviewer ~ default [ ] : ~ f ( : fun r -> [ " final_reviewer " , ` String r ] ) ) let render { name ; vaccine_peptide_length ; padding_around_mutation ; max_vaccine_peptides_per_mutation ; max_mutations_in_report ; min_mapping_quality ; min_variant_sequence_coverage ; min_alt_rna_reads ; include_mismatches_after_variant ; use_duplicate_reads ; drop_secondary_alignments ; mhc_epitope_lengths ; reviewers ; final_reviewer ; xlsx_report ; pdf_report ; ascii_report ; debug_log ; parameters } = let soi = string_of_int in [ " -- vaccine - peptide - length " ; soi vaccine_peptide_length ] @ [ " -- padding - around - mutation " ; soi padding_around_mutation ] @ [ " -- max - vaccine - peptides - per - mutation " ; soi max_vaccine_peptides_per_mutation ] @ [ " -- max - mutations - in - report " ; soi max_mutations_in_report ] @ [ " -- min - mapping - quality " ; soi min_mapping_quality ] @ [ " -- min - variant - sequence - coverage " ; soi min_variant_sequence_coverage ] @ [ " -- min - alt - rna - reads " ; soi min_alt_rna_reads ] @ ( if include_mismatches_after_variant then [ " -- include - mismatches - after - variant " ] else [ ] ) @ ( if use_duplicate_reads then [ " -- use - duplicate - reads " ] else [ ] ) @ ( if drop_secondary_alignments then [ " -- drop_secondary_alignments " ] else [ ] ) @ [ " -- mhc - epitope - lengths " ; ( mhc_epitope_lengths |> List . map ~ f : string_of_int |> String . concat ~ sep " , " ) ] : @ ( List . concat_map parameters ~ f ( : fun ( a , b ) -> [ a ; b ] ) ) @ ( Option . value_map final_reviewer ~ default [ ] : ~ f ( : fun f -> [ " -- output - final - review " ; f ] ) ) @ ( Option . value_map reviewers ~ default [ ] : ~ f ( : fun rs -> let reviewers = String . concat ~ sep " , " : rs in [ " -- output - reviewed - by " ; reviewers ] ) ) |> List . filter ~ f ( : fun s -> not ( String . is_empty s ) ) let default = { name = " default " ; vaccine_peptide_length = 25 ; padding_around_mutation = 0 ; max_vaccine_peptides_per_mutation = 1 ; max_mutations_in_report = 10 ; min_mapping_quality = 1 ; min_variant_sequence_coverage = 1 ; min_alt_rna_reads = 3 ; include_mismatches_after_variant = false ; use_duplicate_reads = false ; drop_secondary_alignments = false ; mhc_epitope_lengths = [ 8 ; 9 ; 10 ; 11 ] ; reviewers = None ; final_reviewer = None ; xlsx_report = false ; pdf_report = false ; ascii_report = true ; debug_log = " vaxrank - debug . log " ; parameters = [ ] } let name t = t . name end
type product = < host : Ketrew_pure . Host . t ; is_done : Ketrew_pure . Target . Condition . t option ; ascii_report_path : string option ; xlsx_report_path : string option ; pdf_report_path : string option ; debug_log_path : string ; output_folder_path : string ; >
let move_vaxrank_product ? host ~ output_folder_path ( vp : product ) : product = let open KEDSL in let open Option in let host = match host with | None -> vp # host | Some h -> h in let sub path = let base = String . chop_prefix_exn ~ prefix : vp # output_folder_path path in output_folder_path // base in let ascii_product = vp # ascii_report_path >>= fun p -> return ( single_file ~ host ( sub p ) ) in let xlsx_product = vp # xlsx_report_path >>= fun p -> return ( single_file ~ host ( sub p ) ) in let pdf_product = vp # pdf_report_path >>= fun p -> return ( single_file ~ host ( sub p ) ) in let debug_log_product = single_file ~ host ( sub vp # debug_log_path ) in let opt_path p = p >>= fun p -> return ( p # path ) in object method host = host method is_done = Some ( ` And ( List . filter_map ~ f ( : fun f -> let open Option in f >>= fun f -> f # is_done ) [ ascii_product ; xlsx_product ; pdf_product ; Some debug_log_product ] ) ) method ascii_report_path = opt_path ascii_product method xlsx_report_path = opt_path xlsx_product method pdf_report_path = opt_path pdf_product method debug_log_path = debug_log_product # path method output_folder_path = output_folder_path end
let run ( ~ run_with : Machine . t ) ~ configuration ~ reference_build ~ vcfs ~ bam ~ predictor ~ alleles_file ~ output_folder = let open KEDSL in let open Hla_utilities in let host = Machine . ( as_host run_with ) in let vaxrank = Machine . get_tool run_with Machine . Tool . Default . vaxrank in let sorted_bam = Samtools . sort_bam_if_necessary ~ run_with ~ by ` : Coordinate bam in let predictor_tool = Hla_utilities . ( predictor_to_tool ~ run_with predictor ) in let ( predictor_edges , predictor_init ) = match predictor_tool with | Some ( e , i ) -> ( [ depends_on e ; ] , i ) | None -> ( [ ] , Program . ( sh " echo ' No external prediction tool required ' " ) ) in let vcfs_arg = List . concat_map vcfs ~ f ( : fun v -> [ " -- vcf " ; v # product # path ] ) in let bam_arg = [ " -- bam " ; sorted_bam # product # path ] in let predictor_arg = [ " -- mhc - predictor " ; ( predictor_to_string predictor ) ] in let allele_arg = [ " -- mhc - alleles - file " ; alleles_file # product # path ] in let output_prefix = output_folder // " vaxrank - result " in let output_of switch kind suffix = let path = output_prefix ^ " . " ^ suffix in let arg = if switch then [ sprintf " -- output -% s - report " kind ; path ] else [ ] in let prod = if switch then Some ( KEDSL . single_file ~ host path ) else None in arg , prod in let ascii_arg , ascii_product = output_of configuration . Configuration . ascii_report " ascii " " txt " in let xlsx_arg , xlsx_product = output_of configuration . Configuration . xlsx_report " xlsx " " xlsx " in let pdf_arg , pdf_product = output_of configuration . Configuration . pdf_report " pdf " " pdf " in let debug_log_arg , debug_log_product = let log_path = output_folder // configuration . Configuration . debug_log in [ " -- log - path " ; log_path ] , ( KEDSL . single_file ~ host log_path ) in let ( ) = match ascii_product , xlsx_product , pdf_product with | None , None , None -> failwith " Vaxrank requires one or more of pdf_report , \ xlsx_report , or ascii_report . " | _ , _ , _ -> ( ) in let arguments = vcfs_arg @ bam_arg @ predictor_arg @ allele_arg @ xlsx_arg @ pdf_arg @ ascii_arg @ debug_log_arg @ Configuration . render configuration in let name = " Vaxrank run " in let product = let path_of f = Option . map f ~ f ( : fun f -> f # path ) in object method host = host method is_done = Some ( ` And ( List . filter_map ~ f ( : fun f -> let open Option in f >>= fun f -> f # is_done ) [ ascii_product ; xlsx_product ; pdf_product ; ( Some debug_log_product ) ; ] ) ) method ascii_report_path = path_of ascii_product method xlsx_report_path = path_of xlsx_product method pdf_report_path = path_of pdf_product method debug_log_path = debug_log_product # path method output_folder_path = output_folder end in let quoted_output_folder = Filename . quote output_folder in workflow_node product ~ name ~ edges ( [ : depends_on ( Samtools . index_to_bai ~ run_with sorted_bam ) ; depends_on Machine . Tool . ( ensure vaxrank ) ; depends_on ( Pyensembl . cache_genome ~ run_with ~ reference_build ) ; depends_on sorted_bam ; depends_on alleles_file ; ] @ ( List . map ~ f : depends_on vcfs ) @ predictor_edges ) ~ make ( : Machine . run_program run_with ~ name Program . ( Machine . Tool . ( init vaxrank ) && predictor_init && Pyensembl . ( set_cache_dir_command ~ run_with ) && shf " mkdir - p % s " quoted_output_folder && shf " cd % s " quoted_output_folder && exec ( [ " vaxrank " ] @ arguments ) ) )
let ba0 = Bigarray . Array1 . create Bigarray . float32 Bigarray . c_layout 0 ; ;
let display ( vertexBuffer , colourBuffer ) = function ( ) -> glClear [ GL_COLOR_BUFFER_BIT ; GL_DEPTH_BUFFER_BIT ] ; glMatrixMode GL_MODELVIEW ; glLoadIdentity ( ) ; glTranslate 0 . 0 . ( - 5 . 0 ) ; glBindBuffer GL_ARRAY_BUFFER vertexBuffer ; glVertexPointer0 3 Coord . GL_FLOAT 0 ; glBindBuffer GL_ARRAY_BUFFER colourBuffer ; glColorPointer0 3 Color . GL_FLOAT 0 ; glDrawArrays GL_TRIANGLE_STRIP 0 3 ; glutSwapBuffers ( ) ; ; ;
let ini_gl ( ) = glMatrixMode GL_PROJECTION ; glLoadIdentity ( ) ; gluPerspective 45 . 0 ( 640 . 0 . / 480 . 0 ) 1 . 0 512 . 0 ; glClearColor 0 . 0 0 . 0 0 . 0 1 . 0 ; let vertexData = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 0 . 0 ; 1 . 0 ; 0 . 0 ; - 1 . 0 ; - 1 . 0 ; 0 . 0 ; 1 . 0 ; - 1 . 0 ; 0 . 0 ; ] | in let colourData = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 0 . 0 ; 0 . 0 ; 1 . 0 ; 0 . 0 ; 1 . 0 ; 1 . 0 ; 1 . 0 ; 1 . 0 ; 1 . 0 ; ] | in let vertexBuffer = glGenBuffer ( ) in glBindBuffer GL_ARRAY_BUFFER vertexBuffer ; glBufferData GL_ARRAY_BUFFER ( ba_sizeof vertexData ) vertexData GL_STATIC_DRAW ; let colourBuffer = glGenBuffer ( ) in glBindBuffer GL_ARRAY_BUFFER colourBuffer ; glBufferData GL_ARRAY_BUFFER ( ba_sizeof colourData ) colourData GL_STATIC_DRAW ; glEnableClientState GL_VERTEX_ARRAY ; glEnableClientState GL_COLOR_ARRAY ; ( vertexBuffer , colourBuffer ) ; ;
let keyboard ( vertexBuffer , colourBuffer ) = fun ~ key ~ x ~ y -> match key with | ' \ 027 ' -> glDisableClientState GL_VERTEX_ARRAY ; glDisableClientState GL_COLOR_ARRAY ; glDeleteBuffer vertexBuffer ; glDeleteBuffer colourBuffer ; exit ( 0 ) ; | _ -> ( ) ; ;
let ( ) = ignore ( glutInit Sys . argv ) ; glutInitDisplayMode [ GLUT_RGB ; GLUT_DEPTH ; GLUT_DOUBLE ] ; glutInitWindowSize 640 480 ; ignore ( glutCreateWindow " VBO demo " ) ; let buffers = ini_gl ( ) in glutDisplayFunc ~ display ( : display buffers ) ; glutKeyboardFunc ~ keyboard ( : keyboard buffers ) ; glutMainLoop ( ) ; ; ;
let vertexData = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 0 . 0 ; 1 . 0 ; 0 . 0 ; - 1 . 0 ; - 1 . 0 ; 0 . 0 ; 1 . 0 ; - 1 . 0 ; 0 . 0 ; ] |
let colourData = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 0 . 0 ; 0 . 0 ; 1 . 0 ; 0 . 0 ; 1 . 0 ; 1 . 0 ; 1 . 0 ; 0 . 5 ; 0 . 0 ; ] |
let display ( vertexBuffer , colourBuffer ) = function ( ) -> glClear [ GL_COLOR_BUFFER_BIT ; GL_DEPTH_BUFFER_BIT ] ; glMatrixMode GL_MODELVIEW ; glLoadIdentity ( ) ; glTranslate 0 . 0 . ( - 5 . 0 ) ; glEnableClientState GL_VERTEX_ARRAY ; glEnableClientState GL_COLOR_ARRAY ; glBindBuffer GL_ARRAY_BUFFER vertexBuffer ; begin let now = Unix . gettimeofday ( ) in vertexData . { 0 } <- ( cos ( now . / 2 . 0 ) ) ; glBufferData GL_ARRAY_BUFFER ( ba_sizeof vertexData ) vertexData GL_DYNAMIC_DRAW ; end ; glVertexPointer0 3 Coord . GL_FLOAT 0 ; glBindBuffer GL_ARRAY_BUFFER colourBuffer ; glColorPointer0 3 Color . GL_FLOAT 0 ; glDrawArrays GL_TRIANGLE_STRIP 0 3 ; glDisableClientState GL_VERTEX_ARRAY ; glDisableClientState GL_COLOR_ARRAY ; glUnbindBuffer GL_ARRAY_BUFFER ; glutSwapBuffers ( ) ; glutPostRedisplay ( ) ; ; ;
let ini_gl ( ) = glMatrixMode GL_PROJECTION ; glLoadIdentity ( ) ; gluPerspective 45 . 0 ( 640 . 0 . / 480 . 0 ) 1 . 0 512 . 0 ; glClearColor 0 . 0 0 . 0 0 . 0 1 . 0 ; let vertexBuffer = glGenBuffer ( ) in glBindBuffer GL_ARRAY_BUFFER vertexBuffer ; glBufferData GL_ARRAY_BUFFER ( ba_sizeof vertexData ) vertexData GL_DYNAMIC_DRAW ; let colourBuffer = glGenBuffer ( ) in glBindBuffer GL_ARRAY_BUFFER colourBuffer ; glBufferData GL_ARRAY_BUFFER ( ba_sizeof colourData ) colourData GL_STATIC_DRAW ; ( vertexBuffer , colourBuffer ) ; ;
let keyboard ( vertexBuffer , colourBuffer ) = fun ~ key ~ x ~ y -> match key with | ' \ 027 ' -> glDeleteBuffer vertexBuffer ; glDeleteBuffer colourBuffer ; exit ( 0 ) ; | _ -> ( ) ; ;
let ( ) = ignore ( glutInit Sys . argv ) ; glutInitDisplayMode [ GLUT_RGB ; GLUT_DEPTH ; GLUT_DOUBLE ] ; glutInitWindowSize 640 480 ; ignore ( glutCreateWindow " VBO demo " ) ; let buffers = ini_gl ( ) in glutDisplayFunc ~ display ( : display buffers ) ; glutKeyboardFunc ~ keyboard ( : keyboard buffers ) ; glutMainLoop ( ) ; ; ;
let vertexData = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 0 . 0 ; 1 . 0 ; 0 . 0 ; - 1 . 0 ; - 1 . 0 ; 0 . 0 ; 1 . 0 ; - 1 . 0 ; 0 . 0 ; ] |
let colourData = Bigarray . Array1 . of_array Bigarray . float32 Bigarray . c_layout [ | 0 . 0 ; 0 . 0 ; 1 . 0 ; 0 . 0 ; 1 . 0 ; 1 . 0 ; 1 . 0 ; 0 . 5 ; 0 . 0 ; ] |
let display ( vertexBuffer , colourBuffer ) = function ( ) -> glClear [ GL_COLOR_BUFFER_BIT ; GL_DEPTH_BUFFER_BIT ] ; glMatrixMode GL_MODELVIEW ; glLoadIdentity ( ) ; glTranslate 0 . 0 . ( - 5 . 0 ) ; glEnableClientState GL_VERTEX_ARRAY ; glEnableClientState GL_COLOR_ARRAY ; glBindBuffer GL_ARRAY_BUFFER vertexBuffer ; begin let now = Unix . gettimeofday ( ) in vertexData . { 0 } <- ( cos ( now . / 2 . 0 ) ) ; let mapped_buffer = glMapBufferAbs GL_ARRAY_BUFFER GL_WRITE_ONLY in ( ( Bigarray . Array1 . dim vertexData ) * ( elem_size vertexData ) ) ; ) * mapped_buffer_blit_ofs mapped_buffer vertexData ~ ofs : 0 ~ len ( : 1 * ( elem_size vertexData ) ) ; glUnmapBuffer GL_ARRAY_BUFFER ; end ; glVertexPointer0 3 Coord . GL_FLOAT 0 ; glBindBuffer GL_ARRAY_BUFFER colourBuffer ; glColorPointer0 3 Color . GL_FLOAT 0 ; glDrawArrays GL_TRIANGLE_STRIP 0 3 ; glDisableClientState GL_VERTEX_ARRAY ; glDisableClientState GL_COLOR_ARRAY ; glUnbindBuffer GL_ARRAY_BUFFER ; glutSwapBuffers ( ) ; glutPostRedisplay ( ) ; ; ;
let ini_gl ( ) = glMatrixMode GL_PROJECTION ; glLoadIdentity ( ) ; gluPerspective 45 . 0 ( 640 . 0 . / 480 . 0 ) 1 . 0 512 . 0 ; glClearColor 0 . 0 0 . 0 0 . 0 1 . 0 ; let vertexBuffer = glGenBuffer ( ) in glBindBuffer GL_ARRAY_BUFFER vertexBuffer ; glBufferData GL_ARRAY_BUFFER ( ba_sizeof vertexData ) vertexData GL_DYNAMIC_DRAW ; let colourBuffer = glGenBuffer ( ) in glBindBuffer GL_ARRAY_BUFFER colourBuffer ; glBufferData GL_ARRAY_BUFFER ( ba_sizeof colourData ) colourData GL_STATIC_DRAW ; ( vertexBuffer , colourBuffer ) ; ;
let keyboard ( vertexBuffer , colourBuffer ) = fun ~ key ~ x ~ y -> match key with | ' \ 027 ' -> glDeleteBuffer vertexBuffer ; glDeleteBuffer colourBuffer ; exit ( 0 ) ; | _ -> ( ) ; ;
let ( ) = ignore ( glutInit Sys . argv ) ; glutInitDisplayMode [ GLUT_RGB ; GLUT_DEPTH ; GLUT_DOUBLE ] ; glutInitWindowSize 640 480 ; ignore ( glutCreateWindow " VBO demo " ) ; let buffers = ini_gl ( ) in glutDisplayFunc ~ display ( : display buffers ) ; glutKeyboardFunc ~ keyboard ( : keyboard buffers ) ; glutMainLoop ( ) ; ; ;
module Make ( S : Comb . S ) = struct open S open Circuit open Cyclesim . Api type t = S . t let vcdmin = 33 let vcdmax = 126 let vcdcycle = 10 type trace = { w : int ; id : string ; name : string ; data : S . t ref ; prev : string ref ; } type cyclesim = t Cyclesim . Api . cyclesim let wrap os sim = let osl s = os ( s ^ " \ n " ) in let si = string_of_int in let ( ) ^:^ a b = a ^ " " ^ b in let gen_id = let i = ref 2 in let range = vcdmax - vcdmin in let rec gen x = let d = x / range in let m = x mod range in if d = 0 then [ m ] else d :: gen ( x - range ) in let code x = List . fold_left ( fun a x -> ( String . v ~ len : 1 ( fun _ -> Char . of_byte ( x + vcdmin ) ) ) ^ a ) " " ( gen x ) in ( fun ( ) -> let x = ! i in incr i ; code x ) in let write_var v d w = if w = 1 then osl ( d ^ v ) else osl ( " b " ^ d ^:^ v ) in let trace signals = let width s = String . length ( to_bstr s ) in let xs w = String . v w ( fun _ -> ' x ' ) in List . map ( fun ( n , s ) -> { w = width ! s ; id = gen_id ( ) ; name = n ; data = s ; prev = ref ( xs ( width ! s ) ) ; } ) signals in let trace_in = trace sim . sim_in_ports in let trace_out = trace sim . sim_out_ports in let trace_internal = trace sim . sim_internal_ports in let trace_in = List . filter ( fun s -> s . name <> " clock " && s . name <> " reset " ) trace_in in let write_header ( ) = os " $ date \ n . . . \ n $ end \ n " ; os " $ version \ n HardCaml \ n $ end \ n " ; os " $ comment \ n Hardware design in ocaml \ n $ end \ n " ; os " $ timescale 1ns $ end \ n " ; os " $ scope module inputs $ end \ n " ; os " $ var wire 1 ! clock $ end \ n " ; os " $ var wire 1 " \ reset $ end \ n " ; let trv t = osl ( " $ var wire " ^ si t . w ^:^ t . id ^:^ t . name " ^:^$ end " ) in List . iter trv trace_in ; os " $ upscope $ end \ n " ; os " $ scope module outputs $ end \ n " ; List . iter trv trace_out ; os " $ upscope $ end \ n " ; os " $ scope module various $ end \ n " ; List . iter trv trace_internal ; os " $ upscope $ end \ n " ; os " $ enddefinitions $ end \ n " ; os " $ dumpvars \ n " ; os " x !\ n " ; os " x " \\ n " ; List . iter ( fun t -> write_var t . id ( ! t . prev ) t . w ) trace_in ; List . iter ( fun t -> write_var t . id ( ! t . prev ) t . w ) trace_out ; List . iter ( fun t -> write_var t . id ( ! t . prev ) t . w ) trace_internal ; os " $ end \ n " ; in let time = ref 0 in write_header ( ) ; let write_reset ( ) = osl ( " " #^ si ( ! time ) ) ; osl " 0 " ; ! osl " 1 " " ; \ List . iter ( fun t -> write_var t . id ( S . to_bstr ( ! t . data ) ) t . w ; t . prev := ( S . to_bstr ( ! t . data ) ) ) trace_in ; List . iter ( fun t -> write_var t . id ( S . to_bstr ( ! t . data ) ) t . w ; t . prev := ( S . to_bstr ( ! t . data ) ) ) trace_out ; List . iter ( fun t -> write_var t . id ( S . to_bstr ( ! t . data ) ) t . w ; t . prev := ( S . to_bstr ( ! t . data ) ) ) trace_internal ; time := ( ! time ) + vcdcycle in let write_cycle ( ) = osl ( " " #^ si ( ! time ) ) ; osl " 1 " ; ! osl " 0 " " ; \ List . iter ( fun t -> let data = S . to_bstr ( ! t . data ) in if data <> ( ! t . prev ) then ( write_var t . id data t . w ; t . prev := data ) ) trace_in ; List . iter ( fun t -> let data = S . to_bstr ( ! t . data ) in if data <> ( ! t . prev ) then ( write_var t . id data t . w ; t . prev := data ) ) trace_out ; List . iter ( fun t -> let data = S . to_bstr ( ! t . data ) in if data <> ( ! t . prev ) then ( write_var t . id data t . w ; t . prev := data ) ) trace_internal ; osl ( " " #^ si ( ( ! time ) + ( vcdcycle / 2 ) ) ) ; osl " 0 " ; ! time := ( ! time ) + vcdcycle in { sim with sim_reset = ( fun ( ) -> reset sim ; write_reset ( ) ) ; sim_cycle_seq = ( fun ( ) -> cycle_seq sim ; write_cycle ( ) ) ; } end
module Gtkwave ( S : Comb . S ) = struct module Vcd = Make ( S ) type t = S . t type cyclesim = t Cyclesim . Api . cyclesim let wrap chan sim = let o s = output_string chan s ; flush chan in Vcd . wrap o sim let gtkwave ( ? args " " ) = sim = let fifoname = Filename . temp_file " sim " " fifo " in Printf . printf " Created tempfile % s \ n " fifoname ; Unix . unlink fifoname ; Unix . mkfifo fifoname 0o600 ; Printf . printf " Made fifo , launching shmidcat and gtkwave \ n " ; ignore ( Unix . open_process_in ( " shmidcat " ^ fifoname ^ " | gtkwave - v - I " ^ args ) ) ; let fifo = open_out fifoname in at_exit ( fun ( ) -> Printf . printf " Destroying FIFO \ n " ; close_out fifo ; Unix . unlink fifoname ) ; wrap fifo sim end
module Safe = struct type error = [ ` invalid_int of string | ` invalid_float of string ] let int_of_string s = try Ok ( Int . of_string s ) s with _ -> Error ( ` invalid_int s ) s let float_of_string s = try Ok ( Float . of_string s ) s with _ -> Error ( ` invalid_float s ) s end
let is_valid_dna = String . for_all ~ f ( : String . contains " ACGTN ) "
type vcf_number = | Number of int | OnePerAllele | OnePerGenotype | Unknown
type vcf_format_type = [ ` integer_value | ` float_value | ` character_value | ` string_value ]
type vcf_info_type = [ vcf_format_type | ` flag_value ]