Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add diff_from(self, other) method to CfgNode #53

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions yacs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,29 @@ def _immutable(self, is_immutable):
if isinstance(v, CfgNode):
v._immutable(is_immutable)

def diff_from(self, other):
out = CfgNode()
out["add"] = CfgNode()
out["minus"] = CfgNode()
out["change"] = CfgNode()

return self._diff_from(other, out)

def _diff_from(self, other, out):
for key in self.keys():
if key not in other.keys():
out.minus[key] = self[key]
for key in other.keys():
if key not in self.keys():
out.add[key] = other[key]
elif self[key] != other[key]:
if isinstance(other[key], CfgNode):
out.change[key] = CfgNode()
out.change[key] = self[key]._diff_from(other[key], out.change[key])
else:
out[key] = other[key]
return out

def clone(self):
"""Recursively copy this CfgNode."""
return copy.deepcopy(self)
Expand Down
18 changes: 18 additions & 0 deletions yacs/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,24 @@ def test_load_cfg_from_file(self):
with open(f.name, "rt") as f_read:
yacs.config.load_cfg(f_read)

def test_diff_cfg(self):
# Test a change in config gives correct diff config
cfg = get_cfg()
cfg2 = cfg.clone()
cfg2.pop("NUM_GPUS")
cfg2.MODEL.TYPE = "a_bar_model"
cfg2.TEST = "new_key"
expected = CN()
expected["add"] = CN()
expected.add.TEST = "new_key"
expected["minus"] = CN()
expected.minus.NUM_GPUS = 8
expected["change"] = CN()
expected.change.MODEL = CN()
expected.change.MODEL.TYPE = "a_bar_model"
print(cfg.diff_from(cfg2))
assert cfg.diff_from(cfg2) == expected

def test_load_from_python_file(self):
# Case 1: exports CfgNode
cfg = get_cfg()
Expand Down