/
continuous_attribute.gleam
94 lines (86 loc) · 2.41 KB
/
continuous_attribute.gleam
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import gleam/string
import gleam/float
import gleam/int
import gleam/map.{Map}
import gleam/result
import gleam_zlists.{ZList} as zlist
import decode.{Decoder}
import gleam/jsone.{JsonValue}
import gleam_synapses/model/encoding/serialization.{
Attribute, AttributeSerialized, ContinuousAttribute, ContinuousAttributeSerialized,
}
pub fn parse(s: String) -> Float {
let trimmed = string.trim(s)
case tuple(float.parse(trimmed), int.parse(trimmed)) {
tuple(Ok(x), _) -> x
tuple(_, Ok(x)) -> int.to_float(x)
}
}
pub fn updated(
continuous_attribute: Attribute,
datapoint: Map(String, String),
) -> Attribute {
let ContinuousAttribute(key, min, max) = continuous_attribute
let Ok(v) =
datapoint
|> map.get(key)
|> result.map(parse)
ContinuousAttribute(key, min: float.min(v, min), max: float.max(v, max))
}
pub fn encode(continuous_attribute: Attribute, value: String) -> ZList(Float) {
let ContinuousAttribute(_, min, max) = continuous_attribute
case min == max {
True -> 0.5
False -> {
let nomin = parse(value) -. min
let denomin = max -. min
nomin /. denomin
}
}
|> zlist.singleton
}
pub fn decode(
continuous_attribute: Attribute,
encoded_values: ZList(Float),
) -> String {
let ContinuousAttribute(_, min, max) = continuous_attribute
case min == max {
True -> min
False -> {
let Ok(v) = zlist.head(encoded_values)
let factor = max -. min
v *. factor +. min
}
}
|> float.to_string
}
pub fn serialized(continuous_attribute: Attribute) -> AttributeSerialized {
let ContinuousAttribute(key, min, max) = continuous_attribute
ContinuousAttributeSerialized(key, min, max)
}
pub fn deserialized(
continuous_attribute_serialized: AttributeSerialized,
) -> Attribute {
let ContinuousAttributeSerialized(key, min, max) =
continuous_attribute_serialized
ContinuousAttribute(key, min, max)
}
pub fn json_encoded(
continuous_attribute_serialized: AttributeSerialized,
) -> JsonValue {
let ContinuousAttributeSerialized(key, min, max) =
continuous_attribute_serialized
jsone.object([
tuple("key", jsone.string(key)),
tuple("min", jsone.float(min)),
tuple("max", jsone.float(max)),
])
}
pub fn json_decoder() -> Decoder(AttributeSerialized) {
decode.map3(
ContinuousAttributeSerialized,
decode.field("key", decode.string()),
decode.field("min", decode.float()),
decode.field("max", decode.float()),
)
}