File size: 93,346 Bytes
5980447 |
1 2 |
{"repo": "talmolab/sleap", "pull_number": 120, "instance_id": "talmolab__sleap-120", "issue_numbers": "", "base_commit": "03a1e1c772578e9f1e0118329f8cd21cec11eb73", "patch": "diff --git a/sleap/gui/active.py b/sleap/gui/active.py\n--- a/sleap/gui/active.py\n+++ b/sleap/gui/active.py\n@@ -660,7 +660,7 @@ def run_active_learning_pipeline(\n \n if not skip_learning:\n timestamp = datetime.now().strftime(\"%y%m%d_%H%M%S\")\n- inference_output_path = os.path.join(save_dir, f\"{timestamp}.inference.json\")\n+ inference_output_path = os.path.join(save_dir, f\"{timestamp}.inference.h5\")\n \n # Create Predictor from the results of training\n predictor = Predictor(sleap_models=training_jobs,\ndiff --git a/sleap/gui/app.py b/sleap/gui/app.py\n--- a/sleap/gui/app.py\n+++ b/sleap/gui/app.py\n@@ -514,6 +514,9 @@ def importData(self, filename=None, do_load=True):\n labels = filename\n filename = None\n has_loaded = True\n+ elif filename.endswith(\".h5\"):\n+ labels = Labels.load_hdf5(filename, video_callback=gui_video_callback)\n+ has_loaded = True\n elif filename.endswith((\".json\", \".json.zip\")):\n labels = Labels.load_json(filename, video_callback=gui_video_callback)\n has_loaded = True\n@@ -526,7 +529,7 @@ def importData(self, filename=None, do_load=True):\n has_loaded = True\n \n if do_load:\n- Instance.drop_all_nan_points(labels.all_instances)\n+\n self.labels = labels\n self.filename = filename\n \n@@ -1268,10 +1271,14 @@ def openProject(self, first_open=False):\n def saveProject(self):\n if self.filename is not None:\n filename = self.filename\n+\n if filename.endswith((\".json\", \".json.zip\")):\n compress = filename.endswith(\".zip\")\n Labels.save_json(labels = self.labels, filename = filename,\n compress = compress)\n+ elif filename.endswith(\".h5\"):\n+ Labels.save_hdf5(labels = self.labels, filename = filename)\n+\n # Mark savepoint in change stack\n self.changestack_savepoint()\n # Redraw. Not sure why, but sometimes we need to do this.\n@@ -1301,8 +1308,15 @@ def saveProjectAs(self):\n self.changestack_savepoint()\n # Redraw. Not sure why, but sometimes we need to do this.\n self.plotFrame()\n+ elif filename.endswith(\".h5\"):\n+ Labels.save_hdf5(labels = self.labels, filename = filename)\n+ self.filename = filename\n+ # Mark savepoint in change stack\n+ self.changestack_savepoint()\n+ # Redraw. Not sure why, but sometimes we need to do this.\n+ self.plotFrame()\n else:\n- QMessageBox(text=f\"File not saved. Only .json currently implemented.\").exec_()\n+ QMessageBox(text=f\"File not saved. Try saving as json.\").exec_()\n \n def closeEvent(self, event):\n if not self.changestack_has_changes():\ndiff --git a/sleap/instance.py b/sleap/instance.py\n--- a/sleap/instance.py\n+++ b/sleap/instance.py\n@@ -7,22 +7,24 @@\n import numpy as np\n import h5py as h5\n import pandas as pd\n+import cattr\n \n from typing import Dict, List, Optional, Union, Tuple\n \n-from attr import __init__\n+from numpy.lib.recfunctions import structured_to_unstructured\n \n from sleap.skeleton import Skeleton, Node\n from sleap.io.video import Video\n-from sleap.util import attr_to_dtype\n \n import attr\n \n+try:\n+ from typing import ForwardRef\n+except:\n+ from typing import _ForwardRef as ForwardRef\n \n-# This can probably be a namedtuple but has been made a full class just in case\n-# we need more complicated functionality later.\n-@attr.s(auto_attribs=True, slots=True)\n-class Point:\n+\n+class Point(np.record):\n \"\"\"\n A very simple class to define a labelled point and any metadata associated with it.\n \n@@ -30,41 +32,98 @@ class Point:\n x: The horizontal pixel location of the point within the image frame.\n y: The vertical pixel location of the point within the image frame.\n visible: Whether point is visible in the labelled image or not.\n+ complete: Has the point been verified by the a user labeler.\n \"\"\"\n \n- x: float = attr.ib(default=math.nan, converter=float)\n- y: float = attr.ib(default=math.nan, converter=float)\n- visible: bool = True\n- complete: bool = False\n+ # Define the dtype from the point class attributes plus some\n+ # additional fields we will use to relate point to instances and\n+ # nodes.\n+ dtype = np.dtype(\n+ [('x', 'f8'),\n+ ('y', 'f8'),\n+ ('visible', '?'),\n+ ('complete', '?')])\n+\n+ def __new__(cls, x: float = math.nan, y: float = math.nan,\n+ visible: bool = True, complete: bool = False):\n+\n+ # HACK: This is a crazy way to instantiate at new Point but I can't figure\n+ # out how recarray does it. So I just use it to make matrix of size 1 and\n+ # index in to get the np.record/Point\n+ # All of this is a giant hack so that Point(x=2,y=3) works like expected.\n+ val = PointArray(1)\n+ val[0] = (x, y, visible, complete)\n+ val = val[0]\n+\n+ # val.x = x\n+ # val.y = y\n+ # val.visible = visible\n+ # val.complete = complete\n+\n+ return val\n \n def __str__(self):\n return f\"({self.x}, {self.y})\"\n \n- @classmethod\n- def dtype(cls):\n+ def isnan(self):\n \"\"\"\n- Get the compound numpy dtype of a point. This is very important for\n- serialization.\n+ Are either of the coordinates a NaN value.\n \n Returns:\n- The compound numpy dtype of the point\n+ True if x or y is NaN, False otherwise.\n \"\"\"\n- return attr_to_dtype(cls)\n-\n- def isnan(self):\n return math.isnan(self.x) or math.isnan(self.y)\n \n \n-@attr.s(auto_attribs=True, slots=True)\n+# This turns PredictedPoint into an attrs class. Defines comparators for\n+# us and generaly makes it behave better. Crazy that this works!\n+Point = attr.s(these={name: attr.ib()\n+ for name in Point.dtype.names},\n+ init=False)(Point)\n+\n+\n class PredictedPoint(Point):\n \"\"\"\n A predicted point is an output of the inference procedure. It has all\n the properties of a labeled point with an accompanying score.\n \n Args:\n+ x: The horizontal pixel location of the point within the image frame.\n+ y: The vertical pixel location of the point within the image frame.\n+ visible: Whether point is visible in the labelled image or not.\n+ complete: Has the point been verified by the a user labeler.\n score: The point level prediction score.\n \"\"\"\n- score: float = attr.ib(default=0.0, converter=float)\n+\n+ # Define the dtype from the point class attributes plus some\n+ # additional fields we will use to relate point to instances and\n+ # nodes.\n+ dtype = np.dtype(\n+ [('x', 'f8'),\n+ ('y', 'f8'),\n+ ('visible', '?'),\n+ ('complete', '?'),\n+ ('score', 'f8')])\n+\n+ def __new__(cls, x: float = math.nan, y: float = math.nan,\n+ visible: bool = True, complete: bool = False,\n+ score: float = 0.0):\n+\n+ # HACK: This is a crazy way to instantiate at new Point but I can't figure\n+ # out how recarray does it. So I just use it to make matrix of size 1 and\n+ # index in to get the np.record/Point\n+ # All of this is a giant hack so that Point(x=2,y=3) works like expected.\n+ val = PredictedPointArray(1)\n+ val[0] = (x, y, visible, complete, score)\n+ val = val[0]\n+\n+ # val.x = x\n+ # val.y = y\n+ # val.visible = visible\n+ # val.complete = complete\n+ # val.score = score\n+\n+ return val\n \n @classmethod\n def from_point(cls, point: Point, score: float = 0.0):\n@@ -78,7 +137,126 @@ def from_point(cls, point: Point, score: float = 0.0):\n Returns:\n A scored point based on the point passed in.\n \"\"\"\n- return cls(**{**attr.asdict(point), 'score': score})\n+ return cls(**{**Point.asdict(point), 'score': score})\n+\n+\n+# This turns PredictedPoint into an attrs class. Defines comparators for\n+# us and generaly makes it behave better. Crazy that this works!\n+PredictedPoint = attr.s(these={name: attr.ib()\n+ for name in PredictedPoint.dtype.names},\n+ init=False)(PredictedPoint)\n+\n+\n+class PointArray(np.recarray):\n+ \"\"\"\n+ PointArray is a sub-class of numpy recarray which stores\n+ Point objects as records.\n+ \"\"\"\n+\n+ _record_type = Point\n+\n+ def __new__(subtype, shape, buf=None, offset=0, strides=None,\n+ formats=None, names=None, titles=None,\n+ byteorder=None, aligned=False, order='C'):\n+\n+ dtype = subtype._record_type.dtype\n+\n+ if dtype is not None:\n+ descr = np.dtype(dtype)\n+ else:\n+ descr = np.format_parser(formats, names, titles, aligned, byteorder)._descr\n+\n+ if buf is None:\n+ self = np.ndarray.__new__(subtype, shape, (subtype._record_type, descr), order=order)\n+ else:\n+ self = np.ndarray.__new__(subtype, shape, (subtype._record_type, descr),\n+ buffer=buf, offset=offset,\n+ strides=strides, order=order)\n+ return self\n+\n+ def __array_finalize__(self, obj):\n+ \"\"\"\n+ Overide __array_finalize__ on recarray because it converting the dtype\n+ of any np.void subclass to np.record, we don't want this.\n+ \"\"\"\n+ pass\n+\n+ @classmethod\n+ def make_default(cls, size: int):\n+ \"\"\"\n+ Construct a point array of specific size where each value in the array\n+ is assigned the default values for a Point.\n+\n+ Args:\n+ size: The number of points to allocate.\n+\n+ Returns:\n+ A point array with all elements set to Point()\n+ \"\"\"\n+ p = cls(size)\n+ p[:] = cls._record_type()\n+ return p\n+\n+ def __getitem__(self, indx):\n+ obj = super(np.recarray, self).__getitem__(indx)\n+\n+ # copy behavior of getattr, except that here\n+ # we might also be returning a single element\n+ if isinstance(obj, np.ndarray):\n+ if obj.dtype.fields:\n+ obj = obj.view(type(self))\n+ #if issubclass(obj.dtype.type, numpy.void):\n+ # return obj.view(dtype=(self.dtype.type, obj.dtype))\n+ return obj\n+ else:\n+ return obj.view(type=np.ndarray)\n+ else:\n+ # return a single element\n+ return obj\n+\n+class PredictedPointArray(PointArray):\n+ \"\"\"\n+ PredictedPointArray is analogous to PointArray except for predicted\n+ points.\n+ \"\"\"\n+ _record_type = PredictedPoint\n+\n+ @classmethod\n+ def from_array(cls, a: PointArray):\n+ \"\"\"\n+ Convert a PointArray to a PredictedPointArray, use the default\n+ attribute values for PredictedPoints.\n+\n+ Args:\n+ a: The array to convert.\n+\n+ Returns:\n+ A PredictedPointArray with the same points as a.\n+ \"\"\"\n+ v = cls.make_default(len(a))\n+\n+ for field in Point.dtype.names:\n+ v[field] = a[field]\n+\n+ return v\n+\n+ @classmethod\n+ def to_array(cls, a: 'PredictedPointArray'):\n+ \"\"\"\n+ Convert a PredictedPointArray to a normal PointArray.\n+\n+ Args:\n+ a: The array to convert.\n+\n+ Returns:\n+ The converted array.\n+ \"\"\"\n+ v = PointArray.make_default(len(a))\n+\n+ for field in Point.dtype.names:\n+ v[field] = a[field]\n+\n+ return v\n \n \n @attr.s(slots=True, cmp=False)\n@@ -113,23 +291,30 @@ def matches(self, other: 'Track'):\n # attributes _frame and _point_array_cache after init. These are private variables\n # that are created in post init so they are not serialized.\n \n-@attr.s(auto_attribs=True)\n+@attr.s(cmp=False, slots=True)\n class Instance:\n \"\"\"\n The class :class:`Instance` represents a labelled instance of skeleton\n \n Args:\n skeleton: The skeleton that this instance is associated with.\n- points: A dictionary where keys are skeleton node names and values are _points.\n+ points: A dictionary where keys are skeleton node names and values are Point objects. Alternatively,\n+ a point array whose length and order matches skeleton.nodes\n track: An optional multi-frame object track associated with this instance.\n This allows individual animals/objects to be tracked across frames.\n from_predicted: The predicted instance (if any) that this was copied from.\n+ frame: A back reference to the LabeledFrame that this Instance belongs to.\n+ This field is set when Instances are added to LabeledFrame objects.\n \"\"\"\n \n- skeleton: Skeleton\n+ skeleton: Skeleton = attr.ib()\n track: Track = attr.ib(default=None)\n from_predicted: Optional['PredictedInstance'] = attr.ib(default=None)\n- _points: Dict[Node, Union[Point, PredictedPoint]] = attr.ib(default=attr.Factory(dict))\n+ _points: PointArray = attr.ib(default=None)\n+ frame: Union['LabeledFrame', None] = attr.ib(default=None)\n+\n+ # The underlying Point array type that this instances point array should be.\n+ _point_array_type = PointArray\n \n @from_predicted.validator\n def _validate_from_predicted_(self, attribute, from_predicted):\n@@ -147,39 +332,57 @@ def _validate_all_points(self, attribute, points):\n Raises:\n ValueError: If a point is associated with a skeleton node name that doesn't exist.\n \"\"\"\n- is_string_dict = set(map(type, self._points)) == {str}\n- if is_string_dict:\n- for node_name in points.keys():\n- if not self.skeleton.has_node(node_name):\n- raise KeyError(f\"There is no node named {node_name} in {self.skeleton}\")\n+ if type(points) is dict:\n+ is_string_dict = set(map(type, points)) == {str}\n+ if is_string_dict:\n+ for node_name in points.keys():\n+ if not self.skeleton.has_node(node_name):\n+ raise KeyError(f\"There is no node named {node_name} in {self.skeleton}\")\n+ elif isinstance(points, PointArray):\n+ if len(points) != len(self.skeleton.nodes):\n+ raise ValueError(\"PointArray does not have the same number of rows as skeleton nodes.\")\n \n def __attrs_post_init__(self):\n \n- # If the points dict is non-empty, validate it.\n- if self._points:\n- # Check if the dict contains all strings\n- is_string_dict = set(map(type, self._points)) == {str}\n+ if not self.skeleton:\n+ raise ValueError(\"No skeleton set for Instance\")\n \n- # Check if the dict contains all Node objects\n- is_node_dict = set(map(type, self._points)) == {Node}\n+ # If the user did not pass a points list initialize a point array for future\n+ # points.\n+ if self._points is None:\n \n- # If the user fed in a dict whose keys are strings, these are node names,\n- # convert to node indices so we don't break references to skeleton nodes\n- # if the node name is relabeled.\n- if self._points and is_string_dict:\n- self._points = {self.skeleton.find_node(name): point for name,point in self._points.items()}\n+ # Initialize an empty point array that is the size of the skeleton.\n+ self._points = self._point_array_type.make_default(len(self.skeleton.nodes))\n \n- if not is_string_dict and not is_node_dict:\n- raise ValueError(\"points dictionary must be keyed by either strings \" +\n- \"(node names) or Nodes.\")\n+ else:\n+\n+ if type(self._points) is dict:\n+ parray = self._point_array_type.make_default(len(self.skeleton.nodes))\n+ Instance._points_dict_to_array(self._points, parray, self.skeleton)\n+ self._points = parray\n+\n+ @staticmethod\n+ def _points_dict_to_array(points, parray, skeleton):\n+\n+ # Check if the dict contains all strings\n+ is_string_dict = set(map(type, points)) == {str}\n+\n+ # Check if the dict contains all Node objects\n+ is_node_dict = set(map(type, points)) == {Node}\n \n- # Create here in post init so it is not serialized by cattrs, wish there was better way\n- # This field keeps track of any labeled frame that this Instance has been associated with.\n- self.frame: Union[LabeledFrame, None] = None\n+ # If the user fed in a dict whose keys are strings, these are node names,\n+ # convert to node indices so we don't break references to skeleton nodes\n+ # if the node name is relabeled.\n+ if points and is_string_dict:\n+ points = {skeleton.find_node(name): point for name, point in points.items()}\n \n- # A variable used to cache a constructed points_array call to save on time. This is only\n- # used when cached=True is passed to points_array\n- self._points_array_cache: Union[np.array, None] = None\n+ if not is_string_dict and not is_node_dict:\n+ raise ValueError(\"points dictionary must be keyed by either strings \" +\n+ \"(node names) or Nodes.\")\n+\n+ # Get rid of the points dict and replace with equivalent point array.\n+ for node, point in points.items():\n+ parray[skeleton.node_to_index(node)] = point\n \n def _node_to_index(self, node_name):\n \"\"\"\n@@ -195,7 +398,7 @@ def _node_to_index(self, node_name):\n \n def __getitem__(self, node):\n \"\"\"\n- Get the _points associated with particular skeleton node or list of skeleton nodes\n+ Get the Points associated with particular skeleton node or list of skeleton nodes\n \n Args:\n node: A single node or list of nodes within the skeleton associated with this instance.\n@@ -213,14 +416,10 @@ def __getitem__(self, node):\n \n return ret_list\n \n- if isinstance(node, str):\n- node = self.skeleton.find_node(node)\n- if node in self.skeleton.nodes:\n- if not node in self._points:\n- self._points[node] = Point()\n-\n+ try:\n+ node = self._node_to_index(node)\n return self._points[node]\n- else:\n+ except ValueError:\n raise KeyError(f\"The underlying skeleton ({self.skeleton}) has no node '{node}'\")\n \n def __contains__(self, node):\n@@ -233,7 +432,17 @@ def __contains__(self, node):\n Returns:\n bool: True if the point with the node name specified has a point in this instance.\n \"\"\"\n- return node in self._points\n+\n+ if type(node) is Node:\n+ node = node.name\n+\n+ if node not in self.skeleton:\n+ return False\n+\n+ node_idx = self._node_to_index(node)\n+\n+ # If the points are nan, then they haven't been allocated.\n+ return not self._points[node_idx].isnan()\n \n def __setitem__(self, node, value):\n \n@@ -250,18 +459,20 @@ def __setitem__(self, node, value):\n for n, v in zip(node, value):\n self.__setitem__(n, v)\n else:\n- if isinstance(node,str):\n- node = self.skeleton.find_node(node)\n-\n- if node in self.skeleton.nodes:\n- self._points[node] = value\n- else:\n+ try:\n+ node_idx = self._node_to_index(node)\n+ self._points[node_idx] = value\n+ except ValueError:\n raise KeyError(f\"The underlying skeleton ({self.skeleton}) has no node '{node}'\")\n \n def __delitem__(self, node):\n \"\"\" Delete node key and points associated with that node. \"\"\"\n- # TODO: handle this case somehow?\n- pass\n+ try:\n+ node_idx = self._node_to_index(node)\n+ self._points[node_idx].x = math.nan\n+ self._points[node_idx].y = math.nan\n+ except ValueError:\n+ raise KeyError(f\"The underlying skeleton ({self.skeleton}) has no node '{node}'\")\n \n def matches(self, other):\n \"\"\"\n@@ -273,6 +484,9 @@ def matches(self, other):\n Returns:\n True if match, False otherwise.\n \"\"\"\n+ if type(self) is not type(other):\n+ return False\n+\n if list(self.points()) != list(other.points()):\n return False\n \n@@ -297,10 +511,10 @@ def nodes(self):\n Get the list of nodes that have been labelled for this instance.\n \n Returns:\n- A list of nodes that have been labelled for this instance.\n+ A tuple of nodes that have been labelled for this instance.\n \n \"\"\"\n- return tuple(self._points.keys())\n+ return tuple(self.skeleton.nodes[i] for i, point in enumerate(self._points) if not point.isnan())\n \n @property\n def nodes_points(self):\n@@ -311,42 +525,51 @@ def nodes_points(self):\n Returns:\n The instance's (node, point) tuple pairs for all labelled point.\n \"\"\"\n- names_to_points = {node: point for node, point in self._points.items()}\n+ names_to_points = dict(zip(self.nodes, self.points()))\n return names_to_points.items()\n \n- def points(self) -> Tuple:\n+ def points(self) -> Tuple[Point]:\n \"\"\"\n Return the list of labelled points, in order they were labelled.\n \n Returns:\n The list of labelled points, in order they were labelled.\n \"\"\"\n- return tuple(self._points.values())\n+ return tuple(point for point in self._points if not point.isnan())\n \n- def points_array(self, cached=False, invisible_as_nan=False) -> np.ndarray:\n+ def points_array(self, copy: bool = True,\n+ invisible_as_nan: bool = False,\n+ full: bool = False) -> np.ndarray:\n \"\"\"\n Return the instance's points in array form.\n \n Args:\n- cached: If True, use a cached version of the points data if available,\n- create cache if it doesn't exist. If False, recompute and cache each\n- call.\n+ copy: If True, the return a copy of the points array as an\n+ Nx2 ndarray where first column is x and second column is y.\n+ If False, return a view of the underlying recarray.\n+ invisible_as_nan: Should invisible points be marked as NaN.\n+ full: If True, return the raw underlying recarray with all attributes\n+ of the point, if not, return just the x and y coordinate. Assumes\n+ copy is False and invisible_as_nan is False.\n Returns:\n A Nx2 array containing x and y coordinates of each point\n as the rows of the array and N is the number of nodes in the skeleton.\n The order of the rows corresponds to the ordering of the skeleton nodes.\n Any skeleton node not defined will have NaNs present.\n \"\"\"\n- if not cached or (cached and self._points_array_cache is None):\n- pts = np.ndarray((len(self.skeleton.nodes), 2))\n- for i, n in enumerate(self.skeleton.nodes):\n- p = self._points.get(n, Point())\n- pts[i, 0] = p.x if p.visible or not invisible_as_nan else np.nan\n- pts[i, 1] = p.y if p.visible or not invisible_as_nan else np.nan\n \n- self._points_array_cache = pts\n+ if full:\n+ return self._points\n+\n+ if not copy and not invisible_as_nan:\n+ return self._points[['x', 'y']]\n+ else:\n+ parray = structured_to_unstructured(self._points[['x', 'y']])\n+\n+ if invisible_as_nan:\n+ parray[self._points.visible is False, :] = math.nan\n \n- return self._points_array_cache\n+ return parray\n \n @property\n def centroid(self) -> np.ndarray:\n@@ -355,250 +578,6 @@ def centroid(self) -> np.ndarray:\n centroid = np.nanmedian(points, axis=0)\n return centroid\n \n- @classmethod\n- def to_pandas_df(cls, instances: Union['Instance', List['Instance']], skip_nan:bool = True) -> pd.DataFrame:\n- \"\"\"\n- Given an instance or list of instances, generate a pandas DataFrame that contains\n- all of the data in normalized form.\n- Args:\n- instances: A single instance or list of instances.\n- skip_nan: Whether to drop points that have NaN values for x or y.\n-\n- Returns:\n- A pandas DataFrame that contains all of the isntance's points level data\n- in and normalized form. The columns of the DataFrame are:\n-\n- * id - A unique number for each row of the table.\n- * instanceId - a unique id for each unique instance.\n- * skeleton - the name of the skeleton that this point is a part of.\n- * node - A string specifying the name of the skeleton node that this point value corresponds.\n- * videoId - A string specifying the video that this instance is in.\n- * frameIdx - The frame number of the video that this instance occurs on.\n- * visible - Whether the point in this row for this instance is visible.\n- * x - The horizontal pixel position of this node for this instance.\n- * y - The vertical pixel position of this node for this instance.\n- \"\"\"\n-\n- # If this is a single instance, make it a list\n- if type(instances) is Instance:\n- instances = [instances]\n-\n- # Lets construct a list of dicts which will be records for the pandas data frame\n- records = []\n-\n- # Extract all the data from each instance and its points\n- id = 0\n- for instance_id, instance in enumerate(instances):\n-\n- # Get all the attributes from the instance except the points dict or from_predicted\n- irecord = {'id': id, 'instance_id': instance_id,\n- **attr.asdict(instance, filter=lambda attr, value: attr.name not in (\"_points\", \"from_predicted\"))}\n-\n- # Convert the skeleton to it's name\n- irecord['skeleton'] = irecord['skeleton'].name\n-\n- # FIXME: Do the same for the video\n-\n- for (node, point) in instance.nodes_points:\n-\n- # Skip any NaN points if the user has asked for it.\n- if skip_nan and (math.isnan(point.x) or math.isnan(point.y)):\n- continue\n-\n- precord = {'node': node.name, **attr.asdict(point)} # FIXME: save other node attributes?\n-\n- records.append({**irecord, **precord})\n-\n- id = id + 1\n-\n- # Construct a pandas data frame from this list of instances\n- if len(records) == 1:\n- df = pd.DataFrame.from_records(records, index=[0])\n- else:\n- df = pd.DataFrame.from_records(records)\n-\n- return df\n-\n- @classmethod\n- def save_hdf5(cls, file: Union[str, h5.File],\n- instances: Union['Instance', List['Instance']],\n- skip_nan: bool = True):\n- \"\"\"\n- Write the instance point level data to an HDF5 file and group. This\n- function writes the data to an HDF5 group not a dataset. Each\n- column of the data is a dataset. The datasets within the group\n- will be all the same length (the total number of points across all\n- instances). They are as follows:\n-\n- * id - A unique number for each row of the table.\n- * instanceId - a unique id for each unique instance.\n- * skeleton - the name of the skeleton that this point is a part of.\n- * node - A string specifying the name of the skeleton node that this point value corresponds.\n- * videoId - A string specifying the video that this instance is in.\n- * frameIdx - The frame number of the video that this instance occurs on.\n- * visible - Whether the point in this row for this instance is visible.\n- * x - The horizontal pixel position of this node for this instance.\n- * y - The vertical pixel position of this node for this instance.\n-\n- Args:\n- file: The HDF5 file to save the instance data to.\n- instances: A single instance or list of instances.\n- skip_nan: Whether to drop points that have NaN values for x or y.\n-\n- Returns:\n- None\n- \"\"\"\n-\n- # Make it into a list of length one if needed.\n- if type(instances) is Instance:\n- instances = [instances]\n-\n- if type(file) is str:\n- with h5.File(file) as _file:\n- Instance._save_hdf5(file=_file, instances=instances, skip_nan=skip_nan)\n- else:\n- Instance._save_hdf5(file=file, instances=instances, skip_nan=skip_nan)\n-\n- @classmethod\n- def _save_hdf5(cls, file: h5.File, instances: List['Instance'], skip_nan: bool = True):\n-\n- # Get all the unique skeleton objects in this list of instances\n- skeletons = {i.skeleton for i in instances}\n-\n- # First, lets save the skeletons to the file\n- Skeleton.save_all_hdf5(file=file, skeletons=list(skeletons))\n-\n- # Second, lets get the instance data as a pandas data frame.\n- df = cls.to_pandas_df(instances=instances, skip_nan=skip_nan)\n-\n- # If the group doesn't exists, create it, but do so with track order.\n- # If it does exists, leave it be.\n- if 'points' not in file:\n- group = file.create_group('points', track_order=True)\n- else:\n- group = file['points']\n-\n- # Write each column as a data frame.\n- for col in df:\n- vals = df[col].values\n- if col in group:\n- del group[col]\n-\n- # If the column are objects (should be strings), convert to dtype=S, strings as per\n- # h5py recommendations.\n- if vals.dtype == np.dtype('O'):\n- dtype = h5.special_dtype(vlen=str)\n- group.create_dataset(name=col, shape=vals.shape,\n- data=vals,\n- dtype=dtype,\n- compression=\"gzip\")\n- else:\n- group.create_dataset(name=col, shape=vals.shape,\n- data=vals, compression=\"gzip\")\n-\n- @classmethod\n- def load_hdf5(cls, file: Union[h5.File, str]) -> List['Instance']:\n- \"\"\"\n- Load instance data from an HDF5 dataset.\n-\n- Args:\n- file: The name of the HDF5 file or the open h5.File object.\n-\n- Returns:\n- A list of Instance objects.\n- \"\"\"\n-\n- if type(file) is str:\n- with h5.File(file) as _file:\n- return Instance._load_hdf5(_file)\n- else:\n- return Instance._load_hdf5(file)\n-\n- @classmethod\n- def _load_hdf5(self, file: h5.File):\n-\n- # First, get all the skeletons in the HDF5 file\n- skeletons = Skeleton.load_all_hdf5(file=file, return_dict=True)\n-\n- if 'points' not in file:\n- raise ValueError(\"No instance data found in dataset.\")\n-\n- group = file['points']\n-\n- # Next get a dict that contains all the datasets for the instance\n- # data.\n- records = {}\n- for key, dset in group.items():\n- records[key] = dset[...]\n-\n- # Convert to a data frame.\n- df = pd.DataFrame.from_dict(records)\n-\n- # Lets first create all the points, start by grabbing the Point columns, grab only\n- # columns that exist. This is just in case we are reading an older form of the dataset\n- # format and the fields don't line up.\n- point_cols = [f.name for f in attr.fields(Point)]\n- point_cols = list(filter(lambda x: x in group, point_cols))\n-\n- # Extract the points columns and convert dicts of keys and values.\n- points = df[[*point_cols]].to_dict('records')\n-\n- # Convert to points dicts to points objects\n- points = [Point(**args) for args in points]\n-\n- # Instance columns\n- instance_cols = [f.name for f in attr.fields(Instance)]\n- instance_cols = list(filter(lambda x: x in group, instance_cols))\n-\n- instance_records = df[[*instance_cols]].to_dict('records')\n-\n- # Convert skeletons references to skeleton objects\n- for r in instance_records:\n- r['skeleton'] = skeletons[r['skeleton']]\n-\n- instances: List[Instance] = []\n- curr_id = -1 # Start with an invalid instance id so condition is tripped\n- for idx, r in enumerate(instance_records):\n- if curr_id == -1 or curr_id != df['instance_id'].values[idx]:\n- curr_id = df['instance_id'].values[idx]\n- curr_instance = Instance(**r)\n- instances.append(curr_instance)\n-\n- # Add the point the instance\n- curr_instance[df['node'].values[idx]] = points[idx]\n-\n- return instances\n-\n- def drop_nan_points(self):\n- \"\"\"\n- Drop any points for the instance that are not completely specified.\n-\n- Returns:\n- None\n- \"\"\"\n- is_nan = []\n- for n, p in self._points.items():\n- if p.isnan():\n- is_nan.append(n)\n-\n- # Remove them\n- for n in is_nan:\n- self._points.pop(n, None)\n-\n- @classmethod\n- def drop_all_nan_points(cls, instances: List['Instance']):\n- \"\"\"\n- Call drop_nan_points on a list of Instances.\n-\n- Args:\n- instances: The list of instances to call drop_nan_points() on.\n-\n- Returns:\n- None\n- \"\"\"\n- for i in instances:\n- i.drop_nan_points()\n-\n @property\n def frame_idx(self) -> Union[None, int]:\n \"\"\"\n@@ -614,7 +593,7 @@ def frame_idx(self) -> Union[None, int]:\n return self.frame.frame_idx\n \n \n-@attr.s(auto_attribs=True)\n+@attr.s(cmp=False, slots=True)\n class PredictedInstance(Instance):\n \"\"\"\n A predicted instance is an output of the inference procedure. It is\n@@ -625,8 +604,12 @@ class PredictedInstance(Instance):\n \"\"\"\n score: float = attr.ib(default=0.0, converter=float)\n \n+ # The underlying Point array type that this instances point array should be.\n+ _point_array_type = PredictedPointArray\n+\n def __attrs_post_init__(self):\n super(PredictedInstance, self).__attrs_post_init__()\n+\n if self.from_predicted is not None:\n raise ValueError(\"PredictedInstance should not have from_predicted.\")\n \n@@ -645,14 +628,92 @@ def from_instance(cls, instance: Instance, score):\n Returns:\n A PredictedInstance for the given Instance.\n \"\"\"\n- kw_args = attr.asdict(instance, recurse=False)\n- kw_args['points'] = {key: PredictedPoint.from_point(val)\n- for key, val in kw_args['_points'].items()}\n- del kw_args['_points']\n+ kw_args = attr.asdict(instance, recurse=False, filter=lambda attr, value: attr.name != \"_points\")\n+ kw_args['points'] = PredictedPointArray.from_array(instance._points)\n kw_args['score'] = score\n return cls(**kw_args)\n \n \n+def make_instance_cattr():\n+ \"\"\"\n+ Create a cattr converter for handling Lists of Instances/PredictedInstances\n+\n+ Returns:\n+ A cattr converter with hooks registered for structuring and unstructuring\n+ Instances.\n+ \"\"\"\n+\n+ converter = cattr.Converter()\n+\n+ #### UNSTRUCTURE HOOKS\n+\n+ # JSON dump cant handle NumPy bools so convert them. These are present\n+ # in Point/PredictedPoint objects now since they are actually custom numpy dtypes.\n+ converter.register_unstructure_hook(np.bool_, bool)\n+\n+ converter.register_unstructure_hook(PointArray, lambda x: None)\n+ converter.register_unstructure_hook(PredictedPointArray, lambda x: None)\n+ def unstructure_instance(x: Instance):\n+\n+ # Unstructure everything but the points array and frame attribute\n+ d = {field.name: converter.unstructure(x.__getattribute__(field.name))\n+ for field in attr.fields(x.__class__)\n+ if field.name not in ['_points', 'frame']}\n+\n+ # Replace the point array with a dict\n+ d['_points'] = converter.unstructure({k: v for k, v in x.nodes_points})\n+\n+ return d\n+\n+ converter.register_unstructure_hook(Instance, unstructure_instance)\n+ converter.register_unstructure_hook(PredictedInstance, unstructure_instance)\n+\n+ ## STRUCTURE HOOKS\n+\n+ def structure_points(x, type):\n+ if 'score' in x.keys():\n+ return cattr.structure(x, PredictedPoint)\n+ else:\n+ return cattr.structure(x, Point)\n+\n+ converter.register_structure_hook(Union[Point, PredictedPoint], structure_points)\n+\n+ def structure_instances_list(x, type):\n+ inst_list = []\n+ for inst_data in x:\n+ if 'score' in inst_data.keys():\n+ inst = converter.structure(inst_data, PredictedInstance)\n+ else:\n+ inst = converter.structure(inst_data, Instance)\n+ inst_list.append(inst)\n+\n+ return inst_list\n+\n+ converter.register_structure_hook(Union[List[Instance], List[PredictedInstance]],\n+ structure_instances_list)\n+\n+ converter.register_structure_hook(ForwardRef('PredictedInstance'),\n+ lambda x, type: converter.structure(x, PredictedInstance))\n+\n+ # We can register structure hooks for point arrays that do nothing\n+ # because Instance can have a dict of points passed to it in place of\n+ # a PointArray\n+ def structure_point_array(x, t):\n+ if x:\n+ point1 = x[list(x.keys())[0]]\n+ if 'score' in point1.keys():\n+ return converter.structure(x, Dict[Node, PredictedPoint])\n+ else:\n+ return converter.structure(x, Dict[Node, Point])\n+ else:\n+ return {}\n+\n+ converter.register_structure_hook(PointArray, structure_point_array)\n+ converter.register_structure_hook(PredictedPointArray, structure_point_array)\n+\n+ return converter\n+\n+\n @attr.s(auto_attribs=True)\n class LabeledFrame:\n video: Video = attr.ib()\n@@ -786,4 +847,5 @@ def merge_frames(labeled_frames, video):\n # remove labeled frames with no instances\n labeled_frames = list(filter(lambda lf: len(lf.instances),\n labeled_frames))\n- return labeled_frames\n\\ No newline at end of file\n+ return labeled_frames\n+\ndiff --git a/sleap/io/dataset.py b/sleap/io/dataset.py\n--- a/sleap/io/dataset.py\n+++ b/sleap/io/dataset.py\n@@ -17,6 +17,7 @@\n import attr\n import cattr\n import json\n+import rapidjson\n import shutil\n import tempfile\n import numpy as np\n@@ -35,10 +36,38 @@\n \n from sleap.skeleton import Skeleton, Node\n from sleap.instance import Instance, Point, LabeledFrame, \\\n- Track, PredictedPoint, PredictedInstance\n+ Track, PredictedPoint, PredictedInstance, \\\n+ make_instance_cattr, PointArray, PredictedPointArray\n from sleap.rangelist import RangeList\n from sleap.io.video import Video\n-from sleap.util import save_dict_to_hdf5\n+from sleap.util import uniquify\n+\n+\n+def json_loads(json_str: str):\n+ try:\n+ return rapidjson.loads(json_str)\n+ except:\n+ return json.loads(json_str)\n+\n+def json_dumps(d: Dict, filename: str = None):\n+ \"\"\"\n+ A simple wrapper around the JSON encoder we are using.\n+\n+ Args:\n+ d: The dict to write.\n+ f: The filename to write to.\n+\n+ Returns:\n+ None\n+ \"\"\"\n+ import codecs\n+ encoder = rapidjson\n+\n+ if filename:\n+ with open(filename, 'w') as f:\n+ encoder.dump(d, f, ensure_ascii=False)\n+ else:\n+ return encoder.dumps(d)\n \n \"\"\"\n The version number to put in the Labels JSON format.\n@@ -76,37 +105,50 @@ def __attrs_post_init__(self):\n \n # Add any videos that are present in the labels but\n # missing from the video list\n- self.videos = list(set(self.videos).union({label.video for label in self.labels}))\n+ if len(self.videos) == 0:\n+ self.videos = list({label.video for label in self.labels})\n \n # Ditto for skeletons\n- self.skeletons = list(set(self.skeletons).union({instance.skeleton\n- for label in self.labels\n- for instance in label.instances}))\n+ if len(self.skeletons) == 0:\n+ self.skeletons = list({instance.skeleton\n+ for label in self.labels\n+ for instance in label.instances})\n \n # Ditto for nodes\n- self.nodes = list(set(self.nodes).union({node for skeleton in self.skeletons for node in skeleton.nodes}))\n-\n- # Keep the tracks we already have\n- tracks = set(self.tracks)\n+ if len(self.nodes) == 0:\n+ self.nodes = list({node\n+ for skeleton in self.skeletons\n+ for node in skeleton.nodes})\n+\n+ # Ditto for tracks, a pattern is emerging here\n+ if len(self.tracks) == 0:\n+\n+ # Add tracks from any Instances or PredictedInstances\n+ tracks = {instance.track\n+ for frame in self.labels\n+ for instance in frame.instances\n+ if instance.track}\n+\n+ # Add tracks from any PredictedInstance referenced by instance\n+ # This fixes things when there's a referenced PredictionInstance\n+ # which is no longer in the frame.\n+ tracks = tracks.union({instance.from_predicted.track\n+ for frame in self.labels\n+ for instance in frame.instances\n+ if instance.from_predicted\n+ and instance.from_predicted.track})\n+\n+ self.tracks = list(tracks)\n \n- # Add tracks from any Instances or PredictedInstances\n- tracks = tracks.union({instance.track\n- for frame in self.labels\n- for instance in frame.instances\n- if instance.track})\n+ # Lets sort the tracks by spawned on and then name\n+ self.tracks.sort(key=lambda t:(t.spawned_on, t.name))\n \n- # Add tracks from any PredictedInstance referenced by instance\n- # This fixes things when there's a referenced PredictionInstance\n- # which is no longer in the frame.\n- tracks = tracks.union({instance.from_predicted.track\n- for frame in self.labels\n- for instance in frame.instances\n- if instance.from_predicted\n- and instance.from_predicted.track})\n+ self._update_lookup_cache()\n \n- # Lets sort the tracks by spawned on and then name\n- self.tracks = sorted(list(tracks), key=lambda t:(t.spawned_on, t.name))\n+ # Create a variable to store a temporary storage directory. When we unzip\n+ self.__temp_dir = None\n \n+ def _update_lookup_cache(self):\n # Data structures for caching\n self._lf_by_video = dict()\n self._frame_idx_map = dict()\n@@ -116,9 +158,6 @@ def __attrs_post_init__(self):\n self._frame_idx_map[video] = {lf.frame_idx: lf for lf in self._lf_by_video[video]}\n self._track_occupancy[video] = self._make_track_occupany(video)\n \n- # Create a variable to store a temporary storage directory. When we unzip\n- self.__temp_dir = None\n-\n # Below are convenience methods for working with Labels as list.\n # Maybe we should just inherit from list? Maybe this class shouldn't\n # exists since it is just a list really with some class methods. I\n@@ -599,13 +638,16 @@ def merge_matching_frames(self, video=None):\n else:\n self.labeled_frames = LabeledFrame.merge_frames(self.labeled_frames, video=video)\n \n- def to_dict(self):\n+ def to_dict(self, skip_labels: bool = False):\n \"\"\"\n Serialize all labels in the underling list of LabeledFrames to a\n dict structure. This function returns a nested dict structure\n composed entirely of primitive python types. It is used to create\n JSON and HDF5 serialized datasets.\n \n+ Args:\n+ skip_labels: If True, skip labels serialization and just do the metadata.\n+\n Returns:\n A dict containing the followings top level keys:\n * version - The version of the dict/json serialization format.\n@@ -617,6 +659,7 @@ def to_dict(self):\n * suggestions - The suggested frames.\n * negative_anchors - The negative training sample anchors.\n \"\"\"\n+\n # FIXME: Update list of nodes\n # We shouldn't have to do this here, but for some reason we're missing nodes\n # which are in the skeleton but don't have points (in the first instance?).\n@@ -626,12 +669,13 @@ def to_dict(self):\n # of video and skeleton objects present in the labels. We will serialize these\n # as references to the above constructed lists to limit redundant data in the\n # json\n- label_cattr = cattr.Converter()\n- label_cattr.register_unstructure_hook(Skeleton, lambda x: self.skeletons.index(x))\n- label_cattr.register_unstructure_hook(Video, lambda x: self.videos.index(x))\n- label_cattr.register_unstructure_hook(Node, lambda x: self.nodes.index(x))\n- label_cattr.register_unstructure_hook(Track, lambda x: self.tracks.index(x))\n+ label_cattr = make_instance_cattr()\n+ label_cattr.register_unstructure_hook(Skeleton, lambda x: str(self.skeletons.index(x)))\n+ label_cattr.register_unstructure_hook(Video, lambda x: str(self.videos.index(x)))\n+ label_cattr.register_unstructure_hook(Node, lambda x: str(self.nodes.index(x)))\n+ label_cattr.register_unstructure_hook(Track, lambda x: str(self.tracks.index(x)))\n \n+ # Make a converter for the top level skeletons list.\n idx_to_node = {i: self.nodes[i] for i in range(len(self.nodes))}\n \n skeleton_cattr = Skeleton.make_cattr(idx_to_node)\n@@ -642,12 +686,14 @@ def to_dict(self):\n 'skeletons': skeleton_cattr.unstructure(self.skeletons),\n 'nodes': cattr.unstructure(self.nodes),\n 'videos': Video.cattr().unstructure(self.videos),\n- 'labels': label_cattr.unstructure(self.labeled_frames),\n 'tracks': cattr.unstructure(self.tracks),\n 'suggestions': label_cattr.unstructure(self.suggestions),\n 'negative_anchors': label_cattr.unstructure(self.negative_anchors)\n }\n \n+ if not skip_labels:\n+ dicts['labels'] = label_cattr.unstructure(self.labeled_frames)\n+\n return dicts\n \n def to_json(self):\n@@ -660,7 +706,7 @@ def to_json(self):\n \"\"\"\n \n # Unstructure the data into dicts and dump to JSON.\n- return json.dumps(self.to_dict())\n+ return json_dumps(self.to_dict())\n \n @staticmethod\n def save_json(labels: 'Labels', filename: str,\n@@ -719,11 +765,8 @@ def save_json(labels: 'Labels', filename: str,\n d = labels.to_dict()\n d['videos'] = Video.cattr().unstructure(new_videos)\n \n- # We can't call Labels.to_json, so we need to do this here. Not as clean as I\n- # would like.\n- json_str = json.dumps(d)\n else:\n- json_str = labels.to_json()\n+ d = labels.to_dict()\n \n if compress or save_frame_data:\n \n@@ -732,23 +775,22 @@ def save_json(labels: 'Labels', filename: str,\n filename = re.sub(\"(\\.json)?(\\.zip)?$\", \".json\", filename)\n \n # Write the json to the tmp directory, we will zip it up with the frame data.\n- with open(os.path.join(tmp_dir, os.path.basename(filename)), 'w') as file:\n- file.write(json_str)\n+ full_out_filename = os.path.join(tmp_dir, os.path.basename(filename))\n+ json_dumps(d, full_out_filename)\n \n # Create the archive\n shutil.make_archive(base_name=filename, root_dir=tmp_dir, format='zip')\n \n # If the user doesn't want to compress, then just write the json to the filename\n else:\n- with open(filename, 'w') as file:\n- file.write(json_str)\n+ json_dumps(d, filename)\n \n @classmethod\n def from_json(cls, data: Union[str, dict], match_to: Optional['Labels'] = None) -> 'Labels':\n \n # Parse the json string if needed.\n- if data is str:\n- dicts = json.loads(data)\n+ if type(data) is str:\n+ dicts = json_loads(data)\n else:\n dicts = data\n \n@@ -798,41 +840,25 @@ def from_json(cls, data: Union[str, dict], match_to: Optional['Labels'] = None)\n else:\n negative_anchors = dict()\n \n- label_cattr = cattr.Converter()\n- label_cattr.register_structure_hook(Skeleton, lambda x,type: skeletons[x])\n- label_cattr.register_structure_hook(Video, lambda x,type: videos[x])\n- label_cattr.register_structure_hook(Node, lambda x,type: x if isinstance(x,Node) else nodes[int(x)])\n- label_cattr.register_structure_hook(Track, lambda x, type: None if x is None else tracks[x])\n-\n- def structure_points(x, type):\n- if 'score' in x.keys():\n- return cattr.structure(x, PredictedPoint)\n- else:\n- return cattr.structure(x, Point)\n-\n- label_cattr.register_structure_hook(Union[Point, PredictedPoint], structure_points)\n-\n- def structure_instances_list(x, type):\n- inst_list = []\n- for inst_data in x:\n- if 'score' in inst_data.keys():\n- inst = label_cattr.structure(inst_data, PredictedInstance)\n- else:\n- inst = label_cattr.structure(inst_data, Instance)\n- inst_list.append(inst)\n- return inst_list\n+ # If there is actual labels data, get it.\n+ if 'labels' in dicts:\n+ label_cattr = make_instance_cattr()\n+ label_cattr.register_structure_hook(Skeleton, lambda x,type: skeletons[int(x)])\n+ label_cattr.register_structure_hook(Video, lambda x,type: videos[int(x)])\n+ label_cattr.register_structure_hook(Node, lambda x,type: x if isinstance(x,Node) else nodes[int(x)])\n+ label_cattr.register_structure_hook(Track, lambda x, type: None if x is None else tracks[int(x)])\n \n- label_cattr.register_structure_hook(Union[List[Instance], List[PredictedInstance]],\n- structure_instances_list)\n- label_cattr.register_structure_hook(ForwardRef('PredictedInstance'), lambda x,type: label_cattr.structure(x, PredictedInstance))\n- labels = label_cattr.structure(dicts['labels'], List[LabeledFrame])\n+ labels = label_cattr.structure(dicts['labels'], List[LabeledFrame])\n+ else:\n+ labels = []\n \n return cls(labeled_frames=labels,\n videos=videos,\n skeletons=skeletons,\n nodes=nodes,\n suggestions=suggestions,\n- negative_anchors=negative_anchors)\n+ negative_anchors=negative_anchors,\n+ tracks=tracks)\n \n @classmethod\n def load_json(cls, filename: str,\n@@ -885,7 +911,7 @@ def load_json(cls, filename: str,\n # We do this to tell apart old JSON data from leap_dev vs the\n # newer format for sLEAP.\n json_str = file.read()\n- dicts = json.loads(json_str)\n+ dicts = json_loads(json_str)\n \n # If we have a version number, then it is new sLEAP format\n if \"version\" in dicts:\n@@ -926,12 +952,18 @@ def load_json(cls, filename: str,\n else:\n return load_labels_json_old(data_path=filename, parsed_json=dicts)\n \n- def save_hdf5(self, filename: str, save_frame_data: bool = True):\n+ @staticmethod\n+ def save_hdf5(labels: 'Labels', filename: str,\n+ append: bool = False,\n+ save_frame_data: bool = False):\n \"\"\"\n Serialize the labels dataset to an HDF5 file.\n \n Args:\n+ labels: The Labels dataset to save\n filename: The file to serialize the dataset to.\n+ append: Whether to append these labeled frames to the file or\n+ not.\n save_frame_data: Whether to save the image frame data for any\n labeled frame as well. This is useful for uploading the HDF5 for\n model training when video files are to large to move. This will only\n@@ -941,45 +973,242 @@ def save_hdf5(self, filename: str, save_frame_data: bool = True):\n None\n \"\"\"\n \n- # Unstructure this labels dataset to a bunch of dicts, same as we do for\n- # JSON serialization.\n- d = self.to_dict()\n+ # FIXME: Need to implement this.\n+ if save_frame_data:\n+ raise NotImplementedError('Saving frame data is not implemented yet with HDF5 Labels datasets.')\n \n # Delete the file if it exists, we want to start from scratch since\n # h5py truncates the file which seems to not actually delete data\n- # from the file.\n- if os.path.exists(filename):\n+ # from the file. Don't if we are appending of course.\n+ if os.path.exists(filename) and not append:\n os.unlink(filename)\n \n- with h5.File(filename, 'w') as f:\n-\n- # Save the skeletons\n- #Skeleton.save_all_hdf5(filename=f, skeletons=self.skeletons)\n+ # Serialize all the meta-data to JSON.\n+ d = labels.to_dict(skip_labels=True)\n+\n+ with h5.File(filename, 'a') as f:\n+\n+ # Add all the JSON metadata\n+ meta_group = f.require_group('metadata')\n+\n+ # If we are appending and there already exists JSON metadata\n+ if append and 'json' in meta_group.attrs:\n+\n+ # Otherwise, we need to read the JSON and append to the lists\n+ old_labels = Labels.from_json(meta_group.attrs['json'].tostring().decode())\n+\n+ # A function to join to list but only include new non-dupe entries\n+ # from the right hand list.\n+ def append_unique(old, new):\n+ unique = []\n+ for x in new:\n+ try:\n+ matches = [y.matches(x) for y in old]\n+ except AttributeError:\n+ matches = [x == y for y in old]\n+\n+ # If there were no matches, this is a unique object.\n+ if sum(matches) == 0:\n+ unique.append(x)\n+ else:\n+ # If we have an object that matches, replace the instance with\n+ # the one from the new list. This will will make sure objects\n+ # on the Instances are the same as those in the Labels lists.\n+ for i, match in enumerate(matches):\n+ if match:\n+ old[i] = x\n+\n+ return old + unique\n+\n+ # Append the lists\n+ labels.tracks = append_unique(old_labels.tracks, labels.tracks)\n+ labels.skeletons = append_unique(old_labels.skeletons, labels.skeletons)\n+ labels.videos = append_unique(old_labels.videos, labels.videos)\n+ labels.nodes = append_unique(old_labels.nodes, labels.nodes)\n+\n+ # FIXME: Do something for suggestions and negative_anchors\n+\n+ # Get the dict for JSON and save it over the old data\n+ d = labels.to_dict(skip_labels=True)\n+\n+ # Output the dict to JSON\n+ meta_group.attrs['json'] = np.string_(json_dumps(d))\n+\n+ # FIXME: We can probably construct these from attrs fields\n+ # We will store Instances and PredcitedInstances in the same\n+ # table. instance_type=0 or Instance and instance_type=1 for\n+ # PredictedInstance, score will be ignored for Instances.\n+ instance_dtype = np.dtype([('instance_id', 'i8'),\n+ ('instance_type', 'u1'),\n+ ('frame_id', 'u8'),\n+ ('skeleton', 'u4'),\n+ ('track', 'i4'),\n+ ('from_predicted', 'i8'),\n+ ('score', 'f4'),\n+ ('point_id_start', 'u8'),\n+ ('point_id_end', 'u8')])\n+ frame_dtype = np.dtype([('frame_id', 'u8'),\n+ ('video', 'u4'),\n+ ('frame_idx', 'u8'),\n+ ('instance_id_start', 'u8'),\n+ ('instance_id_end', 'u8')])\n+\n+ num_instances = len(labels.all_instances)\n+ max_skeleton_size = max([len(s.nodes) for s in labels.skeletons])\n+\n+ # Initialize data arrays for serialization\n+ points = np.zeros(num_instances * max_skeleton_size, dtype=Point.dtype)\n+ pred_points = np.zeros(num_instances * max_skeleton_size, dtype=PredictedPoint.dtype)\n+ instances = np.zeros(num_instances, dtype=instance_dtype)\n+ frames = np.zeros(len(labels), dtype=frame_dtype)\n+\n+ # Pre compute some structures to make serialization faster\n+ skeleton_to_idx = {skeleton: labels.skeletons.index(skeleton) for skeleton in labels.skeletons}\n+ track_to_idx = {track: labels.tracks.index(track) for track in labels.tracks}\n+ track_to_idx[None] = -1\n+ video_to_idx = {video: labels.videos.index(video) for video in labels.videos}\n+ instance_type_to_idx = {Instance: 0, PredictedInstance: 1}\n+\n+ # If we are appending, we need look inside to see what frame, instance, and point\n+ # ids we need to start from. This gives us offsets to use.\n+ if append and 'points' in f:\n+ point_id_offset = f['points'].shape[0]\n+ pred_point_id_offset = f['pred_points'].shape[0]\n+ instance_id_offset = f['instances'][-1]['instance_id'] + 1\n+ frame_id_offset = int(f['frames'][-1]['frame_id']) + 1\n+ else:\n+ point_id_offset = 0\n+ pred_point_id_offset = 0\n+ instance_id_offset = 0\n+ frame_id_offset = 0\n+\n+ point_id = 0\n+ pred_point_id = 0\n+ instance_id = 0\n+ frame_id = 0\n+ all_from_predicted = []\n+ from_predicted_id = 0\n+ for frame_id, label in enumerate(labels):\n+ frames[frame_id] = (frame_id+frame_id_offset, video_to_idx[label.video], label.frame_idx,\n+ instance_id+instance_id_offset, instance_id+instance_id_offset+len(label.instances))\n+ for instance in label.instances:\n+ parray = instance.points_array(copy=False, full=True)\n+ instance_type = type(instance)\n+\n+ # Check whether we are working with a PredictedInstance or an Instance.\n+ if instance_type is PredictedInstance:\n+ score = instance.score\n+ pid = pred_point_id + pred_point_id_offset\n+ else:\n+ score = np.nan\n+ pid = point_id + point_id_offset\n+\n+ # Keep track of any from_predicted instance links, we will insert the\n+ # correct instance_id in the dataset after we are done.\n+ if instance.from_predicted:\n+ all_from_predicted.append(instance.from_predicted)\n+ from_predicted_id = from_predicted_id + 1\n+\n+ # Copy all the data\n+ instances[instance_id] = (instance_id+instance_id_offset,\n+ instance_type_to_idx[instance_type],\n+ frame_id,\n+ skeleton_to_idx[instance.skeleton],\n+ track_to_idx[instance.track],\n+ -1,\n+ score,\n+ pid, pid + len(parray))\n+\n+ # If these are predicted points, copy them to the predicted point array\n+ # otherwise, use the normal point array\n+ if type(parray) is PredictedPointArray:\n+ pred_points[pred_point_id:pred_point_id + len(parray)] = parray\n+ pred_point_id = pred_point_id + len(parray)\n+ else:\n+ points[point_id:point_id + len(parray)] = parray\n+ point_id = point_id + len(parray)\n+\n+ instance_id = instance_id + 1\n+\n+ # We pre-allocated our points array with max possible size considering the max\n+ # skeleton size, drop any unused points.\n+ points = points[0:point_id]\n+ pred_points = pred_points[0:pred_point_id]\n+\n+ # Create datasets if we need to\n+ if append and 'points' in f:\n+ f['points'].resize((f[\"points\"].shape[0] + points.shape[0]), axis = 0)\n+ f['points'][-points.shape[0]:] = points\n+ f['pred_points'].resize((f[\"pred_points\"].shape[0] + pred_points.shape[0]), axis=0)\n+ f['pred_points'][-pred_points.shape[0]:] = pred_points\n+ f['instances'].resize((f[\"instances\"].shape[0] + instances.shape[0]), axis=0)\n+ f['instances'][-instances.shape[0]:] = instances\n+ f['frames'].resize((f[\"frames\"].shape[0] + frames.shape[0]), axis=0)\n+ f['frames'][-frames.shape[0]:] = frames\n+ else:\n+ f.create_dataset(\"points\", data=points, maxshape=(None,), dtype=Point.dtype)\n+ f.create_dataset(\"pred_points\", data=pred_points, maxshape=(None,), dtype=PredictedPoint.dtype)\n+ f.create_dataset(\"instances\", data=instances, maxshape=(None,), dtype=instance_dtype)\n+ f.create_dataset(\"frames\", data=frames, maxshape=(None,), dtype=frame_dtype)\n \n- # Save the frame data for the videos. For each video, we will\n- # save a dataset that contains only the frame data that has been\n- # labelled.\n- if save_frame_data:\n+ @classmethod\n+ def load_hdf5(cls, filename: str, video_callback=None):\n+\n+ with h5.File(filename, 'r') as f:\n+\n+ # Extract the Labels JSON metadata and create Labels object with just\n+ # this metadata.\n+ dicts = json_loads(f.require_group('metadata').attrs['json'].tostring().decode())\n+\n+ # Use the callback if given to handle missing videos\n+ if callable(video_callback):\n+ video_callback(dicts[\"videos\"])\n+\n+ labels = cls.from_json(dicts)\n+\n+ frames_dset = f['frames'][:]\n+ instances_dset = f['instances'][:]\n+ points_dset = f['points'][:]\n+ pred_points_dset = f['pred_points'][:]\n+\n+ # Rather than instantiate a bunch of Point\\PredictedPoint objects, we will\n+ # use inplace numpy recarrays. This will save a lot of time and memory\n+ # when reading things in.\n+ points = PointArray(buf=points_dset, shape=len(points_dset))\n+ pred_points = PredictedPointArray(buf=pred_points_dset, shape=len(pred_points_dset))\n+\n+ # Extend the tracks list with a None track. We will signify this with a -1 in the\n+ # data which will map to last element of tracks\n+ tracks = labels.tracks.copy()\n+ tracks.extend([None])\n+\n+ # Create the instances\n+ instances = []\n+ for i in instances_dset:\n+ track = tracks[i['track']]\n+ skeleton = labels.skeletons[i['skeleton']]\n+\n+ if i['instance_type'] == 0: # Instance\n+ instance = Instance(skeleton=skeleton, track=track,\n+ points=points[i['point_id_start']:i['point_id_end']])\n+ else: # PredictedInstance\n+ instance = PredictedInstance(skeleton=skeleton, track=track,\n+ points=pred_points[i['point_id_start']:i['point_id_end']],\n+ score=i['score'])\n+ instances.append(instance)\n+\n+ # Create the labeled frames\n+ frames = [LabeledFrame(video=labels.videos[frame['video']],\n+ frame_idx=frame['frame_idx'],\n+ instances=instances[frame['instance_id_start']:frame['instance_id_end']])\n+ for i, frame in enumerate(frames_dset)]\n+\n+ labels.labeled_frames = frames\n+\n+ # Do the stuff that should happen after we have labeled frames\n+ labels._update_lookup_cache()\n \n- #\n- # # All videos data will be put in the videos group\n- # if 'frames' not in f:\n- # frames_group = f.create_group('frames', track_order=True)\n- # else:\n- # frames_group = f.require_group('frames')\n- self.save_frame_data_imgstore()\n-\n- #\n- # dset = f.create_dataset(f\"/frames/{v_idx}\",\n- # data=v.get_frames(frame_idxs),\n- # compression=\"gzip\")\n- #\n- # # Write the dataset to JSON string, then store it in a string\n- # # attribute\n- # dset.attrs[f\"video_json\"] = np.string_(json.dumps(d['videos'][v_idx]))\n-\n- # Save the instance level data\n- Instance.save_hdf5(file=f, instances=self.all_instances)\n+ return labels\n \n def save_frame_data_imgstore(self, output_dir: str = './', format: str = 'png'):\n \"\"\"\n@@ -1068,7 +1297,6 @@ def load_mat(cls, filename):\n x = points_[node_idx][0][i]\n y = points_[node_idx][1][i]\n new_inst[node] = Point(x, y)\n- new_inst.drop_nan_points()\n if len(new_inst.points()):\n new_frame = LabeledFrame(video=vid, frame_idx=i)\n new_frame.instances = new_inst,\n@@ -1266,7 +1494,7 @@ def load_labels_json_old(data_path: str, parsed_json: dict = None,\n A newly constructed Labels object.\n \"\"\"\n if parsed_json is None:\n- data = json.loads(open(data_path).read())\n+ data = json_loads(open(data_path).read())\n else:\n data = parsed_json\n \ndiff --git a/sleap/io/video.py b/sleap/io/video.py\n--- a/sleap/io/video.py\n+++ b/sleap/io/video.py\n@@ -76,6 +76,21 @@ def check(self, attribute, value):\n self.__width_idx = 2\n self.__height_idx = 1\n \n+ def matches(self, other):\n+ \"\"\"\n+ Check if attributes match.\n+\n+ Args:\n+ other: The instance to compare with.\n+\n+ Returns:\n+ True if attributes match, False otherwise\n+ \"\"\"\n+ return self.filename == other.filename and \\\n+ self.dataset == other.dataset and \\\n+ self.convert_range == other.convert_range and \\\n+ self.input_format == other.input_format\n+\n # The properties and methods below complete our contract with the\n # higher level Video interface.\n \n@@ -159,6 +174,21 @@ def __attrs_post_init__(self):\n if self._detect_grayscale is True:\n self.grayscale = bool(np.alltrue(self.__test_frame[..., 0] == self.__test_frame[..., -1]))\n \n+ def matches(self, other):\n+ \"\"\"\n+ Check if attributes match.\n+\n+ Args:\n+ other: The instance to compare with.\n+\n+ Returns:\n+ True if attributes match, False otherwise\n+ \"\"\"\n+ return self.filename == other.filename and \\\n+ self.grayscale == other.grayscale and \\\n+ self.bgr == other.bgr\n+\n+\n @property\n def fps(self):\n return self.__reader.get(cv2.CAP_PROP_FPS)\n@@ -245,6 +275,18 @@ def __attrs_post_init__(self):\n # The properties and methods below complete our contract with the\n # higher level Video interface.\n \n+ def matches(self, other):\n+ \"\"\"\n+ Check if attributes match.\n+\n+ Args:\n+ other: The instance to comapare with.\n+\n+ Returns:\n+ True if attributes match, False otherwise\n+ \"\"\"\n+ return np.all(self.__data == other.__data)\n+\n @property\n def frames(self):\n return self.__data.shape[self.__frame_idx]\n@@ -306,6 +348,18 @@ def __attrs_post_init__(self):\n # The properties and methods below complete our contract with the\n # higher level Video interface.\n \n+ def matches(self, other):\n+ \"\"\"\n+ Check if attributes match.\n+\n+ Args:\n+ other: The instance to comapare with.\n+\n+ Returns:\n+ True if attributes match, False otherwise\n+ \"\"\"\n+ return self.filename == other.filename and self.index_by_original == other.index_by_original\n+\n @property\n def frames(self):\n return self.__store.frame_count\ndiff --git a/sleap/nn/inference.py b/sleap/nn/inference.py\n--- a/sleap/nn/inference.py\n+++ b/sleap/nn/inference.py\n@@ -51,10 +51,8 @@ class Predictor:\n Pipeline:\n \n * Pre-processing to load, crop and scale images\n-\n * Inference to predict confidence maps and part affinity fields,\n and use these to generate PredictedInstances in LabeledFrames\n-\n * Post-processing to collate data from all frames, track instances\n across frames, and save the results\n \n@@ -139,6 +137,10 @@ def predict(self,\n # anything in OpenCV that is actually multi-threaded but maybe\n # we will down the line.\n cv2.setNumThreads(usable_cpu_count())\n+ \n+ # Delete the output file if it exists already\n+ if os.path.exists(self.output_path):\n+ os.unlink(self.output_path)\n \n logger.info(f\"Predict is async: {is_async}\")\n \n@@ -174,6 +176,10 @@ def predict(self,\n # Initialize tracking\n tracker = FlowShiftTracker(window=self.flow_window, verbosity=0)\n \n+ # Delete the output file if it exists already\n+ if os.path.exists(output_path):\n+ os.unlink(output_path)\n+\n # Process chunk-by-chunk!\n t0_start = time()\n predicted_frames: List[LabeledFrame] = []\n@@ -329,7 +335,10 @@ def predict(self,\n # We should save in chunks then combine at the end.\n labels = Labels(labeled_frames=predicted_frames)\n if self.output_path is not None:\n- Labels.save_json(labels, filename=self.output_path, compress=True)\n+ if output_path.endswith('json'):\n+ Labels.save_json(labels, filename=output_path, compress=True)\n+ else:\n+ Labels.save_hdf5(labels, filename=output_path)\n \n logger.info(\" Saved to: %s [%.1fs]\" % (self.output_path, time() - t0))\n \n@@ -718,6 +727,9 @@ def frame_list(frame_str: str):\n 'a range separated by hyphen (e.g. 1-3). (default is entire video)')\n parser.add_argument('-o', '--output', type=str, default=None,\n help='The output filename to use for the predicted data.')\n+ parser.add_argument('--out_format', choices=['hdf5', 'json'], help='The format to use for'\n+ ' the output file. Either hdf5 or json. hdf5 is the default.',\n+ default='hdf5')\n parser.add_argument('--save-confmaps-pafs', dest='save_confmaps_pafs', action='store_const',\n const=True, default=False,\n help='Whether to save the confidence maps or pafs')\n@@ -729,7 +741,11 @@ def frame_list(frame_str: str):\n \n args = parser.parse_args()\n \n- output_suffix = \".predictions.json\"\n+ if args.out_format == 'json':\n+ output_suffix = \".predictions.json\"\n+ else:\n+ output_suffix = \".predictions.h5\"\n+\n if args.frames is not None:\n output_suffix = f\".frames{min(args.frames)}_{max(args.frames)}\" + output_suffix\n \ndiff --git a/sleap/nn/tracking.py b/sleap/nn/tracking.py\n--- a/sleap/nn/tracking.py\n+++ b/sleap/nn/tracking.py\n@@ -222,7 +222,7 @@ def process(self,\n self.last_frame_index = t\n t = frame.frame_idx\n \n- instances_pts = [i.points_array(cached=True) for i in frame.instances]\n+ instances_pts = [i.points_array() for i in frame.instances]\n \n # If we do not have any active tracks, we will spawn one for each\n # matched instance and continue to the next frame.\n@@ -240,7 +240,7 @@ def process(self,\n \n # Get all points in reference frame\n instances_ref = self.tracks.get_frame_instances(self.last_frame_index, max_shift=self.window - 1)\n- pts_ref = [instance.points_array(cached=True) for instance in instances_ref]\n+ pts_ref = [instance.points_array() for instance in instances_ref]\n \n tmp = min([instance.frame_idx for instance in instances_ref] +\n [instance.source.frame_idx for instance in instances_ref\n@@ -305,7 +305,7 @@ def process(self,\n cost_matrix = np.full((len(unassigned_pts), len(shifted_tracks)), np.nan)\n for i, track in enumerate(shifted_tracks):\n # Get shifted points for current track\n- track_pts = np.stack([instance.points_array(cached=True)\n+ track_pts = np.stack([instance.points_array()\n for instance in shifted_instances\n if instance.track == track], axis=0) # track_instances x nodes x 2\n \ndiff --git a/sleap/nn/util.py b/sleap/nn/util.py\n--- a/sleap/nn/util.py\n+++ b/sleap/nn/util.py\n@@ -1,10 +1,12 @@\n from typing import Generator, Sequence, Tuple\n \n+\n def batch_count(data, batch_size):\n \"\"\"Return number of batch_size batches into which data can be divided.\"\"\"\n from math import ceil\n return ceil(len(data) / batch_size)\n \n+\n def batch(data: Sequence, batch_size: int) -> Generator[Tuple[int, int, Sequence], None, None]:\n \"\"\"Iterate over sequence data in batches.\n \n@@ -23,6 +25,7 @@ def batch(data: Sequence, batch_size: int) -> Generator[Tuple[int, int, Sequence\n end = min(start + batch_size, total_row_count)\n yield i, start, data[start:end]\n \n+\n def save_visual_outputs(output_path: str, data: dict):\n import h5py\n import numpy as np\n@@ -48,4 +51,5 @@ def save_visual_outputs(output_path: str, data: dict):\n f.create_dataset(key, data=val, maxshape=maxshape,\n compression=\"gzip\", compression_opts=9)\n \n- # logger.info(\" Saved visual outputs [%.1fs]\" % (time() - t0))\n\\ No newline at end of file\n+ # logger.info(\" Saved visual outputs [%.1fs]\" % (time() - t0))\n+\ndiff --git a/sleap/skeleton.py b/sleap/skeleton.py\n--- a/sleap/skeleton.py\n+++ b/sleap/skeleton.py\n@@ -57,6 +57,18 @@ def from_names(name_list: str):\n def as_node(cls, node):\n return node if isinstance(node, cls) else cls(node)\n \n+ def matches(self, other):\n+ \"\"\"\n+ Check whether all attributes match between two nodes.\n+\n+ Args:\n+ other: The node to compare to this one.\n+\n+ Returns:\n+ True if all attributes match, False otherwise.\n+ \"\"\"\n+ return other.name == self.name and other.weight == self.weight\n+\n \n class Skeleton:\n \"\"\"The main object for representing animal skeletons in LEAP.\n@@ -303,17 +315,21 @@ def symmetries_full(self):\n # Find all symmetric edges\n return [(src, dst, key, attr) for src, dst, key, attr in self._graph.edges(keys=True, data=True) if attr[\"type\"] == EdgeType.SYMMETRY]\n \n- def node_to_index(self, node_name: str):\n+ def node_to_index(self, node: Union[str, Node]):\n \"\"\"\n- Return the index of the node with name node_name.\n+ Return the index of the node, accepts either a node or string name of a Node.\n \n Args:\n- node_name: The name of the node.\n+ node: The name of the node or the Node object.\n \n Returns:\n The index of the node in the graph.\n \"\"\"\n- return list(self.graph.nodes).index(self.find_node(node_name))\n+ node_list = list(self._graph.nodes)\n+ try:\n+ return node_list.index(node)\n+ except ValueError:\n+ return node_list.index(self.find_node(node))\n \n def add_node(self, name: str):\n \"\"\"Add a node representing an animal part to the skeleton.\ndiff --git a/sleap/util.py b/sleap/util.py\n--- a/sleap/util.py\n+++ b/sleap/util.py\n@@ -96,4 +96,23 @@ def frame_list(frame_str: str):\n max_frame = int(min_max[1])\n return list(range(min_frame, max_frame+1))\n \n- return [int(x) for x in frame_str.split(\",\")] if len(frame_str) else None\n\\ No newline at end of file\n+ return [int(x) for x in frame_str.split(\",\")] if len(frame_str) else None\n+\n+\n+def uniquify(seq):\n+ \"\"\"\n+ Given a list, return unique elements but preserve order.\n+\n+ Note: This will not work on Python 3.5 or lower since dicts don't\n+ preserve order.\n+\n+ Args:\n+ seq: The list to remove duplicates from.\n+\n+ Returns:\n+ The unique elements from the input list extracted in original order.\n+ \"\"\"\n+\n+ # Raymond Hettinger\n+ # https://twitter.com/raymondh/status/944125570534621185\n+ return list(dict.fromkeys(seq))\n\\ No newline at end of file\n", "test_patch": "diff --git a/tests/io/test_dataset.py b/tests/io/test_dataset.py\n--- a/tests/io/test_dataset.py\n+++ b/tests/io/test_dataset.py\n@@ -3,7 +3,7 @@\n import numpy as np\n \n from sleap.skeleton import Skeleton\n-from sleap.instance import Instance, Point, LabeledFrame\n+from sleap.instance import Instance, Point, LabeledFrame, PredictedInstance\n from sleap.io.video import Video, MediaVideo\n from sleap.io.dataset import Labels, load_labels_json_old\n \n@@ -24,22 +24,52 @@ def _check_labels_match(expected_labels, other_labels, format = 'png'):\n \n # Check the top level objects\n for x, y in zip(expected_labels.skeletons, other_labels.skeletons):\n- assert x.matches(y)\n+\n+ # Inline the skeleton matches check to see if we can get a better\n+ # idea of why this test fails non-deterministically. The callstack\n+ # doesn't go deeper than the method call in pytest for some reason.\n+ # assert x.matches(y). The code below is weird because it is converted\n+ # from Skeleton.__eq__.\n+ self = x\n+ other = y\n+\n+ # First check names, duh!\n+ if other.name != self.name:\n+ assert False\n+\n+ def dict_match(dict1, dict2):\n+ return dict1 == dict2\n+\n+ # Check if the graphs are iso-morphic\n+ import networkx as nx\n+ is_isomorphic = nx.is_isomorphic(self._graph, other._graph, node_match=dict_match)\n+\n+ if not is_isomorphic:\n+ assert False\n+\n+ # Now check that the nodes have the same labels and order. They can have\n+ # different weights I guess?!\n+ for node1, node2 in zip(self._graph.nodes, other._graph.nodes):\n+ if node1.name != node2.name:\n+ assert False\n \n for x, y in zip(expected_labels.tracks, other_labels.tracks):\n assert x.name == y.name and x.spawned_on == y.spawned_on\n \n # Check that we have the same thing\n for expected_label, label in zip(expected_labels.labels, other_labels.labels):\n+\n assert expected_label.frame_idx == label.frame_idx\n \n frame_idx = label.frame_idx\n \n+ frame_data = label.video.get_frame(frame_idx)[0:15, 0:15, :]\n+ expected_frame_data = expected_label.video.get_frame(frame_idx)[0:15, 0:15, :]\n+\n # Compare the first frames of the videos, do it on a small sub-region to\n # make the test reasonable in time.\n if format is 'png':\n- assert np.allclose(expected_label.video.get_frame(frame_idx)[0:15, 0:15, :],\n- label.video.get_frame(frame_idx)[0:15, 0:15, :])\n+ assert np.allclose(frame_data, expected_frame_data)\n \n # Compare the instances\n assert all(i1.matches(i2) for (i1, i2) in zip(expected_label.instances, label.instances))\n@@ -49,7 +79,6 @@ def _check_labels_match(expected_labels, other_labels, format = 'png'):\n break\n \n \n-\n def test_labels_json(tmpdir, multi_skel_vid_labels):\n json_file_path = os.path.join(tmpdir, 'dataset.json')\n \n@@ -236,10 +265,12 @@ def test_instance_access():\n assert len(list(labels.instances(video=dummy_video))) == 20\n assert len(list(labels.instances(video=dummy_video2))) == 30\n \n+\n def test_load_labels_mat(mat_labels):\n assert len(mat_labels.nodes) == 6\n assert len(mat_labels) == 43\n \n+\n @pytest.mark.parametrize(\"format\", ['png', 'mjpeg/avi'])\n def test_save_labels_with_frame_data(multi_skel_vid_labels, tmpdir, format):\n \"\"\"\n@@ -263,6 +294,54 @@ def test_save_labels_with_frame_data(multi_skel_vid_labels, tmpdir, format):\n loaded_labels = Labels.load_json(f\"{filename}.zip\")\n \n \n-def test_save_labels_hdf5(multi_skel_vid_labels, tmpdir):\n- # FIXME: This is not really implemented yet and needs a real test\n- multi_skel_vid_labels.save_hdf5(filename=os.path.join(tmpdir, 'test.h5'), save_frame_data=False)\n+def test_labels_hdf5(multi_skel_vid_labels, tmpdir):\n+ labels = multi_skel_vid_labels\n+ filename = os.path.join(tmpdir, 'test.h5')\n+\n+ Labels.save_hdf5(filename=filename, labels=labels)\n+\n+ loaded_labels = Labels.load_hdf5(filename=filename)\n+\n+ _check_labels_match(labels, loaded_labels)\n+\n+\n+def test_labels_predicted_hdf5(multi_skel_vid_labels, tmpdir):\n+ labels = multi_skel_vid_labels\n+ filename = os.path.join(tmpdir, 'test.h5')\n+\n+ # Lets promote some of these Instances to predicted instances\n+ for label in labels:\n+ for i, instance in enumerate(label.instances):\n+ if i % 2 == 0:\n+ label.instances[i] = PredictedInstance.from_instance(instance, 0.3)\n+\n+ # Lets also add some from_predicted values\n+ for label in labels:\n+ label.instances[1].from_predicted = label.instances[0]\n+\n+ Labels.save_hdf5(filename=filename, labels=labels)\n+\n+ loaded_labels = Labels.load_hdf5(filename=filename)\n+\n+ _check_labels_match(labels, loaded_labels)\n+\n+def test_labels_append_hdf5(multi_skel_vid_labels, tmpdir):\n+ labels = multi_skel_vid_labels\n+ filename = os.path.join(tmpdir, 'test.h5')\n+\n+ # Save each frame of the Labels dataset one by one in append\n+ # mode\n+ for label in labels:\n+\n+ # Just do the first 20 to speed things up\n+ if label.frame_idx > 20:\n+ break\n+\n+ Labels.save_hdf5(filename=filename, labels=Labels([label]), append=True)\n+\n+ # Now load the dataset and make sure we get the same thing we started\n+ # with.\n+ loaded_labels = Labels.load_hdf5(filename=filename)\n+\n+ _check_labels_match(labels, loaded_labels)\n+\ndiff --git a/tests/test_instance.py b/tests/test_instance.py\n--- a/tests/test_instance.py\n+++ b/tests/test_instance.py\n@@ -76,55 +76,6 @@ def test_instance_point_iter(skeleton):\n assert points[node.name] == point\n \n \n-def test_instance_to_pandas_df(skeleton, instances):\n- \"\"\"\n- Test generating pandas DataFrames from lists of instances.\n- \"\"\"\n-\n- # How many columns are supposed to be in point DataFrame\n- NUM_COLS = 9\n-\n- NUM_INSTANCES = len(instances)\n-\n- df = Instance.to_pandas_df(instances)\n-\n- # Check to make sure we got the expected shape\n- assert df.shape == (3*NUM_INSTANCES, NUM_COLS)\n-\n- # Check skip_nan is working\n- assert Instance.to_pandas_df(instances, skip_nan=False).shape == (4*NUM_INSTANCES, NUM_COLS)\n-\n-# Skip HDF5 saving of instances now because tracks are not saved properly\n-@pytest.mark.skip\n-def test_hdf5(instances, tmpdir):\n- out_dir = tmpdir\n- path = os.path.join(out_dir, 'dataset.h5')\n-\n- if os.path.isfile(path):\n- os.remove(path)\n-\n- Instance.save_hdf5(file=path, instances=instances)\n-\n- assert os.path.isfile(path)\n-\n- # Make a deep copy, because we are gonna drop nan points in place.\n- # and I don't want to change the fixture.\n- instances_copy = copy.deepcopy(instances)\n-\n- # Drop the NaN points\n- Instance.drop_all_nan_points(instances_copy)\n-\n- # Make sure we can overwrite\n- Instance.save_hdf5(file=path, instances=instances_copy[0:100], skip_nan=False)\n-\n- # Load the data back\n- instances2 = Instance.load_hdf5(file=path)\n-\n- # Check that we get back the same instances\n- for i in range(len(instances2)):\n- assert instances_copy[i].matches(instances2[i])\n-\n-\n def test_skeleton_node_name_change():\n \"\"\"\n Test that and instance is not broken after a node on the\n@@ -194,18 +145,6 @@ def test_points_array(skeleton):\n assert np.allclose(pts[skeleton.node_to_index('head'), :], [0, 4])\n assert np.allclose(pts[skeleton.node_to_index('thorax'), :], [1, 2])\n \n- # Now use the cached version and make sure changes are not\n- # reflected\n- pts = instance1.points_array(cached=True)\n- assert np.allclose(pts[skeleton.node_to_index('thorax'), :], [1, 2])\n- instance1['thorax'] = Point(1, 6)\n- pts = instance1.points_array(cached=True)\n- assert np.allclose(pts[skeleton.node_to_index('thorax'), :], [1, 2])\n-\n- # Now drop the cache and make sure changes are reflected.\n- pts = instance1.points_array()\n- assert np.allclose(pts[skeleton.node_to_index('thorax'), :], [1, 6])\n-\n def test_instance_labeled_frame_ref(skeleton, centered_pair_vid):\n \"\"\"\n Test whether links between labeled frames and instances are kept\ndiff --git a/tests/test_point_array.py b/tests/test_point_array.py\nnew file mode 100644\n--- /dev/null\n+++ b/tests/test_point_array.py\n@@ -0,0 +1,87 @@\n+import numpy as np\n+import pytest\n+\n+from sleap.instance import Point, PredictedPoint, PointArray, PredictedPointArray\n+\n+@pytest.mark.parametrize(\"p1\", [Point(0.0, 0.0), PredictedPoint(0.0, 0.0, 0.0),\n+ PointArray(3)[0], PredictedPointArray(3)[0]])\n+def test_point(p1):\n+ \"\"\"\n+ Test the Point and PredictedPoint API. This is mainly a safety\n+ check to make sure numpy record array stuff doesn't change\n+ \"\"\"\n+\n+ # Make sure we are getting Points or PredictedPoints only.\n+ # This makes sure that PointArray(3)[0] returns a point for\n+ # example\n+ assert type(p1) in [PredictedPoint, Point]\n+\n+ # Check getters and setters\n+ p1.x = 3.0\n+ assert p1.x == 3.0\n+\n+ if type(p1) is PredictedPoint:\n+ p1.score = 30.0\n+ assert p1.score == 30.0\n+\n+\n+def test_constructor():\n+ p = Point(x=1.0, y=2.0, visible=False, complete=True)\n+ assert p.x == 1.0\n+ assert p.y == 2.0\n+ assert p.visible == False\n+ assert p.complete == True\n+\n+ p = PredictedPoint(x=1.0, y=2.0, visible=False, complete=True, score=0.3)\n+ assert p.x == 1.0\n+ assert p.y == 2.0\n+ assert p.visible == False\n+ assert p.complete == True\n+ assert p.score == 0.3\n+\n+\n+@pytest.mark.parametrize('parray_cls', [PointArray, PredictedPointArray])\n+def test_point_array(parray_cls):\n+\n+ p = parray_cls(5)\n+\n+ # Make sure length works\n+ assert len(p) == 5\n+ assert len(p['x']) == 5\n+ assert len(p[['x', 'y']]) == 5\n+\n+ # Check that single point getitem returns a Point class\n+ if parray_cls is PredictedPointArray:\n+ assert type(p[0]) is PredictedPoint\n+ else:\n+ assert type(p[0]) is Point\n+\n+ # Check that slices preserve type as well\n+ assert type(p[0:4]) is type(p)\n+\n+ # Check field access\n+ assert type(p.x) is np.ndarray\n+\n+ # Check make_default\n+ d1 = parray_cls.make_default(3)\n+ d2 = parray_cls.make_default(3)\n+\n+ # I have to convert from structured to unstructured to get this comparison\n+ # to work.\n+ from numpy.lib.recfunctions import structured_to_unstructured\n+ np.testing.assert_array_equal(structured_to_unstructured(d1), structured_to_unstructured(d2))\n+\n+\n+def test_from_and_to_array():\n+ p = PointArray(3)\n+\n+ # Do a round trip conversion\n+ r = PredictedPointArray.to_array(PredictedPointArray.from_array(p))\n+\n+ from numpy.lib.recfunctions import structured_to_unstructured\n+ np.testing.assert_array_equal(structured_to_unstructured(p), structured_to_unstructured(r))\n+\n+ # Make sure conversion uses default score\n+ r = PredictedPointArray.from_array(p)\n+ assert r.score[0] == PredictedPointArray.make_default(1)[0].score\n+\n", "problem_statement": "", "hints_text": "", "created_at": "2019-08-29T19:35:44Z"}
|