public final class Utils
extends java.lang.Object
Modifier and Type | Field and Description |
---|---|
static java.util.Comparator<? super java.lang.String> |
COMPARE_STRINGS_NULLS_FIRST
Comparator for strings that sorts null first;
|
static float |
JAVA_DEFAULT_HASH_LOAD_FACTOR |
Modifier and Type | Method and Description |
---|---|
static <T> java.util.List<T> |
append(java.util.List<T> left,
T... elts)
Create a new list that contains the elements of left along with elements elts
|
static java.util.List<java.lang.Double> |
asList(double... values)
Returns a
List<Double> representation of an primitive double array. |
static java.util.List<java.lang.Integer> |
asList(int... values)
Returns a
List<Integer> representation of an primitive int array. |
static java.lang.String |
calcMD5(byte[] bytes)
Calculate the md5 for bytes, and return the result as a 32 character string
|
static java.lang.String |
calcMD5(java.lang.String s) |
static java.lang.String |
calculateFileMD5(java.io.File file)
Calculates the MD5 for the specified file and returns it as a String
|
static java.lang.String |
calculatePathMD5(java.nio.file.Path path)
Calculates the MD5 for the specified file and returns it as a String
|
static <E> java.util.Set<E> |
checkForDuplicatesAndReturnSet(java.util.Collection<E> c,
java.lang.String message)
Checks that the collection does not contain a duplicate value (throws an
IllegalArgumentException if it does). |
static byte[] |
concat(byte[]... allBytes)
Concatenates byte arrays
|
static byte[] |
concat(byte[] a,
byte[] b)
Concats two byte arrays.
|
static <T> T[] |
concat(T[] a,
T[] b,
java.util.function.IntFunction<T[]> constructor) |
static <T> java.util.Iterator<T> |
concatIterators(java.util.Iterator<? extends java.lang.Iterable<T>> iterator)
Concatenates a series of
Iterator s (all of the same type) into a single Iterator . |
static <T> java.util.List<T> |
cons(T elt,
java.util.List<T> l) |
static void |
containsNoNull(java.util.Collection<?> collection,
java.lang.String message)
Checks that the collection does not contain a
null value (throws an IllegalArgumentException if it does). |
static int |
countBooleanOccurrences(boolean element,
boolean[] array)
Returns the number of occurrences of a boolean element in a boolean array.
|
static byte[] |
dupBytes(byte b,
int nCopies)
Create a new byte array that's n copies of b
|
static java.lang.String |
dupChar(char c,
int nCopies)
Create a new string that's n copies of c
|
static java.lang.String |
dupString(java.lang.String s,
int nCopies)
Create a new string thats a n duplicate copies of s
|
static boolean |
equalRange(byte[] left,
int leftOffset,
byte[] right,
int rightOffset,
int length)
Compares sections from to byte arrays to verify whether they contain the same values.
|
static java.lang.String[] |
escapeExpressions(java.lang.String args)
Splits expressions in command args by spaces and returns the array of expressions.
|
static java.util.Set<java.lang.String> |
filterCollectionByExpressions(java.util.Collection<java.lang.String> sourceValues,
java.util.Collection<java.lang.String> filterExpressions,
boolean exactMatch)
Given a collection of strings and a collection of regular expressions, generates the set of strings that match
any expression
|
static void |
forceJVMLocaleToUSEnglish()
Set the Locale to US English so that numbers will always be formatted in the US style.
|
static java.lang.String |
formattedPercent(long x,
long total)
Convenience function that formats a percentage as a %.2f string
|
static java.lang.String |
formattedRatio(long num,
long denom)
Convenience function that formats a ratio as a %.2f string
|
static java.lang.String |
getDateTimeForDisplay(java.time.ZonedDateTime dateTime)
Return the given
dateTime formatted as string for display. |
static <T> java.util.Set<T> |
getDuplicatedItems(java.util.Collection<T> objects)
Gets duplicated items in the collection.
|
static <T extends java.lang.Comparable<?>> |
getMedianValue(java.util.List<T> values)
Streams and sorts a collection of objects and returns the integer median entry of the sorted list
|
static org.apache.commons.math3.random.RandomDataGenerator |
getRandomDataGenerator() |
static java.util.Random |
getRandomGenerator() |
static <T,U> java.util.Map<U,java.util.Set<T>> |
getReverseValueToListMap(java.util.Map<T,java.util.List<U>> somethingToListMap)
Take a map of a value to a list and reverse it.
|
static <T> java.util.function.Function<T,T> |
identityFunction()
Returns a function that always returns its input argument.
|
static boolean |
isNonEmpty(java.util.Collection<?> collection)
Checks that a
Collection is not null and that it is not empty. |
static java.lang.String |
join(java.lang.CharSequence separator,
java.lang.Object... objects)
Returns a string of the values in an
Object array joined by a separator. |
static <T> java.lang.String |
join(java.lang.String separator,
java.util.Collection<T> objects)
Returns a string of the form elt1.toString() [sep elt2.toString() ...
|
static java.lang.String |
join(java.lang.String separator,
double[] doubles)
Returns a string of the values in joined by separator, such as A,B,C
|
static java.lang.String |
join(java.lang.String separator,
int[] ints)
Returns a string of the values in ints joined by separator, such as A,B,C
|
static int |
lastIndexOf(byte[] reference,
byte[] query)
Find the last occurrence of the query sequence in the reference sequence
Returns the index of the last occurrence or -1 if the query sequence is not found
|
static java.util.List<java.lang.Integer> |
listFromPrimitives(int[] ar)
Simple wrapper for sticking elements of a int[] array into a List
|
static <T> java.util.List<java.util.List<T>> |
makePermutations(java.util.List<T> objects,
int n,
boolean withReplacement)
Make all combinations of N size of objects
if objects = [A, B, C]
if N = 1 => [[A], [B], [C]]
if N = 2 => [[A, A], [B, A], [C, A], [A, B], [B, B], [C, B], [A, C], [B, C], [C, C]]
|
static java.lang.String |
nonEmpty(java.lang.String string)
Checks that a
String is not null and that it is not empty. |
static java.lang.String |
nonEmpty(java.lang.String string,
java.lang.String message)
Checks that a
String is not null and that it is not empty. |
static <I,T extends java.util.Collection<I>> |
nonEmpty(T collection)
Checks that a
Collection is not null and that it is not empty. |
static <I,T extends java.util.Collection<I>> |
nonEmpty(T collection,
java.lang.String message)
Checks that a
Collection is not null and that it is not empty. |
static <T> T |
nonNull(T object)
Checks that an Object
object is not null and returns the same object or throws an IllegalArgumentException |
static <T> T |
nonNull(T object,
java.lang.String message)
Checks that an
Object is not null and returns the same object or throws an IllegalArgumentException |
static <T> T |
nonNull(T object,
java.util.function.Supplier<java.lang.String> message)
Checks that an
Object is not null and returns the same object or throws an IllegalArgumentException |
static int |
optimumHashSize(int maxElements)
Calculates the optimum initial size for a hash table given the maximum number
of elements it will need to hold.
|
static byte[] |
repeatBytes(byte b,
int n)
makes an array filled with n copies of the given byte.
|
static byte[] |
repeatChars(char c,
int n)
makes an array filled with n copies of the given char.
|
static void |
resetRandomGenerator() |
static <T> T |
runInParallel(int threads,
java.util.function.Supplier<T> supplier)
Runs a task in parallel returning it returned result.
|
static <T> T |
skimArray(T original,
boolean[] remove)
Skims out positions of an array returning a shorter one with the remaning positions in the same order.
|
static <T> T |
skimArray(T source,
int sourceOffset,
T dest,
int destOffset,
boolean[] remove,
int removeOffset)
Skims out positions of an array returning a shorter one with the remaining positions in the same order.
|
static <T> T |
skimArray(T source,
int sourceOffset,
T dest,
int destOffset,
boolean[] remove,
int removeOffset,
int length)
Skims out positions of an array returning a shorter one with the remaning positions in the same order.
|
static java.util.List<java.lang.String> |
split(java.lang.String str,
char delimiter)
Splits a String using indexOf instead of regex to speed things up.
|
static java.util.List<java.lang.String> |
split(java.lang.String str,
java.lang.String delimiter)
Splits a String using indexOf instead of regex to speed things up.
|
static <T> java.util.stream.Stream<T> |
stream(java.util.Enumeration<T> enumeration) |
static <T> java.util.stream.Stream<T> |
stream(java.lang.Iterable<T> iterable) |
static <T> java.util.stream.Stream<T> |
stream(java.util.Iterator<T> iterator) |
static <F,T> java.util.Iterator<T> |
transformParallel(java.util.Iterator<F> fromIterator,
java.util.function.Function<F,T> function,
int numThreads)
Like Guava's
Iterators.transform(Iterator, com.google.common.base.Function) , but runs a fixed number
(numThreads ) of transformations in parallel, while maintaining ordering of the output iterator. |
static void |
validate(boolean condition,
java.lang.String msg)
Check a condition that should always be true and throw an
IllegalStateException if false. |
static void |
validate(boolean condition,
java.util.function.Supplier<java.lang.String> msg)
Check a condition that should always be true and throw an
IllegalStateException if false. |
static void |
validateArg(boolean condition,
java.lang.String msg) |
static void |
validateArg(boolean condition,
java.util.function.Supplier<java.lang.String> msg) |
static int |
validIndex(int index,
int length)
Checks whether an index is within bounds considering a collection or array of a particular size
whose first position index is 0
|
static int |
validIndex(int index,
int length,
java.lang.String errorMessage)
Checks whether an index is within bounds considering a collection or array of a particular size
whose first position index is 0
|
static void |
warnOnNonIlluminaReadGroups(htsjdk.samtools.SAMFileHeader readsHeader,
org.apache.logging.log4j.Logger logger)
Checks if the read header contains any reads groups from non-Illumina and issue a warning of that's the case.
|
static void |
warnUser(org.apache.logging.log4j.Logger logger,
java.lang.String msg) |
static void |
warnUser(java.lang.String msg) |
static java.util.List<java.lang.String> |
warnUserLines(java.lang.String msg) |
static boolean |
xor(boolean x,
boolean y)
Boolean xor operation.
|
public static final java.util.Comparator<? super java.lang.String> COMPARE_STRINGS_NULLS_FIRST
public static final float JAVA_DEFAULT_HASH_LOAD_FACTOR
public static java.util.Random getRandomGenerator()
public static org.apache.commons.math3.random.RandomDataGenerator getRandomDataGenerator()
public static void resetRandomGenerator()
public static <T> java.util.List<T> cons(T elt, java.util.List<T> l)
public static void warnUser(java.lang.String msg)
public static void warnUser(org.apache.logging.log4j.Logger logger, java.lang.String msg)
public static java.util.List<java.lang.String> warnUserLines(java.lang.String msg)
public static java.lang.String join(java.lang.CharSequence separator, java.lang.Object... objects)
Object
array joined by a separator.separator
- separator characterobjects
- the array with valuesjava.lang.IllegalArgumentException
- if separator
or objects
is null
.public static java.lang.String join(java.lang.String separator, int[] ints)
separator
- separator characterints
- the array with valuespublic static java.lang.String join(java.lang.String separator, double[] doubles)
separator
- separator characterdoubles
- the array with valuespublic static <T> java.lang.String join(java.lang.String separator, java.util.Collection<T> objects)
T
- the type of the objectsseparator
- the string to use to separate objectsobjects
- a collection of objects. the element order is defined by the iterator over objectspublic static byte[] concat(byte[]... allBytes)
public static <T> T[] concat(T[] a, T[] b, java.util.function.IntFunction<T[]> constructor)
public static byte[] concat(byte[] a, byte[] b)
A bit more efficient than calling the more general #concat(byte[]...)
.
a
- left array to concat.b
- right array to concat.null
;public static java.util.List<java.lang.Integer> asList(int... values)
List<Integer>
representation of an primitive int array.values
- the primitive int array to represent.null
. The returned list will be unmodifiable yet it will reflect changes in values in the original array yet
you cannot change the valuespublic static java.util.List<java.lang.Double> asList(double... values)
List<Double>
representation of an primitive double array.values
- the primitive int array to represent.null
. The returned list will be unmodifiable yet it will reflect changes in values in the original array yet
you cannot change the values.@SafeVarargs public static <T> java.util.List<T> append(java.util.List<T> left, T... elts)
left
- a non-null list of elementselts
- a varargs vector for elts to append in order to leftpublic static java.lang.String dupChar(char c, int nCopies)
c
- the char to duplicatenCopies
- how many copies?public static java.lang.String dupString(java.lang.String s, int nCopies)
s
- the string to duplicatenCopies
- how many copies?public static byte[] dupBytes(byte b, int nCopies)
b
- the byte to duplicatenCopies
- how many copies?public static int countBooleanOccurrences(boolean element, boolean[] array)
element
- array
- cannot be nullpublic static java.lang.String[] escapeExpressions(java.lang.String args)
args
- Arguments to parse.public static byte[] repeatChars(char c, int n)
public static byte[] repeatBytes(byte b, int n)
public static <T> java.util.List<java.util.List<T>> makePermutations(java.util.List<T> objects, int n, boolean withReplacement)
objects
- list of objectsn
- size of each combinationwithReplacement
- if false, the resulting permutations will only contain unique objects from objectspublic static java.lang.String calcMD5(java.lang.String s)
calcMD5(byte[])
public static java.lang.String calcMD5(byte[] bytes)
bytes
- the bytes to calculate the md5 ofpublic static java.lang.String calculateFileMD5(java.io.File file) throws java.io.IOException
file
- file whose MD5 to calculatejava.io.IOException
- if the file could not be readpublic static java.lang.String calculatePathMD5(java.nio.file.Path path) throws java.io.IOException
path
- file whose MD5 to calculatejava.io.IOException
- if the file could not be readpublic static <T> T nonNull(T object)
object
is not null and returns the same object or throws an IllegalArgumentException
object
- any Objectjava.lang.IllegalArgumentException
- if a o == null
public static <T> T nonNull(T object, java.lang.String message)
Object
is not null
and returns the same object or throws an IllegalArgumentException
object
- any Objectmessage
- the text message that would be passed to the exception thrown when o == null
.java.lang.IllegalArgumentException
- if a o == null
public static <T> T nonNull(T object, java.util.function.Supplier<java.lang.String> message)
Object
is not null
and returns the same object or throws an IllegalArgumentException
object
- any Objectmessage
- the text message that would be passed to the exception thrown when o == null
.java.lang.IllegalArgumentException
- if a o == null
public static <I,T extends java.util.Collection<I>> T nonEmpty(T collection, java.lang.String message)
Collection
is not null
and that it is not empty.
If it's non-null and non-empty it returns the input, otherwise it throws an IllegalArgumentException
collection
- any Collectionmessage
- a message to include in the outputjava.lang.IllegalArgumentException
- if collection is null or emptypublic static boolean isNonEmpty(java.util.Collection<?> collection)
Collection
is not null
and that it is not empty.
If it's non-null and non-empty it returns the truecollection
- any Collectionpublic static java.lang.String nonEmpty(java.lang.String string, java.lang.String message)
String
is not null
and that it is not empty.
If it's non-null and non-empty it returns the input, otherwise it throws an IllegalArgumentException
string
- any Stringmessage
- a message to include in the outputjava.lang.IllegalArgumentException
- if string is null or emptypublic static java.lang.String nonEmpty(java.lang.String string)
String
is not null
and that it is not empty.
If it's non-null and non-empty it returns the input, otherwise it throws an IllegalArgumentException
string
- any Stringjava.lang.IllegalArgumentException
- if string is null or emptypublic static <I,T extends java.util.Collection<I>> T nonEmpty(T collection)
Collection
is not null
and that it is not empty.
If it's non-null and non-empty it returns the input, otherwise it throws an IllegalArgumentException
collection
- any Collectionjava.lang.IllegalArgumentException
- if collection is null or emptypublic static void containsNoNull(java.util.Collection<?> collection, java.lang.String message)
null
value (throws an IllegalArgumentException
if it does).collection
- collectionmessage
- the text message that would be pass to the exception thrown when c contains a null.java.lang.IllegalArgumentException
- if collection is null or contains any null elementspublic static <E> java.util.Set<E> checkForDuplicatesAndReturnSet(java.util.Collection<E> c, java.lang.String message)
IllegalArgumentException
if it does).
The implementation creates a Set
as an intermediate step or detecting duplicates and returns this Set because
it is sometimes useful to do so.c
- collectionmessage
- A message to emit in case of error, in addition to reporting the first duplicate value found.java.lang.IllegalArgumentException
- if a o == null
public static int validIndex(int index, int length)
index
- the query index.length
- the collection or array size.index
.public static int validIndex(int index, int length, java.lang.String errorMessage)
index
- the query index.length
- the collection or array size.errorMessage
- the error message to use in case of an exception is thrown.index
.public static void validateArg(boolean condition, java.lang.String msg)
public static void validateArg(boolean condition, java.util.function.Supplier<java.lang.String> msg)
public static void validate(boolean condition, java.lang.String msg)
IllegalStateException
if false. If msg is not a
String literal i.e. if it requires computation, use the Supplierpublic static void validate(boolean condition, java.util.function.Supplier<java.lang.String> msg)
IllegalStateException
if false.public static int optimumHashSize(int maxElements)
maxElements
- The maximum number of elements you expect the hash table
will need to holdpublic static boolean equalRange(byte[] left, int leftOffset, byte[] right, int rightOffset, int length)
left
- first array to compare.leftOffset
- first position of the first array to compare.right
- second array to compare.rightOffset
- first position of the second array to compare.length
- number of positions to compare.true
iff length
is 0 or all the bytes in both ranges are the same two-by-two.java.lang.IllegalArgumentException
- if left
or right
is null
orpublic static <T> T skimArray(T original, boolean[] remove)
T
- the array type.original
- the original array to splice.remove
- for each position in original
indicates whether it should be spliced away (true
),
or retained (false
)null
.java.lang.IllegalArgumentException
- if either original
or remove
is null
,
or remove length is different to {@code original}'s
, or original
is not in
fact an array.public static <T> T skimArray(T source, int sourceOffset, T dest, int destOffset, boolean[] remove, int removeOffset)
If the dest
array provide is not long enough a new one will be created and returned with the
same component type. All elements before destOffset
will be copied from the input to the
result array. If dest
is null
, a brand-new array large enough will be created where
the position preceding destOffset
will be left with the default value. The component type
Will match the one of the source
array.
T
- the array type.source
- the original array to splice.sourceOffset
- the first position to skim.dest
- the destination array.destOffset
- the first position where to copy the skimmed array values.remove
- for each position in original
indicates whether it should be spliced away (true
),
or retained (false
)removeOffset
- the first position in the remove index array to consider.null
.java.lang.IllegalArgumentException
- if either original
or remove
is null
,
or remove length is different to {@code original}'s
, or original
is not in
fact an array.public static <T> T skimArray(T source, int sourceOffset, T dest, int destOffset, boolean[] remove, int removeOffset, int length)
If the dest
array provide is not long enough a new one will be created and returned with the
same component type. All elements before destOffset
will be copied from the input to the
result array. If dest
is null
, a brand-new array large enough will be created where
the position preceding destOffset
will be left with the default value. The component type
Will match the one of the source
array.
T
- the array type.source
- the original array to splice.sourceOffset
- the first position to skim.dest
- the destination array.destOffset
- the first position where to copy the skimed array values.remove
- for each position in original
indicates whether it should be spliced away (true
),
or retained (false
)removeOffset
- the first position in the remove index array to consider.length
- the total number of position in source
to consider. Thus only the sourceOffset
to
sourceOffset + length - 1
region will be skimmed.null
.java.lang.IllegalArgumentException
- if either original
or remove
is null
,
or remove length is different to {@code original}'s
, or original
is not in
fact an array.public static void warnOnNonIlluminaReadGroups(htsjdk.samtools.SAMFileHeader readsHeader, org.apache.logging.log4j.Logger logger)
public static boolean xor(boolean x, boolean y)
x
- a booleany
- a booleanpublic static int lastIndexOf(byte[] reference, byte[] query)
reference
- the reference sequencequery
- the query sequencepublic static java.util.List<java.lang.Integer> listFromPrimitives(int[] ar)
ar
- - the array whose elements should be listifiedpublic static <T> java.util.Iterator<T> concatIterators(java.util.Iterator<? extends java.lang.Iterable<T>> iterator)
Iterator
s (all of the same type) into a single Iterator
.T
- the type of the iteratoriterator
- an Iterator
of Iterator
sIterator
over the underlying Iterator
spublic static <T> java.util.stream.Stream<T> stream(java.util.Enumeration<T> enumeration)
public static <T> java.util.stream.Stream<T> stream(java.lang.Iterable<T> iterable)
public static <T> java.util.stream.Stream<T> stream(java.util.Iterator<T> iterator)
public static <T> java.util.function.Function<T,T> identityFunction()
Function.identity()
the returned
function is also serializable.T
- the type of the input and output objects to the functionpublic static <F,T> java.util.Iterator<T> transformParallel(java.util.Iterator<F> fromIterator, java.util.function.Function<F,T> function, int numThreads)
Iterators.transform(Iterator, com.google.common.base.Function)
, but runs a fixed number
(numThreads
) of transformations in parallel, while maintaining ordering of the output iterator.
This is useful if the transformations are CPU intensive.public static <T> java.util.Set<T> getDuplicatedItems(java.util.Collection<T> objects)
public static java.lang.String getDateTimeForDisplay(java.time.ZonedDateTime dateTime)
dateTime
formatted as string for display.dateTime
- the date/time to be formatteddateTime
.public static void forceJVMLocaleToUSEnglish()
public static <T extends java.lang.Comparable<?>> T getMedianValue(java.util.List<T> values)
values
- List of sortable entries from which to select the medianpublic static java.util.List<java.lang.String> split(java.lang.String str, char delimiter)
String.split(String)
and String.split(String, 0)
,
but has been measured to be ~2x faster (see StringSplitSpeedUnitTest
for details).str
- the string to split.delimiter
- the delimiter used to split the string.List
of String
tokens.public static java.util.List<java.lang.String> split(java.lang.String str, java.lang.String delimiter)
String.split(String)
and String.split(String, 0)
,
but has been measured to be ~2x faster (see StringSplitSpeedUnitTest
for details).str
- the string to split.delimiter
- the delimiter used to split the string.List
of String
tokens.public static <T,U> java.util.Map<U,java.util.Set<T>> getReverseValueToListMap(java.util.Map<T,java.util.List<U>> somethingToListMap)
For example:
Input:T
- class of the key of the inputU
- class of the values in the list of the inputsomethingToListMap
- a map from a value to a list of values. Never null
null
public static java.lang.String formattedPercent(long x, long total)
x
- number of objects part of total that meet some criteriatotal
- count of all objects, including xpublic static java.lang.String formattedRatio(long num, long denom)
num
- number of observations in the numeratordenom
- number of observations in the denumeratorpublic static java.util.Set<java.lang.String> filterCollectionByExpressions(java.util.Collection<java.lang.String> sourceValues, java.util.Collection<java.lang.String> filterExpressions, boolean exactMatch)
sourceValues
- collection of strings from which to to selectfilterExpressions
- list of expressions to use for matchingexactMatch
- If true match filters exactly, otherwise use as both exact and regular expressionspublic static <T> T runInParallel(int threads, java.util.function.Supplier<T> supplier)
This call will wait until such task is completed.
T
- the type of the return.threads
- number of threads requested. 0 would result in using a system default,
usually the host number of CPU cores.supplier
- the task to run.null
.GATKException
- if the run was interrupted or resulted in a checked exception. Unchecked exceptions and Error
progragate as they are.