text:
package owltools.sim2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.math.MathException;
import org.apache.commons.math3.stat.descriptive.StatisticalSummaryValues;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.OWLReasoner;

import owltools.sim2.FastOwlSim.ClassCount;
import owltools.sim2.SimpleOwlSim.Direction;
import owltools.sim2.SimpleOwlSim.Metric;
import owltools.sim2.SimpleOwlSim.SimConfigurationProperty;
import owltools.sim2.io.SimResultRenderer.AttributesSimScores;
import owltools.sim2.scores.AttributePairScores;
import owltools.sim2.scores.ElementPairScores;

/**
 *
 *
Semantic Similarity

 *
 *
Basic Concepts

 *
 * This class allows the comparison of one or more entities (modeled as
 * OWLIndividuals) to another set, based on the attributes they possess (modeled
 * as OWLClasses).
 *
 * Entities may be genes, genotypes, diseases, organisms, ...
 *
 * Attributes may be functions, phenotypes, ...
 *
 * Usage is generic beyond biology. The entities compared could be pizzas,
 * and the attrubutes could be toppings.
 *
 * Similarity scores are generated for any pair of entities based on
 * shared attributes. An ontology is used so that we can compare based
 * on shared inferred attributes as well.
 *
 *
Pre-processing (optional)

 *
 * Each individual is assumed to be an instance of the class used in the
 * comparison. This may not be the natural representation, so some
 * pre-processing may be required.
 *
 * For example, for representing the relationships between gene individuals and
 * tissues, the natural representation may be
 *
 *

 * Individual: g1
 *   Types: gene, expressed_in some hand
 * Individual: g2
 *   Types: gene, expressed_in some toe
 *

 *
 * Here the only *named* class commonly instantiated between g1 and g2 is
 * 'gene'. OWLReasoners do not return anonymous class expressions.
 *
 * The input ontology should be pre-processed to pre-generate named classes such
 * as
 *
 *

 * "X gene" EquivalentTo expressed_in some X
 *

 *
 * If we assume a property chain
 *
 *

 * expressed_in o part_of -> expressed_in
 *

 *
 * And a typical partonomy
 *
 * Then g1 and g2 will both instantiate "expressed_in some autopod"
 *
 * See the "--mpi" command in OWLTools for building these views
 *
 * Note that for some applications, it may be best to model entities such as
 * genes and diseases as classes. However, to compare these effectively, the
 * representation should be translated to individuals.
 *
 *
Reasoning

 *
 * Any reasoner can be plugged in but for most datasets we use Elk 0.4.x, which
 * can scale well.
 *
 * A reasoner performs operations over an ontology consisting of OWLIndividuals and OWLClasses.
 * We typically use i, j for variable names for instances, and a, b, c, d as variable names
 * for classes.
 *
 * The following operations are used:
 *
 *

 *
 Type(i) : {@link OWLReasoner#getTypes(OWLNamedIndividual, boolean)}
 *  - to find all of the attributes possessed
 * by an entity - may be direct or indirect. The inverse operation is Inst(c)
 *
 Sub(c) :  {@link OWLReasoner#getSuperClasses(OWLClassExpression, boolean)}
 *  - to find all the ancestors (subsumers) of an attribute - direct and indirect.
 * The inverse operation is SubBy(c)
 *
 Eq(c) : {@link OWLReasoner#getEquivalentClasses(OWLClassExpression)} - find all all equivalent attributes/
 * Note that OWLSim is cycle-safe - cycles over SubClassOf are permitted, these are the same as an equivalence axiom between the classes
 *

 *
 * The latter two are combined to yield the reflexive common subsumers list -
 * see {@link #getNamedReflexiveSubsumers(OWLClass)}. We write this here as
 * RSub(c). i.e.
 *

 * RSub(c) = Sub(c) ∪ Eq(c)
 *

 *
 * The use of an OWLReasoner could be replaced with a basic graph traversal algorithm,
 * but it's useful to use a reasoner here, as the ontology may not have been pre-reasoned
 *
 *
 *
Similarity metrics

 *
 * See individual methods for details. Generally there are two kinds of
 * comparison
 *
 *

 *
Between two classes (aka attributes, which are used to describe individuals)
 *
Between two individuals (aka entities, e.g. between two genes, two organisms, or a
 * disease vs genotype)
 *

 *
 * The former can be used to calculate the latter.
 *
 *
Common Subsumers and Lowest Common Subsumers

 *
 * class-class comparisons are based on inferred common subsumers.
 *

 * CS(c,d) = RSub(c) ∪ RSub(d)
 *

 *
 * The Lowest Common Subsumer is the set of common subsumers that are not
 * redundant with other common subsumers:
 *
 *

 * LCS(c,d) = { a : a ∈ CS(c,d), not [ &E; a' : a' ∈ CS(c,d), c' in Sub(c) ] }
 *

 *
 * This is implemented by {@link #getLowestCommonSubsumerWithIC(OWLClass, OWLClass)}
 *
 *
Information Content

 *
 * The information content (IC) of an class is a measure of how rare the class is
 *
 *

 *  IC(c) = -log2( Pr(c) )
 *

 *
 *  Where the probability Pr of a class c is the frequency of that class (number of
 *  instances that instantiate it) divided by the number of instances in the corpus:
 *
 *

 *  Pr(c) = | Inst(c) | / | Inst(RootClass) |
 *

 *
 *  Here the semantics of Inst(c) are provided by
 *   {@link OWLReasoner#getInstances(OWLClassExpression, boolean)}
 *
 *
Similarity between classes

 *
 *  One measure of similarity between two classes is the IC of the lowest common
 *  subsumer. See {@link #getLowestCommonSubsumerWithIC(OWLClass, OWLClass)}
 *
 *
Similarity Measures between Entities (Individuals)

 *
 *  There are a variety of methods for comparing two entities based on the
 *  attributes they share.
 *
 *  Some methods take the two best-mtaching attributes, others compute some kind of
 *  sum of similarity over the ensemble of attributes.
 *
 *  An example of a best-attribute method is the maximum information content
 *  of the lowest common subsumers. This is implemented by
 *  {@link #getSimilarityMaxIC(OWLNamedIndividual, OWLNamedIndividual)}. This
 *  is the same method as described in Lord et al 2003.
 *
 *  Other methods
 *

 *
 {@link #getElementJaccardSimilarity(OWLNamedIndividual, OWLNamedIndividual)}
 *
 {@link #getElementGraphInformationContentSimilarity(OWLNamedIndividual, OWLNamedIndividual)}
 *

 *

 *
 * @author cjm
 *
 */
public interface OwlSim {

