public override BaseNode VisitFilterExpression(QueryFilteringParser.FilterExpressionContext context) { BaseNode resultNode = context.children[0].Accept(this); for (int i = 1; i < context.children.Count; i += 2) { var left = resultNode; var right = context.children[i + 1].Accept(this); var aggregateNode = (ITerminalNode)context.children[i]; switch (aggregateNode.Symbol.Type) { case QueryFilteringLexer.AND: resultNode = new AndNode(left, right); continue; case QueryFilteringLexer.OR: resultNode = new OrNode(left, right); continue; default: throw new ParseRuleException( nameof(FilterExpressionVisitor), $"неизвестный тип предиката '{aggregateNode.Symbol.Type}'"); } } return(resultNode); }
/// <summary> /// Takes a list of tokenized input and create the corresponding expression tree. /// </summary> /// <param name="tokenList"> /// Tokenized list of the input string. /// </param> private Node ConstructExpressionTree(List <Token> tokenList) { bool notFlag = false; Queue <Node> andQueue = new Queue <Node>(); Queue <Node> orQueue = new Queue <Node>(); for (int i = 0; i < tokenList.Count; i++) { Token token = tokenList[i]; TokenKind kind = token.Kind; if (kind == TokenKind.Identifier) { Node idNode = new OperandNode(token.Text); if (notFlag) // identifier preceded by NOT { Node notNode = new NotNode(); notNode.Operand1 = idNode; notFlag = false; andQueue.Enqueue(notNode); } else { andQueue.Enqueue(idNode); } } else if (kind == TokenKind.Not) { notFlag = true; } else if (kind == TokenKind.And) { ; // do nothing } else if (kind == TokenKind.Or) { // Dequeue all nodes from AND queue, // create the AND tree, then add to the OR queue. Node andCurrent = andQueue.Dequeue(); while (andQueue.Count > 0) { Node andNode = new AndNode(andCurrent); andNode.Operand1 = andQueue.Dequeue(); andCurrent = andNode; } orQueue.Enqueue(andCurrent); } } // Dequeue all nodes from OR queue, // create the OR tree (final expression tree) Node orCurrent = orQueue.Dequeue(); while (orQueue.Count > 0) { Node orNode = new OrNode(orCurrent); orNode.Operand1 = orQueue.Dequeue(); orCurrent = orNode; } return(orCurrent); }
public void ValidCheckWithLoops() { var inputNode1 = new InputNode("in1", new State(true)); var notNode = new NotNode("not"); var andNode = new AndNode("and"); var outputNode = new OutputNode("out"); var nodeConnections = new List <NodeConnection> { new NodeConnection(andNode, notNode), new NodeConnection( new List <NodeBase> { inputNode1, notNode }, andNode), new NodeConnection(andNode, outputNode) }; var inputNodes = new List <InputNode> { inputNode1 }; var simulation = new NodeSimulation(nodeConnections); Assert.Throws <PathException>(() => simulation.ValidSimulationCheck()); }
public virtual void Visit(AndNode node) { var right = Nodes.Pop(); var left = Nodes.Pop(); Nodes.Push(new AndNode(left, right)); }
public void Visit(AndNode node) { var mode = Query.EvaluationMode.Index; var exclude = Enumerable.Empty <IndexItem>(); var excludeCount = 0L; var include = new List <IEnumerable <IndexItem> >(); var estimate = long.MaxValue; // generate include/exclude enumerators for (var i = 0; i < node.Inner.Count; i++) { if (node.Inner[i] is NotNode) { node.Inner[i].Inner[0].Accept(this); exclude = exclude.Concat(Index); excludeCount += EstimatedCount; } else { node.Inner[i].Accept(this); if (EstimatedCount != _log.Count) { include.Add(Index); estimate = Math.Min(estimate, EstimatedCount); } } mode = new[] { Mode, mode }.Max(); } // if no include is found, scan all if (include.Count == 0) { include.Add(_log.Search()); } // define the iterator function IEnumerable <IndexItem> Iterator() { var except = new HashSet <IndexItem>(exclude); var enumerator = include.Select(i => Buffered(i).GetEnumerator()).ToArray(); var hasNext = enumerator.Select(i => i.MoveNext()).ToArray(); while (hasNext.All(i => i)) { var lowest = enumerator.Aggregate <IEnumerator <IndexItem>, IEnumerator <IndexItem> >(null, (a, i) => a != null ? (a.Current.CompareTo(i.Current) < 0 ? a : i) : i); if (!except.Contains(lowest.Current) && enumerator.All(i => lowest.Current.CompareTo(i.Current) == 0)) { yield return(lowest.Current); } hasNext[Array.IndexOf(enumerator, lowest)] = lowest.MoveNext(); } }; // and set the results EstimatedCount = estimate - excludeCount; Mode = mode; Index = Iterator(); }
public void RootIsSetCorrectly() { var root = new AndNode(); var tree = new ParameterTree(root); Assert.Equal(root, tree.Root); }
public void CheckIfTreeCanBeDeserialized() { var root = new AndNode(); root.AddChild(new ValueNode <int>("a", new IntegerDomain())); root.AddChild(new ValueNode <int>("b", new IntegerDomain())); var tree = new ParameterTree(root); var serializer = new Hyperion.Serializer(); var treeStream = new MemoryStream(); serializer.Serialize(tree, treeStream); var streamCopy = new MemoryStream(treeStream.GetBuffer()); var restoredTree = serializer.Deserialize <ParameterTree>(streamCopy); Assert.NotNull(restoredTree); var originalNodes = tree.GetParameters().ToList(); var restoredNodes = restoredTree.GetParameters().ToList(); Assert.Equal(originalNodes.Count, restoredNodes.Count); for (var i = 0; i < originalNodes.Count; i++) { var expectedNode = originalNodes[i]; var restoredNode = restoredNodes[i]; Assert.True(expectedNode.Identifier == restoredNode.Identifier, "Nodes were deserialized in wrong order."); Assert.Equal(expectedNode.Domain.DomainSize, restoredNode.Domain.DomainSize); } }
public AndNode And() { AndNode andNode = new AndNode(); Match(TokenType.AND); return(andNode); }
/// <summary> /// Creates a <see cref="Optano.Algorithm.Tuner.Parameters.ParameterTree"/> which consists of two independent parameters: /// <see cref="FreeParameterName"/> and <see cref="ExtractIntegerValue.ParameterName"/>, both integers between /// -5 and 5. /// </summary> /// <returns>The created <see cref="Optano.Algorithm.Tuner.Parameters.ParameterTree"/>.</returns> private static ParameterTree CreateParameterTree() { var root = new AndNode(); root.AddChild(new ValueNode <int>(GenomeAssistedSorterBaseTest <TSearchPoint> .FreeParameterName, new IntegerDomain(-5, 5))); root.AddChild(new ValueNode <int>(ExtractIntegerValue.ParameterName, new IntegerDomain(-5, 5))); return(new ParameterTree(root)); }
void PropagateNotToLeaves(ref IQueryNode rootNode) { if (rootNode.leaf || !(rootNode is CombinedNode cn)) { return; } if (rootNode.type != QueryNodeType.Not) { return; } var parent = rootNode.parent; var oldNode = rootNode.children[0]; if (!(oldNode is CombinedNode oldCombinedNode) || (oldCombinedNode.type != QueryNodeType.And && oldCombinedNode.type != QueryNodeType.Or)) { return; } CombinedNode newCombinedNode; if (oldNode.type == QueryNodeType.And) { newCombinedNode = new OrNode(); } else { newCombinedNode = new AndNode(); } cn.RemoveNode(oldNode); foreach (var child in oldNode.children) { var propagatedNotNode = new NotNode(); propagatedNotNode.AddNode(child); newCombinedNode.AddNode(propagatedNotNode); } oldCombinedNode.Clear(); // If the old not is the root of the evaluationGraph, then the new combined node // becomes the new root. if (parent == null) { this.root = newCombinedNode; } else { // In order to not change the parent's enumeration, swap directly the old // children with the new one SwapChild(parent, rootNode, newCombinedNode); } // Set the current tree root to the new combined node. rootNode = newCombinedNode; }
public void ClearNodesFromProvider_LeavesOtherNodes() { var n0 = new AndNode {tempId = node0}; var n2 = new AndNode {tempId = node2}; var nodesToClear = new List<AbstractMaterialNode>() { n0, n2 }; m_ComplexMgr.ClearNodesFromProvider(p1, nodesToClear); var ret = GetListFrom(m_ComplexMgr); Assert.AreEqual(3, ret.Find(kpv => kpv.Key.Equals(node1)).Value.Count); }
private Node And() { var node = Shift(); while (_lexer.TryReadChar('&')) { node = new AndNode(node, Shift()); } return(node); }
public void ChildIsReturnedCorrectly() { IParameterTreeNode child = new AndNode(); this._valueNode.SetChild(child); Assert.True( TestUtils.SetsAreEquivalent(new List <IParameterTreeNode> { child }, this._valueNode.Children), $"Expected single child, but got {TestUtils.PrintList(this._valueNode.Children)}."); }
private Node ConstructExpressionTree(List <Token> tokenList) { bool flag = false; Queue <Node> queue = new Queue <Node>(); Queue <Node> queue2 = new Queue <Node>(); for (int i = 0; i < tokenList.Count; i++) { Token token = tokenList[i]; TokenKind kind = token.Kind; if (kind == TokenKind.Identifier) { Node item = new OperandNode(token.Text); if (flag) { Node node2 = new NotNode { Operand1 = item }; flag = false; queue.Enqueue(node2); } else { queue.Enqueue(item); } } else if (kind == TokenKind.Not) { flag = true; } else if ((kind != TokenKind.And) && (kind == TokenKind.Or)) { Node node3 = queue.Dequeue(); while (queue.Count > 0) { node3 = new AndNode(node3) { Operand1 = queue.Dequeue() }; } queue2.Enqueue(node3); } } Node n = queue2.Dequeue(); while (queue2.Count > 0) { n = new OrNode(n) { Operand1 = queue2.Dequeue() }; } return(n); }
protected virtual BaseQuery HandleAnd(AndNode node, ElasticSearchQueryMapperState state) { var query1 = Handle(node.LeftNode, state); var query2 = Handle(node.RightNode, state); if (!query1) { return(query1); } return(query1 & query2); }
private ExpressionNode ParseJoin() { var lhs = ParseEquality(); while (_reader.Peek() is And) { Match <And>(); lhs = new AndNode(lhs, ParseEquality()); } return(lhs); }
/// <summary> /// Initializes a new instance of the <see cref="GenomeTransformationTest"/> class. /// Serves as test initialize method. /// </summary> public GenomeTransformationTest() { this._categoricalDomain = new CategoricalDomain <int>(Enumerable.Range(0, 10).ToList()); var root = new AndNode(); var contNode = new ValueNode <double>("continuous", new ContinuousDomain()); var categoricalNode = new ValueNode <int>("test", this._categoricalDomain); root.AddChild(contNode); root.AddChild(categoricalNode); this._tree = new ParameterTree(root); }
public void Visit(AndNode visitee) { _cumulativeDelay += (visitee.EndTime - visitee.StartTime); _outputHandler.SendNodeValues( visitee.Name, "AndNode", visitee.Inputs, visitee.Result, (visitee.EndTime - visitee.StartTime) ); }
private void Initialize() { _prototypes["AND"] = new AndNode(); _prototypes["NOT"] = new NotNode(); _prototypes["NAND"] = new NotAndNode(); _prototypes["NOR"] = new NotOrNode(); _prototypes["OR"] = new OrNode(); _prototypes["PROBE"] = new OutputNode(); _prototypes["INPUT"] = new InputNode(); _prototypes["XOR"] = new XorNode(); _prototypes["NODE"] = new Node(); }
Node expr() { switch (currToken.Type) { case TokenType.IDE: return ide(); case TokenType.LET: Env savedEnv = top; top = new Env(top); Token letToken = match(currToken.Type); IdeNode id = ide(); match(TokenType.EQUAL); Node definition = expr(); top.Put(id.Token, definition.eval()); match(TokenType.IN); Node body = expr(); LetNode let = new LetNode(letToken, id, definition, body, top); top = savedEnv; return let; case TokenType.AND: Token andToken = match(currToken.Type); match(TokenType.OPENB); AndNode and = new AndNode(andToken); while (currToken.Type != TokenType.CLOSEB) { and.addExpression(expr()); if (currToken.Type != TokenType.CLOSEB) match(TokenType.COMMA); } match(TokenType.CLOSEB); return and; case TokenType.BOOL: return new Node(match(currToken.Type)); default: Error("Error: invalid token: " + currToken.Type.ToString()); return null; } }
public void Handle(string instruction) { AbstractNode left = null, right = null; AbstractNode direction = null, action = null, distance = null; // 声明一个栈用以存储抽象语法树 Stack <AbstractNode> nodeStack = new Stack <AbstractNode>(); // 以空格分隔指令字符串 string[] words = instruction.Split(' '); for (int i = 0; i < words.Length; i++) { // 这里采用栈的方式来处理指令,如果遇到"and", // 则将其后的3个单词作为3个终结符表达式连成一个简单句子 // SentenseNode作为"and"的右表达式,而将从栈顶弹出的表达式作为"and"的左表达式, // 最后将"and"表达式压栈 if (words[i].Equals("and", StringComparison.OrdinalIgnoreCase)) { // 弹出栈顶表达式作为左表达式 left = nodeStack.Pop(); // 构造右表达式 string word1 = words[++i]; direction = new DirectionNode(word1); string word2 = words[++i]; action = new ActionNode(word2); string word3 = words[++i]; distance = new DistanceNode(word3); right = new SentenseNode(direction, action, distance); // 新表达式压栈 AndNode newNode = new AndNode(left, right); nodeStack.Push(newNode); } // 如果是从头开始进行解释,则将前3个单词组成一个简单句子SentenseNode并将该句子压栈 else { // 构造左表达式 string word1 = words[i]; direction = new DirectionNode(word1); string word2 = words[++i]; action = new ActionNode(word2); string word3 = words[++i]; distance = new DistanceNode(word3); left = new SentenseNode(direction, action, distance); nodeStack.Push(left); } } // 全部表达式出栈 this.node = nodeStack.Pop(); }
private void Push(Expression node, int depth) { while ((this._tests.Count > 0) && (this._tests.Peek().Depth == depth)) { node = Expression.AndAlso(this._tests.Pop().Node, node); depth++; } AndNode item = new AndNode { Node = node, Depth = depth }; this._tests.Push(item); }
public DomainId <IAndNode> CreateAndOperation( string definition, DomainId <IBooleanLogicNode> leftExpression, DomainId <IBooleanLogicNode> rightExpression) { var andNode = new AndNode( m_ids.Next, definition, leftExpression, rightExpression); return(DomainItemRegistration <IAndNode>(andNode)); }
public void AndNodeTest(bool input1, bool input2, bool expectedOutput) { var node = new AndNode(""); var states = new List <State> { new State(input1), new State(input2) }; node.Calculate(states.ToArray()); Assert.Equal(expectedOutput, node.CurrentState.LogicState); }
public void ContainsParametersReturnsFalseForTreeConsistingOfAndNodes() { // Build tree consisting of two AND nodes. var root = new AndNode(); root.AddChild(new AndNode()); var tree = new ParameterTree(root); // Check that it is recognized as having no parameters. Assert.False( tree.ContainsParameters(), "Parameter tree was wrongly identified as containing parameters."); }
public void ContainsParametersReturnsTrueForTreeContainingParameters() { // Build tree containing a node representing a parameter. var root = new AndNode(); root.AddChild(new ValueNode <int>("parameter", new IntegerDomain())); var tree = new ParameterTree(root); // Check that it is recognized as having parameters. Assert.True( tree.ContainsParameters(), "Parameter tree was wrongly identified as not containing parameters."); }
private IStalkNode NewMultiChildNode(XmlElement fragment) { MultiChildLogicalNode node; switch (fragment.Name) { case "and": node = new AndNode(); break; case "or": node = new OrNode(); break; case "x-of": var xofnode = new XOfStalkNode(); var minAttr = fragment.Attributes["minimum"]; if (minAttr != null) { xofnode.Minimum = XmlConvert.ToInt32(minAttr.Value); } var maxAttr = fragment.Attributes["maximum"]; if (maxAttr != null) { xofnode.Maximum = XmlConvert.ToInt32(maxAttr.Value); } node = xofnode; break; default: throw new XmlException("Unknown element " + fragment.Name); } node.ChildNodes = new List <IStalkNode>(); foreach (XmlNode fragmentChildNode in fragment.ChildNodes) { var elem = fragmentChildNode as XmlElement; if (elem == null) { continue; } var n = this.NewFromXmlFragment(elem); node.ChildNodes.Add(n); } return(node); }
public void IdentifiersAreUniqueReturnsTrueForUniqueIdentifiers() { // Build tree with two parameters having different identifiers. var root = new AndNode(); root.AddChild(new ValueNode <int>("a", new IntegerDomain())); root.AddChild(new ValueNode <int>("b", new IntegerDomain())); var tree = new ParameterTree(root); // Check that this is recognized. Assert.True( tree.IdentifiersAreUnique(), "Parameter tree was wrongly identified as having duplicate identifiers."); }
/// <summary> /// Creates a <see cref="ParameterTree"/> containing parameters of different domain types. /// </summary> /// <returns>The created <see cref="ParameterTree"/>.</returns> private ParameterTree CreateParameterTree() { var root = new AndNode(); root.AddChild(new ValueNode <int>("discrete", new IntegerDomain(-5, 5))); root.AddChild(new ValueNode <double>("continuous", new ContinuousDomain(0, 1.4))); root.AddChild(new ValueNode <double>("categorical", new CategoricalDomain <double>(new List <double> { 123.6, -12.5 }))); root.AddChild(new ValueNode <string>("single_categorical", new CategoricalDomain <string>(new List <string> { "foo" }))); return(new ParameterTree(root)); }
public void Visit(AndNode node) { var set = new HashSet <KeyValuePair <string, Type> >(); foreach (var inner in node.Inner) { inner.Accept(this); foreach (var field in Fields) { set.Add(field); } } Fields = set.ToDictionary(f => f.Key, f => f.Value); }
/// <summary> /// Creates a <see cref="ParameterTree"/> containing parameters of many different domain types. /// </summary> /// <returns>The created <see cref="ParameterTree"/>.</returns> private ParameterTree CreateParameterTree() { var root = new AndNode(); root.AddChild(new ValueNode <int>("a", new IntegerDomain(0, this._minimumDomainSize - 1))); root.AddChild(new ValueNode <int>("b", new IntegerDomain(0, this._minimumDomainSize - 2))); root.AddChild(new ValueNode <double>("e", new ContinuousDomain(0, 1))); root.AddChild(new ValueNode <double>("f", new LogDomain(0.1, 1))); root.AddChild(new ValueNode <int>("c", new DiscreteLogDomain(1, this._minimumDomainSize))); root.AddChild(new ValueNode <int>("d", new DiscreteLogDomain(1, this._minimumDomainSize - 1))); root.AddChild(new ValueNode <double>("aa", new CategoricalDomain <double>(new List <double> { 0d, 1d }))); return(new ParameterTree(root)); }
public void Should_return_composite_descriptor_for_and_node() { AndNode andNode = new AndNode() { First = DateTimeComparison(), Second = StringFunction() }; andNode.Accept(visitor); CompositeFilterDescriptor descriptor = (CompositeFilterDescriptor)visitor.Result; Assert.Equal(FilterCompositionLogicalOperator.And, descriptor.LogicalOperator); Assert.Equal(FilterOperator.IsEqualTo, ((FilterDescriptor)descriptor.FilterDescriptors[0]).Operator); Assert.Equal(FilterOperator.StartsWith, ((FilterDescriptor)descriptor.FilterDescriptors[1]).Operator); }
// throws RecognitionException [1] // $ANTLR end "expr_or" // $ANTLR start "expr_and" // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:100:1: expr_and returns [TigerNode and] : exp1= expr_comp ( AND exp2= expr_comp )* ; public TigerNode expr_and() { TigerNode and = null; IToken AND3 = null; TigerNode exp1 = null; TigerNode exp2 = null; try { // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:100:35: (exp1= expr_comp ( AND exp2= expr_comp )* ) // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:100:37: exp1= expr_comp ( AND exp2= expr_comp )* { PushFollow(FOLLOW_expr_comp_in_expr_and631); exp1 = expr_comp(); state.followingStackPointer--; if (state.failed) return and; if ( (state.backtracking==0) ) { and = exp1; } // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:101:26: ( AND exp2= expr_comp )* do { int alt3 = 2; int LA3_0 = input.LA(1); if ( (LA3_0 == AND) ) { alt3 = 1; } switch (alt3) { case 1 : // C:\\Users\\Danaice\\Desktop\\lastversion\\Dany_gramatica tiger ANTLR oficial\\tiger_grammar.g:101:27: AND exp2= expr_comp { AND3=(IToken)Match(input,AND,FOLLOW_AND_in_expr_and661); if (state.failed) return and; PushFollow(FOLLOW_expr_comp_in_expr_and665); exp2 = expr_comp(); state.followingStackPointer--; if (state.failed) return and; if ( (state.backtracking==0) ) { and = new AndNode(and, exp2); and.Col=AND3.CharPositionInLine; and.Row = AND3.Line; } } break; default: goto loop3; } } while (true); loop3: ; // Stops C# compiler whining that label 'loop3' has no statements } } catch (RecognitionException re) { ReportError(re); Recover(input,re); } finally { } return and; }