dimod icon indicating copy to clipboard operation
dimod copied to clipboard

Add ability to merge serveral DQM or BQM objects

Open arcondello opened this issue 4 years ago • 8 comments

It would be useful to merge several BQM/DQMs.

At the moment one can do

bqm.update(other_bqm)

to merge two BQM objects.

We should add a DQM.update as well.

Further, it would be useful to combine many DQM/BQM together at relative weights. See https://github.com/dwavesystems/dimod/pull/784#issuecomment-769358918

One way to accomplish this would be a merge function, as suggested in https://github.com/dwavesystems/dimod/pull/784#issuecomment-769358918

Another would be to add a weight parameter to the BQM.update() and DQM.update() methods. Likely the function would end up calling the methods, but rolling them together would be nice.

arcondello avatar Jan 28 '21 20:01 arcondello

This could either use a function or operator overloading of __add__ and __radd__

new_bqm = sum(bqms)

hsadeghidw avatar Jan 28 '21 20:01 hsadeghidw

Agree. Or even new = bqm + 2 * other_bqm

Could even allow bqm ** 2 when there are no quadratic biases...

arcondello avatar Jan 28 '21 20:01 arcondello

I have been thinking about this. I believe that the operations (+, -, *, pow(), sum()) should always return a new object.

For example: bqm + bqm + bqm

can be unambiguous, if bqm changes in the first operation. For example, if the bqm only has a bqm.offset = 1, the expression above can result in bqm.offset being 4 instead of 3.

hsadeghidw avatar Feb 02 '21 00:02 hsadeghidw

Yes, of course. + should always make a new one, += modifies an existing. Did I imply otherwise?

arcondello avatar Feb 02 '21 00:02 arcondello

nope. I had the wrong starting point in my head. To save space, one might consider modifying the largest BQM rather than creating a new one.

hsadeghidw avatar Feb 02 '21 00:02 hsadeghidw

Makes sense, I think merge would look something like

def merge(bqms):
    merged_bqm = bqms[0].copy()
    for bqm in bqms[1:]:
        merged_bqm += bqm
    return merged_bqm

Obviously with input checking and avoiding the copy on list slice.

arcondello avatar Feb 02 '21 00:02 arcondello

In 0.10.x there are two BQM objects, AdjVectorBQM and AdjDictBQM. right? Should all methods add to both objects as well as DQM?

All in one PR or multiple PR?

hsadeghidw avatar Feb 02 '21 02:02 hsadeghidw

Unless it's urgent, I would not make any PRs on this. There are some fundamental decisions about structure and API that need to be worked out. In the case that we need performant merging urgently, I'd like to address https://github.com/dwavesystems/dimod/issues/757. It's not a hard change to make, but given the current implementation work, I should do it so we're not doing redundant work.

Likely I can easily fold this into the 0.10.x release.

arcondello avatar Feb 02 '21 03:02 arcondello