	//TODO: replace with enum
	public String[] metrics = {"bmaAsymIC","bmaSymIC","bmaInverseAsymIC", "combinedScore", "simJ", "simGIC","maxIC"};

	public enum Stat {
		MEAN,MIN,MAX,N,SUM
	}

	/**
	 * @return ontology used to store both classes and individuals
	 */
	public OWLOntology getSourceOntology();

	/**
	 * @return reasoner initialized with source ontology
	 */
	public OWLReasoner getReasoner();

	/**
	 * @param a
	 * @return Sub(c)
	 */
	public Set<Node<OWLClass>> getNamedSubsumers(OWLClass a);

	/**
	 *
	 * @param i
	 * @return Type(i) - nodes for all classes that a instantiates - direct and inferred
	 */
	public Set<Node<OWLClass>> getInferredAttributes(
			OWLNamedIndividual i);

	/**
	 *
	 * @param a
	 * @return anc(a)
	 */
	public Set<Node<OWLClass>> getNamedReflexiveSubsumers(
			OWLClass a);

	/**
	 *
	 *

	 *   CS(a,b) = { c : c ∈ RSub(a), c ∈ RSub(b) }
	 *

	 *
	 * NOT CACHED.
	 * Always returns a copy of the CS list
	 *
	 * @param a
	 * @param b
	 * @return nodes
	 * @throws UnknownOWLClassException
	 */
	public Set<Node<OWLClass>> getNamedCommonSubsumers(
			OWLClass a, OWLClass b) throws UnknownOWLClassException;

	/**
	 *

	 *  | CS(i,j) | = | { c : c ∈ Type(i), c ∈ Type(j) } |
	 *

	 * @param a
	 * @param b
	 * @return | CS(a,b) |
	 * @throws UnknownOWLClassException
	 */
	public int getNamedCommonSubsumersCount(OWLClass a,
			OWLClass b) throws UnknownOWLClassException;

	/**
	 *

	 *   CS(i,j) = { c : c ∈ Type(i), c ∈ Type(j) }
	 *

	 *
	 * @param a
	 * @param b
	 * @return CS(i,j)
	 * @throws UnknownOWLClassException
	 */
	public Set<Node<OWLClass>> getNamedCommonSubsumers(
			OWLNamedIndividual a, OWLNamedIndividual b) throws UnknownOWLClassException;

	/**
	 *

	 *   CSredundant(a,b) = { c : c ∈ CS(a,b), &E; c' : c' ∈ CS(a,b), c' &in Sub(c) }
	 *   LCS(a,b) = CS(a,b) - CSredundant
	 *

	 *
	 * @param a
	 * @param b
	 * @return LCS(a,b)
	 * @throws UnknownOWLClassException
	 */
	public Set<Node<OWLClass>> getNamedLowestCommonSubsumers(
			OWLClass a, OWLClass b) throws UnknownOWLClassException;

	/**
	 * This method provides a generic wrapper onto other attribute-based similarity
	 * methods
	 *
	 * Compares two classes (attributes) according to the specified metric
	 *
	 * @param a
	 * @param b
	 * @param metric
	 * @return SimM(a,b)
	 * @throws UnknownOWLClassException
	 */
	public double getAttributeSimilarity(OWLClass a,
			OWLClass b, Metric metric) throws UnknownOWLClassException;

	/**
	 *

	 * SimJ(a,b) = | anc(a) ∩ anc(b) | / | anc(a) ∪ anc(b) |
	 *

	 *
	 * @param a
	 * @param b
	 * @return SimJ of two attribute classes
	 * @throws UnknownOWLClassException
	 */
	public double getAttributeJaccardSimilarity(OWLClass a,
			OWLClass b) throws UnknownOWLClassException;

	/**
	 *

	 * SimJ(i,j) = | Type(i) ∩ Type(j) | / | Type(i) ∪ Type(j) |
	 *

	 *
	 * Here Type(i) is the set of all (direct and indirect) inferred types
	 * for an individual.
	 *
	 * @param i
	 * @param j
	 * @return SimJ
	 * @throws UnknownOWLClassException
	 */
	public double getElementJaccardSimilarity(OWLNamedIndividual i,
			OWLNamedIndividual j) throws UnknownOWLClassException;

	/**
	 *

	 * SimJ(i,j) = | Type(i) ∩ Type(j) | / | Type(j) |
	 *

	 *
	 *
	 * @param i
	 * @param j
	 * @return SimJ(i,j)
	 * @throws UnknownOWLClassException
	 */
	public double getAsymmetricElementJaccardSimilarity(OWLNamedIndividual i,
			OWLNamedIndividual j) throws UnknownOWLClassException;

	/**
	 *

	 * SimJASym(c,d) = | anc(c) ∩ anc(d) | / | anc(d)  |
	 *

	 *
	 * If c is subsumed by d then the score is 1. i.e.
	 *

	 * c ∈ Sub(d) →  SimJASym(c,d) = 1
	 *

	 *
	 * @param c
	 * @param d
	 * @return Asymmetric SimJ of two attribute classes
	 * @throws UnknownOWLClassException
	 */
	public double getAsymmetricAttributeJaccardSimilarity(
			OWLClass c, OWLClass d) throws UnknownOWLClassException;

