List of usage examples for java.util BitSet nextSetBit
public int nextSetBit(int fromIndex)
From source file:dendroscope.autumn.hybridnumber.ComputeHybridNumber.java
/** * recursively compute the hybrid number * * @param root1/* w w w. ja v a 2 s . c o m*/ * @param root2 * @param isReduced @return hybrid number * @param retry * @param topLevel * @param scoreAbove * @param additionalAbove */ private int computeHybridNumberRec(final Root root1, final Root root2, boolean isReduced, Integer previousHybrid, BitSet retry, final boolean topLevel, final int scoreAbove, final ValuesList additionalAbove) throws IOException, CanceledException { if (System.currentTimeMillis() > nextTime) { synchronized (progressListener) { nextTime += waitTime; waitTime *= 1.5; progressListener.incrementProgress(); } } else progressListener.checkForCancel(); // System.err.println("computeHybridNumberRec: tree1=" + Basic.toString(root1.getTaxa()) + " tree2=" + Basic.toString(root2.getTaxa())); // root1.reorderSubTree(); // root2.reorderSubTree(); if (checking) { root1.checkTree(); root2.checkTree(); } BitSet taxa = root1.getTaxa(); String key = root1.toStringTreeSparse() + root2.toStringTreeSparse(); // System.err.println("Key: "+key); Integer value; synchronized (lookupTable) { value = (Integer) lookupTable.get(key); if (value != null) return value; } if (!root2.getTaxa().equals(taxa)) throw new RuntimeException("Unequal taxon sets: X=" + Basic.toString(root1.getTaxa()) + " vs " + Basic.toString(root2.getTaxa())); if (!isReduced) { switch (SubtreeReduction.apply(root1, root2, null)) { case ISOMORPHIC: synchronized (lookupTable) { lookupTable.put(key, 0); } if (topLevel) { bestScore.lowerTo(0); progressListener.setSubtask("Best score: " + bestScore); } return 0; // two trees are isomorphic, no hybrid node needed case REDUCED: // a reduction was performed, cannot maintain lexicographical ordering in removal loop below previousHybrid = null; break; case IRREDUCIBLE: break; } Single<Integer> placeHolderTaxa = new Single<Integer>(); final Pair<Root, Root> clusterTrees = ClusterReduction.apply(root1, root2, placeHolderTaxa); final boolean retryTop = false && (previousHybrid != null && placeHolderTaxa.get() < previousHybrid); // if the taxa involved in the cluster reduction come before the previously removed hybrid, do full retry // retryTop doesn't work final BitSet fRetry = retry; if (clusterTrees != null) // will perform cluster-reduction { final Value score1 = new Value(0); final Value score2 = new Value(1); // because the cluster could not be reduced using an subtree reduction, can assume that we will need one reticulation for this final boolean verbose = ProgramProperties.get("verbose-HL-parallel", false); if (verbose) System.err.println("Starting parallel loop"); final CountDownLatch countDownLatch = new CountDownLatch(2); final Integer fPrevious = previousHybrid; // setup task: final Task task1 = new Task(); // first of two cluster-reduction tasks task1.setRunnable(new Runnable() { public void run() { try { if (verbose) { System.err.println("Launching thread on cluster-reduction"); System.err .println("Active threads " + scheduledThreadPoolExecutor.getActiveCount()); } final ValuesList additionalAbove1 = additionalAbove.copyWithAdditionalElement(score2); if (scoreAbove + additionalAbove1.sum() < bestScore.get()) { int h = computeHybridNumberRec(root1, root2, false, fPrevious, fRetry, false, scoreAbove, additionalAbove1); score1.set(h); } else { score1.set(LARGE); } additionalAbove1.clear(); } catch (Exception ex) { while (countDownLatch.getCount() > 0) countDownLatch.countDown(); } countDownLatch.countDown(); } }); final Task task2 = new Task(); // second of two cluster-reduction tasks task2.setRunnable(new Runnable() { public void run() { try { if (verbose) { System.err.println("Launching thread on cluster-reduction"); System.err .println("Active threads " + scheduledThreadPoolExecutor.getActiveCount()); } final ValuesList additionalAbove2 = additionalAbove.copyWithAdditionalElement(score1); if (scoreAbove + additionalAbove2.sum() < bestScore.get()) { int h = computeHybridNumberRec(clusterTrees.getFirst(), clusterTrees.getSecond(), true, fPrevious, fRetry, false, scoreAbove, additionalAbove2); score2.set(h); } else { score2.set(LARGE); } additionalAbove2.clear(); } catch (Exception ex) { while (countDownLatch.getCount() > 0) countDownLatch.countDown(); } countDownLatch.countDown(); } }); // start a task in this thread scheduledThreadPoolExecutor.execute(task1); task2.run(); task1.run(); // try to run task1 in current thread if it hasn't yet started execution. If the task is already running or has completed, will simply return try { if (verbose) System.err.println("waiting..."); // wait until all tasks have completed countDownLatch.await(); if (verbose) System.err.println("done"); } catch (InterruptedException e) { Basic.caught(e); } clusterTrees.getFirst().deleteSubTree(); clusterTrees.getSecond().deleteSubTree(); int total = scoreAbove + additionalAbove.sum() + score1.get() + score2.get(); if (topLevel && (total < bestScore.get())) // score above will be zero, but put this here anyway to avoid confusion { bestScore.lowerTo(total); progressListener.setSubtask("Current best score: " + bestScore); } synchronized (lookupTable) { Integer old = (Integer) lookupTable.get(key); if (old == null || total < old) lookupTable.put(key, total); } return score1.get() + score2.get(); } } List<Root> leaves1 = root1.getAllLeaves(); if (leaves1.size() <= 2) // try 2 rather than one... { return 0; } final boolean verbose = ProgramProperties.get("verbose-HL-parallel", false); if (verbose) System.err.println("Starting parallel loop"); final CountDownLatch countDownLatch = new CountDownLatch(leaves1.size()); final Value bestSubH = new Value(LARGE); // schedule all tasks to be performed final ConcurrentLinkedQueue<Task> queue = new ConcurrentLinkedQueue<Task>(); for (Node leaf2remove : leaves1) { final BitSet taxa2remove = ((Root) leaf2remove).getTaxa(); if (previousHybrid == null || previousHybrid < taxa2remove.nextSetBit(0)) { if (scoreAbove + additionalAbove.sum() + 1 >= bestScore.get()) return LARGE; // other thread has found a better result, abort // setup task: final Task task = new Task(); task.setRunnable(new Runnable() { public void run() { try { if (verbose) { System.err.println("Launching thread on " + Basic.toString(taxa2remove)); System.err .println("Active threads " + scheduledThreadPoolExecutor.getActiveCount()); } queue.remove(task); if (scoreAbove + additionalAbove.sum() + 1 < bestScore.get()) { Root tree1X = CopyWithTaxaRemoved.apply(root1, taxa2remove); Root tree2X = CopyWithTaxaRemoved.apply(root2, taxa2remove); Refine.apply(tree1X, tree2X); int scoreBelow = computeHybridNumberRec(tree1X, tree2X, false, taxa2remove.nextSetBit(0), null, false, scoreAbove + 1, additionalAbove) + 1; if (topLevel && scoreBelow < bestScore.get()) { bestScore.lowerTo(scoreBelow); progressListener.setSubtask("Current best score: " + bestScore); } synchronized (bestSubH) { if (scoreBelow < bestSubH.get()) bestSubH.set(scoreBelow); } tree1X.deleteSubTree(); tree2X.deleteSubTree(); } } catch (Exception ex) { while (countDownLatch.getCount() > 0) countDownLatch.countDown(); } countDownLatch.countDown(); } }); queue.add(task); } else // no task for this item, count down { countDownLatch.countDown(); progressListener.checkForCancel(); } } // grab one task for the current thread: Task taskForCurrentThread = queue.size() > 0 ? queue.poll() : null; // launch all others in the executor for (Task task : queue) scheduledThreadPoolExecutor.execute(task); // start a task in this thread if (taskForCurrentThread != null) taskForCurrentThread.run(); // try to run other tasks from the queue. Note that any task that is already running will return immediately while (queue.size() > 0) { Task task = queue.poll(); if (task != null) task.run(); } try { if (verbose) System.err.println("waiting..."); // wait until all tasks have completed countDownLatch.await(); if (verbose) System.err.println("done"); } catch (InterruptedException e) { Basic.caught(e); return LARGE; } // return the best value synchronized (lookupTable) { Integer old = (Integer) lookupTable.get(key); if (old == null || old > bestSubH.get()) lookupTable.put(key, bestSubH.get()); } return bestSubH.get(); }
From source file:com.google.uzaygezen.core.LongArrayBitVector.java
@Override public void copyFrom(BitSet from) { Preconditions.checkArgument(size >= from.length()); clear();//w w w .j av a 2s.c o m for (int i = from.nextSetBit(0); i >= 0; i = from.nextSetBit(i + 1)) { set(i); } assert checkSanity(); }
From source file:com.asakusafw.runtime.stage.input.DefaultSplitCombiner.java
private SlotDef[] resolveSlots(int slots, String[] locationNames, List<SplitDef> splits) { assert locationNames != null; assert locationNames.length >= 1; assert splits != null; double[] locationScores = new double[locationNames.length]; for (SplitDef split : splits) { BitSet locations = split.locations; for (int i = locations.nextSetBit(0); i >= 0; i = locations.nextSetBit(i + 1)) { locationScores[i] += split.localTime; }/*from w ww .ja va 2 s .co m*/ } LocationAndTime[] pairs = new LocationAndTime[locationNames.length]; for (int i = 0; i < pairs.length; i++) { LocationAndTime pair = new LocationAndTime(i, locationScores[i]); pairs[i] = pair; } Arrays.sort(pairs); SlotDef[] results = new SlotDef[slots]; for (int i = 0; i < results.length; i++) { LocationAndTime pair = pairs[i % pairs.length]; SlotDef slot = new SlotDef(pair.location, locationNames[pair.location]); results[i] = slot; if (LOG.isTraceEnabled()) { LOG.trace(MessageFormat.format("Slot[{0}]: {1}", //$NON-NLS-1$ i, slot)); } } return results; }
From source file:com.asakusafw.runtime.stage.input.DefaultSplitCombiner.java
private String[] computeLocations(Environment env, List<SplitDef> splits) { String[] locationNames = env.locations; LocationAndTime[] pairs = new LocationAndTime[locationNames.length]; for (int i = 0; i < pairs.length; i++) { pairs[i] = new LocationAndTime(i, 0); }/*from www.j a v a2s .c o m*/ double totalLocalTime = 0.0; for (SplitDef split : splits) { BitSet locations = split.locations; totalLocalTime += split.localTime; for (int i = locations.nextSetBit(0); i >= 0; i = locations.nextSetBit(i + 1)) { pairs[i].time += split.localTime; } } Arrays.sort(pairs); double first = pairs[0].time; if (first == 0) { return null; } List<String> locations = new ArrayList<>(); locations.add(locationNames[pairs[0].location]); for (int i = 1; i < pairs.length; i++) { double totalScore = pairs[i].time / totalLocalTime; double comparisonScore = pairs[i].time / first; if (totalScore < LOCALITY_TOTAL_FACTOR) { break; } if (comparisonScore < LOCALITY_COMPARISON_FACTOR) { break; } locations.add(locationNames[pairs[i].location]); } return locations.toArray(new String[locations.size()]); }
From source file:dendroscope.autumn.hybridnetwork.ComputeHybridizationNetwork.java
/** * recursively compute the hybrid number * * @param root1//w w w. ja va 2 s . com * @param root2 * @param isReduced @return hybrid number * @param k * @param totalResults */ private int computeRec(Root root1, Root root2, boolean isReduced, BitSet candidateHybridsOriginal, int k, Collection<Root> totalResults, String depth) throws IOException, CanceledException { if (verbose) { System.err.println(depth + "---------- ComputeRec:"); System.err.println(depth + "Tree1: " + root1.toStringFullTreeX()); System.err.println(depth + "Tree2: " + root2.toStringFullTreeX()); } if (System.currentTimeMillis() > nextTime) { progressListener.incrementProgress(); nextTime += waitTime; waitTime *= 1.5; } else progressListener.checkForCancel(); // root1.reorderSubTree(); // root2.reorderSubTree(); if (checking) { root1.checkTree(); root2.checkTree(); if (!root2.getTaxa().equals(root1.getTaxa())) throw new RuntimeException("Unequal taxon sets: X=" + Basic.toString(root1.getTaxa()) + " vs " + Basic.toString(root2.getTaxa())); } if (!isReduced) { // 1. try to perform a subtree reduction: { final Single<Integer> placeHolderTaxon = new Single<Integer>(); List<Pair<Root, Root>> reducedSubtreePairs = new LinkedList<Pair<Root, Root>>(); switch (SubtreeReduction.apply(root1, root2, reducedSubtreePairs, placeHolderTaxon)) { case ISOMORPHIC: Root isomorphicTree = MergeIsomorphicInducedTrees.apply(root1, root2); if (verbose) { System.err.println(depth + "Trees are isomorphic"); System.err.println(depth + "Isomorphic tree: " + isomorphicTree.toStringFullTreeX()); } totalResults.add(isomorphicTree); return 0; // two trees are isomorphic, no hybrid node needed case REDUCED: // a reduction was performed, cannot maintain lexicographical ordering in removal loop below List<Root> subTrees = new LinkedList<Root>(); for (Pair<Root, Root> pair : reducedSubtreePairs) { subTrees.add(MergeIsomorphicInducedTrees.apply(pair.getFirst(), pair.getSecond())); } if (verbose) { System.err.println(depth + "Trees are reducible:"); System.err.println(depth + "Tree1-reduced: " + root1.toStringFullTreeX()); System.err.println(depth + "Tree2-reduced: " + root2.toStringFullTreeX()); for (Root root : subTrees) { System.err.println(depth + "Merged reduced subtree: " + root.toStringFullTreeX()); } } BitSet candidateHybrids; if (false) candidateHybrids = getAllAliveTaxa(root1, root2); // need to reconsider all possible hybrids else { candidateHybrids = (BitSet) candidateHybridsOriginal.clone(); candidateHybrids.set(placeHolderTaxon.get(), true); } Collection<Root> currentResults = new TreeSet<Root>(new NetworkComparator()); int h = cacheComputeRec(root1, root2, false, candidateHybrids, k, currentResults, depth + " >"); List<Root> merged = MergeNetworks.apply(currentResults, subTrees); if (verbose) { for (Root r : merged) { System.err.println(depth + "Result-merged: " + r.toStringNetworkFull()); } } totalResults.addAll(fixOrdering(merged)); return h; case IRREDUCIBLE: if (verbose) System.err.println(depth + "Trees are subtree-irreducible"); break; } } // 2. try to perform a cluster reduction: { final Single<Integer> placeHolderTaxon = new Single<Integer>(); Pair<Root, Root> clusterTrees = ClusterReduction.apply(root1, root2, placeHolderTaxon); if (clusterTrees != null) { Set<Root> resultBottomPair = new TreeSet<Root>(new NetworkComparator()); int h = cacheComputeRec(clusterTrees.getFirst(), clusterTrees.getSecond(), true, candidateHybridsOriginal, k, resultBottomPair, depth + " >"); // for the top pair, we should reconsider the place holder in the top pair as a possible place holder BitSet candidateHybrids = (BitSet) candidateHybridsOriginal.clone(); candidateHybrids.set(placeHolderTaxon.get(), true); Set<Root> resultTopPair = new TreeSet<Root>(new NetworkComparator()); h += cacheComputeRec(root1, root2, false, candidateHybrids, k - h, resultTopPair, depth + " >"); Set<Root> currentResults = new TreeSet<Root>(new NetworkComparator()); for (Root r : resultBottomPair) { currentResults.addAll(MergeNetworks.apply(resultTopPair, Arrays.asList(r))); } if (verbose) { System.err.println(depth + "Cluster reduction applied::"); System.err.println(depth + "Tree1-reduced: " + root1.toStringFullTreeX()); System.err.println(depth + "Tree2-reduced: " + root2.toStringFullTreeX()); System.err.println(depth + "Subtree-1: " + clusterTrees.getFirst().toStringFullTreeX()); System.err .println(depth + "Subtree-2: " + clusterTrees.getSecond().toStringFullTreeX()); for (Root r : resultBottomPair) { System.err.println(depth + "Results for reduced-trees: " + r.toStringNetworkFull()); } for (Root r : resultTopPair) { System.err.println(depth + "Results for sub-trees: " + r.toStringNetworkFull()); } for (Root r : currentResults) { System.err .println(depth + "Merged cluster-reduced networks: " + r.toStringNetworkFull()); } } totalResults.addAll(currentResults); clusterTrees.getFirst().deleteSubTree(); clusterTrees.getSecond().deleteSubTree(); return h; } } } else { if (verbose) System.err.println(depth + "Trees are already reduced"); } if (k <= 0) // 1, if only interested in number or in finding only one network, 0 else return LARGE; int hBest = LARGE; List<Root> leaves1 = getAllAliveLeaves(root1); /* if (leaves1.size() <= 2) // try 2 rather than one... { totalResults.add(MergeNetworks.apply(root1,root2)); // todo: this needs to be fixed return 0; } */ for (Root leaf2remove : leaves1) { BitSet taxa2remove = leaf2remove.getTaxa(); if (taxa2remove.cardinality() != 1) throw new IOException(depth + "Leaf taxa cardinality: " + taxa2remove.cardinality()); int hybridTaxon = taxa2remove.nextSetBit(0); if (candidateHybridsOriginal.get(hybridTaxon)) { if (verbose) { System.err.println(depth + "Removing: " + hybridTaxon); System.err.println(depth + "candidateHybrids: " + Basic.toString(candidateHybridsOriginal)); System.err.println(depth + "Tree1: " + root1.toStringFullTreeX()); System.err.println(depth + "Tree2: " + root2.toStringFullTreeX()); } Root root1x = root1.copySubNetwork(); Root root2x = root2.copySubNetwork(); RemoveTaxon.apply(root1x, 1, hybridTaxon); RemoveTaxon.apply(root2x, 2, hybridTaxon); // now we keep removed taxa as separate sets if (verbose) { System.err.println(depth + "Tree1-x: " + root1x.toStringFullTreeX()); System.err.println(depth + "Tree2-x: " + root2x.toStringFullTreeX()); } Refine.apply(root1x, root2x); if (verbose) { System.err.println(depth + "Tree1-x-refined: " + root1x.toStringFullTreeX()); System.err.println(depth + "Tree2-x-refined: " + root2x.toStringFullTreeX()); } Collection<Root> currentResults = new TreeSet<Root>(new NetworkComparator()); candidateHybridsOriginal.set(hybridTaxon, false); int h = cacheComputeRec(root1x, root2x, false, candidateHybridsOriginal, k - 1, currentResults, depth + " >") + 1; candidateHybridsOriginal.set(hybridTaxon, true); if (h < k) k = h; // System.err.println("Subproblem with " + Basic.toString(taxa2remove) + " removed, h=" + h); if (h < hBest && h <= k) { hBest = h; totalResults.clear(); } if (h == hBest && h <= k) { if (verbose) { for (Root r : currentResults) { System.err.println(depth + "Result: " + r.toStringNetworkFull()); } } // add the hybrid node: currentResults = copyAll(currentResults); AddHybridNode.apply(currentResults, hybridTaxon); totalResults.addAll(fixOrdering(currentResults)); } root1x.deleteSubTree(); root2x.deleteSubTree(); } } return hBest; }
From source file:org.intermine.bio.postprocess.CreateIntronFeaturesProcess.java
/** * Return a set of Intron objects that don't overlap the Locations * in the locationSet argument. The caller must call ObjectStoreWriter.store() on the * Intron, its chromosomeLocation and the synonym in the synonyms collection. * @param locationSet a set of Locations for the exons on a particular transcript * @param transcript Transcript that the Locations refer to * @param tranLoc The Location of the Transcript * @param gene gene for the transcript/*from w w w . j a v a 2 s. c o m*/ * @return a set of Intron objects * @throws ObjectStoreException if there is an ObjectStore problem */ protected int createIntronFeatures(Set<Location> locationSet, SequenceFeature transcript, Location tranLoc, Gene gene) throws ObjectStoreException { if (locationSet.size() == 1 || tranLoc == null || transcript == null || transcript.getLength() == null) { return 0; } final BitSet bs = new BitSet(transcript.getLength().intValue()); Chromosome chr = transcript.getChromosome(); int tranStart = tranLoc.getStart().intValue(); for (Location location : locationSet) { bs.set(location.getStart().intValue() - tranStart, (location.getEnd().intValue() - tranStart) + 1); } int prevEndPos = 0; int intronCount = 0; while (prevEndPos != -1) { intronCount++; int nextIntronStart = bs.nextClearBit(prevEndPos + 1); int intronEnd; int nextSetBit = bs.nextSetBit(nextIntronStart); if (nextSetBit == -1) { intronEnd = transcript.getLength().intValue(); } else { intronEnd = nextSetBit - 1; } if (nextSetBit == -1 || intronCount == (locationSet.size() - 1)) { prevEndPos = -1; } else { prevEndPos = intronEnd; } int newLocStart = nextIntronStart + tranStart; int newLocEnd = intronEnd + tranStart; String identifier = "intron_chr" + chr.getPrimaryIdentifier() + "_" + Integer.toString(newLocStart) + ".." + Integer.toString(newLocEnd); if (intronMap.get(identifier) == null) { Class<?> intronCls = model.getClassDescriptorByName("Intron").getType(); Intron intron = (Intron) DynamicUtil.createObject(Collections.singleton(intronCls)); Location location = (Location) DynamicUtil.createObject(Collections.singleton(Location.class)); intron.setChromosome(chr); intron.setOrganism(chr.getOrganism()); intron.addDataSets(dataSet); intron.setPrimaryIdentifier(identifier); intron.setGenes(Collections.singleton(gene)); location.setStart(new Integer(newLocStart)); location.setEnd(new Integer(newLocEnd)); location.setStrand(tranLoc.getStrand()); location.setFeature(intron); location.setLocatedOn(transcript); location.addDataSets(dataSet); intron.setChromosomeLocation(location); osw.store(location); int length = location.getEnd().intValue() - location.getStart().intValue() + 1; intron.setLength(new Integer(length)); addToIntronTranscripts(intron, transcript); intronMap.put(identifier, intron); } else { SequenceFeature intron = intronMap.get(identifier); addToIntronTranscripts(intron, transcript); intronMap.put(identifier, intron); } } return intronCount; }
From source file:com.healthmarketscience.jackcess.impl.UsageMap.java
private void reAddPages(int oldStartPage, BitSet oldPageNumbers, int newPageNumber) throws IOException { // add all the old pages back in for (int i = oldPageNumbers.nextSetBit(0); i >= 0; i = oldPageNumbers.nextSetBit(i + 1)) { addPageNumber(oldStartPage + i); }// w w w . ja va 2s. co m if (newPageNumber > PageChannel.INVALID_PAGE_NUMBER) { // and then add the new page addPageNumber(newPageNumber); } }
From source file:net.sf.extjwnl.princeton.file.PrincetonRandomAccessDictionaryFile.java
private String renderSynset(Synset synset) { int estLength = offsetLength + 1//offset + 2 + 1 //lexfilenum + 1//ss_type + offsetLength + 1//w_cnt + (10 + 3 + 1) * synset.getWords().size()//avg word 10 chars + lex_id max 3 chars + offsetLength + 1//p_cnt + (1 + 1 + offsetLength + 1 + 1 + 1 + 4 + 1) * synset.getPointers().size() + synset.getGloss().length() + 2 + 2; if (POS.VERB == synset.getPOS()) { estLength = estLength + 8 * synset.getWords().size();//8 for verb flag, about one per word }//from w w w .j a va 2 s. c om //synset_offset lex_filenum ss_type w_cnt word lex_id [word lex_id...] p_cnt [ptr...] [frames...] | gloss //w_cnt Two digit hexadecimal integer indicating the number of words in the synset. String posKey = synset.getPOS().getKey(); if (POS.ADJECTIVE == synset.getPOS() && synset.isAdjectiveCluster()) { posKey = POS.ADJECTIVE_SATELLITE_KEY; } if (checkLexFileNumber && log.isWarnEnabled() && !LexFileIdFileNameMap.getMap().containsKey(synset.getLexFileNum())) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_001", synset.getLexFileNum())); } if (checkWordCountLimit && log.isWarnEnabled() && (0xFF < synset.getWords().size())) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_004", new Object[] { synset.getOffset(), synset.getWords().size() })); } StringBuilder result = new StringBuilder(estLength); formatOffset(synset.getOffset(), offsetLength, result); if (synset.getLexFileNum() < 10) { result.append(" 0").append(synset.getLexFileNum()); } else { result.append(" ").append(synset.getLexFileNum()); } result.append(" ").append(posKey); if (synset.getWords().size() < 0x10) { result.append(" 0").append(Integer.toHexString(synset.getWords().size())).append(" "); } else { result.append(" ").append(Integer.toHexString(synset.getWords().size())).append(" "); } for (Word w : synset.getWords()) { //ASCII form of a word as entered in the synset by the lexicographer, with spaces replaced by underscore characters (_ ). The text of the word is case sensitive. //lex_id One digit hexadecimal integer that, when appended onto lemma , uniquely identifies a sense within a lexicographer file. String lemma = w.getLemma().replace(' ', '_'); if (w instanceof Adjective) { Adjective a = (Adjective) w; if (AdjectivePosition.NONE != a.getAdjectivePosition()) { lemma = lemma + "(" + a.getAdjectivePosition().getKey() + ")"; } } if (checkLexIdLimit && log.isWarnEnabled() && (0xF < w.getLexId())) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_005", new Object[] { synset.getOffset(), w.getLemma(), w.getLexId() })); } result.append(lemma).append(" "); result.append(Long.toHexString(w.getLexId())).append(" "); } //Three digit decimal integer indicating the number of pointers from this synset to other synsets. If p_cnt is 000 the synset has no pointers. if (checkRelationLimit && log.isWarnEnabled() && (999 < synset.getPointers().size())) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_002", new Object[] { synset.getOffset(), synset.getPointers().size() })); } if (synset.getPointers().size() < 100) { result.append("0"); if (synset.getPointers().size() < 10) { result.append("0"); } } result.append(synset.getPointers().size()).append(" "); for (Pointer p : synset.getPointers()) { //pointer_symbol synset_offset pos source/target result.append(p.getType().getKey()).append(" "); //synset_offset is the byte offset of the target synset in the data file corresponding to pos formatOffset(p.getTargetOffset(), offsetLength, result); result.append(" "); //pos result.append(p.getTargetPOS().getKey()).append(" "); //source/target //The source/target field distinguishes lexical and semantic pointers. // It is a four byte field, containing two two-digit hexadecimal integers. // The first two digits indicates the word number in the current (source) synset, // the last two digits indicate the word number in the target synset. // A value of 0000 means that pointer_symbol represents a semantic relation between the current (source) synset and the target synset indicated by synset_offset . //A lexical relation between two words in different synsets is represented by non-zero values in the source and target word numbers. // The first and last two bytes of this field indicate the word numbers in the source and target synsets, respectively, between which the relation holds. // Word numbers are assigned to the word fields in a synset, from left to right, beginning with 1 . if (checkPointerIndexLimit && log.isWarnEnabled() && (0xFF < p.getSourceIndex())) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_006", new Object[] { synset.getOffset(), p.getSource().getSynset().getOffset(), p.getSourceIndex() })); } if (checkPointerIndexLimit && log.isWarnEnabled() && (0xFF < p.getTargetIndex())) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_006", new Object[] { synset.getOffset(), p.getTarget().getSynset().getOffset(), p.getTargetIndex() })); } if (p.getSourceIndex() < 0x10) { result.append("0"); } result.append(Integer.toHexString(p.getSourceIndex())); if (p.getTargetIndex() < 0x10) { result.append("0"); } result.append(Integer.toHexString(p.getTargetIndex())).append(" "); } //frames In data.verb only if (POS.VERB == synset.getPOS()) { BitSet verbFrames = synset.getVerbFrameFlags(); int verbFramesCount = verbFrames.cardinality(); for (Word word : synset.getWords()) { if (word instanceof Verb) { BitSet bits = ((Verb) word).getVerbFrameFlags(); for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) { //WN TRICK - there are duplicates in data //02593551 41 v 04 lord_it_over 0 queen_it_over 0 put_on_airs 0 act_superior 0 001 @ 02367363 v 0000 // 09 + 02 00 + 02 04 + 22 04 + 02 03 + 22 03 + 08 02 + 09 02 + 08 01 + 09 01 | act like the master of; "He is lording it over the students" // + 02 04 and + 02 03 duplicate + 02 00 // it is the only one, but it causes offsets to differ on WN30 rewrite if (!verbFrames.get(i)) { verbFramesCount++; } } } } if (checkVerbFrameLimit && log.isWarnEnabled() && (99 < verbFramesCount)) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_007", new Object[] { synset.getOffset(), verbFramesCount })); } if (verbFramesCount < 10) { result.append("0"); } result.append(Integer.toString(verbFramesCount)).append(" "); for (int i = verbFrames.nextSetBit(0); i >= 0; i = verbFrames.nextSetBit(i + 1)) { if (checkVerbFrameLimit && log.isWarnEnabled() && (99 < i)) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_008", new Object[] { synset.getOffset(), i })); } result.append("+ "); if (i < 10) { result.append("0"); } result.append(Integer.toString(i)); result.append(" 00 "); } for (Word word : synset.getWords()) { if (word instanceof Verb) { BitSet bits = ((Verb) word).getVerbFrameFlags(); for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) { if (!verbFrames.get(i)) { if (checkVerbFrameLimit && log.isWarnEnabled() && (0xFF < word.getIndex())) { log.warn(JWNL.resolveMessage("PRINCETON_WARN_008", new Object[] { synset.getOffset(), word.getIndex() })); } result.append("+ "); if (i < 10) { result.append("0"); } result.append(Integer.toString(i)).append(" "); if (word.getIndex() < 0x10) { result.append("0"); } result.append(Integer.toHexString(word.getIndex())).append(" "); } } } } } result.append("| ").append(synset.getGloss()).append(" ");//why every line in most WN files ends with two spaces? return result.toString(); }
From source file:model.DecomposableModel.java
@Override public String toString() { List<BitSet> cliques = graph.getCliquesBFS(); String res = ""; for (BitSet clique : cliques) { res += "["; for (int var = clique.nextSetBit(0); var >= 0; var = clique.nextSetBit(var + 1)) { res += var + " "; }//from w ww.j a v a2 s. com res += "]"; } return res; }
From source file:model.DecomposableModel.java
/** * @param variableNames/*from w w w .j ava 2 s . co m*/ * names of the variables * @return a string representation of the model */ public String toString(String[] variableNames) { List<BitSet> cliques = graph.getCliques(); String res = ""; for (BitSet clique : cliques) { res += "["; for (int var = clique.nextSetBit(0); var >= 0; var = clique.nextSetBit(var + 1)) { res += variableNames[var] + " "; } res += "]"; } return res; }