aimclub / GOLEM

Graph Optimiser for Learning and Evolution of Models
https://thegolem.readthedocs.io
BSD 3-Clause "New" or "Revised" License
64 stars 7 forks source link

Oprator + on `Sequence`s #266

Closed donRumata03 closed 7 months ago

donRumata03 commented 8 months ago

Linter complains about this line: + operator is used here for PopulationTs that are aliases for Sequences:

https://github.com/aimclub/GOLEM/blob/68706bebbf0050c23a2d015821a276ddb6a2ae69/golem/core/optimisers/genetic/operators/inheritance.py#L43

Some kind of Sequence chaining should probably be used here (wrapping into lists would be suboptimal).

This works now since in most cases the Sequence passed also supports the + operator.

donRumata03 commented 7 months ago

Unfortunately, itertols.chain doesn't implement Sequence because it doesn't support indexing.

Something hacky like this could be used if nothing else would work:

class ChainSequence(Sequence):
    def __init__(self, *sequences):
        self.sequences = sequences
        self._lengths = [len(seq) for seq in sequences]
        self._total_length = sum(self._lengths)

    def __len__(self):
        return self._total_length

    def __getitem__(self, index):
        if index < 0 or index >= self._total_length:
            raise IndexError('Index out of range')
        for seq, length in zip(self.sequences, self._lengths):
            if index < length:
                return seq[index]
            index -= length

    def __iter__(self):
        return itertools.chain(*self.sequences)