Skip to content

Commit

Permalink
serialize inf as strings
Browse files Browse the repository at this point in the history
  • Loading branch information
rickwierenga committed Jan 5, 2025
1 parent 8dd8c13 commit 5303983
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 3 deletions.
6 changes: 5 additions & 1 deletion pylabrobot/gui/welcome.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ window.addEventListener("load", () => {
const reader = new FileReader();

reader.onload = (e) => {
const deck = JSON.parse(e.target.result);
const deck = JSON.parse(e.target.result, (key, value) => {
if (value == "Infinity") return Infinity;
if (value == "-Infinity") return -Infinity;
return value;
});
fileContents = deck;

// TODO: validate deck on the server
Expand Down
2 changes: 1 addition & 1 deletion pylabrobot/resources/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def material_z_thickness(self) -> float:
def serialize(self) -> dict:
return {
**super().serialize(),
"max_volume": self.max_volume,
"max_volume": serialize(self.max_volume),
"material_z_thickness": self._material_z_thickness,
"compute_volume_from_height": serialize(self._compute_volume_from_height),
"compute_height_from_volume": serialize(self._compute_height_from_volume),
Expand Down
4 changes: 4 additions & 0 deletions pylabrobot/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import enum
import inspect
import marshal
import math
import sys
import types
from typing import Any, Dict, List, Union, cast
Expand All @@ -29,6 +30,9 @@ def serialize(obj: Any) -> JSON:
"""Serialize an object."""

if isinstance(obj, (int, float, str, bool, type(None))):
# infinities and NaNs are not valid JSON, so we convert them to strings
if isinstance(obj, float) and not math.isfinite(obj):
return "nan" if math.isnan(obj) else ("Infinity" if obj > 0 else "-Infinity")
return obj
if isinstance(obj, (list, tuple, set)):
return [serialize(item) for item in obj]
Expand Down
6 changes: 5 additions & 1 deletion pylabrobot/visualizer/vis.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,11 @@ function openSocket() {
// webSocket.onmessage = function (event) {
webSocket.addEventListener("message", function (event) {
var data = event.data;
data = JSON.parse(data);
data = JSON.parse(data, (key, value) => {
if (value == "Infinity") return Infinity;
if (value == "-Infinity") return -Infinity;
return value;
});
console.log(`[message] Data received from server:`, data);
handleEvent(data.id, data.event, data.data);
});
Expand Down

0 comments on commit 5303983

Please sign in to comment.