text
stringlengths
0
601k
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 ]
type vcf_info_meta = Info of vcf_number * vcf_info_type * vcf_description
type vcf_filter_meta = Filter of vcf_description
type vcf_format_meta = Format of vcf_number * vcf_format_type * vcf_description
type vcf_alt_meta = Alt of vcf_description
type vcf_meta = { vcfm_version : string ; vcfm_id_cache : vcf_id Set . Poly . t ; vcfm_info : ( vcf_id , vcf_info_meta ) vcf_info_meta Hashtbl . t ; vcfm_filters : ( vcf_id * vcf_filter_meta ) vcf_filter_meta list ; vcfm_format : ( vcf_id , vcf_format_meta ) vcf_format_meta Hashtbl . t ; vcfm_alt : ( string , vcf_alt_meta ) vcf_alt_meta Hashtbl . t ; vcfm_arbitrary : ( string , string ) string Hashtbl . t ; vcfm_header : string list ; vcfm_samples : string list }
type vcf_format = [ ` integer of int | ` float of float | ` character of char | ` string of string | ` missing ]
type vcf_info = [ vcf_format | ` flag of string ]
type vcf_row = { vcfr_chrom : string ; vcfr_pos : int ; vcfr_ids : string list ; vcfr_ref : string ; vcfr_alts : string list ; vcfr_qual : float option ; vcfr_filter : vcf_id list ; vcfr_info : ( vcf_id , vcf_info list ) list Hashtbl . t ; vcfr_samples : ( vcf_id , ( vcf_id * vcf_format list ) list list ) list Hashtbl . t }
type vcf_parse_row_error = [ Safe . error | ` info_type_coersion_failure of vcf_info_type * string | ` format_type_coersion_failure of vcf_format_type * string | ` invalid_dna of string | ` unknown_info of vcf_id | ` unknown_filter of vcf_id | ` unknown_alt of string | ` duplicate_ids of vcf_id list | ` invalid_arguments_length of vcf_id * int * int | ` invalid_row_length of int * int | ` malformed_sample of string | ` unknown_format of vcf_id ]
type vcf_parse_error = [ ` malformed_meta of Pos . t * string | ` malformed_row of Pos . t * vcf_parse_row_error * string | ` malformed_header of Pos . t * string | ` incomplete_input of Pos . t * string list * string option | ` not_ready ]
let string_to_vcf_number = function | " A " -> OnePerAllele | " G " -> OnePerGenotype | " . " -> Unknown | arity -> Number ( int_of_string arity ) arity
let string_to_vcf_format_type s = match String . lowercase s with | " integer " -> ` integer_value | " float " -> ` float_value | " character " -> ` character_value | " string " -> ` string_value | v -> failwith ( " string_to_vcf_format_type : invalid format : " ^ v ) v
let vcf_format_type_to_string = function | ` integer_value -> " integer " | ` float_value -> " float " | ` character_value -> " character " | ` string_value -> " string "
let coerce_to_vcf_format_type t s = if String . equal s " . " then Ok ` missing else match t with | ` integer_value -> Result . map ( Safe . int_of_string s ) s ~ f ( : fun x -> ` integer x ) x | ` float_value -> Result . map ( Safe . float_of_string s ) s ~ f ( : fun x -> ` float x ) x | ` character_value when String . length s = 1 -> Ok ( ` character s [ . 0 ] 0 ) 0 | ` string_value -> Ok ( ` string s ) s | _ -> Error ( ` format_type_coersion_failure ( t , s ) s ) s
let coerce_n ~ f key n s = let open Result . Monad_infix in let res = lazy ( Result . all ( List . map ~ f ( String . split ~ on : ' , ' s ) s ) s ) s in match n with | Number n -> Lazy . force res >>= fun values -> if List . length values = n then Ok values else Error ( ` invalid_arguments_length ( key , List . length values , n ) n ) n | Unknown | OnePerAllele | OnePerGenotype -> Lazy . force res
let string_to_vcf_info_type s = match String . lowercase s with | " flag " -> ` flag_value | s -> string_to_vcf_format_type s
let vcf_info_type_to_string = function | ` flag_value -> " flag " | # vcf_format_type as t -> vcf_format_type_to_string t
let coerce_to_vcf_info_type t s = let res = match t with | ` flag_value -> Ok ( ` flag s ) s | # vcf_format_type -> coerce_to_vcf_format_type t s in Result . map_error res ~ f ( : fun _exn -> ` info_type_coersion_failure ( t , s ) s ) s
let parse_row_error_to_string = function | ` invalid_int s -> sprintf " invalid_integer ( % s ) s " s | ` invalid_float s -> sprintf " invalid_float ( % s ) s " s | ` info_type_coersion_failure ( t , s ) s -> sprintf " info_type_coersion_failure ( % s , % S ) S " ( vcf_info_type_to_string t ) t s | ` format_type_coersion_failure ( t , s ) s -> sprintf " format_type_coersion_failure ( % s , % S ) S " ( vcf_format_type_to_string t ) t s | ` invalid_dna s -> sprintf " invalid_dna ( % s ) s " s | ` unknown_info s -> sprintf " unknown_info ( % s ) s " s | ` unknown_filter f -> sprintf " unknown_filter ( % s ) s " f | ` unknown_alt s -> sprintf " unknown_alt ( % s ) s " s | ` duplicate_ids ids -> sprintf " duplicate_ids ( % s ) s " ( String . concat ~ sep " , : " ids ) ids | ` invalid_arguments_length ( key , got , expected ) expected -> sprintf " invalid_arguments_length ( % s , % i , % i ) i " key got expected | ` invalid_row_length ( got , expected ) expected -> sprintf " invalid_row_length ( % i , % i ) i " got expected | ` malformed_sample s -> sprintf " malformed_sample ( % s ) s " s | ` unknown_format f -> sprintf " unknown_formar ( % s ) s " f
let parse_error_to_string = let pos ( ) a = Pos . to_string a in function | ` malformed_meta ( p , s ) s -> sprintf " malformed_meta ( % a , % S ) S " pos p s | ` malformed_row ( p , err , s ) s -> sprintf " malformed_row ( % s , % a , % S ) S " ( parse_row_error_to_string err ) err pos p s | ` malformed_header ( p , s ) s -> sprintf " malformed_header ( % a , % s ) s " pos p s | _ -> sprintf " unknown_error "
let reserved_info = Hashtbl . Poly . of_alist_exn [ ( " AA " , ` string_value ) string_value ; ( " AC " , ` integer_value ) integer_value ; ( " AF " , ` float_value ) float_value ; ( " AN " , ` integer_value ) integer_value ; ( " BQ " , ` float_value ) float_value ; ( " CIGAR " , ` string_value ) string_value ; ( " DB " , ` flag_value ) flag_value ; ( " DP " , ` integer_value ) integer_value ; ( " H2 " , ` flag_value ) flag_value ; ( " MQ " , ` float_value ) float_value ; ( " MQ0 " , ` integer_value ) integer_value ; ( " NS " , ` integer_value ) integer_value ; ( " SB " , ` string_value ) string_value ; ( " SOMATIC " , ` flag_value ) flag_value ; ( " VALIDATED " , ` flag_value ) flag_value ; ( " IMPRECISE " , ` flag_value ) flag_value ; ( " NOVEL " , ` flag_value ) flag_value ; ( " END " , ` integer_value ) integer_value ; ( " SVTYPE " , ` string_value ) string_value ; ( " CIPOS " , ` integer_value ) integer_value ; ( " CIEND " , ` integer_value ) integer_value ; ( " HOMLEN " , ` integer_value ) integer_value ; ( " HOMSEQ " , ` integer_value ) integer_value ; ( " BKPTID " , ` string_value ) string_value ; ( " MEINFO " , ` string_value ) string_value ; ( " METRANS " , ` string_value ) string_value ; ( " DGVID " , ` string_value ) string_value ; ( " DBVARID " , ` string_value ) string_value ; ( " MATEID " , ` string_value ) string_value ; ( " PARID " , ` string_value ) string_value ; ( " EVENT " , ` string_value ) string_value ; ( " CILEN " , ` integer_value ) integer_value ; ( " CN " , ` integer_value ) integer_value ; ( " CNADJ " , ` integer_value ) integer_value ; ( " CICN " , ` integer_value ) integer_value ; ( " CICNADJ " , ` integer_value ) integer_value ] ( " GT " , ` string_value ) string_value ; ( " DP " , ` integer_value ) integer_value ; ( " FT " , ` string_value ) string_value ; ( " GL " , ` float_value ) float_value ; ( " GQ " , ` float_value ) float_value ; ( " HQ " , ` float_value ) float_value ; ( " CN " , ` integer_value ) integer_value ; ( " CNQ " , ` float_value ) float_value ; ( " CNL " , ` float_value ) float_value ; ( " NQ " , ` integer_value ) integer_value ; ( " HAP " , ` integer_value ) integer_value ; ( " AHAP " , ` integer_value ) integer_value ] ( " DEL " , Alt " Deletion relative to the reference ) " ; ( " INS " , Alt " Insertion of novel sequence relative to the reference ) " ; ( " DUP " , Alt " Region of elevated copy number relative to the reference ) " ; ( " INV " , Alt " Inversion of reference sequence ) " ; ( " CNV " , Alt " Copy number variable region ) " ; ( " DUP : TANDEM " , Alt " TANDEM Tandem duplication ) " ; ( " DEL : ME " , Alt " ME Deletion of mobile element relative to the reference ) " ; ( " INS : ME " , Alt " ME Insertion of a mobile element relative to the reference ) " ; ]
let default_meta = { vcfm_version = " < unknown " ; > vcfm_id_cache = Set . Poly . empty ; vcfm_info = Hashtbl . Poly . create ( ) ; vcfm_filters = [ ] ; vcfm_format = Hashtbl . Poly . create ( ) ; vcfm_alt = reserved_alt ; vcfm_arbitrary = Hashtbl . Poly . create ( ) ; vcfm_header = [ ] ; vcfm_samples = [ ] }
let string_to_vcfr_ref s = let s = String . uppercase s in if is_valid_dna s then Ok s else Error ( ` invalid_dna s ) s
let string_to_vcfr_info { vcfm_info ; _ } s = let go values = List . map ( String . split ~ on : ' ; ' s ) s ~ f ( : fun chunk -> let ( key , raw_value ) raw_value = Option . value ~ default ( : chunk , ) " " ( String . lsplit2 ~ on : ' = ' chunk ) chunk in let chunk_values = match Hashtbl . find vcfm_info key with | Some ( Info ( _t , ` flag_value , _description ) _description ) _description when String . equal raw_value " " -> Ok [ ` flag key ] key | Some ( Info ( n , t , _description ) _description ) _description -> coerce_n ~ f ( : coerce_to_vcf_info_type t ) t key n raw_value | None -> Error ( ` unknown_info key ) key in Result . map chunk_values ~ f ( : fun data -> Hashtbl . set values ~ key ~ data ) data ) data and values = Hashtbl . Poly . create ( ) in Result ( . map ( all_unit ( go values ) values ) values ~ f ( : Fn . const values ) values ) values
let string_to_vcfr_filter { vcfm_filters ; _ } s = match String . split ~ on : ' ; ' s with | [ " PASS ] " -> Ok [ ] | chunks -> match List . find chunks ~ f ( : fun chunk -> not ( List . Assoc . mem ~ equal : String . equal vcfm_filters chunk ) chunk ) chunk with | Some unknown_filter -> Error ( ` unknown_filter unknown_filter ) unknown_filter | None -> Ok chunks
let string_to_vcfr_ids { vcfm_id_cache ; _ } s = match String . split ~ on : ' ; ' s with | [ ] " . " -> Ok [ ] | chunks -> let duplicate_ids = List . filter chunks ~ f ( : Set . mem vcfm_id_cache ) vcfm_id_cache in if List . is_empty duplicate_ids then Ok chunks else Error ( ` duplicate_ids duplicate_ids ) duplicate_ids
let string_to_vcfr_alts { vcfm_alt ; _ } s = match String . split ~ on : ' , ' s with | [ ] " . " -> Ok [ ] | chunks -> let res = List . map chunks ~ f ( : fun chunk -> let n = String . length chunk in match Char ( . chunk [ . 0 ] 0 = ' < ' && chunk [ . n - 1 ] 1 = ' > ' , is_valid_dna chunk ) chunk with | ( true , _ ) _ -> if Hashtbl . mem vcfm_alt ( String . sub ~ pos : 1 ~ len ( : n - 2 ) 2 chunk ) chunk then Ok chunk else Error ( ` unknown_alt chunk ) chunk | ( false , true ) true -> Ok chunk | ( false , false ) false -> Error ( ` invalid_dna chunk ) chunk ) chunk in Result . all res
let list_to_vcfr_samples { vcfm_format ; vcfm_samples ; _ } chunks = let open Result . Monad_infix in let samples = Hashtbl . Poly . create ( ) in let go sample_keys id raw_sample = let sample_chunks = String . split ~ on : ' : ' raw_sample in if List ( . length sample_keys <> length sample_chunks ) sample_chunks then Error ( ` malformed_sample raw_sample ) raw_sample else let res = List . map2_exn sample_keys sample_chunks ~ f ( : fun key raw_value -> match Hashtbl . find vcfm_format key with | Some ( Format ( n , t , _description ) _description ) _description -> coerce_n ~ f ( : coerce_to_vcf_format_type t ) t key n raw_value >>= fun value -> Ok ( key , value ) value | None -> Error ( ` unknown_format key ) key ) key in Result ( . map ( all res ) res ~ f ( : fun data -> Hashtbl . set samples ~ key : id ~ data ) data ) data in match chunks with | raw_sample_keys :: raw_samples -> let sample_keys = String . split ~ on : ' : ' raw_sample_keys in let res = List . map2_exn vcfm_samples raw_samples ~ f ( : go sample_keys ) sample_keys in Result . map ( Result . all_unit res ) res ~ f ( : Fn . const samples ) samples | [ ] -> Ok samples
let list_to_vcf_row meta chunks = let open Result . Monad_infix in let n_chunks = List . length chunks and n_columns = List ( . length meta . vcfm_header + length meta . vcfm_samples ) vcfm_samples in match chunks with | vcfr_chrom :: raw_pos :: raw_id :: raw_ref :: raw_alt :: raw_qual :: raw_filter :: raw_info :: raw_samples when n_chunks = n_columns -> Safe . int_of_string raw_pos >>= fun vcfr_pos -> string_to_vcfr_ids meta raw_id >>= fun vcfr_ids -> string_to_vcfr_ref raw_ref >>= fun vcfr_ref -> string_to_vcfr_alts meta raw_alt >>= fun vcfr_alts -> string_to_vcfr_info meta raw_info >>= fun vcfr_info -> string_to_vcfr_filter meta raw_filter >>= fun vcfr_filter -> list_to_vcfr_samples meta raw_samples >>= fun vcfr_samples -> let row = { vcfr_chrom ; vcfr_pos ; vcfr_ids ; vcfr_ref ; vcfr_alts ; vcfr_qual = Result . ok ( Safe . float_of_string raw_qual ) raw_qual ; vcfr_filter ; vcfr_info ; vcfr_samples } in Ok row | _ -> Error ( ` invalid_row_length ( n_chunks , n_columns ) n_columns ) n_columns
module Transform = struct let next_vcf_header meta p = let open Lines . Buffer in let { vcfm_info ; vcfm_format ; _ } = meta in let l = Option . value_exn ( next_line p :> string option ) option in let chunks = List . filter ~ f : String ( . fun s -> s <> ) " " ( String . split ~ on : ' \ t ' l ) l in begin match chunks with | " # CHROM " :: " POS " :: " ID " :: " REF " :: " ALT " :: " QUAL " :: " FILTER " :: " INFO " :: rest -> begin match rest with | " FORMAT " :: ( ( _ :: _ ) _ as samples ) samples | ( [ ] as samples ) samples -> let merge_with_reserved ~ c = Hashtbl . merge ~ f ( : fun ~ key : _ v -> match v with | ` Left t -> Some ( c Unknown t " < reserved ) " > | ` Right parsed -> Some parsed | ` Both ( _t , parsed ) parsed -> Some parsed ) parsed in let vcfm_info = merge_with_reserved reserved_info vcfm_info ~ c ( : fun n t description -> Info ( n , t , description ) description ) description ; and vcfm_format = merge_with_reserved reserved_format vcfm_format ~ c ( : fun n t description -> Format ( n , t , description ) description ) description ; and ( vcfm_header , vcfm_samples ) vcfm_samples = if List . is_empty samples then ( chunks , samples ) samples else List . split_n chunks List ( . length chunks - length samples ) samples in Ok ( ` complete { meta with vcfm_info ; vcfm_format ; vcfm_header ; vcfm_samples } ) | _ :: _ -> Error ( ` malformed_header ( current_position p , l ) l ) l end | _ -> Error ( ` malformed_header ( current_position p , l ) l ) l end let next_vcf_meta meta p = let open Lines . Buffer in let { vcfm_info ; vcfm_filters ; vcfm_format ; vcfm_alt ; _ } = meta in match ( peek_line p :> string option ) option with | Some l when String . is_prefix l ~ prefix " " :## -> let _l = next_line p in let s = String . suffix l ( String . length l - 2 ) 2 in begin match String . lsplit2 s ~ on : ' = ' with | Some ( " fileformat " , v ) v -> Ok ( ` partial { meta with vcfm_version = v } ) | Some ( " INFO " , v ) v -> Scanf . sscanf v " < ID =% s , @ Number =% s , @ Type =% s , @ Description =% S " > ( fun id n t description -> let info_meta = Info ( string_to_vcf_number n , string_to_vcf_info_type t , description ) description in Hashtbl . set vcfm_info ~ key : id ~ data : info_meta ) info_meta ; Ok ( ` partial meta ) meta | Some ( " FILTER " , v ) v -> Scanf . sscanf v " < ID =% s , @ Description =% S " > ( fun id description -> let filter_meta = Filter description in let meta = { meta with vcfm_filters = ( id , filter_meta ) filter_meta :: vcfm_filters } in Ok ( ` partial meta ) meta ) meta | Some ( " FORMAT " , v ) v -> Scanf . sscanf v " < ID =% s , @ Number =% s , @ Type =% s , @ Description =% S " > ( fun id n t description -> let format_meta = Format ( string_to_vcf_number n , string_to_vcf_format_type t , description ) description in Hashtbl . set vcfm_format ~ key : id ~ data : format_meta ) format_meta ; Ok ( ` partial meta ) meta | Some ( " ALT " , v ) v -> Scanf . sscanf v " < ID =% s , @ Description =% S " > ( fun id description -> let alt_meta = Alt description in Hashtbl . set vcfm_alt ~ key : id ~ data : alt_meta ) alt_meta ; Ok ( ` partial meta ) meta | Some ( k , v ) v -> begin Hashtbl . set meta . vcfm_arbitrary ~ key : k ~ data : v ; Ok ( ` partial meta ) meta end | None -> Error ( ` malformed_meta ( current_position p , s ) s ) s end | Some _l -> next_vcf_header meta p | None -> Error ` not_ready let next_vcf_row meta p = let open Lines . Buffer in match ( next_line p :> string option ) option with | Some l when not ( String . is_empty l ) l -> let chunks = List . filter ~ f : String ( . fun s -> s <> ) " " ( String . split ~ on : ' \ t ' l ) l in begin match list_to_vcf_row meta chunks with | Ok row -> ` output ( Ok row ) row | Error err -> ` output ( Error ( ` malformed_row ( current_position p , err , l ) l ) l ) l end | Some _ | None -> ` not_ready let next meta_ref p = match ! meta_ref with | ` complete meta -> next_vcf_row meta p | ` partial meta -> begin match next_vcf_meta meta p with | Ok meta -> meta_ref := meta ; ` not_ready | Error ` not_ready -> ` not_ready | Error err -> ` output ( Error err ) err end let string_to_item ? filename ( ) = let name = sprintf " vcf_parser :% s " Option ( . value ~ default " " :<> filename ) filename in let meta_ref = ref ( ` partial default_meta ) default_meta in Lines . Transform . make_merge_error ~ name ? filename ~ next ( : next meta_ref ) meta_ref ( ) end
module type Cohttp_IO_S = sig type + ' a t val ( ) >>= : ' a t -> ( ' a -> ' b t ) t -> ' b t val return : ' a -> ' a t type ic type oc val iter : ( ' a -> unit t ) t -> ' a list -> unit t val read_line : ic -> string option t val read : ic -> int -> string t val read_exactly : ic -> int -> string option t val write : oc -> string -> unit t val flush : oc -> unit t end
module IO = struct type ' a t = ' a Lwt . t let ( >>= ) = Lwt ( . >>= ) let return = Lwt . return type ic = Lwt_io . input_channel type oc = Lwt_io . output_channel let iter = Lwt_list . iter_s let read_line = Lwt_io . read_line_opt let read ic count = Lwt . catch ( fun ( ) -> Lwt_io . read ~ count ic ) ic ( function End_of_file -> return " " | e -> Lwt . fail e ) e let read_exactly ic buf off len = Lwt . catch ( fun ( ) -> Lwt_io . read_into_exactly ic buf off len >>= fun ( ) -> return true ) true ( function End_of_file -> return false | e -> Lwt . fail e ) e let read_exactly ic len = let buf = Bytes . create len in read_exactly ic buf 0 len >>= function | true -> return ( Some ( Bytes . to_string buf ) buf ) buf | false -> return None let write = Lwt_io . write let flush = Lwt_io . flush end
let reader t = let frag = ref ( Cstruct . create 0 ) 0 in let rec aux buf ofs len = if len = 0 then return 0 else let available = Cstruct . length ! frag in if available = 0 then begin M . read t >>= function | Ok ` Eof -> return 0 | Ok ( ` Data b ) b -> frag := b ; aux buf ofs len | Error e -> Fmt . kstr Lwt . fail_with " % a " M . pp_error e end else begin let n = min available len in Cstruct . blit ! frag 0 ( Cstruct . of_bigarray buf ) buf ofs n ; frag := Cstruct . shift ! frag n ; return n end in aux
let writer t ( buf : Lwt_bytes . t ) t ( ofs : int ) int ( len : int ) int = let b = Cstruct . sub ( Cstruct . of_bigarray buf ) buf ofs len in M . write t b >>= function | Ok ( ) -> return len | Error ` Closed -> return 0 | Error e -> Fmt . kstr Lwt . fail_with " % a " M . pp_write_error e
let open_client ~ domid ~ port ( ? buffer_size = 1024 ) 1024 ( ) = M . client ~ domid ~ port ( ) >>= fun t -> let close ( ) = M . close t in let in_buffer = Lwt_bytes . create buffer_size in let ic = Lwt_io . make ~ buffer : in_buffer ~ mode : Lwt_io . input ~ close ( reader t ) t in let out_buffer = Lwt_bytes . create buffer_size in let oc = Lwt_io . make ~ buffer : out_buffer ~ mode : Lwt_io . output ( writer t ) t in return ( ic , oc ) oc
let open_server ~ domid ~ port ( ? buffer_size = 1024 ) 1024 ( ) = M . server ~ domid ~ port ~ read_size : buffer_size ~ write_size : buffer_size ( ) >>= fun t -> let close ( ) = M . close t in let in_buffer = Lwt_bytes . create buffer_size in let ic = Lwt_io . make ~ buffer : in_buffer ~ mode : Lwt_io . input ~ close ( reader t ) t in let out_buffer = Lwt_bytes . create buffer_size in let oc = Lwt_io . make ~ buffer : out_buffer ~ mode : Lwt_io . output ( writer t ) t in return ( ic , oc ) oc
module Kind = struct type t = | Git | Hg let of_dir_contents files = if String . Set . mem files " . git " then Some Git else if String . Set . mem files " . hg " then Some Hg else None let to_dyn t = Dyn . Variant ( ( match t with | Git -> " Git " | Hg -> " Hg " ) , [ ] ) let equal = ( = ) end
module T = struct type t = { root : Path . t ; kind : Kind . t } let to_dyn { root ; kind } = Dyn . record [ ( " root " , Path . to_dyn root ) ; ( " kind " , Kind . to_dyn kind ) ] let equal { root = ra ; kind = ka } { root = rb ; kind = kb } = Path . equal ra rb && Kind . equal ka kb let hash t = Path . hash t . root end
let git , hg = let get prog = lazy ( match Bin . which ~ path ( : Env . path Env . initial ) prog with | Some x -> x | None -> Utils . program_not_found prog ~ loc : None ) in ( get " git " , get " hg " )
let select git hg t = Memo . of_non_reproducible_fiber ( match t . kind with | Git -> git t | Hg -> hg t )
let prog t = Lazy . force ( match t . kind with | Git -> git | Hg -> hg )
let run t args = let open Fiber . O in let + s = Process . run_capture Strict ( prog t ) args ~ dir : t . root ~ env : Env . initial in String . trim s
let git_accept ( ) = Process . Accept ( Predicate_lang . union [ Element 0 ; Element 128 ] )
let run_git t args = let res = Process . run_capture ( git_accept ( ) ) ( prog t ) args ~ dir : t . root ~ env : Env . initial ~ stderr_to ( : Process . Io . file Config . dev_null Out ) in let open Fiber . O in let + res = res in match res with | Ok s -> Some ( String . trim s ) | Error 128 -> None | Error _ -> assert false
let hg_describe t = let open Fiber . O in let * s = run t [ " log " ; " -- rev " ; " . " ; " - T " ; " { latesttag } { latesttagdistance } " ] in let + id = run t [ " id " ; " - i " ] in let id , dirty_suffix = match String . drop_suffix id ~ suffix " " :+ with | Some id -> ( id , " - dirty " ) | None -> ( id , " " ) in let s = let s , dist = Option . value_exn ( String . rsplit2 s ~ on ' : ' ) in match s with | " null " -> id | _ -> ( match int_of_string dist with | 1 -> s | n -> sprintf " % s -% d -% s " s ( n - 1 ) id | exception _ -> sprintf " % s -% s -% s " s dist id ) in s ^ dirty_suffix
let make_fun name ~ git ~ hg = let memo = Memo . create name ~ input ( : module T ) ( select git hg ) in Staged . stage ( Memo . exec memo )
let describe = Staged . unstage @@ make_fun " vcs - describe " ~ git ( : fun t -> run_git t [ " describe " ; " -- always " ; " -- dirty " ; " -- abbrev = 7 " ] ) ~ hg ( : fun x -> let open Fiber . O in let + res = hg_describe x in Some res )
let commit_id = Staged . unstage @@ make_fun " vcs - commit - id " ~ git ( : fun t -> run_git t [ " rev - parse " ; " HEAD " ] ) ~ hg ( : fun t -> let open Fiber . O in let + res = run t [ " id " ; " - i " ] in Some res )
let files = let run_zero_separated_hg t args = Process . run_capture_zero_separated Strict ( prog t ) args ~ dir : t . root ~ env : Env . initial in let run_zero_separated_git t args = let open Fiber . O in let + res = Process . run_capture_zero_separated ( git_accept ( ) ) ( prog t ) args ~ dir : t . root ~ env : Env . initial in match res with | Ok s -> s | Error 128 -> [ ] | Error _ -> assert false in let f run args t = let open Fiber . O in let + l = run t args in List . map l ~ f : Path . in_source in Staged . unstage @@ make_fun " vcs - files " ~ git : ( f run_zero_separated_git [ " ls - tree " ; " - z " ; " - r " ; " -- name - only " ; " HEAD " ] ) ~ hg ( : f run_zero_separated_hg [ " files " ; " - 0 " ] )
let ( ) = init ( )
let temp_dir = lazy ( Path . of_string " vcs - tests " )
let ( ) = at_exit ( fun ( ) -> Path . rm_rf ( Lazy . force temp_dir ) )
let has_hg = match Lazy . force Vcs . hg with | ( _ : Path . t ) -> true | exception _ -> false
let run ( vcs : Vcs . t ) args = let prog , prog_str , real_args = match vcs . kind with | Git -> ( Vcs . git , " git " , args ) | Hg -> ( if has_hg then ( Vcs . hg , " hg " , args ) else ( Vcs . git , " hg " , match args with | [ " tag " ; s ; " - u " ; _ ] -> [ " tag " ; " - a " ; s ; " - m " ; s ] | [ " commit " ; " - m " ; msg ; " - u " ; _ ] -> [ " commit " ; " - m " ; msg ] | _ -> args ) ) in printf " $ % s \ n " ( List . map ( prog_str :: args ) ~ f : String . quote_for_shell |> String . concat ~ sep " : " ) ; Process . run Strict ( Lazy . force prog ) real_args ~ env : ( Env . add Env . initial ~ var " : GIT_DIR " ~ value ( : Filename . concat ( Path . to_absolute_filename vcs . root ) " . git " ) ) ~ dir : vcs . root ~ stdout_to ( : Process . Io . file Config . dev_null Process . Io . Out )
type action = | Init | Add of string | Write of string * string | Commit | Tag of string | Describe of string
let run_action ( vcs : Vcs . t ) action = match action with | Init -> run vcs [ " init " ; " - q " ] | Add fn -> run vcs [ " add " ; fn ] | Commit -> ( match vcs . kind with | Git -> run vcs [ " commit " ; " - m " ; " commit message " ] | Hg -> run vcs [ " commit " ; " - m " ; " commit message " ; " - u " ; " toto " ] ) | Write ( fn , s ) -> printf " $ echo % S > % s \ n " s fn ; Io . write_file ( Path . relative ( Lazy . force temp_dir ) fn ) s ; Fiber . return ( ) | Describe expected -> printf " $ % s describe [ . . . ] \ n " ( match vcs . kind with | Git -> " git " | Hg -> " hg " ) ; Memo . reset ( Memo . Invalidation . clear_caches ~ reason : Test ) ; let vcs = match vcs . kind with | Hg when not has_hg -> { vcs with kind = Git } | _ -> vcs in let + s = Memo . run ( Vcs . describe vcs ) in let s = Option . value s ~ default " : n / a " in let processed = String . split s ~ on ' ' :- |> List . map ~ f ( : fun s -> match s with | " " | " dirty " -> s | s when String . length s = 1 && String . for_all s ~ f ( : function | ' 0 ' . . ' 9 ' -> true | _ -> false ) -> s | _ when String . for_all s ~ f ( : function | ' 0 ' . . ' 9 ' | ' a ' . . ' z ' -> true | _ -> false ) -> " < commit - id " > | _ -> s ) |> String . concat ~ sep " " :- in printf " % s \ n " processed ; if processed <> expected then printf " Expected : % s \ nOriginal : % s \ n " expected s ; printf " \ n " | Tag s -> ( match vcs . kind with | Git -> run vcs [ " tag " ; " - a " ; s ; " - m " ; s ] | Hg -> run vcs [ " tag " ; s ; " - u " ; " toto " ] )
let run kind script = let ( lazy temp_dir ) = temp_dir in Path . rm_rf temp_dir ; Path . mkdir_p temp_dir ; let vcs = { Vcs . kind ; root = temp_dir } in let config = { Scheduler . Config . concurrency = 1 ; display = { verbosity = Short ; status_line = false } ; rpc = None ; stats = None } in Scheduler . Run . go ~ on_event ( : fun _ _ -> ( ) ) config ( fun ( ) -> Fiber . sequential_iter script ~ f ( : run_action vcs ) )
let script = [ Init ; Write ( " a " , " " ) - ; Add " a " ; Commit ; Describe " < commit - id " > ; Write ( " b " , " " ) - ; Add " b " ; Describe " < commit - id >- dirty " ; Commit ; Describe " < commit - id " > ; Tag " 1 . 0 " ; Describe " 1 . 0 " ; Write ( " c " , " " ) - ; Add " c " ; Describe " 1 . 0 - dirty " ; Commit ; Describe " 1 . 0 - 1 -< commit - id " > ; Write ( " d " , " " ) - ; Add " d " ; Describe " 1 . 0 - 1 -< commit - id >- dirty " ; Commit ; Describe " 1 . 0 - 2 -< commit - id " > ] run Git script ; [ % expect { | < commit - id > < commit - id >- dirty < commit - id > 1 . 0 1 . 0 - dirty 1 . 0 - 1 -< commit - id > 1 . 0 - 1 -< commit - id >- dirty 1 . 0 - 2 -< commit - id > } ] | run Hg script ; [ % expect { | < commit - id > < commit - id >- dirty < commit - id > 1 . 0 1 . 0 - dirty 1 . 0 - 1 -< commit - id > 1 . 0 - 1 -< commit - id >- dirty 1 . 0 - 2 -< commit - id > } ] |
type ' msg applicationCallbacks = { enqueue : ' msg -> unit ; }
type ' msg eventHandler = | EventHandlerCallback of string * ( Web . Node . event -> ' msg option ) | EventHandlerMsg of ' msg
type ' msg eventCache = { handler : Web . Node . event_cb ; cb : ( Web . Node . event -> ' msg option ) ref }
type ' msg property = | NoProp | RawProp of string * string | Attribute of string * string * string | Data of string * string | Event of string * ' msg eventHandler * ' msg eventCache option ref | Style of ( string * string ) list
type ' msg properties = ' msg property list