package picasso

  1. Overview
  2. Docs

Source file tools.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
let foi = float_of_int

let iof = int_of_float

(** removes ending zeros of a string *)
let trail_ending_zeros str =
  let len = String.length str in
  let rec aux cpt i =
    if i >= len then cpt
    else if str.[len - i - 1] = '0' then aux (cpt + 1) (i + 1)
    else cpt
  in
  let nb_end_zero = aux 0 0 in
  String.sub str 0 (len - nb_end_zero)

let pp_float ?max_decimals:(max = 16) fmt f =
  let i_c = iof (ceil f) in
  let i_f = iof (floor f) in
  let i =
    if abs_float (float i_c -. f) < abs_float (float i_f -. f) then i_c else i_f
  in
  if abs_float (foi i -. f) < 0.001 then Format.fprintf fmt "%i" i
  else
    Format.fprintf fmt "%s" (trail_ending_zeros (Format.asprintf "%.*f" max f))

let newline_sep fmt () = Format.fprintf fmt "\n"

let iterate f x0 next until =
  let rec loop () cur = if not (until cur) then loop (f cur) (next cur) in
  loop () x0

(* helper : project from a value n from [a;b] to [c;d] *)
let projection (a, b) (c, d) n =
  let perc (x, y) r = x +. (r *. (y -. x))
  and to_perc (x, y) r =
    if x < 0. then (r -. x) /. (y -. x) else (r -. x) /. (y -. x)
  in
  if b = a then c else perc (c, d) (to_perc (a, b) n)

let spawn_filename default1 default2 prefix ext =
  match default1 with
  | Some s -> s
  | None ->
      Filename.(
        temp_file ~temp_dir:current_dir_name
          (match default2 with None -> prefix | Some s -> s)
          ext )