	/**
	 * sums of IC of the intersection attributes/ sum of IC of union attributes.
	 *
	 *
	 * @param i
	 * @param j
	 * @return Σt ∈ Type(i) ∩ Type(j) IC(t) / Σt ∈ Type(i) ∪ Type(j) IC(t)
	 * @throws UnknownOWLClassException
	 */
	public double getElementGraphInformationContentSimilarity(
			OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException;

	/**
	 * sums of IC of the intersection attributes/ sum of IC of union attributes.
	 *
	 *
	 *
	 * @param c
	 * @param d
	 * @return Σt ∈ RSub(c) ∩ RSub(d) IC(t) / Σt ∈ RSub(c) ∪ RSub(d) IC(t)
	 * @throws UnknownOWLClassException
	 */
	public double getAttributeGraphInformationContentSimilarity(
			OWLClass c, OWLClass d) throws UnknownOWLClassException;

	/**
	 * Find the inferred attribute shared by both i and j that has highest IC. If
	 * there is a tie then the resulting structure will have multiple classes.
	 *
	 *

	 * MaxIC(i,j) = max { IC(c) : c ∈ LCS(i,j) }
	 * CMaxIC(i,j) =  { c : c ∈ LCS(i,j), IC(c) = MaxIC(i,j) }
	 *

	 *
	 * As a convenience, this method also returns the LCS class as well as the IC
	 *
	 * This is the same metric used by Lord et al in
	 * Investigating semantic similarity measures  across the Gene Ontology: the relationship between sequence and annotation.
	 *
	 * @param i
	 * @param j
	 * @return <MaxIC(i,j) CMaxIC(i,j)
	 * @throws UnknownOWLClassException
	 */
	public ScoreAttributeSetPair getSimilarityMaxIC(
			OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException;

	/**
	 * @param i
	 * @param j
	 * @return BMAAsym(i,j)
	 */
	@Deprecated
	public ScoreAttributeSetPair getSimilarityBestMatchAverageAsym(
			OWLNamedIndividual i, OWLNamedIndividual j);

	/**
	 * @param c
	 * @param d
	 * @return scores
	 * @throws UnknownOWLClassException
	 */
	@Deprecated
	public AttributePairScores getPairwiseSimilarity(OWLClass c, OWLClass d) throws UnknownOWLClassException;

	/**
	 * See: Pesquita et al
	 *
	 *

	 * BMAM(i,j) = avg { s : c ∈ Attr(i), max { s : d ∈ Attr(j), s = M(c,d) } }
	 *

	 *
	 *
	 * @param i
	 * @param j
	 * @param metric
	 * @return pair
	 */
	public ScoreAttributeSetPair getSimilarityBestMatchAverageAsym(
			OWLNamedIndividual i, OWLNamedIndividual j, Metric metric);

	/**
	 * @param i
	 * @param j
	 * @param metric
	 * @param dir
	 * @return scores
	 */
	@Deprecated
	public ScoreAttributeSetPair getSimilarityBestMatchAverage(
			OWLNamedIndividual i, OWLNamedIndividual j, Metric metric,
			Direction dir);

	// Possible optimizations:

	/**
	 * Equivalent to {@link #getAttributeJaccardSimilarity(OWLClass, OWLClass)} * 100
	 * @param a
	 * @param b
	 * @return simj*100
	 * @throws UnknownOWLClassException
	 */
	public int getAttributeJaccardSimilarityAsPercent(OWLClass a,
			OWLClass b) throws UnknownOWLClassException;

	/**
	 * Equivalent to {@link #getElementJaccardSimilarity(OWLNamedIndividual, OWLNamedIndividual)} * 100
	 * @param i
	 * @param j
	 * @return simj*100
	 * @throws UnknownOWLClassException
	 */
	public int getElementJaccardSimilarityAsPercent(OWLNamedIndividual i,
			OWLNamedIndividual j) throws UnknownOWLClassException;

	/**
	 * Equivalent to {@link #getAsymmetricAttributeJaccardSimilarity(OWLClass, OWLClass)} * 100
	 * @param a
	 * @param b
	 * @return asimj*100
	 * @throws UnknownOWLClassException
	 */
	public int getAsymmetricAttributeJaccardSimilarityAsPercent(OWLClass a,
			OWLClass b) throws UnknownOWLClassException;

	/**
	 * Equivalent to {@link #getAsymmetricElementJaccardSimilarity(OWLNamedIndividual, OWLNamedIndividual)} * 100
	 * @param i
	 * @param j
	 * @return asimj*100
	 * @throws UnknownOWLClassException
	 */
	public int getAsymmetricElementJaccardSimilarityAsPercent(OWLNamedIndividual i,
			OWLNamedIndividual j) throws UnknownOWLClassException;

	/**
	 * returns all attribute classes - i.e. the classes used to annotate the
	 * elements (genes, diseases, etc) being studied, either directly or indirectly
	 *
	 * defaults to all classes in source ontology signature
	 *
	 * @return set of classes
	 */
	public Set<OWLClass> getAllAttributeClasses();

	/**
	 * This must be called prior to calculation of any similarity metrics.
	 *
	 * It creates a set of attribute classes (the subset of classes that
	 * have inferred or direct individuals) and the set of elements (individuals),
	 * together with any internal indexing
	 *
	 * assumes that the ontology contains both attributes (TBox) and elements +
	 * associations (ABox)
	 *
	 * @throws UnknownOWLClassException
	 */
	public void createElementAttributeMapFromOntology() throws UnknownOWLClassException;

	/**
	 * For implementations that use a cache, this performs an all by all comparison
	 * of all attributes and caches the results.
	 *
	 * @throws UnknownOWLClassException
	 */
	public void precomputeAttributeAllByAll()  throws UnknownOWLClassException;

	/**
	 * Gets all attribute classes used to describe individual element e.
	 *
	 * Does *not* include inferred classes
	 * @param e
	 * @return Type(e,indirect)
	 * @throws UnknownOWLClassException
	 */
	public Set<OWLClass> getAttributesForElement(OWLNamedIndividual e) throws UnknownOWLClassException;

	/**
	 * inferred
	 *
	 * @param c
	 * @return set of entities
	 * @throws UnknownOWLClassException
	 */
	public Set<OWLNamedIndividual> getElementsForAttribute(OWLClass c) throws UnknownOWLClassException;

	/**
	 * |{e : e ∈ Inst(c)}|
	 *
	 * @param c
	 * @return count
	 * @throws UnknownOWLClassException
	 */
	public int getNumElementsForAttribute(OWLClass c) throws UnknownOWLClassException;

	/**
	 * @return E = {e : e ∈ Inst(Τ)}
	 */
	public Set<OWLNamedIndividual> getAllElements();

	/**
	 * The number of entities in the entire set being analyzed.
	 *
	 * Typically this is
	 * |{e : e ∈ Inst(Τ)}|
	 * But this can be overridden (for the scenario where the ABox is a subset
	 * of the known universe)
	 *
	 * @return corpus size
	 */
	public int getCorpusSize();

	/**
	 * Sets the number of entities in domain. Can be used to override
	 * the default amount, which is the number of elements
	 *
	 * @param size
	 */
	public void setCorpusSize(int size);

	// IC = 0.0 : 100% (1/1)
	// IC = 1.0 : 50% (1/2)
	// IC = 2.0 : 25% (1/4)
	// IC = 3.0 : 12.5% (1/8)
	/**
	 * IC = -(log {@link #getNumElementsForAttribute(OWLClass)} / corpus size) / log(2)
	 * @param c
	 * @return Information Content value for a given class
	 * @throws UnknownOWLClassException
	 */
	public Double getInformationContentForAttribute(OWLClass c) throws UnknownOWLClassException;

	/**
	 * @return -Σi[ (P(xi)log2P(xi)]
	 * @throws UnknownOWLClassException
	 */
	public Double getEntropy() throws UnknownOWLClassException;

	/**
	 * @param cset
	 * @return -Σi[ (P(xi)log2P(xi)] for xi ∈ cset
	 * @throws UnknownOWLClassException
	 */
	public Double getEntropy(Set<OWLClass> cset) throws UnknownOWLClassException;

	/**
	 * @param c - query class
	 * @param ds - target class set
	 * @return list of scores
	 * @throws UnknownOWLClassException
	 */
	public List<AttributesSimScores> compareAllAttributes(OWLClass c, Set<OWLClass> ds) throws UnknownOWLClassException;

	/**
	 *
Find all similar matches to a pseudo-individual with a set of attributes
	 * when compared to loaded individuals using {@link getGroupwiseSimilarity}
	 * with default cutoffs.

	 * {@code minSimJPct = getPropertyAsDouble({@link SimConfigurationProperty.minimumSimJ}, 0.05) * 100) }

	 * {@code minMaxIC = getPropertyAsDouble({@link SimConfigurationProperty.minimumMaxIC}, 2.5); }
	 * @param atts
	 * @param targetIdSpace
	 * @return sorted scores
	 * @throws Exception
	 */
	public List<ElementPairScores> findMatches(Set<OWLClass> atts, String targetIdSpace) throws UnknownOWLClassException, Exception;

	/**
	 * Find all similar matches to a pseudo-individual with a set of attributes
	 * when compared to loaded individuals using {@link getGroupwiseSimilarity}
	 * with {@code minSimJPct} and {@code minMaxIC} cutoffs.
	 * @param atts
	 * @param targetIdSpace
	 * @param minSimJPct
	 * @param minMaxIC
	 * @return
	 * @throws Exception
	 */
	public List<ElementPairScores> findMatches(Set<OWLClass> atts, String targetIdSpace, double minSimJPct, double minMaxIC) throws Exception;

	/**
	 *
Compare a named individual {@code i} to itself.
	 * For efficiency, the phenoDigm score should be calculated in the calling
	 * function.

	 *
This will use no cutoff (-1,-1).

	 * @param atts
	 * @param targetIdSpace
	 * @return sorted scores
	 * @throws Exception
	 */
	public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i) throws Exception;

	/**
	 * Compare two named individuals {@code (i,j)}.
	 *
This will default to using the following cutoffs:

	 * {@code minSimJPct = getPropertyAsDouble({@link SimConfigurationProperty.minimumSimJ}, 0.05) * 100) }

	 * {@code minMaxIC = getPropertyAsDouble({@link SimConfigurationProperty.minimumMaxIC}, 2.5); }
   *

	 *
	 * @param i
	 * @param j
	 * @return scores
	 * @throws Exception
	 */
	public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i,
			OWLNamedIndividual j) throws Exception;

