Search in sources :

Example 11 with ImmutableTriple

use of org.apache.commons.lang3.tuple.ImmutableTriple in project graal by graphik-team.

the class ChaseWithGRDAndUnfiers method next.

// /////////////////////////////////////////////////////////////////////////
// METHODS
// /////////////////////////////////////////////////////////////////////////
@Override
public void next() throws ChaseException {
    Rule rule, unifiedRule;
    Substitution unificator;
    Queue<Triple<Rule, Substitution, InMemoryAtomSet>> newQueue = new LinkedList<Triple<Rule, Substitution, InMemoryAtomSet>>();
    InMemoryAtomSet newAtomSet = new DefaultInMemoryGraphStore();
    try {
        while (!queue.isEmpty()) {
            Triple<Rule, Substitution, InMemoryAtomSet> pair = queue.poll();
            if (pair != null) {
                unificator = pair.getMiddle();
                InMemoryAtomSet part = pair.getRight();
                rule = pair.getLeft();
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("\nExecute rule: {} with unificator {}", rule, unificator);
                }
                unifiedRule = DefaultUnifierAlgorithm.getTargetVariablesSubstitution().createImageOf(rule);
                unifiedRule = unificator.createImageOf(unifiedRule);
                unifiedRule.getBody().removeAll(part);
                unificator = targetToSource(unificator);
                ConjunctiveQuery query = DefaultConjunctiveQueryFactory.instance().create(unifiedRule.getBody(), new LinkedList<Term>(unifiedRule.getFrontier()));
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Rule to execute: {}", unifiedRule.toString());
                    LOGGER.debug("       -- Query: {}", query.toString());
                }
                // Get projections
                List<Substitution> projections = Iterators.toList(SmartHomomorphism.instance().execute(query, atomSet));
                try {
                    for (Substitution proj : projections) {
                        InMemoryAtomSet newFacts = proj.createImageOf(unifiedRule.getHead());
                        ConjunctiveQuery q = new DefaultConjunctiveQuery(newFacts);
                        if (!SmartHomomorphism.instance().execute(q, newAtomSet).hasNext()) {
                            // Existential variables instantiation added to proj
                            CloseableIterator<Atom> it = hc.apply(unifiedRule, proj, atomSet);
                            if (it.hasNext()) {
                                LinkedListAtomSet foundPart = new LinkedListAtomSet();
                                foundPart.addAll(it);
                                newAtomSet.addAll(foundPart);
                                // Makes the projection compatible with triggered rules unifiers
                                Substitution compatibleProj = targetToSource(proj);
                                for (Pair<Rule, Substitution> p : this.grd.getTriggeredRulesWithUnifiers(rule)) {
                                    Rule triggeredRule = p.getKey();
                                    Substitution u = p.getValue();
                                    if (u != null) {
                                        Substitution comp = unificator.compose(u);
                                        Substitution aggreg = compatibleProj.aggregate(comp);
                                        aggreg = forgetSource(aggreg);
                                        if (LOGGER.isDebugEnabled()) {
                                            LOGGER.debug("-- -- Dependency: {}", triggeredRule);
                                            LOGGER.debug("-- -- Substitution:{} ", compatibleProj);
                                            LOGGER.debug("-- -- Unificator: {}", u);
                                            LOGGER.debug("-- -- Aggregation: {}\n", aggreg);
                                        }
                                        if (aggreg != null) {
                                            newQueue.add(new ImmutableTriple<Rule, Substitution, InMemoryAtomSet>(triggeredRule, aggreg, foundPart));
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (HomomorphismFactoryException e) {
                    throw new RuleApplicationException("Error during rule application", e);
                } catch (HomomorphismException e) {
                    throw new RuleApplicationException("Error during rule application", e);
                } catch (IteratorException e) {
                    throw new RuleApplicationException("Error during rule application", e);
                }
            }
        }
        queue = newQueue;
        atomSet.addAll(newAtomSet);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ChaseException("An error occur pending saturation step.", e);
    }
}
Also used : IteratorException(fr.lirmm.graphik.util.stream.IteratorException) RuleApplicationException(fr.lirmm.graphik.graal.api.forward_chaining.RuleApplicationException) HomomorphismFactoryException(fr.lirmm.graphik.graal.api.homomorphism.HomomorphismFactoryException) HomomorphismException(fr.lirmm.graphik.graal.api.homomorphism.HomomorphismException) LinkedListAtomSet(fr.lirmm.graphik.graal.core.atomset.LinkedListAtomSet) Term(fr.lirmm.graphik.graal.api.core.Term) ChaseException(fr.lirmm.graphik.graal.api.forward_chaining.ChaseException) LinkedList(java.util.LinkedList) Atom(fr.lirmm.graphik.graal.api.core.Atom) HomomorphismFactoryException(fr.lirmm.graphik.graal.api.homomorphism.HomomorphismFactoryException) RuleApplicationException(fr.lirmm.graphik.graal.api.forward_chaining.RuleApplicationException) HomomorphismException(fr.lirmm.graphik.graal.api.homomorphism.HomomorphismException) ChaseException(fr.lirmm.graphik.graal.api.forward_chaining.ChaseException) IteratorException(fr.lirmm.graphik.util.stream.IteratorException) Triple(org.apache.commons.lang3.tuple.Triple) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) DefaultConjunctiveQuery(fr.lirmm.graphik.graal.core.DefaultConjunctiveQuery) Substitution(fr.lirmm.graphik.graal.api.core.Substitution) HashMapSubstitution(fr.lirmm.graphik.graal.core.HashMapSubstitution) InMemoryAtomSet(fr.lirmm.graphik.graal.api.core.InMemoryAtomSet) Rule(fr.lirmm.graphik.graal.api.core.Rule) DefaultInMemoryGraphStore(fr.lirmm.graphik.graal.core.atomset.graph.DefaultInMemoryGraphStore) ConjunctiveQuery(fr.lirmm.graphik.graal.api.core.ConjunctiveQuery) DefaultConjunctiveQuery(fr.lirmm.graphik.graal.core.DefaultConjunctiveQuery)

Example 12 with ImmutableTriple

use of org.apache.commons.lang3.tuple.ImmutableTriple in project BWAPI4J by OpenBW.

the class MapTest method assertEquals_MiniTileAltitudes.

/**
 * Tests that each MiniTile's Altitude for all WalkPositions match between
 * the original BWAPI/BWEM in C++ and this Java port.
 */
private void assertEquals_MiniTileAltitudes(AdvancedData data, BWEM_DummyData dummyBwemData) {
    final List<ImmutableTriple<WalkPosition, Integer, Integer>> wrongAltitudes = new ArrayList<>();
    for (int y = 0; y < data.getMapData().getWalkSize().getY(); ++y) {
        for (int x = 0; x < data.getMapData().getWalkSize().getX(); ++x) {
            final WalkPosition w = new WalkPosition(x, y);
            final int expected = dummyBwemData.getMiniTileAltitudes()[data.getMapData().getWalkSize().getX() * y + x];
            final int actual = data.getMiniTile(w).getAltitude().intValue();
            // Assert.assertEquals(w + ": mini tile altitude is wrong.", expected, actual);
            if (expected != actual) {
                wrongAltitudes.add(new ImmutableTriple<>(w, expected, actual));
            }
        }
    }
    for (final ImmutableTriple<WalkPosition, Integer, Integer> triple : wrongAltitudes) {
        logger.warn("Wrong MiniTile altitude for WalkPosition: " + triple.getLeft().toString() + ", expected=" + triple.getMiddle() + ", actual=" + triple.getRight());
    }
}
Also used : ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) ArrayList(java.util.ArrayList) WalkPosition(org.openbw.bwapi4j.WalkPosition) ChokePoint(bwem.ChokePoint)

Example 13 with ImmutableTriple

use of org.apache.commons.lang3.tuple.ImmutableTriple in project pravega by pravega.

the class EndToEndTransactionOrderTest method testOrder.

@Ignore
@Test(timeout = 100000)
public void testOrder() throws Exception {
    final AtomicBoolean done = new AtomicBoolean(false);
    CompletableFuture<Void> writer1 = startWriter("1", clientFactory, done);
    CompletableFuture<Void> writer2 = startWriter("2", clientFactory, done);
    CompletableFuture<Void> writer3 = startWriter("3", clientFactory, done);
    CompletableFuture<Void> writer4 = startWriter("4", clientFactory, done);
    // perform multiple scale stream operations so that rolling transactions may happen
    Stream s = new StreamImpl("test", "test");
    Map<Double, Double> map = new HashMap<>();
    map.put(0.0, 1.0);
    @Cleanup("shutdownNow") ScheduledExecutorService executor = ExecutorServiceHelpers.newScheduledThreadPool(1, "order");
    controller.scaleStream(s, Collections.singletonList(0L), map, executor).getFuture().get();
    controller.scaleStream(s, Collections.singletonList(NameUtils.computeSegmentId(1, 1)), map, executor).getFuture().get();
    controller.scaleStream(s, Collections.singletonList(NameUtils.computeSegmentId(2, 2)), map, executor).getFuture().get();
    // stop writers
    done.set(true);
    CompletableFuture.allOf(writer1, writer2, writer3, writer4).join();
    // wait for all transactions to commit
    Futures.allOf(eventToTxnMap.entrySet().stream().map(x -> waitTillCommitted(controller, s, x.getValue(), uncommitted)).collect(Collectors.toList())).join();
    assertTrue(uncommitted.isEmpty());
    // read all events using a single reader and verify the order
    List<Triple<Integer, UUID, String>> eventOrder = new LinkedList<>();
    // create a reader
    while (!eventToTxnMap.isEmpty()) {
        EventRead<Integer> integerEventRead = reader.readNextEvent(SECONDS.toMillis(60));
        if (integerEventRead.getEvent() != null) {
            int event1 = integerEventRead.getEvent();
            UUID txnId = eventToTxnMap.remove(event1);
            String writerId = txnToWriter.get(txnId);
            UUID first = writersList.get(writerId).remove(0);
            eventOrder.add(new ImmutableTriple<>(event1, txnId, writerId));
            assertEquals(first, txnId);
        }
    }
}
Also used : TableStore(io.pravega.segmentstore.contracts.tables.TableStore) AutoScaleMonitor(io.pravega.segmentstore.server.host.stat.AutoScaleMonitor) ReaderGroupManagerImpl(io.pravega.client.admin.impl.ReaderGroupManagerImpl) Cleanup(lombok.Cleanup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ServiceBuilderConfig(io.pravega.segmentstore.server.store.ServiceBuilderConfig) EventRead(io.pravega.client.stream.EventRead) ServiceBuilder(io.pravega.segmentstore.server.store.ServiceBuilder) ClientFactoryImpl(io.pravega.client.stream.impl.ClientFactoryImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReaderGroupManager(io.pravega.client.admin.ReaderGroupManager) Stream(io.pravega.client.stream.Stream) Duration(java.time.Duration) Map(java.util.Map) After(org.junit.After) PravegaConnectionListener(io.pravega.segmentstore.server.host.handler.PravegaConnectionListener) Transaction(io.pravega.client.stream.Transaction) Triple(org.apache.commons.lang3.tuple.Triple) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) AutoScalerConfig(io.pravega.segmentstore.server.host.stat.AutoScalerConfig) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletionException(java.util.concurrent.CompletionException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) IntegerSerializer(io.pravega.test.integration.utils.IntegerSerializer) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Config(io.pravega.controller.util.Config) TestUtils(io.pravega.test.common.TestUtils) ControllerWrapper(io.pravega.test.integration.demo.ControllerWrapper) Controller(io.pravega.client.control.impl.Controller) MockClientFactory(io.pravega.client.stream.mock.MockClientFactory) Futures(io.pravega.common.concurrent.Futures) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) StreamImpl(io.pravega.client.stream.impl.StreamImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TestingServerStarter(io.pravega.test.common.TestingServerStarter) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TestingServer(org.apache.curator.test.TestingServer) LinkedList(java.util.LinkedList) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) TransactionalEventStreamWriter(io.pravega.client.stream.TransactionalEventStreamWriter) Before(org.junit.Before) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) NameUtils(io.pravega.shared.NameUtils) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) Assert.assertTrue(org.junit.Assert.assertTrue) EventStreamReader(io.pravega.client.stream.EventStreamReader) Test(org.junit.Test) SecurityConfigDefaults(io.pravega.test.common.SecurityConfigDefaults) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) Ignore(org.junit.Ignore) ReaderConfig(io.pravega.client.stream.ReaderConfig) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Collections(java.util.Collections) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) ClientConfig(io.pravega.client.ClientConfig) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Cleanup(lombok.Cleanup) LinkedList(java.util.LinkedList) Triple(org.apache.commons.lang3.tuple.Triple) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StreamImpl(io.pravega.client.stream.impl.StreamImpl) Stream(io.pravega.client.stream.Stream) UUID(java.util.UUID) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 14 with ImmutableTriple

