/*
* Redberry: symbolic tensor computations.
*
* Copyright (c) 2010-2012:
* Stanislav Poslavsky <stvlpos@mail.ru>
* Bolotin Dmitriy <bolotin.dmitriy@gmail.com>
*
* This file is part of Redberry.
*
* Redberry is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Redberry is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Redberry. If not, see <http://www.gnu.org/licenses/>.
*/
package cc.redberry.transformation.collect;
import cc.redberry.core.context.CC;
import cc.redberry.core.tensor.Sum;
import cc.redberry.core.tensor.Tensor;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author Dmitry Bolotin
* @author Stanislav Poslavsky
*/
//ThreadUnSafe
public class CollectInputPortImpl implements CollectInputPort {
private final SplitCriteria splitCriteria;
private final List<Split> collectedTerms = new LinkedList<>();
private boolean closed = false;
public CollectInputPortImpl(SplitCriteria splitCriteria) {
this.splitCriteria = splitCriteria;
}
@Override
public void put(Tensor tensor) {
if (closed)
throw new RuntimeException("Port is closed.");
if (tensor == null) {
closed = true;
return;
}
if (tensor instanceof Sum) {
for (Tensor t : tensor)
put(t);
return;
}
Split split = splitCriteria.split(tensor);
for (Split collected : collectedTerms)
if (collected.mergeFrom(split)) {
// collected.mergeFrom(split);
return;
}
collectedTerms.add(split);
}
public boolean closed() {
return closed;
}
@Override
public final Tensor result() {
Sum sum = new Sum();
for (Split sp : collectedTerms)
sum.add(sp.tensorEquvivalent());
Tensor result = sum.equivalent();
result.setParent(CC.getRootParentTensor());
return result;
}
@Override
public CollectInputPort create() {
return new CollectInputPortImpl(splitCriteria);
}
@Override
public boolean initialized() {
return !collectedTerms.isEmpty();
}
}