	/**
	 *
Compare two named individuals {@code i}, filtering on
	 * {@code minSimJ} and {@code minMaxIC}

	 *
While an initial {@code combinedScore} is populated in the returned
	 * {@link ElementPairScores} object, it should be properly set in
	 * the calling function with {@link calculateCombinedScore} and
	 * {@code i.maxIC and i.bmaAsymIC}

	 * @param atts
	 * @param targetIdSpace
	 * @return sorted scores
	 * @throws Exception
	 */
	public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i, OWLNamedIndividual j, double minSimJ, double minMaxIC) throws Exception;

	/**
	 *
Compare a set of attributes against the named individual {@code i}.
	 * For efficiency, the phenoDigm score should be calculated in the calling
	 * function.

	 *
This will default to using the following cutoffs:

	 * {@code minSimJPct = getPropertyAsDouble({@link SimConfigurationProperty.minimumSimJ}, 0.05) * 100) }

	 * {@code minMaxIC = getPropertyAsDouble({@link SimConfigurationProperty.minimumMaxIC}, 2.5); }
   *

	 * @param atts
	 * @param targetIdSpace
	 * @return sorted scores
	 * @throws Exception
	 */
	public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> atts, OWLNamedIndividual j) throws Exception;

	/**
	 * Compare a set of attributes against the named individual {@code i}.
	 * For efficiency, the phenoDigm score should be calculated in the calling
	 * function.
	 *
If no cutoffs are desired, set {@code minSimJPct} and {@code minMaxIC} = -1

   *
	 * @param atts
	 * @param targetIdSpace
	 * @return sorted scores
	 * @throws Exception
	 */
	public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> atts, OWLNamedIndividual j, double minSimJPct, double minMaxIC) throws Exception;

	public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> objAs, Set<OWLClass> objBs) throws Exception;

	public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> objAs, Set<OWLClass> objBs, double minSimJPct, double minMaxIC) throws Exception;

	/**
	 * @param i
	 * @param targetIdSpace
	 * @return sorted scores
	 * @throws Exception
	 */
	public List<ElementPairScores> findMatches(OWLNamedIndividual i, String targetIdSpace) throws Exception;

	/**
	 * @param i
	 * @param targetIdSpace
	 * @return sorted scores
	 * @throws Exception
	 */
	public List<ElementPairScores> findMatches(OWLNamedIndividual i, String targetIdSpace, double minSimJPct, double minMaxIC) throws Exception;

	public List<ElementPairScores> findMatchesWithin(OWLNamedIndividual i, Set<OWLNamedIndividual> candidateTargets) throws Exception;

	/**
	 * Resnick similarity measure, together with all LCSs (MICAs) that
	 * have this as IC
	 *
	 * @param c
	 * @param d
	 * @return LCS together with IC(LCS)
	 * @throws UnknownOWLClassException
	 */
	public ScoreAttributeSetPair getLowestCommonSubsumerWithIC(OWLClass c, OWLClass d)
			throws UnknownOWLClassException;

	public ScoreAttributeSetPair getLowestCommonSubsumerWithLinScore(OWLClass c, OWLClass d)
			throws UnknownOWLClassException;

	/**
	 * @param i
	 * @param j
	 * @param thresh
	 * @return LCS together with IC(LCS)
	 * @throws UnknownOWLClassException
	 */
	public ScoreAttributeSetPair getLowestCommonSubsumerWithIC(OWLClass i, OWLClass j, Double thresh)
			throws UnknownOWLClassException;

	/**
	 * Experimental: save internal state of object
	 * @param fileName
	 * @throws IOException
	 */
	public void saveState(String fileName) throws IOException;

	/**
	 * Saves the contents of the LCS-IC cache
	 *
	 * Assumes that this has already been filled by comparing all classes by all classes.
	 *
	 *
	 * @param fileName
	 * @throws IOException
	 */
	public void saveLCSCache(String fileName) throws IOException;

	/**
	 * As {@link #saveLCSCache(String)}, but do not write a line for any LCS
	 * whose IC falls below the threshold.
	 *
	 * Use this if you expect the size of the cache to be large. If not set,
	 * the number of lines will be |A| x |A|
	 *
	 * @param fileName
	 * @param thresholdIC
	 * @throws IOException
	 */
	public void saveLCSCache(String fileName, Double thresholdIC) throws IOException;

	/**
	 * Loads a pregenerated IC cache.
	 *
	 * May or may not set IC values of LCS classes - implementation dependent
	 *
	 * @param fileName
	 * @throws IOException
	 */
	public void loadLCSCache(String fileName) throws IOException;

	/**
	 * Generates an ontology containing annotation assertion axioms connecting
	 * a class to an IC value.
	 *
	 * Can be used to persist class to IC mappings
	 *
	 * @return ontology containing annotation assertions
	 * @throws OWLOntologyCreationException
	 * @throws UnknownOWLClassException
	 */
	public OWLOntology cacheInformationContentInOntology() throws OWLOntologyCreationException, UnknownOWLClassException;

	/**
	 * Populate the IC cache from an ontology of class-IC mappings.
	 *
	 * Can be used to restore an IC cache from a previously persisted state.
	 *
	 *
	 * @param o
	 */
	public void setInformationContentFromOntology(OWLOntology o);

	/**
	 *  Ff set, the cache is written to but not read from.
	 *
	 *  Set this is you are building a cached to be persisted.
	 *
	 * @param b
	 */
	public void setNoLookupForLCSCache(boolean b);

	/**
	 * A pair consisting of a set of equal-scoring attributes, and a score
	 *
	 * @author cjm
	 *
	 */
	public class ScoreAttributeSetPair implements Comparable<ScoreAttributeSetPair> {
		/**
		 * Score shared by all attributes in attribute set
		 */
		public double score;

		/**
		 * Set of attributes that have the score
		 */
		public Set<OWLClass> attributeClassSet = new HashSet<OWLClass>(); // all
		// attributes
		// with
		// this
		// score

		/**
		 * @param score
		 * @param ac
		 */
		public ScoreAttributeSetPair(double score, OWLClass ac) {
			super();
			this.score = score;
			if (ac != null) attributeClassSet.add(ac);
		}

		/**
		 * @param score
		 * @param acs
		 */
		public ScoreAttributeSetPair(double score, Set<OWLClass> acs) {
			super();
			this.score = score;
			this.attributeClassSet = acs;
		}

		/**
		 * Combined/Summary score
		 *
		 * May vary depending on the method used
		 *
		 * @param score
		 */
		public ScoreAttributeSetPair(double score) {
			super();
			this.score = score;
		}

		/**
		 * Adds am attribute to set (first creating empty set if not already present)
		 * @param ac
		 */
		public void addAttributeClass(OWLClass ac) {
			if (attributeClassSet == null)
				attributeClassSet = new HashSet<OWLClass>();
			this.attributeClassSet.add(ac);
		}

		/**
		 * Setter
		 * @param acs
		 */
		public void setAttributeClassSet(Set<OWLClass> acs) {
			attributeClassSet = new HashSet<OWLClass>();
			for (OWLClass ac : acs)
				attributeClassSet.add(ac);
		}

		@Override
		public int compareTo(ScoreAttributeSetPair p2) {
			return 0 - Double.compare(score, p2.score);
		}

		/**
		 * @return an arbitrary member of the attribute class set
		 */
		@Deprecated
		public OWLClass getArbitraryAttributeClass() {
			if (attributeClassSet == null)
				return null;
			return this.attributeClassSet.iterator().next();
		}

	}

	/**
	 *
	 * if set, the cache is neither read nor written to.
	 *
	 * Set this if you expect to do each att comparison once,
	 * and you do not wish to persist the cache when done.
	 * Contrast with {@link OwlSim#setNoLookupForLCSCache(boolean)}
	 * @param isDisableLCSCache
	 */
	public void setDisableLCSCache(boolean isDisableLCSCache);

	/**
	 * call when owlsim object is no longer required
	 */
	public void dispose();

	/**
	 * @param simProperties
	 */
	public void setSimProperties(Properties simProperties);
	/**
	 * @return properties
	 */
	public Properties getSimProperties();

	/**
	 * @return stats
	 */
	SimStats getSimStats();

	/**
	 * Writes timing information using log4j. For benchmarking
	 */
	public void showTimings();

	/**
	 * @return elementToAttributesMap
	 */
	public Map<OWLNamedIndividual, Set<OWLClass>> getElementToAttributesMap();
	// enrichment

	/**
	 * @return current configuration
	 */
	public EnrichmentConfig getEnrichmentConfig();

	/**
	 * @param enrichmentConfig
	 */
	public void setEnrichmentConfig(EnrichmentConfig enrichmentConfig);

	/**
	 * For every c ∈ sample set, test c against all classes ∈ enriched class set.
	 *
	 * Uses {@link #calculatePairwiseEnrichment(OWLClass, OWLClass, OWLClass)}}
	 *
	 * @param populationClass
	 * @param pc1
	 *          - sample set root class
	 * @param pc2
	 *          - enriched set root class
	 * @return enrichment results
	 * @throws MathException
	 * @throws UnknownOWLClassException
	 */
	public List<EnrichmentResult> calculateAllByAllEnrichment(
			OWLClass populationClass, OWLClass pc1, OWLClass pc2)
					throws MathException, UnknownOWLClassException;

	/**
	 * @return
	 * @throws MathException
	 * @throws UnknownOWLClassException
	 */
	public List<EnrichmentResult> calculateAllByAllEnrichment()
	throws MathException, UnknownOWLClassException;

	/**
	 *
	 * Uses {@link #calculatePairwiseEnrichment(OWLClass, OWLClass, OWLClass)}}
	 *
	 * @param populationClass
	 * @param sampleSetClass
	 * @return enrichment results
	 * @throws MathException
	 * @throws UnknownOWLClassException
	 */
	public List<EnrichmentResult> calculateEnrichment(OWLClass populationClass,
			OWLClass sampleSetClass) throws MathException, UnknownOWLClassException;

	/**
	 * Pairwise enrichment test
	 *
	 * @param populationClass
	 * @param sampleSetClass
	 * @param enrichedClass
	 * @return enrichment result
	 * @throws MathException
	 * @throws UnknownOWLClassException
	 */
	public EnrichmentResult calculatePairwiseEnrichment(OWLClass populationClass,
			OWLClass sampleSetClass, OWLClass enrichedClass) throws MathException, UnknownOWLClassException;

	/**
	 * @param c
	 * @param d
	 * @return P(c|d) = P(c ∩ d)|p(d)
	 * @throws UnknownOWLClassException
	 */
	public abstract double getConditionalProbability(OWLClass c, OWLClass d) throws UnknownOWLClassException;

	/**
	 * This will compute the individual summary statistics over the
	 * set of anntoated classes to an individual i.
	 * @param i
	 * @return
	 * @throws UnknownOWLClassException
	 */
	public SummaryStatistics computeIndividualStats(OWLNamedIndividual i)
			throws UnknownOWLClassException;

	/**
	 * This function will compute the IC-based summary statistics over the set of
	 * individuals for direct annotations.  It will generate a statistical
	 * summary over each individual, as well as over the whole set.
	 * @throws UnknownOWLClassException
	 */
	public void computeSystemStats() throws UnknownOWLClassException;

	public StatisticalSummaryValues getSystemStats();

	/**
	 * Fetch the pre-computed summary values
	 * @return {@link SummaryStatistics}
	 */
	public StatsPerIndividual getSummaryStatistics();

	public SummaryStatistics getSimStatistics(String stat);

	void calculateMetricStats(Set<OWLNamedIndividual> iset,
			Set<OWLNamedIndividual> jset) throws Exception;

	public HashMap<String,SummaryStatistics> getMetricStats(Stat stat);

	public double calculateOverallAnnotationSufficiencyForIndividual(OWLNamedIndividual i) throws UnknownOWLClassException;

	public double calculateOverallAnnotationSufficiencyForAttributeSet(Set<OWLClass> atts) throws UnknownOWLClassException;

	public void computeSystemStatsForSubgraph(OWLClass c) throws UnknownOWLClassException;

	public class StatsPerIndividual {
		//TODO: make top-level class
		//TODO: getters and setters
		public SummaryStatistics mean;
		public SummaryStatistics min;
		public SummaryStatistics max;
		public SummaryStatistics n;
		public SummaryStatistics sum;
		public StatisticalSummaryValues aggregate;

		public StatsPerIndividual() {
			this.mean = new SummaryStatistics();
			this.min = new SummaryStatistics();
			this.max = new SummaryStatistics();
			this.n = new SummaryStatistics();
			this.sum = new SummaryStatistics();
		}

		public String toString() {
			String s = "";
			s+="individuals: "+n.getN()+"\n";
			s+="mean(n/indiv): "+String.format("%1$.5f", n.getMean())+"\n";
			s+="mean(meanIC): "+String.format("%1$.5f", mean.getMean())+"\n";
			s+="mean(maxIC): "+String.format("%1$.5f", max.getMean())+"\n";
			s+="max(maxIC): "+String.format("%1$.5f", max.getMax())+"\n";
			s+="mean(sumIC): "+String.format("%1$.5f", sum.getMean())+"\n";
			return s;
		}
	}

	/**
	 * {@link StatsPerIndividual} summary statistic calculations using {@link OWLClass} c as the root node
	 * @param c {@link OWLClass}
	 * @return {@link StatsPerIndividual}
	 */
	public StatsPerIndividual getSummaryStatistics(OWLClass c);

	public double calculateSubgraphAnnotationSufficiencyForAttributeSet(
			Set<OWLClass> atts, OWLClass c) throws UnknownOWLClassException;

	public SummaryStatistics computeAttributeSetSimilarityStatsForSubgraph(
			Set<OWLClass> atts, OWLClass n);

	public SummaryStatistics computeAttributeSetSimilarityStats(Set<OWLClass> goodAtts);

	public void calculateCombinedScore(ElementPairScores eps, double maxIC,
			double bmaAsymIC);

	public OwlSimMetadata getMetadata();

	public String getShortId(OWLClass c);

	public Double[][] computeTFIDFMatrix(int[][] subsetMatrix, int numIndividualsInSubset, int[][] backgroundMatrix, int numIndividualsInBackground ) throws UnknownOWLClassException ;

	public List<ClassCount> getCoannotatedClassesForAttribute(OWLClass c, int numIndividualsInBackground) throws Exception ;
	public List<ClassCount> getCoannotatedClassesForAttribute(OWLClass c) throws Exception;
	public List<ClassCount> getCoannotatedClassesForAttribute(OWLClass c, Double cutoff, int numIndividualsInBackground) throws Exception ;

	public List<ClassCount> getCoAnnotatedClassesForIndividual(OWLNamedIndividual i) throws Exception ;
	public List<ClassCount> getCoAnnotatedClassesForIndividual(OWLNamedIndividual i, int matchCutoff) throws Exception ;

	public List<ClassCount> getCoAnnotatedClassesForAttributes(Set<OWLClass> atts) throws Exception ;
	public List<ClassCount> getCoAnnotatedClassesForAttributes(Set<OWLClass> atts, int matchCutoff) throws Exception ;

	public List<ClassCount> getCoAnnotatedClassesForMatches(List<ElementPairScores> matches, Set<OWLClass> atts) throws Exception ;

	public int[][] getSubsetCoannotationMatrix(Set<OWLNamedIndividual> individualSubset) throws Exception ;

	public void populateFullCoannotationMatrix() throws Exception ;

	public int[][] convertCountMatrixToFrequency(int[][] matrix, int normalizationFactor) ;

	public int[][] initCoannotationMatrix(int[][] coaMatrix) ;

	public void calculateCombinedScores(List<ElementPairScores> scoreSets, double maxIC, double bmaAsymIC);

}