use of org.apache.commons.lang3.tuple.ImmutableTriple in project rskj by rsksmart.

the class RepositoryBlockStoreTest method test.

@Test
public void test() throws Exception {
    // This Is how I produced RepositoryBlockStore_data.ser. I had a bitcoind in regtest with 613 blocks + genesis block
    // NetworkParameters params = RegTestParams.get();
    // Context context = new Context(params);
    // Wallet wallet = new Wallet(context);
    // BlockStore store = new SPVBlockStore(params, new File("spvBlockstore"));
    // AbstractBlockChain chain = new BlockChain(context, wallet, store);
    // PeerGroup peerGroup = new PeerGroup(context, chain);
    // peerGroup.start();
    // final DownloadProgressTracker listener = new DownloadProgressTracker();
    // peerGroup.startBlockChainDownload(listener);
    // listener.await();
    // peerGroup.stop();
    // StoredBlock storedBlock = chain.getChainHead();
    // FileOutputStream fos = new FileOutputStream("RepositoryBlockStore_data.ser");
    // ObjectOutputStream oos = new ObjectOutputStream(fos);
    // for (int i = 0; i < 614; i++) {
    // Triple<byte[], BigInteger , Integer> tripleStoredBlock = new ImmutableTriple<>(storedBlock.getHeader().bitcoinSerialize(), storedBlock.getChainWork(), storedBlock.getHeight());
    // oos.writeObject(tripleStoredBlock);
    // storedBlock = store.get(storedBlock.getHeader().getPrevBlockHash());
    // }
    // oos.close();
    // Read original store
    InputStream fileInputStream = ClassLoader.getSystemResourceAsStream("peg/RepositoryBlockStore_data.ser");
    ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
    Repository repository = new RepositoryImplForTesting();
    RskSystemProperties config = new RskSystemProperties();
    RepositoryBlockStore store = new RepositoryBlockStore(config, repository, PrecompiledContracts.BRIDGE_ADDR);
    for (int i = 0; i < 614; i++) {
        Triple<byte[], BigInteger, Integer> tripleStoredBlock = (Triple<byte[], BigInteger, Integer>) objectInputStream.readObject();
        BtcBlock header = RegTestParams.get().getDefaultSerializer().makeBlock(tripleStoredBlock.getLeft());
        StoredBlock storedBlock = new StoredBlock(header, tripleStoredBlock.getMiddle(), tripleStoredBlock.getRight());
        if (i == 0) {
            store.setChainHead(storedBlock);
        }
        store.put(storedBlock);
    }
    // Create a new instance of the store
    RepositoryBlockStore store2 = new RepositoryBlockStore(config, repository, PrecompiledContracts.BRIDGE_ADDR);
    // Check a specific block that used to fail when we had a bug
    assertEquals(store.get(Sha256Hash.wrap("373941fe83961cf70e181e468abc5f9f7cc440c711c3d06948fa66f3912ed27a")), store2.get(Sha256Hash.wrap("373941fe83961cf70e181e468abc5f9f7cc440c711c3d06948fa66f3912ed27a")));
    // Check new instance content is identical to the original one
    StoredBlock storedBlock = store.getChainHead();
    StoredBlock storedBlock2 = store2.getChainHead();
    int headHeight = storedBlock.getHeight();
    for (int i = 0; i < headHeight; i++) {
        assertNotNull(storedBlock);
        assertEquals(storedBlock, storedBlock2);
        Sha256Hash prevBlockHash = storedBlock.getHeader().getPrevBlockHash();
        storedBlock = store.get(prevBlockHash);
        storedBlock2 = store2.get(prevBlockHash);
    }
}
Also used : StoredBlock(co.rsk.bitcoinj.core.StoredBlock) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) Sha256Hash(co.rsk.bitcoinj.core.Sha256Hash) RepositoryImplForTesting(co.rsk.db.RepositoryImplForTesting) BigInteger(java.math.BigInteger) Triple(org.apache.commons.lang3.tuple.Triple) Repository(org.ethereum.core.Repository) BigInteger(java.math.BigInteger) BtcBlock(co.rsk.bitcoinj.core.BtcBlock) RskSystemProperties(co.rsk.config.RskSystemProperties) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 15 with ImmutableTriple

