/// <summary> /// Gets the numeric value of the function in the given Evaluation Context for the given Binding ID /// </summary> /// <param name="context">Evaluation Context</param> /// <param name="bindingID">Binding ID</param> /// <returns></returns> public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { IValuedNode a = _leftExpr.Evaluate(context, bindingID); IValuedNode b = _rightExpr.Evaluate(context, bindingID); SparqlNumericType type = (SparqlNumericType)Math.Max((int)a.NumericType, (int)b.NumericType); switch (type) { case SparqlNumericType.Integer: return(new LongNode(null, Math.Max(a.AsInteger(), b.AsInteger()))); case SparqlNumericType.Decimal: return(new DecimalNode(null, Math.Max(a.AsDecimal(), b.AsDecimal()))); case SparqlNumericType.Float: return(new FloatNode(null, Math.Max(a.AsFloat(), b.AsFloat()))); case SparqlNumericType.Double: return(new DoubleNode(null, Math.Max(a.AsDouble(), b.AsDouble()))); default: throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined"); } }
/// <summary> /// Compares two Nodes for Numeric Ordering /// </summary> /// <param name="x">Node</param> /// <param name="y">Node</param> /// <param name="type">Numeric Type</param> /// <returns></returns> protected virtual int NumericCompare(IValuedNode x, IValuedNode y, SparqlNumericType type) { if (x == null || y == null) { throw new RdfQueryException("Cannot evaluate numeric ordering when one or both arguments are Null"); } if (type == SparqlNumericType.NaN) { throw new RdfQueryException("Cannot evaluate numeric ordering when the Numeric Type is NaN"); } switch (type) { case SparqlNumericType.Decimal: return(x.AsDecimal().CompareTo(y.AsDecimal())); case SparqlNumericType.Double: return(x.AsDouble().CompareTo(y.AsDouble())); case SparqlNumericType.Float: return(x.AsFloat().CompareTo(y.AsFloat())); case SparqlNumericType.Integer: return(x.AsInteger().CompareTo(y.AsInteger())); default: throw new RdfQueryException("Cannot evaluate numeric equality since of the arguments is not numeric"); } }
/// <summary> /// Evaluates the expression. /// </summary> /// <param name="context">Evaluation Context.</param> /// <param name="bindingID">Binding ID.</param> /// <returns></returns> public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { IValuedNode temp = _expr.Evaluate(context, bindingID); if (temp == null) { throw new RdfQueryException("Cannot evaluate factorial of a null"); } long l = temp.AsInteger(); if (l == 0) { return(new LongNode(null, 0)); } long fac = 1; if (l > 0) { for (long i = l; i > 1; i--) { fac = fac * i; } } else { for (long i = l; i < -1; i++) { fac = fac * i; } } return(new LongNode(null, fac)); }
/// <summary> /// Evaluates the expression /// </summary> /// <param name="context">Evaluation Context</param> /// <param name="bindingID">Binding ID</param> /// <returns></returns> public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { IValuedNode temp = _expr.Evaluate(context, bindingID); if (temp == null) { throw new RdfQueryException("Cannot square a null"); } switch (temp.NumericType) { case SparqlNumericType.Integer: long l = temp.AsInteger(); return(new LongNode(null, l * l * l)); case SparqlNumericType.Decimal: decimal d = temp.AsDecimal(); return(new DecimalNode(null, d * d * d)); case SparqlNumericType.Float: float f = temp.AsFloat(); return(new FloatNode(null, f * f * f)); case SparqlNumericType.Double: double dbl = temp.AsDouble(); return(new DoubleNode(null, Math.Pow(dbl, 3))); case SparqlNumericType.NaN: default: throw new RdfQueryException("Cannot square a non-numeric argument"); } }
/// <summary> /// Gets the Numeric Value of the function as evaluated in the given Context for the given Binding ID /// </summary> /// <param name="context">Evaluation Context</param> /// <param name="bindingID">Binding ID</param> /// <returns></returns> public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { IValuedNode a = this._expr.Evaluate(context, bindingID); if (a == null) { throw new RdfQueryException("Cannot calculate an arithmetic expression on a null"); } int p = 0; if (this._precision != null) { IValuedNode precision = this._precision.Evaluate(context, bindingID); if (precision == null) { throw new RdfQueryException("Cannot use a null precision for rounding"); } try { p = Convert.ToInt32(precision.AsInteger()); } catch { throw new RdfQueryException("Unable to cast precision to an integer"); } } switch (a.NumericType) { case SparqlNumericType.Integer: //Rounding an Integer has no effect return(a); case SparqlNumericType.Decimal: return(new DecimalNode(null, Math.Round(a.AsDecimal(), p, MidpointRounding.AwayFromZero))); case SparqlNumericType.Float: try { return(new FloatNode(null, Convert.ToSingle(Math.Round(a.AsDouble(), p, MidpointRounding.AwayFromZero)))); } catch (RdfQueryException) { throw; } catch (Exception ex) { throw new RdfQueryException("Unable to cast the float value of a round to a float", ex); } case SparqlNumericType.Double: return(new DoubleNode(null, Math.Round(a.AsDouble(), p, MidpointRounding.AwayFromZero))); default: throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined"); } }
private static object GetPrimitiveValue(IValuedNode valuedNode, IEdmPrimitiveType targetType, bool asNullable) { // TODO: Some sort of cast to nullable when necessary switch (targetType.PrimitiveKind) { case EdmPrimitiveTypeKind.Boolean: return(valuedNode.AsBoolean()); case EdmPrimitiveTypeKind.Byte: return((byte)valuedNode.AsInteger()); case EdmPrimitiveTypeKind.DateTime: return(valuedNode.AsDateTime()); case EdmPrimitiveTypeKind.Decimal: return(valuedNode.AsDecimal()); case EdmPrimitiveTypeKind.Double: return(valuedNode.AsDouble()); case EdmPrimitiveTypeKind.Int16: return((Int16)valuedNode.AsInteger()); case EdmPrimitiveTypeKind.Int32: return((Int32)valuedNode.AsInteger()); case EdmPrimitiveTypeKind.Int64: return(valuedNode.AsInteger()); case EdmPrimitiveTypeKind.String: return(valuedNode.AsString()); case EdmPrimitiveTypeKind.DateTimeOffset: return(valuedNode.AsDateTime()); default: throw new NotSupportedException( String.Format("Support for primitive type {0} has not been implemented yet", targetType.PrimitiveKind)); } }
public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingId) { IValuedNode a = _leftExpr.Evaluate(context, bindingId); IValuedNode b = _rightExpr.Evaluate(context, bindingId); var type = (SparqlNumericType)Math.Max((int)a.NumericType, (int)b.NumericType); if (type == SparqlNumericType.Integer) { return(new LongNode(null, a.AsInteger() | b.AsInteger())); } throw new RdfQueryException("Cannot evaluate bitwise OR expression as the arguments are not integer values."); }
/// <summary> /// Gets the Numeric Value of the function as evaluated in the given Context for the given Binding ID. /// </summary> /// <param name="context">Evaluation Context.</param> /// <param name="bindingID">Binding ID.</param> /// <returns></returns> public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { IValuedNode a = _expr.Evaluate(context, bindingID); if (a == null) { throw new RdfQueryException("Cannot calculate an arithmetic expression on a null"); } switch (a.NumericType) { case SparqlNumericType.Integer: return(new LongNode(null, Math.Abs(a.AsInteger()))); case SparqlNumericType.Decimal: return(new DecimalNode(null, Math.Abs(a.AsDecimal()))); case SparqlNumericType.Float: try { return(new FloatNode(null, Convert.ToSingle(Math.Abs(a.AsDouble())))); } catch (RdfQueryException) { throw; } catch (Exception ex) { throw new RdfQueryException("Unable to cast absolute value of float to a float", ex); } case SparqlNumericType.Double: return(new DoubleNode(null, Math.Abs(a.AsDouble()))); default: throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined"); } }
/// <summary> /// Returns the value of the Expression as evaluated for a given Binding as a Literal Node /// </summary> /// <param name="context">Evaluation Context</param> /// <param name="bindingID">Binding ID</param> /// <returns></returns> public IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { ILiteralNode input = (ILiteralNode)CheckArgument(_expr, context, bindingID); IValuedNode start = CheckArgument(_start, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (_length != null) { IValuedNode length = CheckArgument(_length, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (input.Value.Equals(string.Empty)) { return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } int s = Convert.ToInt32(start.AsInteger()); int l = Convert.ToInt32(length.AsInteger()); if (s < 1) { s = 1; } if (l < 1) { // If no/negative characters are being selected the empty string is returned return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else if ((s - 1) > input.Value.Length) { // If the start is after the end of the string the empty string is returned return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { if (((s - 1) + l) > input.Value.Length) { // If the start plus the length is greater than the length of the string the string from the starts onwards is returned return(new StringNode(null, input.Value.Substring(s - 1), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { // Otherwise do normal substring return(new StringNode(null, input.Value.Substring(s - 1, l), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } } } else { if (input.Value.Equals(string.Empty)) { return(new StringNode(null, string.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } int s = Convert.ToInt32(start.AsInteger()); if (s < 1) { s = 1; } return(new StringNode(null, input.Value.Substring(s - 1), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } }
/// <summary> /// Gets the value of the function in the given Evaluation Context for the given Binding ID. /// </summary> /// <param name="context">Evaluation Context.</param> /// <param name="bindingID">Binding ID.</param> /// <returns></returns> public IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { ILiteralNode input = (ILiteralNode)CheckArgument(_expr, context, bindingID); IValuedNode start = CheckArgument(_start, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (_end != null) { IValuedNode end = CheckArgument(_end, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (input.Value.Equals(String.Empty)) { return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } try { int s = Convert.ToInt32(start.AsInteger()); int e = Convert.ToInt32(end.AsInteger()); if (s < 0) { s = 0; } if (e < s) { // If no/negative characters are being selected the empty string is returned return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else if (s > input.Value.Length) { // If the start is after the end of the string the empty string is returned return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { if (e > input.Value.Length) { // If the end is greater than the length of the string the string from the starts onwards is returned return(new StringNode(null, input.Value.Substring(s), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { // Otherwise do normal substring return(new StringNode(null, input.Value.Substring(s, e - s), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } } } catch { throw new RdfQueryException("Unable to convert the Start/End argument to an Integer"); } } else { if (input.Value.Equals(String.Empty)) { return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } try { int s = Convert.ToInt32(start.AsInteger()); if (s < 0) { s = 0; } return(new StringNode(null, input.Value.Substring(s), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } catch { throw new RdfQueryException("Unable to convert the Start argument to an Integer"); } } }
/// <summary> /// Constructs a Full Text Match property function /// </summary> /// <param name="info">Property Function information</param> public FullTextMatchPropertyFunction(PropertyFunctionInfo info) { if (info == null) { throw new ArgumentNullException("info"); } if (!EqualityHelper.AreUrisEqual(info.FunctionUri, this.FunctionUri)) { throw new ArgumentException("Property Function information is not valid for this function"); } //Get basic arguments this._matchVar = info.SubjectArgs[0]; if (this._matchVar.VariableName != null) { this._vars.Add(this._matchVar.VariableName); } if (info.SubjectArgs.Count == 2) { this._scoreVar = info.SubjectArgs[1]; if (this._scoreVar.VariableName != null) { this._vars.Add(this._scoreVar.VariableName); } } //Check extended arguments this._searchVar = info.ObjectArgs[0]; if (this._searchVar.VariableName != null) { this._vars.Add(this._searchVar.VariableName); } switch (info.ObjectArgs.Count) { case 1: break; case 2: PatternItem arg = info.ObjectArgs[1]; if (arg.VariableName != null) { throw new RdfQueryException("Cannot use a variable as the limit/score threshold for full text queries, must use a numeric constant"); } IValuedNode n = ((NodeMatchPattern)arg).Node.AsValuedNode(); switch (n.NumericType) { case SparqlNumericType.Integer: this._limit = (int)n.AsInteger(); break; case SparqlNumericType.Decimal: case SparqlNumericType.Double: case SparqlNumericType.Float: this._threshold = n.AsDouble(); break; default: throw new RdfQueryException("Cannot use a non-numeric constant as the limit/score threshold for full text queries, must use a numeric constant"); } break; case 3: default: PatternItem arg1 = info.ObjectArgs[1]; PatternItem arg2 = info.ObjectArgs[2]; if (arg1.VariableName != null || arg2.VariableName != null) { throw new RdfQueryException("Cannot use a variable as the limit/score threshold for full text queries, must use a numeric constant"); } IValuedNode n1 = ((NodeMatchPattern)arg1).Node.AsValuedNode(); switch (n1.NumericType) { case SparqlNumericType.NaN: throw new RdfQueryException("Cannot use a non-numeric constant as the score threshold for full text queries, must use a numeric constant"); default: this._threshold = n1.AsDouble(); break; } IValuedNode n2 = ((NodeMatchPattern)arg2).Node.AsValuedNode(); switch (n2.NumericType) { case SparqlNumericType.NaN: throw new RdfQueryException("Cannot use a non-numeric constant as the limit for full text queries, must use a numeric constant"); default: this._limit = (int)n2.AsInteger(); break; } break; } }
/// <summary> /// Calculates the Numeric Value of this Expression as evaluated for a given Binding /// </summary> /// <param name="context">Evaluation Context</param> /// <param name="bindingID">Binding ID</param> /// <returns></returns> public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { IValuedNode a = this._expr.Evaluate(context, bindingID); if (a == null) { throw new RdfQueryException("Cannot apply unary minus to a null"); } switch (a.NumericType) { case SparqlNumericType.Integer: return(new LongNode(null, -1 * a.AsInteger())); case SparqlNumericType.Decimal: decimal decvalue = a.AsDecimal(); if (decvalue == Decimal.Zero) { return(new DecimalNode(null, Decimal.Zero)); } else { return(new DecimalNode(null, -1 * decvalue)); } case SparqlNumericType.Float: float fltvalue = a.AsFloat(); if (Single.IsNaN(fltvalue)) { return(new FloatNode(null, Single.NaN)); } else if (Single.IsPositiveInfinity(fltvalue)) { return(new FloatNode(null, Single.NegativeInfinity)); } else if (Single.IsNegativeInfinity(fltvalue)) { return(new FloatNode(null, Single.PositiveInfinity)); } else { return(new FloatNode(null, -1.0f * fltvalue)); } case SparqlNumericType.Double: double dblvalue = a.AsDouble(); if (Double.IsNaN(dblvalue)) { return(new DoubleNode(null, Double.NaN)); } else if (Double.IsPositiveInfinity(dblvalue)) { return(new DoubleNode(null, Double.NegativeInfinity)); } else if (Double.IsNegativeInfinity(dblvalue)) { return(new DoubleNode(null, Double.PositiveInfinity)); } else { return(new DoubleNode(null, -1.0 * dblvalue)); } default: throw new RdfQueryException("Cannot evalute an Arithmetic Expression when the Numeric Type of the expression cannot be determined"); } }
private static object GetPrimitiveValue(IValuedNode valuedNode, IEdmPrimitiveType targetType, bool asNullable) { // TODO: Some sort of cast to nullable when necessary switch (targetType.PrimitiveKind) { case EdmPrimitiveTypeKind.Boolean: return valuedNode.AsBoolean(); case EdmPrimitiveTypeKind.Byte: return (byte) valuedNode.AsInteger(); case EdmPrimitiveTypeKind.DateTime: return valuedNode.AsDateTime(); case EdmPrimitiveTypeKind.Decimal: return valuedNode.AsDecimal(); case EdmPrimitiveTypeKind.Double: return valuedNode.AsDouble(); case EdmPrimitiveTypeKind.Int16: return (Int16) valuedNode.AsInteger(); case EdmPrimitiveTypeKind.Int32: return (Int32) valuedNode.AsInteger(); case EdmPrimitiveTypeKind.Int64: return valuedNode.AsInteger(); case EdmPrimitiveTypeKind.String: return valuedNode.AsString(); case EdmPrimitiveTypeKind.DateTimeOffset: return valuedNode.AsDateTime(); default: throw new NotSupportedException( String.Format("Support for primitive type {0} has not been implemented yet", targetType.PrimitiveKind)); } }
protected override String RunTaskInternal() { // Start from an initial Original Query issued by user SparqlQuery initialQuery; try { initialQuery = this._parser.ParseFromString(this.OriginalQueryString); } catch (RdfParseException parseEx) { throw new RdfQueryException("Unable to parse the given SPARQL Query", parseEx); } if (initialQuery.QueryType != SparqlQueryType.Select && initialQuery.QueryType != SparqlQueryType.SelectDistinct) { throw new RdfQueryException("Only Sparql select Query with variables is supported for table format"); } INamespaceMapper originalPrefixes = new NamespaceMapper(true); originalPrefixes.Import(initialQuery.NamespaceMap); initialQuery.NamespaceMap.Clear(); // Get the predicates for first variable (entity subjects) // SELECT DISTINCT ?p (COUNT(?p) as ?count) // WHERE // { // { // # Original Query // } // ?sx ?p ?o. // } // GROUP BY ?p // Create a dynamic originalQuery SparqlVariable subject = initialQuery.Variables.FirstOrDefault(v => v.IsResultVariable); if (subject == null) { throw new RdfQueryException("At least one result variable is required to generate an entities query"); } INode subjectNode = this._nodeFactory.CreateVariableNode(subject.Name); SparqlParameterizedString getPredicatesQuery = new SparqlParameterizedString(); getPredicatesQuery.Namespaces = originalPrefixes; getPredicatesQuery.CommandText = @" SELECT DISTINCT ?p (COUNT(?p) as ?count) WHERE {"; getPredicatesQuery.AppendSubQuery(initialQuery); getPredicatesQuery.CommandText += @" @subject ?p ?o. } GROUP BY ?p"; getPredicatesQuery.SetParameter("subject", subjectNode); try { // Get predicates and number of usages this.Information = "Running query to extract predicates for entities selected by original query..."; SparqlResultSet sparqlResults = (SparqlResultSet)this._storage.Query(getPredicatesQuery.ToString()); if (sparqlResults == null) { throw new RdfQueryException("Unexpected results type received while trying to build entities query"); } List <String> selectColumns = new List <String>(); selectColumns.Add(subject.Name); SparqlParameterizedString entitiesQuery = new SparqlParameterizedString(); entitiesQuery.Namespaces.Import(getPredicatesQuery.Namespaces); entitiesQuery.SetParameter("subject", subjectNode); // For each predicate add a column and an appropriate OPTIONAL clause int predicateIndex = 0; StringBuilder optionalFilters = new StringBuilder(); this.Information = "Generating Entities Query..."; foreach (SparqlResult sparqlResult in sparqlResults) { if (!sparqlResult.HasBoundValue("p")) { continue; } INode predicate = sparqlResult["p"]; IValuedNode count = sparqlResult["count"].AsValuedNode(); long predicateCount = count != null?count.AsInteger() : 0; // For each predicate with predicateCount > _minValuesPerPredicateLimit add a new column and an optional filter in where clause if (predicateCount <= _minValuesPerPredicateLimit) { continue; } predicateIndex++; String predicateColumnName = GetColumnName(predicate, entitiesQuery.Namespaces); if (predicateColumnName == null) { continue; } selectColumns.Add(predicateColumnName); optionalFilters.AppendLine(" OPTIONAL { @subject @predicate" + predicateIndex + " ?" + predicateColumnName + " }"); entitiesQuery.SetParameter("predicate" + predicateIndex, predicate); } if (selectColumns.Count == 1) { throw new RdfQueryException("No predicates which matched the criteria were found so an entities query cannot be generated"); } entitiesQuery.CommandText = "SELECT DISTINCT "; foreach (String column in selectColumns) { entitiesQuery.CommandText += "?" + column + " "; } entitiesQuery.CommandText += @" WHERE { "; entitiesQuery.AppendSubQuery(initialQuery); entitiesQuery.CommandText += optionalFilters.ToString(); entitiesQuery.CommandText += @" }"; this.Information = "Generated Entities Query with " + (selectColumns.Count - 1) + " Predicate Columns"; this.OutputTableQuery = entitiesQuery.ToString(); } catch (Exception) { this.OutputTableQuery = null; throw; } return(this.OutputTableQuery); }