text:
{{ site.title }}

All my work (2012-2020) is licensed under cc by 4.0

About | Contact | Privacy policy

RSS Feed | Sitemap

          {% if site.github_username %}

            {% include icon-github.html username=site.github_username %}

          {% endif %}

          {% if site.twitter_username %}

            {% include icon-twitter.html username=site.twitter_username %}

          {% endif %}

{{ site.description }}

<link rel="stylesheet" type="text/css" href="//wpcc.io/lib/1.0.2/cookieconsent.min.css"/>

{% include sharebox.html %}

redpajama_set_name: RedPajamaGithub


text:
package eu.cassandra.sim;

import java.util.Calendar;
import java.util.Date;

/**
 * The simulation's calendar.
 *
 * @author Kyriakos C. Chatzidimitriou (kyrcha [at] iti [dot] gr)
 *
 */
public class SimCalendar {

	/** The calendar. */
	private Calendar myCalendar;

	/** The calendar's base date. */
	private Date base;

	/** The calendar's granularity. */
	private String granularity = "Minute";

	/** The calendar's granularity value. */
	private int granularityValue = 1;

	/** The calendar's duration. */
	private int duration = 0;

	/** The Constant ABBR_DAYS. */
	private static final String[] ABBR_DAYS = { "NA", "Sun", "Mon", "Tue",
			"Wed", "Thu", "Fri", "Sat" };