use of org.apache.commons.lang3.tuple.ImmutableTriple in project gridss by PapenfussLab.

the class MisassemblyFixer method createContigTransitionOffsetLookup.

private static NavigableMap<Integer, ImmutableTriple<Integer, LongList, LongList>> createContigTransitionOffsetLookup(List<KmerPathSubnode> contig) {
    NavigableMap<Integer, ImmutableTriple<Integer, LongList, LongList>> lookup = new TreeMap<Integer, ImmutableTriple<Integer, LongList, LongList>>();
    int snoffset = 0;
    for (int i = 0; i < contig.size() - 1; i++) {
        KmerPathSubnode sn = contig.get(i);
        LongArrayList snendkmers = new LongArrayList();
        snendkmers.add(sn.lastKmer());
        for (int j = 0; j < sn.node().collapsedKmerOffsets().size(); j++) {
            int offset = sn.node().collapsedKmerOffsets().getInt(j);
            if (offset == sn.length() - 1) {
                snendkmers.add(sn.node().collapsedKmers().getLong(j));
            }
        }
        KmerPathSubnode snext = contig.get(i + 1);
        LongArrayList snextstartkmers = new LongArrayList();
        snextstartkmers.add(snext.firstKmer());
        for (int j = 0; j < snext.node().collapsedKmerOffsets().size(); j++) {
            int offset = snext.node().collapsedKmerOffsets().getInt(j);
            if (offset == 0) {
                snextstartkmers.add(snext.node().collapsedKmers().getLong(j));
            }
        }
        lookup.put(snoffset + sn.length() - 1, new ImmutableTriple<Integer, LongList, LongList>(i, snendkmers, snextstartkmers));
        snoffset += sn.length();
    }
    return lookup;
}
Also used : ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) LongArrayList(it.unimi.dsi.fastutil.longs.LongArrayList) LongList(it.unimi.dsi.fastutil.longs.LongList) TreeMap(java.util.TreeMap)

Aggregations

ImmutableTriple (org.apache.commons.lang3.tuple.ImmutableTriple)17 Triple (org.apache.commons.lang3.tuple.Triple)12 ArrayList (java.util.ArrayList)6 Test (org.junit.Test)6 LockedInodePath (alluxio.master.file.meta.LockedInodePath)4 SetAndRestoreAuthenticatedUser (alluxio.SetAndRestoreAuthenticatedUser)3 MutableLockedInodePath (alluxio.master.file.meta.MutableLockedInodePath)3 Mode (alluxio.security.authorization.Mode)3 List (java.util.List)3 ConfigProperty (alluxio.grpc.ConfigProperty)2 BtcBlock (co.rsk.bitcoinj.core.BtcBlock)2 Sha256Hash (co.rsk.bitcoinj.core.Sha256Hash)2 StoredBlock (co.rsk.bitcoinj.core.StoredBlock)2 TIntList (gnu.trove.list.TIntList)2 TIntArrayList (gnu.trove.list.array.TIntArrayList)2 InputStream (java.io.InputStream)2 ObjectInputStream (java.io.ObjectInputStream)2 BigInteger (java.math.BigInteger)2 LinkedList (java.util.LinkedList)2 TreeSet (java.util.TreeSet)2