qmcchem/ocaml/Sample.ml

68 lines
1.8 KiB
OCaml
Raw Permalink Normal View History

2019-07-22 11:31:16 +02:00
open Sexplib.Std
2022-01-06 17:43:31 +01:00
type t =
2015-12-19 02:35:13 +01:00
| One_dimensional of float
| Multidimensional of (float array * int)
2019-07-22 11:31:16 +02:00
[@@deriving sexp]
2015-12-19 02:35:13 +01:00
let dimension = function
| One_dimensional _ -> 1
| Multidimensional (_,d) -> d
2022-01-06 17:43:31 +01:00
let to_float ?idx x =
2015-12-19 02:35:13 +01:00
match (idx,x) with
| None , One_dimensional x
2022-01-06 17:43:31 +01:00
| Some 0, One_dimensional x -> x
2015-12-19 02:35:13 +01:00
| Some i, One_dimensional x ->
failwith "Index should not be specified in One_dimensional"
| None , Multidimensional (x,_) -> x.(0)
| Some i, Multidimensional (x,s) when i < s -> x.(i)
2022-01-06 17:43:31 +01:00
| Some i, Multidimensional (x,s) ->
Printf.sprintf "Index out of bounds in Multidimensional
2015-12-19 02:35:13 +01:00
%d not in [0,%d[ " i s
|> failwith
2022-01-06 17:43:31 +01:00
let to_float_array = function
2015-12-19 02:35:13 +01:00
| One_dimensional _ -> failwith "Should be Multidimensional"
| Multidimensional (x,_) -> x
2022-01-06 17:43:31 +01:00
let of_float x =
2015-12-19 02:35:13 +01:00
One_dimensional x
2022-01-06 17:43:31 +01:00
let of_float_array ~dim x =
2015-12-19 02:35:13 +01:00
if (Array.length x) <> dim then
failwith "Inconsistent array size in of_float_array"
else
match dim with
| 1 -> One_dimensional x.(0)
| _ -> Multidimensional (x, dim)
let to_string = function
2019-07-14 18:50:44 +02:00
| One_dimensional x -> string_of_float x
2022-01-06 17:43:31 +01:00
| Multidimensional (x,_) ->
2019-07-14 18:50:44 +02:00
Array.map string_of_float x
|> Array.to_list
2022-01-06 17:43:31 +01:00
|> String.concat " "
2015-12-19 02:35:13 +01:00
2022-01-06 17:43:31 +01:00
let to_bytes = function
| One_dimensional x -> Qptypes.bytes_of_float x
| Multidimensional (x,_) ->
let b = Bytes.create (8 * Array.length x) in
Array.iteri (fun i x ->
Int64.bits_of_float x
2022-01-12 12:48:08 +01:00
|> Bytes.set_int64_ne b (i*8) ) x;
2022-01-06 17:43:31 +01:00
b
2022-01-11 13:41:13 +01:00
let of_bytes b =
match Bytes.length b with
| 8 -> let x = Qptypes.float_of_bytes b in
One_dimensional x
| l -> let len = l/8 in
2022-01-12 00:39:43 +01:00
let result =
2022-01-11 13:41:13 +01:00
Multidimensional ( Array.init len (fun i ->
2022-01-12 12:48:08 +01:00
Bytes.get_int64_ne b (i*8)
2022-01-11 13:41:13 +01:00
|> Int64.float_of_bits ),
len )
2022-01-12 00:39:43 +01:00
in
result