code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
private void writeTagValue(TagValue tag) throws IOException { int id = tag.getId(); // Write tag value for (abstractTiffType tt : tag.getValue()) { if (id == 700) { // XMP XMP xmp = (XMP)tt; try { xmp.write(data); }catch (Exception ex) { XmlType xml = (XmlType)tt; try { xml.writeXml(data); } catch (Exception exx) { exx.printStackTrace(); throw new IOException(); } } } else if (id == 33723) { // IPTC abstractTiffType att = tag.getValue().get(0); if (att instanceof IPTC) { IPTC iptc = (IPTC) att; iptc.write(data); //for (int i = 0; i < iptc.getOriginal().size(); i++) data.put(iptc.getOriginal().get(i).toByte()); //data.put((byte) 0); } else { for (int i = 0; i < tag.getValue().size(); i++) { data.put(tag.getValue().get(i).toByte()); } data.put((byte) 0); } } else if (id == 330) { // SubIFD IFD subifd = ((IFD) tag.getValue().get(0)); writeIFD(subifd); } else if (id == 34665) { // EXIF IFD exif = (IFD) tag.getValue().get(0); writeIFD(exif); } else if (id == 34675) { // ICC for (int off = tag.getReadOffset(); off < tag.getReadOffset() + tag.getReadlength(); off++) { data.put(input.readByte(off).toByte()); } data.put((byte) 0); } else { switch (tag.getType()) { case 3: data.putShort((short) tt.toInt()); break; case 8: data.putSShort((SShort) tt); break; case 4: data.putLong((Long) tt); break; case 9: data.putSLong((SLong) tt); break; case 11: data.putFloat((Float) tt); break; case 13: data.putInt(tt.toInt()); break; case 5: data.putRational((Rational) tt); break; case 10: data.putSRational((SRational) tt); break; case 12: data.putDouble((Double) tt); break; case 2: data.put(tt.toByte()); break; default: data.put(tt.toByte()); break; } } } }
Write tag. @param tag the tag @throws IOException Signals that an I/O exception has occurred.
private ArrayList<Integer> writeStripData(IFD ifd) throws IOException { ArrayList<Integer> newStripOffsets = new ArrayList<Integer>(); IfdTags metadata = ifd.getMetadata(); TagValue stripOffsets = metadata.get(273); TagValue stripSizes = metadata.get(279); for (int i = 0; i < stripOffsets.getCardinality(); i++) { try { int pos = (int) data.position(); newStripOffsets.add(pos); int start = stripOffsets.getValue().get(i).toInt(); int size = stripSizes.getValue().get(i).toInt(); this.input.seekOffset(start); for (int off = start; off < start + size; off++) { byte v = this.input.readDirectByte(); data.put(v); } if (data.position() % 2 != 0) { // Correct word alignment data.put((byte) 0); } } catch (Exception ex) { } } return newStripOffsets; }
Write strip data. @param ifd the ifd @return the array list @throws IOException Signals that an I/O exception has occurred.
private ArrayList<Integer> writeTileData(IFD ifd) throws IOException { ArrayList<Integer> newTileOffsets = new ArrayList<Integer>(); IfdTags metadata = ifd.getMetadata(); TagValue tileOffsets = metadata.get(324); TagValue tileSizes = metadata.get(325); for (int i = 0; i < tileOffsets.getCardinality(); i++) { int pos = (int) data.position(); if (pos % 2 != 0) { // Correct word alignment data.put((byte) 0); pos = (int) data.position(); } newTileOffsets.add(pos); this.input.seekOffset(tileOffsets.getValue().get(i).toInt()); for (int j = 0; j < tileSizes.getValue().get(i).toInt(); j++) { byte v = this.input.readDirectByte(); data.put(v); } if (data.position() % 2 != 0) { // Correct word alignment data.put((byte) 0); } } return newTileOffsets; }
Write tile data. @param ifd the ifd @return the array list @throws IOException Signals that an I/O exception has occurred.
@Override public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) { // get set of candidate IDs for deletion and addition (fixed IDs are discarded) Set<Integer> removeCandidates = getRemoveCandidates(solution); Set<Integer> addCandidates = getAddCandidates(solution); // compute number of possible moves of each type (addition, deletion, swap) int numAdd = canAdd(solution, addCandidates) ? addCandidates.size() : 0; int numDel = canRemove(solution, removeCandidates) ? removeCandidates.size(): 0; int numSwap = canSwap(solution, addCandidates, removeCandidates) ? addCandidates.size()*removeCandidates.size() : 0; // pick move type using roulette selector MoveType selectedMoveType = RouletteSelector.select( Arrays.asList(MoveType.ADDITION, MoveType.DELETION, MoveType.SWAP), Arrays.asList((double) numAdd, (double) numDel, (double) numSwap), rnd ); // in case of no valid moves: return null if(selectedMoveType == null){ return null; } else { // generate random move of chosen type switch(selectedMoveType){ case ADDITION : return new AdditionMove(SetUtilities.getRandomElement(addCandidates, rnd)); case DELETION : return new DeletionMove(SetUtilities.getRandomElement(removeCandidates, rnd)); case SWAP : return new SwapMove( SetUtilities.getRandomElement(addCandidates, rnd), SetUtilities.getRandomElement(removeCandidates, rnd) ); default : throw new Error("This should never happen. If this exception is thrown, " + "there is a serious bug in SinglePerturbationNeighbourhood."); } } }
<p> Generates a random swap, deletion or addition move that transforms the given subset solution into a neighbour within the minimum and maximum allowed subset size. If no valid move can be generated, <code>null</code> is returned. If any fixed IDs have been specified, these will not be considered for deletion nor addition. </p> <p> Note that every individual move is generated with equal probability, taking into account the different number of possible moves of each type. </p> @param solution solution for which a random move is generated @param rnd source of randomness used to generate random move @return random move, <code>null</code> if no valid move can be generated
@Override public List<SubsetMove> getAllMoves(SubsetSolution solution) { // get set of candidate IDs for deletion and addition (fixed IDs are discarded) Set<Integer> removeCandidates = getRemoveCandidates(solution); Set<Integer> addCandidates = getAddCandidates(solution); // create empty list of moves List<SubsetMove> moves = new ArrayList<>(); // generate all addition moves, if valid if(canAdd(solution, addCandidates)){ // create addition move for each add candidate addCandidates.forEach(add -> moves.add(new AdditionMove(add))); } // generate all deletion moves, if valid if(canRemove(solution, removeCandidates)){ // create deletion move for each remove candidate removeCandidates.forEach(remove -> moves.add(new DeletionMove(remove))); } // generate all swap moves, if valid if(canSwap(solution, addCandidates, removeCandidates)){ // create swap move for each combination of add and remove candidate addCandidates.forEach(add -> { removeCandidates.forEach(remove -> { moves.add(new SwapMove(add, remove)); }); }); } // return generated moves return moves; }
Generate all valid swap, deletion and addition moves that transform the given subset solution into a neighbour within the minimum and maximum allowed subset size. The returned list may be empty, if no valid moves exist. If any fixed IDs have been specified, these will not be considered for deletion nor addition. @param solution solution for which a set of all valid moves is generated @return list of all valid swap, deletion and addition moves
private boolean canAdd(SubsetSolution solution, Set<Integer> addCandidates){ return !addCandidates.isEmpty() && isValidSubsetSize(solution.getNumSelectedIDs()+1); }
Check if it is allowed to add one more item to the selection. @param solution solution for which moves are generated @param addCandidates set of candidate IDs to be added @return <code>true</code> if it is allowed to add an item to the selection
private boolean canRemove(SubsetSolution solution, Set<Integer> deleteCandidates){ return !deleteCandidates.isEmpty() && isValidSubsetSize(solution.getNumSelectedIDs()-1); }
Check if it is allowed to remove one more item from the selection. @param solution solution for which moves are generated @param deleteCandidates set of candidate IDs to be deleted @return <code>true</code> if it is allowed to remove an item from the selection
private boolean canSwap(SubsetSolution solution, Set<Integer> addCandidates, Set<Integer> deleteCandidates){ return !addCandidates.isEmpty() && !deleteCandidates.isEmpty() && isValidSubsetSize(solution.getNumSelectedIDs()); }
Check if it is possible to swap a selected and unselected item. @param solution solution for which moves are generated @param addCandidates set of candidate IDs to be added @param deleteCandidates set of candidate IDs to be deleted @return <code>true</code> if it is possible to perform a swap
public static final LCMSRange create(Range<Integer> scanRange, Integer msLevel) { return new LCMSRange(scanRange, msLevel, null); }
A range that will contain all scans with the scan number range, but only at a specific MS-Level. @param scanRange null means the whole range of scan numbers in the run @param msLevel null means any ms-level
public static final LCMSRange create(Range<Integer> scanRange, Integer msLevel, DoubleRange mzRange) { return new LCMSRange(scanRange, msLevel, mzRange); }
A range, containing all scans within the scan number range at a specific MS-Level and a specific precursor range. @param scanRange null means the whole range of scan numbers in the run @param msLevel null means any ms-level @param mzRange null means all ranges. You can't use non-null here, if {@code msLevel} is null
public void addValidation(Object key, Validation validation){ initMapOnce(); validations.put(key, validation); // update aggregated value passedAll = passedAll && validation.passed(); }
Add a validation object. A key is required that can be used to retrieve the validation object. @param key key used to retrieve the validation object @param validation validation object
public Validation getValidation(Object key){ return validations == null ? null : validations.get(key); }
Retrieve the validation object corresponding to the given key. If no validation with this key has been added, <code>null</code> is returned. @param key key specified when adding the validation @return retrieved validation object, <code>null</code> if no validation with this key was added
public static MsmsPipelineAnalysis parse(Path path) throws FileParsingException { try { XMLStreamReader xsr = JaxbUtils.createXmlStreamReader(path, false); MsmsPipelineAnalysis msmsPipelineAnalysis = JaxbUtils .unmarshal(MsmsPipelineAnalysis.class, xsr); return msmsPipelineAnalysis; } catch (JAXBException e) { throw new FileParsingException( String .format("JAXB parsing of PepXML file failed (%s)", path.toAbsolutePath().toString()), e); } }
The simplest method to parse the whole MsmsPipelineAnalysis from a file. @param path Path to the file @return MsmsPipelineAnalysis
public static void main(String[] args) throws FileParsingException { if (args.length == 0) System.err.println("Supply arguments that are paths to pepxml files"); List<Path> paths = Arrays.stream(args).map(s -> Paths.get(s)).collect(Collectors.toList()); if (paths.stream().anyMatch(p -> !Files.exists(p))) System.err.println("Not all input files exist"); for (Path p : paths) { System.out.println("\nParsing: " + p.toString()); MsmsPipelineAnalysis pepxml = PepXmlParser.parse(p); int sum = pepxml.getMsmsRunSummary().stream() .flatMapToInt(msmsRunSummary -> msmsRunSummary.getSpectrumQuery().stream() .flatMapToInt(spectrumQuery -> spectrumQuery.getSearchResult().stream() .mapToInt(value -> value.getSearchHit().size())) ).sum(); System.out.printf("Done, found %d PSMs\n", sum); } }
This entry point may be used to test if JAXB is functioning properly after all the java packaging and minification.<br/> To run use `java -cp path-to.jar umich.ms.fileio.filetypes.pepxml.PepXmlParser`.<br/> @param args List of existing filesystem paths.
public boolean isInSubset(IScan scan) { int num = scan.getNum(); if (scanNumLo != null) { if (num < scanNumLo) { return false; } } if (scanNumHi != null) { if (num > scanNumHi) { return false; } } Integer msLevel = scan.getMsLevel(); if (msLvls != null) { if (!msLvls.contains(msLevel)) { return false; } } DoubleRange range; if (mzRanges != null) { if (msLevel == 1) { if (scan.getScanMzWindowLower() == null || scan.getScanMzWindowUpper() == null) { throw new IllegalStateException(String.format( "Could not check if scan #%d (MS%d) is in LCMSDataSubset, as lower/upper m/z range was not present in the scan.", num, msLevel)); } range = new DoubleRange(scan.getScanMzWindowLower(), scan.getScanMzWindowUpper()); } else { if (scan.getPrecursor() == null) { throw new IllegalStateException(String.format( "Could not check if scan #%d (MS%d) is in LCMSDataSubset, as precursor info was not present in the scan.", num, msLevel)); } range = new DoubleRange(scan.getPrecursor().getMzRangeStart(), scan.getPrecursor().getMzRangeEnd()); } for (DoubleRange listedRange : mzRanges) { if (range.overlapRelative(listedRange) < IScanCollection.MIN_GROUP_OVERLAP) { return false; } } } return true; }
In some cases we don't have the lower/upper mz window (for MS1 this requires either this data to be in scan meta info, or the spectrumRef to be parsed). In this case the method returns TRUE.
public boolean contains(LCMSDataSubset other) { // compare ms levels Set<Integer> msLvlsThis = getMsLvls(); Set<Integer> msLvlsThat = other.getMsLvls(); // if ms levels are null, this definitely matches any other subset // so we need to check msLevelsThis frist! if (msLvlsThis != null && msLvlsThat != null) { if (!msLvlsThis.containsAll(msLvlsThat)) { return false; } } // compare mz ranges List<DoubleRange> mzRangesThis = getMzRanges(); List<DoubleRange> mzRangesThat = other.getMzRanges(); if (mzRangesThis != null && mzRangesThat != null) { if (!mzRangesThis.containsAll(mzRangesThat)) { return false; } } // compare scan number ranges Integer scanNumLoThis = getScanNumLo(); Integer scanNumLoThat = other.getScanNumLo(); if (scanNumLoThis != null && scanNumLoThat != null) { if (scanNumLoThis > scanNumLoThat) { return false; } } Integer scanNumHiThis = getScanNumHi(); Integer scanNumHiThat = other.getScanNumHi(); if (scanNumHiThis != null && scanNumHiThat != null) { if (scanNumHiThis < scanNumHiThat) { return false; } } return true; }
Checks if data ranges described by this subset fully contain ranges specified in another set. According to this definition, for example {@link #WHOLE_RUN} contains any other subset, including itself.
public LCMSDataSubset merge(LCMSDataSubset other) { LCMSDataSubset merged = new LCMSDataSubset(); Set<Integer> msLvlsThis = getMsLvls(); Set<Integer> msLvlsThat = other.getMsLvls(); // only merge if both are not null, otherwise null signifies the whole // run, so we can keep it null in the merged version if (msLvlsThis != null && msLvlsThat != null) { HashSet<Integer> mergedMsLvls = new HashSet<>(msLvlsThis); mergedMsLvls.addAll(msLvlsThat); merged.setMsLvls(mergedMsLvls); } // merge mz ranges List<DoubleRange> mzRangesThis = getMzRanges(); List<DoubleRange> mzRangesThat = other.getMzRanges(); if (mzRangesThis != null && mzRangesThat != null) { ArrayList<DoubleRange> mergedMzRanges = new ArrayList<>(mzRangesThis); mergedMzRanges.addAll(mzRangesThat); merged.setMzRanges(mergedMzRanges); } // compare scan number ranges Integer scanNumLoThis = getScanNumLo(); Integer scanNumLoThat = other.getScanNumLo(); if (scanNumLoThis != null && scanNumLoThat != null) { merged.setScanNumLo(Math.min(scanNumLoThis, scanNumLoThat)); } Integer scanNumHiThis = getScanNumHi(); Integer scanNumHiThat = other.getScanNumHi(); if (scanNumHiThis != null && scanNumHiThat != null) { merged.setScanNumHi(Math.max(scanNumHiThis, scanNumHiThat)); } return merged; }
Doesn't modify original values, always returns a new one. @return a new instance of LCMSDataSubset, even if this subset {@link #contains(umich.ms.datatypes.LCMSDataSubset) } the other one.
public static void initStrictMode() { if (isStrictModeEnabled()) { LOGGER.debug("Initializing strict mode"); innerInitStrictMode(); //restore strict mode after onCreate() returns. new Handler().postAtFrontOfQueue(new Runnable() { @Override public void run() { innerInitStrictMode(); } }); } }
/* Initialize Strict Mode. Please invoke this method on Application#onCreate(), before calling super.onCreate()
public void start(){ // acquire status lock synchronized(statusLock) { // verify that search is idle assertIdle("Cannot start search."); // log LOGGER.debug("Search {} changed status: {} --> {}", this, status, SearchStatus.INITIALIZING); // set status to INITIALIZING status = SearchStatus.INITIALIZING; // fire status update fireStatusChanged(status); } LOGGER.info("Search {} started", this); // fire callback fireSearchStarted(); // initialization and/or validation searchStarted(); // check if search should be continued (may already // have been stopped during initialization) if(continueSearch()){ // instruct stop criterion checker to start checking stopCriterionChecker.startChecking(); // initialization finished: update status synchronized(statusLock){ // log LOGGER.debug("Search {} changed status: {} --> {}", this, status, SearchStatus.RUNNING); // update status = SearchStatus.RUNNING; // fire status update fireStatusChanged(status); } // enter search loop while(continueSearch()){ // reset improvement flag (automatically flipped by // updateBestSolution if improvement found during step) improvementDuringCurrentStep = false; // perform search step searchStep(); // update step count currentSteps++; // update steps since last improvement if(improvementDuringCurrentStep){ // improvement made stepsSinceLastImprovement = 0; } else if (stepsSinceLastImprovement != JamesConstants.INVALID_STEP_COUNT) { // no improvement made now, but found improvement before in current run stepsSinceLastImprovement++; } // fire callback fireStepCompleted(currentSteps); // check stop criteria if(stopCriterionChecker.stopCriterionSatisfied()){ stop(); } } // instruct stop criterion checker to stop checking stopCriterionChecker.stopChecking(); } // finalization searchStopped(); // fire callback fireSearchStopped(); LOGGER.info("Search {} stopped (runtime: {} ms, steps: {})", this, getRuntime(), getSteps()); // search run is complete: update status synchronized(statusLock){ // log LOGGER.debug("Search {} changed status: {} --> {}", this, status, SearchStatus.IDLE); // update status = SearchStatus.IDLE; // fire status update fireStatusChanged(status); } }
<p> Starts a search run and returns when this run has finished. The search run may either complete internally, i.e. come to its natural end, or be terminated by a stop criterion (see {@link #addStopCriterion(StopCriterion)}). This method does not return anything; the best solution found during search can be obtained by calling {@link #getBestSolution()} and its corresponding evaluation and validation with {@link #getBestSolutionEvaluation()} and {@link #getBestSolutionValidation()}, respectively. </p> <p> Note that a search can only be (re)started when it is idle (see {@link #getStatus()}). When attempting to start a search which is already running, terminating or disposed, an exception will be thrown. </p> <p> Before the search is actually started, some initialization may take place. This initialization can also include a verification of the search configuration and in case of an invalid configuration, an exception may be thrown. </p> @throws SearchException if the search is currently not idle, or if initialization fails because of an invalid search configuration @throws JamesRuntimeException in general, any {@link JamesRuntimeException} may be thrown in case of a malfunctioning component used during initialization, execution or finalization
public void stop(){ // acquire status lock synchronized(statusLock){ // check current status if(status == SearchStatus.INITIALIZING || status == SearchStatus.RUNNING){ // log LOGGER.debug("Search {} changed status: {} --> {}", this, status, SearchStatus.TERMINATING); // update status status = SearchStatus.TERMINATING; // fire status update fireStatusChanged(status); } } }
<p> Requests the search to stop. May be called from outside the search, e.g. by a stop criterion, as well as internally, when the search comes to its natural end. In the latter case, it is absolutely guaranteed that the step from which the search was requested to stop will be the last step executed during the current run. If the current search status is not {@link SearchStatus#INITIALIZING} or {@link SearchStatus#RUNNING}, calling this method has no effect. Else, it changes the search status to {@link SearchStatus#TERMINATING}. </p> <p> In case the search is already requested to terminate during initialization, it will complete initialization, but is guaranteed to stop before executing any search steps. </p>
public void dispose(){ // acquire status lock synchronized(statusLock){ // abort if already disposed if(status == SearchStatus.DISPOSED){ return; } // assert idle assertIdle("Cannot dispose search."); // all good, handle disposed searchDisposed(); // log LOGGER.debug("Search {} changed status: {} --> {}", this, status, SearchStatus.DISPOSED); // update status status = SearchStatus.DISPOSED; // fire status update fireStatusChanged(status); } }
Dispose this search, upon which all of its resources are released. Note that only idle searches may be disposed and that a disposed search can never be restarted. Sets the search status to {@link SearchStatus#DISPOSED}. When trying to dispose an already disposed search, nothing happens, i.e. calling this method on a disposed search has no effect. @throws SearchException if the search is currently not idle (and not already disposed)
public void addStopCriterion(StopCriterion stopCriterion){ // acquire status lock synchronized(statusLock){ // assert idle assertIdle("Cannot add stop criterion."); // pass stop criterion to checker (throws error if incompatible) stopCriterionChecker.add(stopCriterion); // log LOGGER.debug("{}: added stop criterion {}", this, stopCriterion); } }
Adds a stop criterion used to decide when the search should stop running. It is verified whether the given stop criterion is compatible with the search and if not, an exception is thrown. Note that this method can only be called when the search is idle. @param stopCriterion stop criterion used to decide when the search should stop running @throws IncompatibleStopCriterionException if the given stop criterion is incompatible with the search @throws SearchException if the search is not idle
public boolean removeStopCriterion(StopCriterion stopCriterion){ // acquire status lock synchronized(statusLock){ // assert idle assertIdle("Cannot remove stop criterion."); // remove from checker if (stopCriterionChecker.remove(stopCriterion)){ // log LOGGER.debug("{}: removed stop criterion {}", this, stopCriterion); return true; } else { return false; } } }
Removes a stop criterion. In case this stop criterion had not been added, <code>false</code> is returned. Note that this method may only be called when the search is idle. @param stopCriterion stop criterion to be removed @return <code>true</code> if the stop criterion has been successfully removed @throws SearchException if the search is not idle
public void setStopCriterionCheckPeriod(long period, TimeUnit timeUnit){ // acquire status lock synchronized(statusLock){ // assert idle assertIdle("Cannot modify stop criterion check period."); // pass new settings to checker stopCriterionChecker.setPeriod(period, timeUnit); // log LOGGER.debug("{}: set stop criterion check period to {} ms", this, timeUnit.toMillis(period)); } }
Instructs the search to check its stop criteria at regular intervals separated by the given period. For the default period, see {@link StopCriterionChecker}, which is used internally for this purpose. The period should be at least 1 millisecond, else the stop criterion checker may thrown an exception when the search is started. Note that this method may only be called when the search is idle. <p> Regardless of the specified period, the stop criteria are also checked after each search step. @param period time between subsequent stop criterion checks (&gt; 0) @param timeUnit corresponding time unit @throws SearchException if the search is not idle @throws IllegalArgumentException if the given period is not strictly positive
public void addSearchListener(SearchListener<? super SolutionType> listener){ // acquire status lock synchronized(statusLock){ // assert idle assertIdle("Cannot add search listener."); // add listener searchListeners.add(listener); // log LOGGER.debug("{}: added search listener {}", this, listener); } }
Add a search listener. Any search listener with a matching solution type (or a more general solution type) may be added. Note that this method can only be called when the search is idle. @param listener search listener to add to the search @throws SearchException if the search is not idle
public boolean removeSearchListener(SearchListener<? super SolutionType> listener){ // acquire status lock synchronized(statusLock){ // assert idle assertIdle("Cannot remove search listener."); // remove listener if (searchListeners.remove(listener)){ // log LOGGER.debug("{}: removed search listener {}", this, listener); return true; } else { return false; } } }
Remove the given search listener. If the search listener had not been added, <code>false</code> is returned. Note that this method may only be called when the search is idle. @param listener search listener to be removed @return <code>true</code> if the listener was present and has now been removed @throws SearchException if the search is not idle
private void fireNewBestSolution(SolutionType newBestSolution, Evaluation newBestSolutionEvaluation, Validation newBestSolutionValidation){ for(SearchListener<? super SolutionType> l : searchListeners){ l.newBestSolution(this, newBestSolution, newBestSolutionEvaluation, newBestSolutionValidation); } }
Calls {@link SearchListener#newBestSolution(Search, Solution, Evaluation, Validation)} on every attached search listener. Should only be executed when search is active (initializing, running or terminating). @param newBestSolution new best solution @param newBestSolutionEvaluation evaluation of new best solution @param newBestSolutionValidation validation of new best solution
private void fireStatusChanged(SearchStatus newStatus){ for(SearchListener<? super SolutionType> l : searchListeners){ l.statusChanged(this, newStatus); } }
Calls {@link SearchListener#statusChanged(Search, SearchStatus)} on every attached search listener. Should only be called exactly once for every status update. @param newStatus new search status
protected void assertIdle(String errorMessage){ // synchronize with status updates synchronized(statusLock){ if(status != SearchStatus.IDLE){ // not idle, throw exception throw new SearchException(errorMessage + " (current status: " + status + "; required: IDLE)"); } } }
Asserts that the search is currently idle, more precisely that its status is equal to {@link SearchStatus#IDLE}. If not, a {@link SearchException} is thrown, which includes the given <code>errorMessage</code> and the current search status (different from IDLE). @param errorMessage message to be included in the {@link SearchException} thrown if the search is not idle @throws SearchException if the search is not idle
protected boolean updateBestSolution(SolutionType newSolution){ // validate solution Validation validation = getProblem().validate(newSolution); if(validation.passed()){ // passed validation: evaluate Evaluation evaluation = getProblem().evaluate(newSolution); // update if better return updateBestSolution(newSolution, evaluation, validation); } else { // invalid solution return false; } }
<p> Checks whether a new best solution has been found and updates it accordingly. The given solution is evaluated and validated, after which the best solution is updated only if the solution is valid and </p> <ul> <li>no best solution had been set before, or</li> <li>the new solution has a better evaluation</li> </ul> <p> If the new solution is invalid or has a worse evaluation than the current best solution, calling this method has no effect. Note that the best solution is <b>retained</b> across subsequent runs of the same search. </p> @param newSolution newly presented solution @return <code>true</code> if the given solution is accepted as the new best solution
protected boolean updateBestSolution(SolutionType newSolution, Evaluation newSolutionEvaluation, Validation newSolutionValidation){ // check: valid solution if(newSolutionValidation.passed()){ // check: improvement or no best solution set Double delta = null; if(bestSolution == null || (delta = computeDelta(newSolutionEvaluation, getBestSolutionEvaluation())) > 0){ // flag improvement improvementDuringCurrentStep = true; // store last improvement time lastImprovementTime = System.currentTimeMillis(); // update minimum delta if applicable (only if first delta or smaller than current minimum delta) if(delta != null && (minDelta == JamesConstants.INVALID_DELTA || delta < minDelta)){ minDelta = delta; } // update best solution (create copy!) bestSolution = Solution.checkedCopy(newSolution); bestSolutionEvaluation = newSolutionEvaluation; bestSolutionValidation = newSolutionValidation; // fire callback fireNewBestSolution(bestSolution, bestSolutionEvaluation, bestSolutionValidation); // found improvement return true; } else { // no improvement return false; } } else { // invalid solution return false; } }
<p> Checks whether a new best solution has been found and updates it accordingly, given that the solution has already been evaluated and validated. The best solution is updated only if the presented solution is valid and </p> <ul> <li>no best solution had been set before, or</li> <li>the new solution has a better evaluation</li> </ul> <p> If the new solution is invalid or has a worse evaluation than the current best solution, calling this method has no effect. Note that the best solution is <b>retained</b> across subsequent runs of the same search. </p> @param newSolution newly presented solution @param newSolutionEvaluation evaluation of given solution @param newSolutionValidation validation of given solution @return <code>true</code> if the given solution is accepted as the new best solution
public long getRuntime(){ // depends on status: synchronize with status updates synchronized(statusLock){ if(status == SearchStatus.INITIALIZING){ // initializing return JamesConstants.INVALID_TIME_SPAN; } else if (status == SearchStatus.IDLE || status == SearchStatus.DISPOSED){ // idle or disposed: check if ran before if(stopTime == JamesConstants.INVALID_TIMESTAMP){ // did not run before return JamesConstants.INVALID_TIME_SPAN; } else { // return total runtime of last run return stopTime - startTime; } } else { // running or terminating return System.currentTimeMillis() - startTime; } } }
<p> Get the runtime of the <i>current</i> (or last) run, in milliseconds. The precise return value depends on the status of the search: </p> <ul> <li> If the search is either RUNNING or TERMINATING, this method returns the time elapsed since the current run was started. </li> <li> If the search is IDLE or DISPOSED, the total runtime of the last run is returned, if any. Before the first run, {@link JamesConstants#INVALID_TIME_SPAN} is returned. </li> <li> While INITIALIZING the current run, {@link JamesConstants#INVALID_TIME_SPAN} is returned. </li> </ul> <p> The return value is always positive, except in those cases when {@link JamesConstants#INVALID_TIME_SPAN} is returned. </p> @return runtime of the current (or last) run, in milliseconds
public long getTimeWithoutImprovement(){ // depends on status: synchronize with status updates synchronized(statusLock){ if(status == SearchStatus.INITIALIZING){ // initializing return JamesConstants.INVALID_TIME_SPAN; } else { // idle, running, terminating or disposed: check last improvement time if(lastImprovementTime == JamesConstants.INVALID_TIMESTAMP){ // no improvement made during current/last run, or did not yet run: equal to total runtime return getRuntime(); } else { // running or ran before, and improvement made during current/last run if(status == SearchStatus.IDLE || status == SearchStatus.DISPOSED){ // idle or disposed: return last time without improvement of previous run return stopTime - lastImprovementTime; } else { // running or terminating: return time elapsed since last improvement return System.currentTimeMillis() - lastImprovementTime; } } } } }
<p> Get the amount of time elapsed during the <i>current</i> (or last) run, without finding any further improvement (in milliseconds). The precise return value depends on the status of the search: </p> <ul> <li> If the search is either RUNNING or TERMINATING, but no improvements have yet been made during the current run, the returned value is equal to the current runtime; else it reflects the time elapsed since the last improvement during the current run. </li> <li> If the search is IDLE or DISPOSED, but has been run before, the time without improvement observed during the last run, up to the point when this run completed, is returned. Before the first run, the return value is {@link JamesConstants#INVALID_TIME_SPAN}. </li> <li> While INITIALIZING the current run, {@link JamesConstants#INVALID_TIME_SPAN} is returned. </li> </ul> <p> The return value is always positive, except in those cases when {@link JamesConstants#INVALID_TIME_SPAN} is returned. </p> @return time without finding improvements during the current (or last) run, in milliseconds
public long getStepsWithoutImprovement(){ // depends on status: synchronize with status updates synchronized(statusLock){ if(status == SearchStatus.INITIALIZING){ // initializing return JamesConstants.INVALID_STEP_COUNT; } else { if(stepsSinceLastImprovement == JamesConstants.INVALID_STEP_COUNT){ // no improvement made during current/last run, or not yet run: equal to total step count return getSteps(); } else { // running or ran before, and improvement made during current/last run return stepsSinceLastImprovement; } } } }
<p> Get the number of consecutive steps completed during the <i>current</i> (or last) run, without finding any further improvement. The precise return value depends on the status of the search: </p> <ul> <li> If the search is either RUNNING or TERMINATING, but no improvements have yet been made during the current run, the returned value is equal to the total number of steps completed so far; else it reflects the number of steps completed since the last improvement during the current run. </li> <li> If the search is IDLE or DISPOSED, but has been run before, the number of steps without improvement observed during the last run, up to the point when this run completed, is returned. Before the first run, the return value is {@link JamesConstants#INVALID_STEP_COUNT}. </li> <li> While INITIALIZING the current run, {@link JamesConstants#INVALID_STEP_COUNT} is returned. </li> </ul> <p> The return value is always positive, except in those cases when {@link JamesConstants#INVALID_STEP_COUNT} is returned. </p> @return number of consecutive completed steps without finding improvements during the current (or last) run
protected double computeDelta(Evaluation currentEvaluation, Evaluation previousEvaluation){ if(problem.isMinimizing()){ // minimization: return decrease return previousEvaluation.getValue() - currentEvaluation.getValue(); } else { // maximization: return increase return currentEvaluation.getValue() - previousEvaluation.getValue(); } }
Computes the amount of improvement of <code>currentEvaluation</code> over <code>previousEvaluation</code>, taking into account whether evaluations are being maximized or minimized. Positive deltas indicate improvement. In case of maximization the amount of increase is returned, which is equal to <pre> currentEvaluation - previousEvaluation </pre> while the amount of decrease, equal to <pre> previousEvaluation - currentEvaluation </pre> is returned in case of minimization. @param currentEvaluation evaluation to be compared with previous evaluation @param previousEvaluation previous evaluation @return amount of improvement of current evaluation over previous evaluation
protected void searchStarted() { // initialize init(); // (re)set metadata startTime = System.currentTimeMillis(); stopTime = JamesConstants.INVALID_TIMESTAMP; currentSteps = 0; lastImprovementTime = JamesConstants.INVALID_TIMESTAMP; stepsSinceLastImprovement = JamesConstants.INVALID_STEP_COUNT; minDelta = JamesConstants.INVALID_DELTA; }
<p> This method is called when a search run is started. It first initializes and validates the search by calling {@link #init()}, which may throw a {@link SearchException} if initialization fails because the search has not been configured validly. Moreover, any {@link JamesRuntimeException} could be thrown in case initialization depends on malfunctioning components. After initialization, all general per run metadata is (re)set, such as the step count and execution time. </p> <p> Always call <code>super.searchStarted()</code> when overriding this method. Note however that it is preferred to override {@link #init()} instead. </p> @throws SearchException if initialization fails, e.g. because the search has not been configured validly @throws JamesRuntimeException in general, any {@link JamesRuntimeException} may be thrown in case of a malfunctioning component used during initialization
public static void setup(View view) { view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { return showCheatSheet(view, view.getContentDescription()); } }); }
Sets up a cheat sheet (tooltip) for the given view by setting its {@link android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with the view's {@link android.view.View#getContentDescription() content description} will be shown either above (default) or below the view (if there isn't room above it). @param view The view to add a cheat sheet for.
public static void setup(View view, final int textResId) { view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { return showCheatSheet(view, view.getContext().getString(textResId)); } }); }
Sets up a cheat sheet (tooltip) for the given view by setting its {@link android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with the given text will be shown either above (default) or below the view (if there isn't room above it). @param view The view to add a cheat sheet for. @param textResId The string resource containing the text to show on long-press.
public static void setup(View view, final CharSequence text) { view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { return showCheatSheet(view, text); } }); }
Sets up a cheat sheet (tooltip) for the given view by setting its {@link android.view.View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with the given text will be shown either above (default) or below the view (if there isn't room above it). @param view The view to add a cheat sheet for. @param text The text to show on long-press.
private static boolean showCheatSheet(View view, CharSequence text) { if (TextUtils.isEmpty(text)) { return false; } final int[] screenPos = new int[2]; // origin is device display final Rect displayFrame = new Rect(); // includes decorations (e.g. status bar) view.getLocationOnScreen(screenPos); view.getWindowVisibleDisplayFrame(displayFrame); final Context context = view.getContext(); final int viewWidth = view.getWidth(); final int viewHeight = view.getHeight(); final int viewCenterX = screenPos[0] + (viewWidth / 2); final int screenWidth = context.getResources().getDisplayMetrics().widthPixels; final int estimatedToastHeight = (int)(ESTIMATED_TOAST_HEIGHT_DPS * context.getResources().getDisplayMetrics().density); Toast cheatSheet = Toast.makeText(context, text, Toast.LENGTH_SHORT); boolean showBelow = screenPos[1] < estimatedToastHeight; if (showBelow) { // Show below // Offsets are after decorations (e.g. status bar) are factored in cheatSheet.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, viewCenterX - (screenWidth / 2), (screenPos[1] - displayFrame.top) + viewHeight); } else { // Show above // Offsets are after decorations (e.g. status bar) are factored in cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, viewCenterX - (screenWidth / 2), displayFrame.bottom - screenPos[1]); } cheatSheet.show(); return true; }
Internal helper method to show the cheat sheet toast.
@RequiresPermission(anyOf = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }) public synchronized void startLocalization() { if (!started && hasSignificantlyOlderLocation()) { started = true; // get all enabled providers List<String> enabledProviders = locationManager.getProviders(true); boolean gpsProviderEnabled = enabledProviders != null && enabledProviders.contains(LocationManager.GPS_PROVIDER); boolean networkProviderEnabled = enabledProviders != null && enabledProviders.contains(LocationManager.NETWORK_PROVIDER); if (gpsProviderEnabled || networkProviderEnabled) { if (gpsProviderEnabled) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_MIN_TIME, 0, this); } if (networkProviderEnabled) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_MIN_TIME, 0, this); } AlarmUtils.scheduleElapsedRealtimeAlarm(SystemClock.elapsedRealtime() + LOCATION_MAX_TIME, getCancelPendingIntent()); LOGGER.info("Localization started"); } else { started = false; LOGGER.info("All providers disabled"); } } }
Register the listener with the Location Manager to receive location updates
@RequiresPermission(anyOf = { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }) public synchronized void stopLocalization() { if (started) { AlarmUtils.cancelAlarm(getCancelPendingIntent()); locationManager.removeUpdates(this); if (location == null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } locationTime = DateUtils.nowMillis(); } started = false; LOGGER.info("Localization stopped"); } }
Remove the listener to receive location updates
public static boolean containsWebSocketScheme(URI uri) { Objects.requireNonNull(uri, "no URI object given"); final String scheme = uri.getScheme(); if (scheme != null && (scheme.equals(WS_SCHEME) || scheme.equals(WSS_SCHEME))) { return true; } return false; }
Checks if the given URI is a contains a valid WebSocket scheme
public static URI applyDefaultPorts(URI uri) throws URISyntaxException { // contains WSS or WS... if (containsWebSocketScheme(uri)) { if (uri.getPort() == -1) { if (WS_SCHEME.equals(uri.getScheme())) { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), 80, uri.getPath(), uri.getQuery(), uri.getFragment()); } else { // must be WSS... return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), 443, uri.getPath(), uri.getQuery(), uri.getFragment()); } } // contains a custom port: return uri; } throw new IllegalArgumentException("Can not apply WebSocket ports to invalid URI scheme"); }
If needed applies the default ports (80 / 443) to the given URI. @param uri the WebSocket URI @return URI containing WebSocket ports @throws IllegalArgumentException if there is a non valid WS URI @throws URISyntaxException given URI can not be parsed
@Override public void read(TagValue tv) throws Exception { xml = ""; bytes = new byte[tv.getCardinality()]; for (int i = 0; i < tv.getCardinality(); i++) { bytes[i]=tv.getValue().get(i).toByte(); } xml = new String(bytes,"UTF-8"); loadXml(); tv.clear(); tv.add(this); }
Reads the XML. @param tv the TagValue containing the array of bytes of the ICCProfile
static ExpressionFactory getExpressionFactory() { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); CacheValue cacheValue = null; ExpressionFactory factory = null; if (tccl == null) { cacheValue = nullTcclFactory; } else { CacheKey key = new CacheKey(tccl); cacheValue = factoryCache.get(key); if (cacheValue == null) { CacheValue newCacheValue = new CacheValue(); cacheValue = factoryCache.putIfAbsent(key, newCacheValue); if (cacheValue == null) { cacheValue = newCacheValue; } } } final Lock readLock = cacheValue.getLock().readLock(); readLock.lock(); try { factory = cacheValue.getExpressionFactory(); } finally { readLock.unlock(); } if (factory == null) { final Lock writeLock = cacheValue.getLock().writeLock(); writeLock.lock(); try { factory = cacheValue.getExpressionFactory(); if (factory == null) { factory = ELUtil.getExpressionFactory(); cacheValue.setExpressionFactory(factory); } } finally { writeLock.unlock(); } } return factory; }
Provides a per class loader cache of ExpressionFactory instances without pinning any in memory as that could trigger a memory leak.
static Method findMethod(Class<?> clazz, String methodName, Class<?>[] paramTypes, Object[] paramValues) { if (clazz == null || methodName == null) { throw new MethodNotFoundException( message(null, "util.method.notfound", clazz, methodName, paramString(paramTypes))); } if (paramTypes == null) { paramTypes = getTypesFromValues(paramValues); } Method[] methods = clazz.getMethods(); List<Wrapper> wrappers = Wrapper.wrap(clazz, methods, methodName); Wrapper result = findWrapper( clazz, wrappers, methodName, paramTypes, paramValues); if (result == null) { return null; } return getMethod(clazz, (Method) result.unWrap()); }
/* This method duplicates code in org.apache.el.util.ReflectionUtil. When making changes keep the code in sync.
private static Wrapper resolveAmbiguousWrapper(Set<Wrapper> candidates, Class<?>[] paramTypes) { // Identify which parameter isn't an exact match Wrapper w = candidates.iterator().next(); int nonMatchIndex = 0; Class<?> nonMatchClass = null; for (int i = 0; i < paramTypes.length; i++) { if (w.getParameterTypes()[i] != paramTypes[i]) { nonMatchIndex = i; nonMatchClass = paramTypes[i]; break; } } for (Wrapper c : candidates) { if (c.getParameterTypes()[nonMatchIndex] == paramTypes[nonMatchIndex]) { // Methods have different non-matching parameters // Result is ambiguous return null; } } if (nonMatchClass == null) { // Since null is ambiguous, return the most general method, if possible. Class<?> mostGeneralType = null; Wrapper mostGeneralMethod = null; boolean generalMatchFound = false; for (Wrapper c : candidates) { Class<?> candidateType = c.getParameterTypes()[nonMatchIndex]; if (mostGeneralType == null) { mostGeneralType = candidateType; mostGeneralMethod = c; } else if (candidateType.isAssignableFrom(mostGeneralType)) { mostGeneralType = candidateType; mostGeneralMethod = c; generalMatchFound = true; } else if (mostGeneralType.isAssignableFrom(candidateType)) { generalMatchFound = true; } } if (generalMatchFound) { return mostGeneralMethod; } else { // Could not determine the most general method return null; } } // Can't be null Class<?> superClass = nonMatchClass.getSuperclass(); while (superClass != null) { for (Wrapper c : candidates) { if (c.getParameterTypes()[nonMatchIndex].equals(superClass)) { // Found a match return c; } } superClass = superClass.getSuperclass(); } // Treat instances of Number as a special case Wrapper match = null; if (Number.class.isAssignableFrom(nonMatchClass)) { for (Wrapper c : candidates) { Class<?> candidateType = c.getParameterTypes()[nonMatchIndex]; if (Number.class.isAssignableFrom(candidateType) || candidateType.isPrimitive()) { if (match == null) { match = c; } else { // Match still ambiguous match = null; break; } } } } return match; }
/* This method duplicates code in org.apache.el.util.ReflectionUtil. When making changes keep the code in sync.
public static LCMSRunInfo createDummyInfo() { LCMSRunInfo lcmsRunInfo = new LCMSRunInfo(); lcmsRunInfo.addInstrument(Instrument.getDummy(), Instrument.ID_UNKNOWN); return lcmsRunInfo; }
Only use if you can't get real run info.
public void addInstrument(Instrument instrument, String id) { if (instrument == null || id == null) { throw new IllegalArgumentException("Instruemnt and ID must be non-null values."); } if (instruments.size() == 0) { defaultInstrumentID = id; } else if (instruments.size() > 0 && !isDefaultExplicitlySet) { unsetDefaultInstrument(); } instruments.put(id, instrument); }
If only one instrument is added, it will be set as the default instrument, all the scans, that you add to the ScanCollection will implicitly refer to this one instrument. @param id some identifier for mapping instruments. Instrumnt list is normally stored at the beginning of the run file, so it's a mapping from this list, to instrument ID specified for each spectrumRef.
public void setDefaultInstrumentID(String id) { if (id == null) { unsetDefaultInstrument(); return; } if (instruments.containsKey(id)) { defaultInstrumentID = id; isDefaultExplicitlySet = true; } else { throw new IllegalArgumentException( "The instrument map did not contain provided instrument ID, " + "have you added the instrument first?"); } }
Call with null parameter to unset. @param id this id must be present in the run info already.
@Override public void trackWidgetAdded(final String widgetName) { execute(new TrackingCommand() { @Override protected void track(T tracker) { tracker.trackWidgetAdded(widgetName); } }); }
Widgets
public static Bitmap toBitmap(Uri uri, Integer maxWidth, Integer maxHeight) { try { Context context = AbstractApplication.get(); // First decode with inJustDecodeBounds=true to check dimensions Options options = new Options(); options.inJustDecodeBounds = true; InputStream openInputStream = context.getContentResolver().openInputStream(uri); BitmapFactory.decodeStream(openInputStream, null, options); openInputStream.close(); // Calculate inSampleSize if ((maxWidth != null) && (maxHeight != null)) { float scale = Math.min(maxWidth.floatValue() / options.outWidth, maxHeight.floatValue() / options.outHeight); options.inSampleSize = Math.round(1 / scale); } // Decode bitmap with inSampleSize set openInputStream = context.getContentResolver().openInputStream(uri); options.inJustDecodeBounds = false; Bitmap result = BitmapFactory.decodeStream(openInputStream, null, options); openInputStream.close(); return result; } catch (Exception e) { LOGGER.error(e.getMessage(), e); return null; } }
Gets a {@link Bitmap} from a {@link Uri}. Resizes the image to a determined width and height. @param uri The {@link Uri} from which the image is obtained. @param maxWidth The maximum width of the image used to scale it. If null, the image won't be scaled @param maxHeight The maximum height of the image used to scale it. If null, the image won't be scaled @return {@link Bitmap} The resized image.
public static ByteArrayInputStream toPNGInputStream(Bitmap bitmap) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes); return new ByteArrayInputStream(bytes.toByteArray()); }
Compress the bitmap to a PNG and return its {@link ByteArrayInputStream} @param bitmap The {@link Bitmap} to compress @return The {@link ByteArrayInputStream}
public Class<?> getType(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base != null && base instanceof List) { context.setPropertyResolved(true); List list = (List) base; int index = toInteger(property); if (index < 0 || index >= list.size()) { throw new PropertyNotFoundException(); } return Object.class; } return null; }
If the base object is a list, returns the most general acceptable type for a value in this list. <p>If the base is a <code>List</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller should ignore the return value.</p> <p>Assuming the base is a <code>List</code>, this method will always return <code>Object.class</code>. This is because <code>List</code>s accept any object as an element.</p> @param context The context of this evaluation. @param base The list to analyze. Only bases of type <code>List</code> are handled by this resolver. @param property The index of the element in the list to return the acceptable type for. Will be coerced into an integer, but otherwise ignored by this resolver. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then the most general acceptable type; otherwise undefined. @throws PropertyNotFoundException if the given index is out of bounds for this list. @throws NullPointerException if context is <code>null</code> @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
public void setValue(ELContext context, Object base, Object property, Object val) { if (context == null) { throw new NullPointerException(); } if (base != null && base instanceof List) { context.setPropertyResolved(base, property); // Safe cast @SuppressWarnings("unchecked") List<Object> list = (List) base; int index = toInteger(property); if (isReadOnly) { throw new PropertyNotWritableException(); } try { list.set(index, val); } catch (UnsupportedOperationException ex) { throw new PropertyNotWritableException(); } catch (IndexOutOfBoundsException ex) { throw new PropertyNotFoundException(); } catch (ClassCastException ex) { throw ex; } catch (NullPointerException ex) { throw ex; } catch (IllegalArgumentException ex) { throw ex; } } }
If the base object is a list, attempts to set the value at the given index with the given value. The index is specified by the <code>property</code> argument, and coerced into an integer. If the coercion could not be performed, an <code>IllegalArgumentException</code> is thrown. If the index is out of bounds, a <code>PropertyNotFoundException</code> is thrown. <p>If the base is a <code>List</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller can safely assume no value was set.</p> <p>If this resolver was constructed in read-only mode, this method will always throw <code>PropertyNotWritableException</code>.</p> <p>If a <code>List</code> was created using {@link java.util.Collections#unmodifiableList}, this method must throw <code>PropertyNotWritableException</code>. Unfortunately, there is no Collections API method to detect this. However, an implementation can create a prototype unmodifiable <code>List</code> and query its runtime type to see if it matches the runtime type of the base object as a workaround.</p> @param context The context of this evaluation. @param base The list to be modified. Only bases of type <code>List</code> are handled by this resolver. @param property The index of the value to be set. Will be coerced into an integer. @param val The value to be set at the given index. @throws ClassCastException if the class of the specified element prevents it from being added to this list. @throws NullPointerException if context is <code>null</code>, or if the value is <code>null</code> and this <code>List</code> does not support <code>null</code> elements. @throws IllegalArgumentException if the property could not be coerced into an integer, or if some aspect of the specified element prevents it from being added to this list. @throws PropertyNotWritableException if this resolver was constructed in read-only mode, or if the set operation is not supported by the underlying list. @throws PropertyNotFoundException if the given index is out of bounds for this list. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
public boolean isReadOnly(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base != null && base instanceof List) { context.setPropertyResolved(true); List list = (List) base; int index = toInteger(property); if (index < 0 || index >= list.size()) { throw new PropertyNotFoundException(); } return list.getClass() == theUnmodifiableListClass || isReadOnly; } return false; }
If the base object is a list, returns whether a call to {@link #setValue} will always fail. <p>If the base is a <code>List</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller should ignore the return value.</p> <p>If this resolver was constructed in read-only mode, this method will always return <code>true</code>.</p> <p>If a <code>List</code> was created using {@link java.util.Collections#unmodifiableList}, this method must return <code>true</code>. Unfortunately, there is no Collections API method to detect this. However, an implementation can create a prototype unmodifiable <code>List</code> and query its runtime type to see if it matches the runtime type of the base object as a workaround.</p> @param context The context of this evaluation. @param base The list to analyze. Only bases of type <code>List</code> are handled by this resolver. @param property The index of the element in the list to return the acceptable type for. Will be coerced into an integer, but otherwise ignored by this resolver. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then <code>true</code> if calling the <code>setValue</code> method will always fail or <code>false</code> if it is possible that such a call may succeed; otherwise undefined. @throws PropertyNotFoundException if the given index is out of bounds for this list. @throws NullPointerException if context is <code>null</code> @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
@Override public void undo(SubsetSolution solution) { // re-add deleted ID solution.select(delete); // remove newly added ID solution.deselect(add); }
Undo this swap move after it has been successfully applied to the given subset solution, by removing the newly added ID and re-adding the deleted ID. @param solution solution to which the move has been applied
@Override public final void run() { LOGGER.debug("Executing " + getClass().getSimpleName()); markAsInProgress(); if (!Lists.isNullOrEmpty(listeners)) { Runnable startUseCaseRunnable = new Runnable() { @Override public void run() { for (UseCaseListener listener : listeners) { notifyUseCaseStart(listener); } } }; if (handler != null) { handler.post(startUseCaseRunnable); } else { startUseCaseRunnable.run(); } } Trace trace = null; if (timingTrackingEnabled()) { trace = TraceHelper.startTrace(getClass()); } try { LOGGER.debug("Started " + getClass().getSimpleName()); executionTime = null; startTime = DateUtils.nowMillis(); doExecute(); executionTime = DateUtils.nowMillis() - startTime; LOGGER.debug("Finished " + getClass().getSimpleName() + ". Execution time: " + DateUtils.formatDuration(executionTime)); if (trace != null) { trace.putAttribute("result", "success"); trace.incrementMetric("successes", 1); } markAsSuccessful(); if (!Lists.isNullOrEmpty(listeners)) { Runnable finishedUseCaseRunnable = new Runnable() { @Override public void run() { for (UseCaseListener listener : listeners) { notifyFinishedUseCase(listener); } markAsNotified(); } }; if (handler != null) { handler.post(finishedUseCaseRunnable); } else { finishedUseCaseRunnable.run(); } } } catch (RuntimeException e) { if (trace != null) { trace.putAttribute("result", "failure"); trace.incrementMetric("failures", 1); } final AbstractException abstractException = wrapException(e); markAsFailed(abstractException); logHandledException(abstractException); if (!Lists.isNullOrEmpty(listeners)) { Runnable finishedFailedUseCaseRunnable = new Runnable() { @Override public void run() { for (UseCaseListener listener : listeners) { notifyFailedUseCase(abstractException, listener); } markAsNotified(); } }; if (handler != null) { handler.post(finishedFailedUseCaseRunnable); } else { finishedFailedUseCaseRunnable.run(); } } } finally { if (trace != null) { trace.stop(); } } }
Executes the use case.
@RestrictTo(LIBRARY) public void notifyUseCaseStart(UseCaseListener listener) { try { LOGGER.debug("Notifying " + getClass().getSimpleName() + " start to listener " + listener.getClass().getSimpleName()); listener.onStartUseCase(); } catch (Exception e) { AbstractException abstractException = wrapException(e); logHandledException(abstractException); } }
Notifies the listener that the use case has started. <br/> You can override this method for a custom notification when your listeners may be listening to multiple use cases at a time. @param listener The listener to notify.
@RestrictTo(LIBRARY) public void notifyFinishedUseCase(UseCaseListener listener) { try { LOGGER.debug("Notifying " + getClass().getSimpleName() + " finish to listener " + listener.getClass().getSimpleName()); listener.onFinishUseCase(); } catch (Exception e) { AbstractException abstractException = wrapException(e); logHandledException(abstractException); } }
Notifies the listener that the use case has finished successfully. <br/> You can override this method for a custom notification when your listeners may be listening to multiple use cases at a time. @param listener The listener to notify.
@RestrictTo(LIBRARY) public void notifyFailedUseCase(AbstractException exception, UseCaseListener listener) { try { LOGGER.debug("Notifying " + getClass().getSimpleName() + " finish failed to listener " + listener.getClass().getSimpleName()); listener.onFinishFailedUseCase(exception); } catch (Exception e) { AbstractException abstractException = wrapException(e); logHandledException(abstractException); } }
Notifies the listener that the use case has failed to execute. <br/> You can override this method for a custom notification when your listeners may be listening to multiple use cases at a time. @param listener The listener to notify.
public static String encrypt(String cleartext) { if (cleartext != null) { byte[] result = doFinal(Base64.decode(getBase64Key(), Base64.DEFAULT), Cipher.ENCRYPT_MODE, cleartext.getBytes()); return Base64.encodeToString(result, Base64.DEFAULT); } return null; }
Returns the data encrypted. Avoid calling this method on the UI thread if possible, since it may access to shared preferences. @param cleartext @return encrypted data
public static String decrypt(String base64Encrypted) { if (base64Encrypted != null) { byte[] enc = Base64.decode(base64Encrypted, Base64.DEFAULT); byte[] result = doFinal(Base64.decode(getBase64Key(), Base64.DEFAULT), Cipher.DECRYPT_MODE, enc); return new String(result); } return null; }
Returns the original data. Avoid calling this method on the UI thread if possible, since it may access to shared preferences. @param base64Encrypted @return the original data
private static String getBase64Key() { if (base64Key == null) { base64Key = SharedPreferencesHelper.get().loadPreference(BASE64_KEY); if (base64Key == null) { base64Key = generateBase64Key(); SharedPreferencesHelper.get().savePreference(BASE64_KEY, base64Key); } } return base64Key; }
Returns the encryption key stored on {@link SharedPreferences}. If the key is already on memory, it doesn't access the file system. You shouldn't call this method in the UI thread.
public static String generateShaHash(String text) { try { MessageDigest digest = MessageDigest.getInstance(SHA_ALGORITHM); byte[] bytes = text.getBytes(UTF_8); bytes = digest.digest(bytes); return toHexEncode(bytes); } catch (Exception e) { throw new UnexpectedException(e); } }
Generates the SHA hash for the input string. @param text the input string to hash @return the hash for the input string in hexadecimal encoding
public static <E> E select(List<E> items, List<Double> weights, Random random){ // check null if(items == null){ throw new NullPointerException("List of items can not be null."); } if(weights == null){ throw new NullPointerException("List of weights can not be null."); } // check list sizes if(items.size() != weights.size()){ throw new IllegalArgumentException("Item and weight lists should be of the same size."); } // return null if no items given if(items.isEmpty()){ return null; } // at least one item: compute total weight double totalWeight = 0; for(Double w : weights){ // check not null if(w == null){ throw new NullPointerException("Null elements not allowed in weights list."); } // check positive if(w < 0){ throw new IllegalArgumentException("Negative weights not allowed."); } // increase sum totalWeight += w; } if(totalWeight > 0){ // roulette wheel selection double r = random.nextDouble() * totalWeight; int i=0; while(i < items.size() && r > 0){ r -= weights.get(i); i++; } return items.get(i-1); } else { // all items have weight zero return null; } }
Select an item from a given list by roulette selection, where each item has a weight expressing the size of its section of the roulette wheel. The total size of the wheel is the sum of all item weights. The list of items and weights should be of the same size and all weights should be positive. A weight of zero is allowed, in which case the respective item will never be selected. One item is always selected, except when the item list is empty or when all weights are zero in which case <code>null</code> is returned. @param items items from which one is to be selected @param weights item weights (same order as items) @param random random generator (cannot be <code>null</code>) @param <E> type of items @return item selected by roulette selection, <code>null</code> if all weights are zero or the item list is empty @throws IllegalArgumentException if both lists are not of the same size or if any of the given weights is &lt; 0 @throws NullPointerException if <code>items</code>, <code>weights</code> or <code>random</code> are <code>null</code> or if <code>weights</code> contains any <code>null</code> elements
@Override public void apply(SubsetSolution solution) { // add IDs for(int ID : add){ if(!solution.select(ID)){ throw new SolutionModificationException("Cannot add ID " + ID + " to selection (already selected).", solution); } } // remove IDs for(int ID : delete){ if(!solution.deselect(ID)){ throw new SolutionModificationException("Cannot remove ID " + ID + " from selection (currently not selected).", solution); } } }
Apply this move to a given subset solution. The move can only be applied to a solution for which none of the added IDs are currently already selected and none of the removed IDs are currently not selected. This guarantees that calling {@link #undo(SubsetSolution)} will correctly undo the move. @throws SolutionModificationException if some added ID is already selected, some removed ID is currently not selected, or any ID does not correspond to an underlying entity @param solution solution to which to move will be applied
@Override public void undo(SubsetSolution solution) { // remove all added IDs solution.deselectAll(add); // add all removed IDs solution.selectAll(delete); }
Undo this move after it has been successfully applied to the given subset solution, by removing all added IDs and adding all removed IDs. If the subset solution has been modified since successful application of this move, the result of this operation is undefined. @param solution solution to which the move has been successfully applied
@Override public Metadata createMetadata() { Metadata metadata = new Metadata(); try { for (DataSet ds : iimFile.getDataSets()) { Object value = ""; try { value = ds.getValue(); } catch (Exception ex) { } DataSetInfo info = ds.getInfo(); //System.out.println(info.toString() + " " + info.getName() + ": " + value); metadata.add(info.getName(), new Text(value.toString())); } } catch (Exception ex) { /*Nothing to be shown*/ } return metadata; }
Creates the metadata. @return the hash map
public void removeTag(String tagName) { int ids = -1; for (DataSet ds : iimFile.getDataSets()) { if (ds.getInfo().getName().equals(tagName)) ids = ds.getInfo().getDataSetNumber(); } if (ids != -1) iimFile.remove(ids); }
Removes the tag. @param tagName the tag name
public void read(TagValue tv, String filename) { originalValue = tv.getValue(); File file = new File(filename); IIMReader reader = null; SubIIMInputStream subStream = null; try { int offset = tv.getReadOffset(); int length = tv.getReadlength(); subStream = new SubIIMInputStream(new FileIIMInputStream(file), offset, length); reader = new IIMReader(subStream, new IIMDataSetInfoFactory()); IIMFile iimFileReader = new IIMFile(); iimFileReader.readFrom(reader, 0); List<DataSet> lds = new ArrayList<DataSet>(); for (DataSet ds : iimFileReader.getDataSets()) { ds.getData(); lds.add(ds); } iimFile = new IIMFile(); iimFile.setDataSets(lds); tv.reset(); tv.add(this); reader.close(); subStream.close(); } catch (IOException e) { //e.printStackTrace(); try { reader.close(); subStream.close(); } catch (Exception ex) { } } catch (InvalidDataSetException e) { //e.printStackTrace(); try { reader.close(); subStream.close(); } catch (Exception ex) { } } }
Reads the IPTC. @param tv the TagValue containing the array of bytes of the IPTC
public void onMessageReceived(RemoteMessage remoteMessage) { if (LoggerUtils.isEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("Message received. "); builder.append("from: "); builder.append(remoteMessage.getFrom()); if (remoteMessage.getMessageType() != null) { builder.append(", "); builder.append("message type: "); builder.append(remoteMessage.getMessageType()); } if (remoteMessage.getData() != null & !remoteMessage.getData().isEmpty()) { builder.append(", "); builder.append("data: "); builder.append(remoteMessage.getData()); } LOGGER.info(builder.toString()); } FcmMessageResolver fcmResolver = AbstractFcmAppModule.get().getFcmMessageResolver(); if (fcmResolver != null) { FcmMessage fcmMessage = null; try { fcmMessage = fcmResolver.resolve(remoteMessage); } catch (Exception e) { AbstractApplication.get().getExceptionHandler().logHandledException("Error when resolving FCM message", e); return; } if (fcmMessage != null) { try { fcmMessage.handle(remoteMessage); } catch (Exception e) { AbstractApplication.get().getExceptionHandler().logHandledException("Error when handling FCM message", e); } } else { LOGGER.warn("The FCM message was not resolved"); } } else { LOGGER.warn("A FCM message was received, but not resolved is configured"); } for (FcmEventsListener fcmEventsListener : FcmContext.getFcmEventsListeners()) { try { fcmEventsListener.onMessageReceived(remoteMessage); } catch (Exception e) { AbstractApplication.get().getExceptionHandler().logHandledException(e); } } }
Called when message is received. Since Android O, have a guaranteed life cycle limited to 10 seconds for this method execution
@Override public IScan addScan(final IScan scan) { IScan oldScan = index.add(scan); // update available precursor m/z ranges map //Double avgWndMz = null; Interval1D<Double> si = null; // search interval if (scan.getMsLevel() == 1) { if (scan.getScanMzWindowLower() != null && scan.getScanMzWindowUpper() != null) { // we don't have precursors for MS1 scans, so we treat their full mass range // as the range for classification //avgWndMz = (scan.getScanMzWindowLower() + scan.getScanMzWindowUpper()) / 2d; si = new Interval1D<>(scan.getScanMzWindowLower(), scan.getScanMzWindowUpper()); } } else { // for MS^N scans, we're only interested in cases, when the precursor window is known, // otherwise we'll try to guess the windows. if (scan.getPrecursor() != null && scan.getPrecursor().getMzRangeStart() != null && scan.getPrecursor().getMzRangeEnd() != null) { // if they're not equal, we have a range to search for // but we still don't want to do the grouping if the range //avgWndMz = (scan.getPrecursor().getMzRangeStart() + scan.getPrecursor().getMzRangeEnd()) / 2d; si = new Interval1D<>(scan.getPrecursor().getMzRangeStart(), scan.getPrecursor().getMzRangeEnd()); } } if (si != null) { IntervalST<Double, TreeMap<Integer, IScan>> rangeTreeAtMsLvl = msLevel2rangeGroups .get(scan.getMsLevel()); if (rangeTreeAtMsLvl == null) { rangeTreeAtMsLvl = new IntervalST<>(); msLevel2rangeGroups.put(scan.getMsLevel(), rangeTreeAtMsLvl); } // get all the nodes intersecting our current interval Iterable<IntervalST.Node<Double, TreeMap<Integer, IScan>>> nodes = rangeTreeAtMsLvl .searchAll(si); IntervalST.Node<Double, TreeMap<Integer, IScan>> bestNode = null; double bestOverlapSum = 0d; // find the best-overlapping interval double siLen = si.hi - si.lo; double ciLen, diff1, diff2, ciOverlap, siOverlap, overlap; for (IntervalST.Node<Double, TreeMap<Integer, IScan>> node : nodes) { Interval1D<Double> ci = node.getInterval(); // current interval (already in collection) ciLen = ci.hi - ci.lo; diff1 = si.hi - ci.lo; diff2 = ci.hi - si.lo; overlap = Math.min(Math.min(Math.min(ciLen, siLen), diff1), diff2); if (ciLen == 0 && siLen == 0) { // that's the case of AB Sciex SWATH data, when precursors are given // as single m/z values, instead of windows. // In that case we just add the interval to the list, but // when finalizing the ScanCollection we'll remove the whole // MS2 subtree, if every precursor interval in it doesn't contain // more than one scan. bestNode = node; // we don't expect to find more than one zero-length interval in the tree, // so it's safe to stop searching for best-overlapping interval break; } if (overlap > 0) { ciOverlap = overlap / ciLen; siOverlap = overlap / siLen; if (ciOverlap >= MIN_GROUP_OVERLAP && siOverlap >= MIN_GROUP_OVERLAP) { double overlapSum = ciOverlap + siOverlap; if (overlapSum > bestOverlapSum) { bestNode = node; bestOverlapSum = overlapSum; } } } } if (bestNode == null) { // there were no intervals intersecting our current interval at all // or they didn't pass the criteria to be accepted. // it's safe to just add the current one. TreeMap<Integer, IScan> scanMap = new TreeMap<>(); scanMap.put(scan.getNum(), scan); rangeTreeAtMsLvl.put(si, scanMap); } else { // we've found a node which overlaps our interval // rolling update of average // x: the update value to be added to the previous average // c: the new incoming value // N: the number of items int prev_avg // x = (c - prev_avg) / (N + 1) Interval1D<Double> ci = bestNode.getInterval(); int nodeSize = bestNode.getValue().size(); if (!si.lo.equals(ci.lo) || !si.hi.equals(ci.hi)) { // if the boundaries need to be updated, the only way is to // update the whole range tree by putting a new interval there double newLo = ci.lo + (si.lo - ci.lo) / (nodeSize + 1); double newHi = ci.hi + (si.hi - ci.hi) / (nodeSize + 1); IntervalST.Node<Double, TreeMap<Integer, IScan>> removed = rangeTreeAtMsLvl.remove(ci); removed.getValue().put(scan.getNum(), scan); rangeTreeAtMsLvl.put(new Interval1D<>(newLo, newHi), removed.getValue()); } else { IntervalST.Node<Double, TreeMap<Integer, IScan>> node = rangeTreeAtMsLvl.get(si); node.getValue().put(scan.getNum(), scan); } } } return oldScan; }
Adds a new scan to this collection, maintains all the proper inside mappings. If a scan with the same scan number is already in the map it will be replaced and the old entry will be returned. If no replacement took place - null is returned. @param scan scan to be added @return null if the scan was just added, or the old Scan, if it was replaced
@Override public TreeMap<Integer, IntervalST<Double, TreeMap<Integer, IScan>>> getMapMsLevel2rangeGroups() { return msLevel2rangeGroups; }
Get a map, holding spectra groupped by precursor m/z isolation window. MS1 spectra are groupped by their overall m/z range. @return Interval search tree for every level, this is only created after a call to {@link #finalize()}. A call to {@link #finalize()} will be made for you automatically, if you load scans using an {@link LCMSDataSubset} with lo/hi scan nums as null.
@Override public IScan getScanByNum(int scanNum) { IScan scan = getNum2scan().get(scanNum); if (scan != null) { return scan; } return null; }
The name says it all. @param scanNum Scan number as it was in the original MS file @return Scan or null, if no such scan number exists in this ScanCollection
@Override public IScan getScanByNumLower(int scanNum) { IScan scan = getNum2scan().lowerEntry(scanNum).getValue(); if (scan != null) { return scan; } return null; }
Scan with closest Number STRICTLY less than the provided one is returned. @param scanNum scan number @return Scan or null, if the ScanCollection didn't have any scans with numbers <= than this one
@Override public IScan getScanByNumUpper(int scanNum) { IScan scan = getNum2scan().ceilingEntry(scanNum).getValue(); if (scan != null) { return scan; } return null; }
Scan with the closest Number greater or equal to the provided one is returned. @param scanNum scan number @return Scan or null, if the ScanCollection didn't have any scans with numbers &gt;= than this one
@Override public IScan getScanByNumClosest(int scanNum) { IScan result = null; Map.Entry<Integer, IScan> lower = getNum2scan().lowerEntry(scanNum); Map.Entry<Integer, IScan> upper = getNum2scan().ceilingEntry(scanNum); if (upper != null && lower != null) { result = Integer.compare(lower.getKey(), upper.getKey()) > 0 ? lower.getValue() : upper.getValue(); } else if (upper != null) { result = upper.getValue(); } else if (lower != null) { result = lower.getValue(); } return result; }
Scan with the closest Number is returned. @param scanNum scan number @return null might be returned in an extreme case when the scan collection is empty.
@Override public List<IScan> getScansByRt(double rt) { List<IScan> scans = getRt2scan().get(rt); if (scans != null) { return scans; } return null; }
Provided RT <i>MUST</i> be <i>EXACT</i> RT, existing in the map. @param rt RT in minutes @return list of Scans or null if no such RT exists
@Override public List<IScan> getScansByRtLower(double rt) { Map.Entry<Double, List<IScan>> lowerEntry = getRt2scan().lowerEntry(rt); if (lowerEntry == null) { return null; } List<IScan> scans = lowerEntry.getValue(); if (scans != null) { return scans; } return null; }
Scan List with closest RT less or equal to the provided one are returned.
@Override public List<IScan> getScansByRtUpper(double rt) { Map.Entry<Double, List<IScan>> ceilingEntry = getMapRt2scan().ceilingEntry(rt); if (ceilingEntry == null) { return null; } List<IScan> scans = ceilingEntry.getValue(); if (scans != null) { return scans; } return null; }
Scan List with the closest RT greater or equal to the provided one are returned.
@Override public List<IScan> getScansByRtClosest(double rt) { List<IScan> result = null; Map.Entry<Double, List<IScan>> lower = getMapRt2scan().lowerEntry(rt); Map.Entry<Double, List<IScan>> upper = getMapRt2scan().ceilingEntry(rt); if (upper != null && lower != null) { if (Math.abs(rt - lower.getKey()) <= Math.abs(rt - upper.getKey())) { result = lower.getValue(); } else { result = upper.getValue(); } // result = Double.compare(lower.getKey(), upper.getKey()) > 0 ? lower.getValue() : upper.getValue(); } else if (upper != null) { result = upper.getValue(); } else if (lower != null) { result = lower.getValue(); } return result; }
Scans with the closest RT are returned. @return null if no scans were found at all, but this should only happen if your ScanCollection is empty.
@Override public NavigableMap<Integer, IScan> getScansByNumSpanAtMsLevel(int numStart, int numEnd, int msLevel) { NavigableMap<Integer, IScan> subMap = null; TreeMap<Integer, IScan> msLevelMap = getMapMsLevel2index().get(msLevel).getNum2scan(); if (msLevelMap != null) { subMap = msLevelMap.subMap(numStart, true, numEnd, true); } if (subMap != null && subMap.size() > 0) { return subMap; } return null; }
A view(not a copy!) of the original scan map, containing only scans from numStart to numEnd (inclusive). Scan numbers don't need to be exact matches, scans from the closed interval [numStart; numEnd] are returned. @return A view or null if there were no scans at this ms level in [numStart; numEnd] interval
@Override public NavigableMap<Integer, IScan> getScansByRtSpanAtMsLevel(double rtStart, double rtEnd, int msLevel) { if (getNum2scan().size() == 0) { return null; } List<IScan> startScans = getScansByRtUpper(rtStart); int startScanNum = startScans == null ? getNum2scan().firstEntry().getValue().getNum() : startScans.get(0).getNum(); List<IScan> endScans = getScansByRtLower(rtEnd); int endScanNum = endScans == null ? getNum2scan().lastEntry().getValue().getNum() : endScans.get(0).getNum(); if (endScanNum < startScanNum) { return null; } NavigableMap<Integer, IScan> scansByNumSpanAtMsLevel = getScansByNumSpanAtMsLevel(startScanNum, endScanNum, msLevel); if (scansByNumSpanAtMsLevel != null && scansByNumSpanAtMsLevel.size() > 0) { return scansByNumSpanAtMsLevel; } return null; }
Same as {@link #getScansByRtSpan(double, double)}, but only searches at one MS Level. If it so happens, that the RTs are between just 2 consecutive scans, then null is returned. You get a view of the original scan map, not a copy! @param rtStart The beginning of RT window @param rtEnd The end of RT window @param msLevel MS Level at which to get scans @return null, if no scans were in this window.
@Override public TreeMap<Integer, NavigableMap<Integer, IScan>> getScansByRtSpan(double rtStart, double rtEnd) { TreeMap<Integer, NavigableMap<Integer, IScan>> viewMap = new TreeMap<>(); boolean hasNonZeroElements = false; for (Integer i : getMapMsLevel2index().keySet()) { NavigableMap<Integer, IScan> scansByRtSpanAtMsLevel = getScansByRtSpanAtMsLevel(rtStart, rtEnd, i); if (scansByRtSpanAtMsLevel != null) { hasNonZeroElements = true; viewMap.put(i, scansByRtSpanAtMsLevel); } } if (hasNonZeroElements) { return viewMap; } return null; }
Returns a range of scans, whose RT is in the inclusive interval [rtStart; rtEnd]. That means, ceil RT match is used for rtStart and floor RT for rtEnd. If it so happens, that the RTs are between just 2 consecutive scans, then null is returned. @param rtStart The beginning of RT window @param rtEnd The end of RT window @return null, if no scans were in this window
@Override public Integer getScanCountAtMsLevel(int msLevel) { TreeMap<Integer, IScan> msLevelScanMap = getMapMsLevel2index().get(msLevel).getNum2scan(); if (msLevelScanMap != null) { return msLevelScanMap.size(); } return null; }
If the msLevel doesn't exist in this ScanCollectionDefault, returns null @return null, if msLevel doesn't exist. Actual number of scans otherwise.
@Override public IScan getNextScanAtMsLevel(int scanNum, int msLevel) { TreeMap<Integer, IScan> msLevelMap = getMapMsLevel2index().get(msLevel).getNum2scan(); if (msLevelMap == null) { return null; } Map.Entry<Integer, IScan> entry = msLevelMap.ceilingEntry(scanNum + 1); if (entry != null) { return entry.getValue(); } return null; }
Finds the next scan at the same MS level, as the scan with scanNum. If the scan number provided is not in the map, this method will find the next existing one. @param scanNum Scan number @param msLevel MS Level at which to search for that scan number. That MS level must be present in the collection, otherwise an NPE is thrown. @return either next Scan, or null, if there are no further scans at this level. If MS level is incorrect, also returns null.
@Override public IScan getNextScanAtSameMsLevel(IScan scan) { return getNextScanAtMsLevel(scan.getNum(), scan.getMsLevel()); }
Convenience method, calls {@link #getNextScanAtMsLevel(int, int)} internally @param scan an existing scan from THIS ScanCollection
@Override public IScan getPrevScanAtMsLevel(int scanNum, int msLevel) { TreeMap<Integer, IScan> msLevelMap = getMapMsLevel2index().get(msLevel).getNum2scan(); if (msLevelMap == null) { return null; } Map.Entry<Integer, IScan> entry = msLevelMap.floorEntry(scanNum - 1); if (entry != null) { return entry.getValue(); } return null; }
Finds the next scan at the same MS level, as the scan with scanNum. If the scan number provided is not in the map, this method will find the next existing one. @param scanNum Scan number @param msLevel MS Level at which to search for that scan number @return either next Scan, or null, if there are no further scans at this level. If MS level is incorrect, also returns null.
@Override public IScan getPrevScanAtSameMsLevel(IScan scan) { return getPrevScanAtMsLevel(scan.getNum(), scan.getMsLevel()); }
Convenience method, calls {@link #getPrevScanAtMsLevel(int, int)} internally
@Override public void setStorageStrategy(LCMSDataSubset subset, StorageStrategy storageStrategy) { NavigableMap<Integer, IScan> scansInSubsetByNumber = getScansInSubsetByNumber(getMapNum2scan(), subset); for (IScan scan : scansInSubsetByNumber.values()) { if (subset.isInSubset(scan)) { scan.setStorageStrategy(storageStrategy); } } }
///////////////////////////////////////////////
private NavigableMap<Integer, IScan> getScansInSubsetByNumber( NavigableMap<Integer, IScan> scanMap, LCMSDataSubset subset) { NavigableMap<Integer, IScan> scansInSubsetByNumber = scanMap; if (subset.getScanNumLo() != null) { scansInSubsetByNumber .subMap(subset.getScanNumLo(), true, scansInSubsetByNumber.lastKey(), true); } if (subset.getScanNumHi() != null) { scansInSubsetByNumber .subMap(scansInSubsetByNumber.firstKey(), true, subset.getScanNumHi(), true); } return scansInSubsetByNumber; }
It won't filter the scanMap according the the full subset predicate, it only selects scan number range. Further checks for ms-levels and precursor ranges is required. It's just a convenience method. @param scanMap use {@link #getMapNum2scan() } for the broadest use @param subset only scan numbers will be used for filtering the scanMap
private void unloadSpectraConditionally(NavigableMap<Integer, IScan> scansInSubsetByNumber, LCMSDataSubset subset, Set<LCMSDataSubset> exlude) { boolean isOkToUnload; for (IScan scan : scansInSubsetByNumber.values()) { if (subset.isInSubset(scan)) { isOkToUnload = true; for (LCMSDataSubset exludedSubset : exlude) { if (exludedSubset.isInSubset(scan)) { isOkToUnload = false; break; } } if (isOkToUnload) { scan.setSpectrum(null, false); } } } }
Unloads spectra from scans that match {@code subset} variable and do not match all of subsets from {@code exclude} variable. @param scansInSubsetByNumber pre-filtered scan map, e.g. by scan numbers, ms-levels, etc.
public void ensureHasSpace(int numBytesToAdd) { if (numBytesToAdd < 0) { throw new IllegalArgumentException("Number of bytes can't be negative"); } int capacityLeft = getCapacityLeft(); if (capacityLeft < numBytesToAdd) { grow(numBytesToAdd - capacityLeft, true); } }
Checks if there is enough space in the buffer to write N additional bytes. Will grow the buffer if necessary. It takes current position in the buffer into account. @param numBytesToAdd the number of bytes you want to add to the buffer
@Override public Object getValue(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base == null && property instanceof String) { if (beanNameResolver.isNameResolved((String) property)) { context.setPropertyResolved(base, property); return beanNameResolver.getBean((String) property); } } return null; }
If the base object is <code>null</code> and the property is a name that is resolvable by the BeanNameResolver, returns the value resolved by the BeanNameResolver. <p>If name is resolved by the BeanNameResolver, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller should ignore the return value.</p> @param context The context of this evaluation. @param base <code>null</code> @param property The name of the bean. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then the value of the bean with the given name. Otherwise, undefined. @throws NullPointerException if context is <code>null</code>. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
@Override public void setValue(ELContext context, Object base, Object property, Object value) { if (context == null) { throw new NullPointerException(); } if (base == null && property instanceof String) { String beanName = (String) property; if (beanNameResolver.isNameResolved(beanName) || beanNameResolver.canCreateBean(beanName)) { beanNameResolver.setBeanValue(beanName, value); context.setPropertyResolved(base, property); } } }
If the base is null and the property is a name that is resolvable by the BeanNameResolver, the bean in the BeanNameResolver is set to the given value. <p>If the name is resolvable by the BeanNameResolver, or if the BeanNameResolver allows creating a new bean, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by the resolver, before returning. If this property is not <code>true</code> after this method is called, the caller can safely assume no value has been set.</p> @param context The context of this evaluation. @param base <code>null</code> @param property The name of the bean @param value The value to set the bean with the given name to. @throws NullPointerException if context is <code>null</code> @throws PropertyNotWritableException if the BeanNameResolver does not allow the bean to be modified. @throws ELException if an exception was thrown while attempting to set the bean with the given name. The thrown exception must be included as the cause property of this exception, if available.
@Override public Class<?> getType(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base == null && property instanceof String) { if (beanNameResolver.isNameResolved((String) property)) { context.setPropertyResolved(true); return beanNameResolver.getBean((String) property).getClass(); } } return null; }
If the base is null and the property is a name resolvable by the BeanNameResolver, return the type of the bean. <p>If the name is resolvable by the BeanNameResolver, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by the resolver, before returning. If this property is not <code>true</code> after this method is called, the caller can safely assume no value has been set.</p> @param context The context of this evaluation. @param base <code>null</code> @param property The name of the bean. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then the type of the bean with the given name. Otherwise, undefined. @throws NullPointerException if context is <code>null</code>. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
@Override public boolean isReadOnly(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base == null && property instanceof String) { if (beanNameResolver.isNameResolved((String) property)) { context.setPropertyResolved(true); return beanNameResolver.isReadOnly((String) property); } } return false; }
If the base is null and the property is a name resolvable by the BeanNameResolver, attempts to determine if the bean is writable. <p>If the name is resolvable by the BeanNameResolver, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by the resolver, before returning. If this property is not <code>true</code> after this method is called, the caller can safely assume no value has been set.</p> @param context The context of this evaluation. @param base <code>null</code> @param property The name of the bean. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then <code>true</code> if the property is read-only or <code>false</code> if not; otherwise undefined. @throws NullPointerException if context is <code>null</code>. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
@Override public void validate() { try { currentIfd = 0; for (TiffObject o : model.getImageIfds()) { currentIfd++; IFD ifd = (IFD) o; IfdTags metadata = ifd.getMetadata(); int sft = -1; int photo = -1; int bps = -1; int planar = -1; int comp = -1; if (metadata.containsTagId(TiffTags.getTagId("SubfileType"))) { sft = (int) metadata.get(TiffTags.getTagId("SubfileType")).getFirstNumericValue(); } if (metadata.containsTagId(TiffTags.getTagId("Compression"))) { comp = (int) metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue(); } if (metadata.containsTagId(TiffTags.getTagId("PhotometricInterpretation"))) { photo = (int) metadata.get(TiffTags.getTagId("PhotometricInterpretation")).getFirstNumericValue(); } if (metadata.containsTagId(TiffTags.getTagId("BitsPerSample"))) { bps = (int) metadata.get(TiffTags.getTagId("BitsPerSample")).getFirstNumericValue(); } if (metadata.containsTagId(TiffTags.getTagId("PlanarConfiguration"))) { planar = (int) metadata.get(TiffTags.getTagId("PlanarConfiguration")).getFirstNumericValue(); } int p = profile; // Determination of TIFF/IT file type if (sft == 1 || sft == -1) { if (comp == 1 || comp == 32895) { if (photo == 5) { if (planar == 1) { validateIfdCT(ifd, p); } else if (planar == 32768) { validateIfdCT(ifd, p); } else if (planar == 2) { if (bps > 1) { validateIfdCT(ifd, p); } else if (bps == 1) { validateIfdSD(ifd, p); } } } else if (photo == 2) { if (planar == 1) { validateIfdCT(ifd, p); } else if (planar == 32768) { validateIfdCT(ifd, p); } else if (planar == 2) { validateIfdCT(ifd, p); } } else if (photo == 8) { if (planar == 1) { validateIfdCT(ifd, p); } else if (planar == 32768) { validateIfdCT(ifd, p); } else if (planar == 2) { validateIfdCT(ifd, p); } } else if (photo == 0 || photo == 1) { if (bps == 1) { validateIfdBP(ifd, p); } else if (bps > 1) { validateIfdMP(ifd, p); } } } else if (comp == 4) { if (photo == 0 || photo == 1) { validateIfdBP(ifd, p); } else if (photo == 5) { validateIfdSD(ifd, p); } } else if (comp == 7) { if (photo == 5) { if (planar == 1) { validateIfdCT(ifd, p); } } else if (photo == 2) { if (planar == 1) { validateIfdCT(ifd, p); } } else if (photo == 6) { if (planar == 1) { validateIfdCT(ifd, p); } } else if (photo == 8) { if (planar == 1) { validateIfdCT(ifd, p); } } else if (photo == 0 || photo == 1) { if (bps > 1) { validateIfdMP(ifd, p); } } } else if (comp == 8) { if (photo == 5) { if (planar == 1) { validateIfdCT(ifd, p); } else if (planar == 32768) { validateIfdCT(ifd, p); } else if (planar == 2) { if (bps > 1) { validateIfdCT(ifd, p); } else if (bps == 1) { validateIfdSD(ifd, p); } } } else if (photo == 2) { if (planar == 1) { validateIfdCT(ifd, p); } else if (planar == 32768) { validateIfdCT(ifd, p); } else if (planar == 2) { validateIfdCT(ifd, p); } } else if (photo == 8) { if (planar == 1) { validateIfdCT(ifd, p); } else if (planar == 32768) { validateIfdCT(ifd, p); } else if (planar == 2) { validateIfdCT(ifd, p); } } else if (photo == 0 || photo == 1) { if (bps == 1) { validateIfdBP(ifd, p); } else if (bps > 1) { validateIfdMP(ifd, p); } } } else if (comp == 32896) { validateIfdLW(ifd, p); } else if (comp == 32897) { validateIfdHC(ifd, p); } else if (comp == 32898) { validateIfdBL(ifd, p); } else if (((sft >> 3) & 1) == 1) { validateIfdFP(ifd, p); } } } } catch (Exception e) { } }
Validates that the IFD conforms the Tiff/IT standard.