	/**
	 * Instantiates a new simulation calendar.
	 *
	 * @param day the day
	 * @param month the month
	 * @param year the year
	 * @param duration the duration
	 */
	public SimCalendar(int day, int month, int year, int duration) {

		myCalendar = Calendar.getInstance();

		myCalendar.set(year, month - 1, day, 0, 0, 0);
		base = myCalendar.getTime();
		this.duration = duration;

	}

	/**
	 * Gets the calendar.
	 *
	 * @return the calendar
	 */
	public Calendar getMyCalendar() {
		return myCalendar;
	}

	/**
	 * Gets the calendar's base date.
	 *
	 * @return the calendar's base date
	 */
	public Date getBase() {
		return base;
	}

	/**
	 * Gets the calendar's granularity.
	 *
	 * @return the calendar's granularity
	 */
	public String getGranularity() {
		return granularity;
	}

	/**
	 * Gets the calendar's granularity (in raw format).
	 *
	 * @return the calendar's granularity (in raw format).
	 */
	public int getGranularityRaw() {

		switch (granularity) {
		case "Minute":

			return Calendar.MINUTE;

		case "Hour":

			return Calendar.HOUR;

		case "Day":

			return Calendar.DAY_OF_YEAR;

		case "Week":

			return Calendar.WEEK_OF_YEAR;

		case "Month":

			return Calendar.MONTH;

		}

		return 0;

	}

