Skip to content

Commit

Permalink
Adding hashing capabilities for Calculators and Parameters.
Browse files Browse the repository at this point in the history
Hash of a calculator ignores the parameters.
  • Loading branch information
shervin86 committed Apr 3, 2024
1 parent 0747ced commit ce63a91
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
6 changes: 6 additions & 0 deletions libpyvinyl/BaseCalculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from pathlib import Path
import logging
import os
import hashlib

from libpyvinyl.AbstractBaseClass import AbstractBaseClass
from libpyvinyl.BaseData import BaseData, DataCollection
Expand Down Expand Up @@ -382,6 +383,11 @@ def __call__(self, parameters=None, **kwargs):
new.parameters = parameters
return new

def __hash__(self):
a = dill.copy(self)
a.init_parameters()
return int.from_bytes(hashlib.sha256(dill.dumps(a)).digest(), "big")

@classmethod
def from_dump(cls, dumpfile: str):
"""Load a dill dump from a dumpfile.
Expand Down
13 changes: 12 additions & 1 deletion libpyvinyl/Parameters/Collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ def new_parameter(self, *args, **kwargs):
self.add(new_parameter)
return new_parameter

def __hash__(self):
"""
Returns a hash for the parameter list
"""
h = 0
for parameter in self.parameters:
h = h + hash(self.parameters[parameter])
return hash(h)

def __contains__(self, key):
"""
Returns True if the parameter exists
Expand Down Expand Up @@ -383,7 +392,9 @@ def add_master_parameter(self, name, links, **kwargs):

for link_key in links:
if link_key not in self.parameters_dict:
raise RuntimeError("A link had a key which was not recognized.")
raise RuntimeError(
f"A link had a key which was not recognized: {link_key}"
)

master_parameter.add_links(links)
self.master.add(master_parameter)
Expand Down
4 changes: 4 additions & 0 deletions libpyvinyl/Parameters/Parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import math
import numpy
import hashlib
from libpyvinyl.AbstractBaseClass import AbstractBaseClass

from pint.unit import Unit
Expand Down Expand Up @@ -506,3 +507,6 @@ def __repr__(self) -> str:
string += " " + str(option) + "\n"

return string

def __hash__(self):
return int.from_bytes(hashlib.sha256(self.value).digest(), "big")

0 comments on commit ce63a91

Please sign in to comment.