Skip to content

Commit

Permalink
Improve(UPState hash and eq): Made hasing with xor (less clashing pro…
Browse files Browse the repository at this point in the history
…bability), added a caching for the hash value (due to UPState immutability) and used hash as a preliminary check in the eq (different hash ==> false equality)
  • Loading branch information
Framba-Luca committed Mar 14, 2024
1 parent 5e2a06d commit 5c54b89
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions unified_planning/model/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
#

from abc import ABC, abstractmethod
from functools import reduce
from operator import xor
from typing import Dict, List, Optional, Tuple
import unified_planning as up
from unified_planning.exceptions import UPUsageError, UPValueError
Expand Down Expand Up @@ -67,6 +69,7 @@ def __init__(
self._ancestors = 0
else:
self._ancestors = _father._ancestors + 1
self._hash: Optional[int] = None

def _condense_state(self):
"""
Expand All @@ -93,12 +96,13 @@ def __repr__(self) -> str:

def __hash__(self) -> int:
self._condense_state()
return sum(map(hash, self._values.items()))
if self._hash is None:
self._hash = reduce(xor, map(hash, self._values.items()), 0)
assert self._hash is not None
return self._hash

def __eq__(self, oth: object) -> bool:
if isinstance(oth, UPState):
self._condense_state()
oth._condense_state()
if isinstance(oth, UPState) and hash(self) == hash(oth):
return self._values == oth._values
return False

Expand Down

0 comments on commit 5c54b89

Please sign in to comment.