	/**
	 * Gets the calendar's granularity value.
	 *
	 * @return the calendar'sgranularity value
	 */
	public int getGranularityValue() {
		return granularityValue;
	}

	/**
	 * Copy a calendar.
	 *
	 * @param cal the calendar to copy
	 * @return the copied calendar
	 */
	private Calendar copyCal(Calendar cal) {
		Calendar temp = Calendar.getInstance();
		temp.set(myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
				myCalendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		return temp;
	}

	/**
	 * Checks if it is weekend.
	 *
	 * @param tick the current tick
	 * @return true, if it is weekend
	 */
	public boolean isWeekend(int tick) {
		Calendar temp = copyCal(myCalendar);
		int gran = getGranularityRaw();
		temp.add(gran, tick * granularityValue);
		int day = temp.get(Calendar.DAY_OF_WEEK);
		if (day == Calendar.SATURDAY || day == Calendar.SUNDAY)
			return true;
		return false;
	}

	/**
	 * Gets the current date.
	 *
	 * @param tick the current tick
	 * @return the current date
	 */
	public String getCurrentDate(int tick) {
		Calendar temp = copyCal(myCalendar);
		int gran = getGranularityRaw();
		temp.add(gran, tick * granularityValue);
		int day = temp.get(Calendar.DAY_OF_MONTH);
		int month = temp.get(Calendar.MONTH) + 1;
		return day + "/" + month;
	}

	/**
	 * Gets the current day of week.
	 *
	 * @param tick the current tick
	 * @return the current day of week
	 */
	public String getDayOfWeek(int tick) {
		Calendar temp = copyCal(myCalendar);
		int gran = getGranularityRaw();
		temp.add(gran, tick * granularityValue);
		return ABBR_DAYS[temp.get(Calendar.DAY_OF_WEEK)];
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		String temp = "Base: " + base + " Granularity: " + granularity
				+ " Granularity Value: " + granularityValue + " Duration: "
				+ duration;
		return temp;
	}

}


text:
package org.basex.http.rest;

import static org.basex.util.Token.*;

import java.io.*;

import org.basex.http.*;
import org.basex.io.serial.*;
import org.basex.query.value.node.*;
import org.basex.util.*;

/**
 * Lists REST resources.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Christian Gruen
 */
final class RESTList extends RESTCmd {
  /**
   * Constructor.
   * @param session REST session
   */
  RESTList(final RESTSession session) {
    super(session);
  }

  @Override
  protected void run0() throws IOException {
    // list all databases
    final Table table = new Table(run(cmds.get(0)));
    final FElem el = new FElem(RESTText.Q_DATABASES).declareNS();
    el.add(RESTText.RESOURCES, token(table.contents.size()));
    list(table, el, RESTText.Q_DATABASE, 1);

    final HTTPContext http = session.http;
    http.initResponse();
    try(final Serializer ser = Serializer.get(http.res.getOutputStream(), http.sopts())) {
      ser.serialize(el);
    }
  }
}


text:
"""The niftyseg module provides classes for interfacing with the `NIFTYSEG
<http://www.fmrib.ox.ac.uk/niftyseg/index.html>`_ command line tools.

Top-level namespace for niftyseg.
"""

from .base import (NIFTYSEGCommand, Info, no_niftyseg)
from .maths import (UnaryMaths, BinaryMaths, BinaryMathsInteger)
from .stats import (UnaryStats, BinaryStats)
from .gif import (Gif)
from .steps import (STEPS, CalcTopNCC)
from .patchmatch import (PatchMatch)


text:
package io.leangen.graphql;

import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLType;
import io.leangen.graphql.annotations.GraphQLEnumValue;
import io.leangen.graphql.annotations.GraphQLId;
import io.leangen.graphql.annotations.GraphQLScalar;
import io.leangen.graphql.domain.Address;
import io.leangen.graphql.domain.SimpleUser;
import io.leangen.graphql.execution.relay.Page;
import io.leangen.graphql.generator.mapping.common.MapToListTypeAdapter;
import io.leangen.graphql.metadata.strategy.query.PublicResolverBuilder;
import io.leangen.graphql.metadata.strategy.value.gson.GsonValueMapperFactory;
import io.leangen.graphql.util.GraphQLUtils;
import org.junit.Test;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class UniquenessTest {

    private static final String thisPackage = UniquenessTest.class.getPackage().getName();

    @Test
    public void testRelayIdUniqueness() {
        GraphQLSchema schema = schemaFor(new RelayIdService());
        testRootQueryTypeUniqueness(schema);
        testRootQueryArgumentTypeUniqueness(schema);
    }

    @Test
    public void testScalarUniqueness() {
        GraphQLSchema schema = schemaFor(new ScalarService());
        testRootQueryTypeUniqueness(schema);
        testRootQueryArgumentTypeUniqueness(schema);
    }

    @Test
    public void testObjectScalarUniqueness() {
        GraphQLSchema schema = schemaFor(new ObjectScalarService());
        testRootQueryTypeUniqueness(schema);
        testRootQueryArgumentTypeUniqueness(schema);
    }

    @Test
    public void testPageUniqueness() {
        testRootQueryTypeUniqueness(schemaFor(new PagingService()));
    }

    @Test
    public void testEnumUniqueness() {
        GraphQLSchema schema = schemaFor(new EnumService());
        testRootQueryTypeUniqueness(schema);
        testRootQueryArgumentTypeUniqueness(schema);
    }

    @Test
    public void testMapUniqueness() {
        GraphQLSchema schema = new TestSchemaGenerator()
                .withTypeAdapters(new MapToListTypeAdapter())
                .withOperationsFromSingleton(new MapService(), new PublicResolverBuilder(thisPackage))
                .generate();
        testRootQueryTypeUniqueness(schema);
        testRootQueryArgumentTypeUniqueness(schema);
    }

    @Test
    public void testEnumMapUniqueness() {
        GraphQLSchema schema = new TestSchemaGenerator()
                .withOperationsFromSingleton(new EnumMapService(), new PublicResolverBuilder(thisPackage))
                .withValueMapperFactory(new GsonValueMapperFactory())
                .generate();
        testRootQueryTypeUniqueness(schema);
        testRootQueryArgumentTypeUniqueness(schema);
        GraphQL exe = GraphQL.newGraphQL(schema).build();
        ExecutionResult res = exe.execute("{map(in: {Lucidus: 12, Tenebris: 13}) {Tenebris, Lucidus}}");
        assertEquals(0, res.getErrors().size());
        res = exe.execute("{mapAgain(in: {Lucidus: 12, Tenebris: 13}) {Tenebris, Lucidus}}");
        assertEquals(0, res.getErrors().size());
    }

    private GraphQLSchema schemaFor(Object service) {
        return new TestSchemaGenerator()
                .withOperationsFromSingleton(service, new PublicResolverBuilder(thisPackage))
                .generate();
    }

    private void testRootQueryTypeUniqueness(GraphQLSchema schema) {
        List<GraphQLType> fieldTypes = schema.getQueryType().getFieldDefinitions().stream()
                .map(GraphQLFieldDefinition::getType)
                .map(GraphQLUtils::unwrap)
                .collect(Collectors.toList());
        assertEquals(2, fieldTypes.size());
        assertTrue(fieldTypes.stream().allMatch(type -> fieldTypes.get(0) == type));
    }

    private void testRootQueryArgumentTypeUniqueness(GraphQLSchema schema) {
        List<GraphQLType> inputTypes = schema.getQueryType().getFieldDefinitions().stream()
                .flatMap(def -> def.getArguments().stream())
                .map(GraphQLArgument::getType)
                .map(GraphQLUtils::unwrap)
                .collect(Collectors.toList());
        assertEquals(2, inputTypes.size());
        assertTrue(inputTypes.stream().allMatch(type -> inputTypes.get(0) == type));
    }

    public static class RelayIdService {

        public @GraphQLId(relayId = true) String getId(@GraphQLId(relayId = true) String in) {
            return in;
        }

        public @GraphQLId(relayId = true) String getIdAgain(@GraphQLId(relayId = true) String in) {
            return in;
        }
    }

    public static class ScalarService {

        public UUID getUuid(UUID in) {
            return in;
        }

        public UUID getUuidAgain(UUID in) {
            return in;
        }
    }

    public static class ObjectScalarService {

        public @GraphQLScalar Address getAddress(@GraphQLScalar Address in) {
            return in;
        }

        public @GraphQLScalar Address getAddressAgain(@GraphQLScalar Address in) {
            return in;
        }
    }

    public static class EnumService {

        enum BLACK_OR_WHITE {
            BLACK, WHITE
        }

        public BLACK_OR_WHITE getEnum(BLACK_OR_WHITE bow) {
            return BLACK_OR_WHITE.BLACK;
        }

        public BLACK_OR_WHITE getEnumAgain(BLACK_OR_WHITE bow) {
            return BLACK_OR_WHITE.WHITE;
        }
    }

    public static class EnumMapService {

        enum LIGHT_OR_DARK {
            @GraphQLEnumValue(name = "Lucidus", description = "Bright") LIGHT,
            @GraphQLEnumValue(name = "Tenebris", description = "Shady") DARK
        }

        public EnumMap<LIGHT_OR_DARK, Number> map(@io.leangen.graphql.annotations.GraphQLArgument(name = "in") EnumMap<LIGHT_OR_DARK, Number> in) {
            return in;
        }

        public EnumMap<LIGHT_OR_DARK, Number> mapAgain(@io.leangen.graphql.annotations.GraphQLArgument(name = "in") EnumMap<LIGHT_OR_DARK, Number> in) {
            return in;
        }
    }

    public static class PagingService {

        public Page<SimpleUser> getUsers(int first, String after) {
            return null;
        }

        public Page<SimpleUser> getUsersAgain(int last, String before) {
            return null;
        }
    }

    public static class MapService {

        public Map<String, SimpleUser> getUsers(Map<String, SimpleUser> in) {
            return null;
        }

        public Map<String, SimpleUser> getUsersAgain(Map<String, SimpleUser> in) {
            return null;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.hewking.custom.constrainlayout.ConstrainActivity">

    <Button
        android:id="@+id/btn_left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</androidx.constraintlayout.widget.ConstraintLayout>


text:
pub mod file_util;
pub mod rand_gen;

pub use self::rand_gen::random_bools;
pub use self::rand_gen::random_bytes;
pub use self::rand_gen::random_numbers;
pub use self::rand_gen::random_numbers_range;
pub use self::rand_gen::RandGen;

pub use self::file_util::get_temp_file;
pub use self::file_util::get_test_file;
pub use self::file_util::get_test_path;


text:
class OrdersController < ApplicationController
  skip_before_action :verify_authenticity_token
  def purchase_status
    begin
      @order = Order.process_razorpayment(payment_params)
      redirect_to :action => "show", :id => @order.id
    rescue Exception
      flash[:alert] = "Unable to process payment."
      redirect_to root_path
    end
  end

  def show
    @order = Order.find_by_id(params[:id])
  end

  def index
    @orders = Order.filter(filter_params).page(params[:page]).per(20)
  end

  def refund
    payment_id = Order.find_by_id(params[:id]).payment_id
    @order = Order.process_refund(payment_id)
    redirect_to :action => "show", :id => @order.id
  end

  private
    def payment_params
      p = params.permit(:payment_id, :user_id, :product_id, :price, :razorpay_payment_id)
      p.merge!({payment_id: p.delete(:razorpay_payment_id) || p[:payment_id]})
      p
    end

    def filter_params
      params.permit(:status, :page)
    end

end