Ejemplo n.º 1
1
 protected OperatorGraph(OperatorGraph original, Cloner cloner)
   : base(original, cloner) {
   operators = cloner.Clone(original.operators);
   initialOperator = cloner.Clone(original.initialOperator);
   visualizationInfo = cloner.Clone(original.visualizationInfo);
   Initialize();
 }
Ejemplo n.º 2
0
    public ScriptTypeConvertExpr(AstNodeArgs args)
        : base(args)
    {
      if (ChildNodes.Count == 2)
      {
        if (args.ChildNodes[0] is ScriptExpr &&
            !(args.ChildNodes[1] is ScriptExpr))
        {
          // ( Expr )
          _expr = args.ChildNodes[0] as ScriptExpr;
          _typeExpr = null;
        }
        else
        {
          //(Type) Expr
          _typeExpr = args.ChildNodes[0] as ScriptExpr;
          _expr = args.ChildNodes[1] as ScriptExpr;         
        }
      }
      else
      {
        throw new ScriptSyntaxErrorException(Strings.GrammarErrorExceptionMessage);
      }

      _operator = RuntimeHost.GetBinaryOperator("+");
      if (_operator == null)
        throw new ScriptRuntimeException(string.Format(Strings.MissingOperatorError, "+"));
    }
        public ScriptTypeConvertExpr(AstNodeArgs args)
            : base(args)
        {
            if (ChildNodes.Count == 2)
              {
            if (args.ChildNodes[0] is ScriptExpr &&
            !(args.ChildNodes[1] is ScriptExpr))
            {
              // ( Expr )
              expr = args.ChildNodes[0] as ScriptExpr;
            }
            else
            {
              //(Type) Expr
              typeExpr = args.ChildNodes[0] as ScriptExpr;
              expr = args.ChildNodes[1] as ScriptExpr;
            }
              }
              else
              {
            throw new ScriptException("Grammar error!");
              }

              @operator = RuntimeHost.GetBinaryOperator("+");
              if (@operator == null)
            throw new ScriptException("RuntimeHost did not initialize property. Can't find binary operators.");
        }
Ejemplo n.º 4
0
        public virtual IList<Tour> Create(IPttRequest request, IOperator op, out TourFactoryStatus status)
        {
            if (op.ExtensiveLoggingNeeded)
            {
                Logger.LogProcess("TourFactory.Create trying to get html for " + request.Url + " with postdata:"+request.PostValue);
            }

            var htmlSource = op.RequestResponseBehavior.GetHtmlMaster(request, false, op.ExtensiveLoggingNeeded, op.Name);
            if(op.ExtensiveLoggingNeeded)
            {
                Logger.LogProcess("TourFactory.Create Html coming from htmlmaster");
                Logger.LogProcess(htmlSource ?? "");
            }
            if (string.IsNullOrEmpty(htmlSource))
            {
                status = new TourFactoryStatus { Success = false };
                return null;
            }

            var htmlSourceRefined = op.Refine(request, htmlSource);
            if (op.ExtensiveLoggingNeeded)
            {
                Logger.LogProcess("TourFactory.Create Html refined");
                Logger.LogProcess(htmlSourceRefined ?? "");
            }
            var html = new HtmlDocument();
            html.LoadHtml(htmlSourceRefined);
            var list = GetToursFromHtml(request, op, html, out status);
            return list;
        }
Ejemplo n.º 5
0
		public Expression(IOperator linkingOperator, object leftOperand, IOperator comparisonOperator, object rightOperand)
		{
			this.linkingOperator = linkingOperator;
			this.leftOperand = leftOperand;
			this.comparisonOperator = comparisonOperator;
			this.rightOperand = rightOperand;
		}
Ejemplo n.º 6
0
 public BasicFilter(string name, ITag tag, IOperator filterOperator, string criteria)
     : base(name)
 {
     _tag = tag;
       _operator = filterOperator;
       _tag.attachObserver(this);
       this._criteria = criteria;
 }
Ejemplo n.º 7
0
 internal EditBasicFilter(BasicFilter target, string newName, ITag newTag, IOperator newOperator, string newCriteria)
 {
     _newName = newName;
       _newTag = newTag;
       _newCriteria = newCriteria;
       _target = target;
       _newOperator = newOperator;
 }
Ejemplo n.º 8
0
 public ObjectRule(ISecurityObject iobject,
     IOperator ioperator,
     OperatorMethod method)
 {
     this.securityObject = iobject;
     this.ioperator = ioperator;
     this.method = method;
     this.ruleId = Guid.NewGuid();
 }
Ejemplo n.º 9
0
        public string Calculate(string operandA, string operandB, IOperator operatorForAAndB)
        {
            var A = ConvertFromRomanToArabNumber(operandA);
            var B = ConvertFromRomanToArabNumber(operandB);

            var answerForExpression = operatorForAAndB.CalculateIt(A, B);

            return ConvertFromArabToRomanNumber(answerForExpression);
        }
Ejemplo n.º 10
0
    public ScriptIsExpr(AstNodeArgs args)
      : base(args)
    {
      Debug.Assert(Oper == "is");

      _operator = RuntimeHost.GetBinaryOperator(Oper);
      if (_operator == null)
        throw new ScriptRuntimeException(string.Format(Strings.MissingOperatorError, "is"));
    }
Ejemplo n.º 11
0
 public override IList<Tour> Create(IPttRequest request, IOperator op, out TourFactoryStatus status)
 {
     if(!Biblo.TourDates.Contains(op.QueryObject.StartDate))
     {
         status = new TourFactoryStatus { Success = true, MoveToNextHotel = true};
         return null;
     }
     return base.Create(request, op, out status);
 }
Ejemplo n.º 12
0
        public OperatorViewModel(IOperator currentOperator, IConnection connection)
        {
            if (currentOperator == null)
                throw new ArgumentNullException("currentOperator");
            if (connection == null)
                throw new ArgumentNullException("connection");

            this.connection = connection;
            this.currentOperator = currentOperator;
            this.ChatHistoryRecords = new ObservableCollection<IOperatorChatHistoryRecord>();
        }
Ejemplo n.º 13
0
        public ScriptBinExpr(AstNodeArgs args)
            : base(args)
        {
            left = (ScriptExpr)ChildNodes[0];
              oper = ((Token)ChildNodes[1]).Text;
              right = (ScriptExpr)ChildNodes[2];

              operatorFunction = RuntimeHost.GetBinaryOperator(oper);
              if (operatorFunction == null)
            throw new ScriptException("RuntimeHost did not initialize property. Can't find binary operators.");
        }
Ejemplo n.º 14
0
        public void edit(string newName, ITag newTag, IOperator newFilterOperator, string newCriteria)
        {
            Data.ActionHandler.beginMacro();
              Data.ActionHandler.storeAction(new EditBasicFilter(this, _name, _tag, _operator, _criteria));
              _name = newName;
              _operator = newFilterOperator;
              _criteria = newCriteria;

              _tag.detachObserver(this);
              _tag = newTag;
              _tag.attachObserver(this);
              Data.ActionHandler.endMacro();
        }
Ejemplo n.º 15
0
        internal NodeFuzzyRelation( FuzzyRelation subrelation1, FuzzyRelation subrelation2, IOperator oper)
        {
            if (
                subrelation1 == null ||
                //subrelation2 == null ||
                oper == null)
                throw new ArgumentNullException();

            _subrelation1 = subrelation1;
            _subrelation2 = subrelation2;
            _operator = oper;
            subrelation1.Parent = this;
            if (subrelation2 !=null)
                subrelation2.Parent = this;
        }
Ejemplo n.º 16
0
    public static IOperatorShapeInfo CreateOperatorShapeInfo(IOperator op) {
      IEnumerable<string> operatorParameterNames = op.Parameters.Where(p => p is IValueParameter && typeof(IOperator).IsAssignableFrom(p.DataType)).Select(p => p.Name);
      IEnumerable<string> paramaterNameValues = op.Parameters.Where(p => !(p is IValueParameter && typeof(IOperator).IsAssignableFrom(p.DataType))).Select(p => p.ToString());

      OperatorShapeInfo operatorShapeInfo = new OperatorShapeInfo(operatorParameterNames, paramaterNameValues);
      operatorShapeInfo.AddConnector(PredecessorConnector);
      operatorShapeInfo.Collapsed = true;
      operatorShapeInfo.Title = op.Name;
      operatorShapeInfo.TypeName = op.GetType().GetPrettyName();
      operatorShapeInfo.Color = Color.LightBlue;
      operatorShapeInfo.LineWidth = 1;
      operatorShapeInfo.LineColor = Color.Black;
      operatorShapeInfo.Icon = new Bitmap(op.ItemImage);

      return operatorShapeInfo;
    }
Ejemplo n.º 17
0
    public ScriptBinExpr(AstNodeArgs args)
        : base(args)
    {
      left = (ScriptExpr)ChildNodes[0];
      Oper = ((TokenAst)ChildNodes[1]).Text;
      right = (ScriptExpr)ChildNodes[2];
      
      Value = RuntimeHost.NullValue;
      if (IsConst)
          Evaluation = ConstFirstEvaluate;
      else
          Evaluation = CompleteEvaluate;

      OperatorFunction = RuntimeHost.GetBinaryOperator(Oper);
      if (OperatorFunction == null)
        throw new ScriptRuntimeException(string.Format(Strings.MissingOperatorError, Oper));
    }
Ejemplo n.º 18
0
		public void Parse()
		{
			try
			{
				bracketLevel = 0;
				CharEnumerator experIter = Exper.GetEnumerator();
				if (experIter.MoveNext())
					Parse(experIter, OperatorOrder.NONE, ref op);
				else
					op = new ValOp(0.0);
			}
			catch (System.Exception ex)
			{
				System.Console.WriteLine("Exper = " + Exper);
				throw;
			}
		}
Ejemplo n.º 19
0
        public ScriptAssignExpr(AstNodeArgs args)
            : base(args)
        {
            nameExpr = (ScriptQualifiedName)args.ChildNodes[0];
              oper = ((Token)args.ChildNodes[1]).Text;
              if (args.ChildNodes.Count == 3)
            rightExpr = (ScriptExpr)args.ChildNodes[2];

              Debug.Assert(oper == "=" || oper == ":=" || oper == "+=" || oper == "-=" || oper == "++" || oper == "--" || oper == ":=");

              switch (oper)
              {
            case "=":
              assignOperation = Assign;
              break;
            case ":=":
              assignOperation = AssignEx;
              break;
            case "++":
              assignOperation = PlusPlus;
              break;
            case "--":
              assignOperation = MinusMinus;
              break;
            case "+=":
              assignOperation = PlusEqual;
              break;
            case "-=":
              assignOperation = MinusEqual;
              break;
            default:
              throw new ScriptException("Assignment operator:" + oper + " is not supported");
              }

              minus = RuntimeHost.GetBinaryOperator("-");
              plus = RuntimeHost.GetBinaryOperator("+");

              if (plus == null || minus == null)
            throw new ScriptException("RuntimeHost did not initialize property. Can't find binary operators.");
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 获取拥有的function
        /// </summary>
        /// <param name="operId"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static DataTable GetOwnFunction(IOperator oper, OperatorMethod method)
        {
//            SecurityObjectType objType = SecurityObjectType.Function;

//            string sql = @"select f.functionId,f.FunctionName from accessControlList a,FunctionList f where
//                            a.operatorId=@operId and a.OperatorMethod=@operMethod and a.ObjectType=@objType and a.ObjectId=f.FunctionId";

//            SqlParameter[] Parameters = new SqlParameter[3];


//            Parameters[0] = new SqlParameter("@operId", SqlDbType.UniqueIdentifier);
//            Parameters[1] = new SqlParameter("@operMethod", SqlDbType.TinyInt);
//            Parameters[2] = new SqlParameter("@objType", SqlDbType.TinyInt);


//            Parameters[0].Value = oper.OperatorId;
//            Parameters[1].Value = (int)method;
//            Parameters[2].Value = (int)objType;

//            return SqlHelper.ExecuteDataset(SqlHelper.SqlCon_QJVRMS, CommandType.Text, sql, Parameters).Tables[0];

            FunctionService fs = new FunctionService();
            return fs.GetOwnFunction(oper.OperatorId, (int)method);
        }
Ejemplo n.º 21
0
		private bool Parse(CharEnumerator experIter, IOperator prevOp, out IOperator op)
		{
			if (!SkipSpace(experIter))
			{
				op = null;
				return true;
			}

			bool isEof = false;
			char curCh = experIter.Current;
			switch (curCh)
			{
				case '-':
					isEof = ParseSub(experIter, prevOp, out op);
					break;
				case '+':
					break;
				default:
					op = null;
					break;
			}
			op = null;
			return isEof;
		}
Ejemplo n.º 22
0
 public IAtomicOperation CreateChildOperation(IOperator op)
 {
     return(new ExecutionContext(this, op, scope));
 }
Ejemplo n.º 23
0
 public IAtomicOperation CreateOperation(IOperator op, IScope scope)
 {
     return(new ExecutionContext(parent, op, scope));
 }
Ejemplo n.º 24
0
 /*! This method modifies an operator \f$ L \f$ before the linear
  *  system \f$ Lu' = u \f$ is solved so that \f$ u' \f$ will
  *  satisfy the given condition. */
 public virtual void applyBeforeSolving(IOperator o, Vector v)
 {
     throw new NotSupportedException();
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Gets the heuristic value for the given state.
 /// </summary>
 /// <param name="state">State to be evaluated.</param>
 /// <param name="predecessor">Preceding state.</param>
 /// <param name="appliedOperator">Applied operator from the preceding state.</param>
 /// <returns>Heuristic value for the specified state.</returns>
 protected virtual double GetValueImpl(IState state, IState predecessor, IOperator appliedOperator)
 {
     return(GetValueImpl(state));
 }
Ejemplo n.º 26
0
 public override void applyBeforeApplying(IOperator o)
 {
     return;
 }
 public UnaryExpression(IOperator operation, IExpression value)
 {
     Value     = value;
     Operation = operation;
 }
Ejemplo n.º 28
0
 private SimulatedAnnealingMainLoop FindMainLoop(IOperator start) {
   IOperator mainLoop = start;
   while (mainLoop != null && !(mainLoop is SimulatedAnnealingMainLoop))
     mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
   if (mainLoop == null) return null;
   else return (SimulatedAnnealingMainLoop)mainLoop;
 }
Ejemplo n.º 29
0
        public bool OnMessageRecieved <T>(T msg) where T : class, IActorMessage
        {
            if (msg is ControlMessages.HangUp)
            {
                Broadcast(msg);
                UnRegisterAll();
                msg.Status?.TrySetResult(msg);
                return(true);
            }

            if (IsUsingSingleOperator())
            {
                return(MainOperator.OnMessageRecieved <T>(msg));
            }

            IOperator op = null;

            switch (this.MessageDispatchProcedure)
            {
            case MessageDispatchProcedureType.RandomSelection:
            {
                var handlesType = LocalSwitchboard.HandleValueTypeMessage(typeof(T));

                if (!msgTypeToOperator.ContainsKey(handlesType))
                {
                    throw new NoOperatorRegisteredToSupportTypeException(handlesType.ToString());
                }

                int nextIndex = rand.Next(0, msgTypeToOperator[handlesType].Count - 1);

                op = msgTypeToOperator[handlesType].ElementAt(nextIndex);
            }
            break;

            case MessageDispatchProcedureType.BroadcastToAll:
                return(Broadcast <T>(msg));

            case MessageDispatchProcedureType.RoundRobin:
            {
                var handlesType = msg.GetType();

                if (!msgTypeToOperator.ContainsKey(handlesType))
                {
                    throw new NoOperatorRegisteredToSupportTypeException(handlesType.ToString());
                }
                if (((ConcurrentQueue <IOperator>)msgTypeToOperator[handlesType]).Count == 1)
                {
                    if (!((ConcurrentQueue <IOperator>)msgTypeToOperator[handlesType]).TryPeek(out op))
                    {
                        throw new CouldNotRetrieveNextOperatorFromQueueException();
                    }
                }
                else
                {
                    if (!((ConcurrentQueue <IOperator>)msgTypeToOperator[handlesType]).TryDequeue(out op))
                    {
                        throw new CouldNotRetrieveNextOperatorFromQueueException();
                    }

                    //Re-Add the operator to the bottom of the queue.
                    ((ConcurrentQueue <IOperator>)msgTypeToOperator[handlesType]).Enqueue(op);
                }
            }
            break;

            case MessageDispatchProcedureType.LeastBusy:
            {
                var handlesType = LocalSwitchboard.HandleValueTypeMessage(typeof(T));

                if (!msgTypeToOperator.ContainsKey(handlesType))
                {
                    throw new NoOperatorRegisteredToSupportTypeException(handlesType.ToString());
                }

                ulong leastCount = ulong.MaxValue;
                for (int i = msgTypeToOperator[handlesType].Count - 1; i >= 0 && i < msgTypeToOperator[handlesType].Count; --i)
                {
                    IOperator tempOp = msgTypeToOperator[handlesType].ElementAt(i);

                    if (leastCount > tempOp.Count)
                    {
                        leastCount = tempOp.Count;
                        op         = tempOp;
                    }

                    if (0 == tempOp.Count)
                    {
                        break;
                    }
                }
            }
            break;

            default:
                throw new UnsupportedDispatchImplementationException();
            }

            return(op.OnMessageRecieved <T>(msg));
        }
 private OffspringSelectionEvolutionStrategyMainLoop FindMainLoop(IOperator start) {
   IOperator mainLoop = start;
   while (mainLoop != null && !(mainLoop is OffspringSelectionEvolutionStrategyMainLoop))
     mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
   return (OffspringSelectionEvolutionStrategyMainLoop) mainLoop;
 }
Ejemplo n.º 31
0
        private ParseErrorType HandleFunctionOrIndexer(IOperator operatorNode) {
            // Indexing or function call is performed on the topmost operand which 
            // generally should be a variable or a node that evaluates to it.
            // However, we leave syntax check to separate code.

            IRValueNode operand = this.SafeGetOperand();
            if (operand == null) {
                // Oddly, no operand
                return ParseErrorType.IndentifierExpected;
            }

            operatorNode.LeftOperand = operand;
            operatorNode.AppendChild(operand);
            _operands.Push(operatorNode);

            return ParseErrorType.None;
        }
 private void BuildUp(Token[] tokens, Expression parent)
 {
     while (_tokenIndex < tokens.Length)
     {
         var       token = tokens[_tokenIndex];
         IOperator op    = null;
         if (token.TokenType == TokenType.Operator && OperatorsDict.Instance.TryGetValue(token.Value, out op))
         {
             SetOperatorOnExpression(parent, op);
         }
         else if (token.TokenType == TokenType.Function)
         {
             BuildFunctionExpression(tokens, parent, token.Value);
         }
         else if (token.TokenType == TokenType.OpeningEnumerable)
         {
             _tokenIndex++;
             BuildEnumerableExpression(tokens, parent);
         }
         else if (token.TokenType == TokenType.OpeningParenthesis)
         {
             _tokenIndex++;
             BuildGroupExpression(tokens, parent);
             //if (parent is FunctionExpression)
             //{
             //    return;
             //}
         }
         else if (token.TokenType == TokenType.ClosingParenthesis || token.TokenType == TokenType.ClosingEnumerable)
         {
             break;
         }
         else if (token.TokenType == TokenType.WorksheetQuote)
         {
             var sb = new StringBuilder();
             sb.Append(tokens[_tokenIndex++].Value);
             sb.Append(tokens[_tokenIndex++].Value);
             sb.Append(tokens[_tokenIndex++].Value);
             sb.Append(tokens[_tokenIndex].Value);
             var t = new Token(sb.ToString(), TokenType.ExcelAddress);
             CreateAndAppendExpression(ref parent, t);
         }
         else if (token.TokenType == TokenType.Negator)
         {
             _negateNextExpression = true;
         }
         else if (token.TokenType == TokenType.Percent)
         {
             SetOperatorOnExpression(parent, Operator.Percent);
             if (parent == null)
             {
                 _graph.Add(ConstantExpressions.Percent);
             }
             else
             {
                 parent.AddChild(ConstantExpressions.Percent);
             }
         }
         else
         {
             CreateAndAppendExpression(ref parent, token);
         }
         _tokenIndex++;
     }
 }
Ejemplo n.º 33
0
 public static BasicExpression Apply(IOperator op, BasicExpression x, BasicExpression y)
 {
     return(op.Apply(x, y));
 }
Ejemplo n.º 34
0
 public long Register <T>(IOperator op)
 {
     return(Register <T>(op, true));
 }
        public override IOperation Apply()
        {
            double maxSelPress    = MaximumSelectionPressureParameter.ActualValue.Value;
            double successRatio   = SuccessRatioParameter.ActualValue.Value;
            IScope scope          = ExecutionContext.Scope;
            IScope parents        = scope.SubScopes[0];
            IScope offspring      = scope.SubScopes[1];
            int    populationSize = parents.SubScopes.Count;

            // retrieve actual selection pressure and success ratio
            DoubleValue selectionPressure = SelectionPressureParameter.ActualValue;

            if (selectionPressure == null)
            {
                selectionPressure = new DoubleValue(0);
                SelectionPressureParameter.ActualValue = selectionPressure;
            }
            DoubleValue currentSuccessRatio = CurrentSuccessRatioParameter.ActualValue;

            if (currentSuccessRatio == null)
            {
                currentSuccessRatio = new DoubleValue(0);
                CurrentSuccessRatioParameter.ActualValue = currentSuccessRatio;
            }

            // retrieve next population
            ItemList <IScope> population         = OffspringPopulationParameter.ActualValue;
            ItemList <IScope> virtual_population = OffspringVirtualPopulationParameter.ActualValue;

            IntValue successfulOffspring;

            if (population == null)
            {
                population = new ItemList <IScope>();
                OffspringPopulationParameter.ActualValue = population;
                selectionPressure.Value   = 0; // initialize selection pressure for this round
                currentSuccessRatio.Value = 0; // initialize current success ratio for this round
                successfulOffspring       = new IntValue(0);
                OffspringPopulationWinnersParameter.ActualValue = successfulOffspring;

                virtual_population = new ItemList <IScope>();
                OffspringVirtualPopulationParameter.ActualValue = virtual_population;
            }
            else
            {
                successfulOffspring = OffspringPopulationWinnersParameter.ActualValue;
            }

            int successfulOffspringAdded = 0;

            // implement the ActualValue fetch here - otherwise the parent scope would also be included, given that there may be 1000 or more parents, this is quite unnecessary
            string tname          = SuccessfulOffspringParameter.TranslatedName;
            double tmpSelPress    = selectionPressure.Value;
            double tmpSelPressInc = 1.0 / populationSize;

            for (int i = 0; i < offspring.SubScopes.Count; i++)
            {
                // fetch value
                IVariable tmpVar;
                if (!offspring.SubScopes[i].Variables.TryGetValue(tname, out tmpVar))
                {
                    throw new InvalidOperationException(Name + ": Could not determine if an offspring was successful or not.");
                }
                BoolValue tmp = (tmpVar.Value as BoolValue);
                if (tmp == null)
                {
                    throw new InvalidOperationException(Name + ": The variable that indicates whether an offspring is successful or not must contain a BoolValue.");
                }

                // add to population
                if (tmp.Value)
                {
                    IScope currentOffspring = offspring.SubScopes[i];
                    offspring.SubScopes.RemoveAt(i);
                    i--; // next loop should continue with the subscope at index i which replaced currentOffspring
                    population.Add(currentOffspring);
                    successfulOffspringAdded++;
                }
                else
                {
                    IScope currentOffspring = offspring.SubScopes[i];
                    offspring.SubScopes.RemoveAt(i);
                    i--;
                    virtual_population.Add(currentOffspring); // add to losers pool
                }
                tmpSelPress += tmpSelPressInc;

                double tmpSuccessRatio = (successfulOffspring.Value + successfulOffspringAdded) / ((double)populationSize);
                if (tmpSuccessRatio >= successRatio && (population.Count + virtual_population.Count) >= populationSize)
                {
                    break;
                }
            }
            successfulOffspring.Value += successfulOffspringAdded;

            // calculate actual selection pressure and success ratio
            selectionPressure.Value   = tmpSelPress;
            currentSuccessRatio.Value = successfulOffspring.Value / ((double)populationSize);

            // check if enough children have been generated (or limit of selection pressure or evaluted solutions is reached)
            if (((EvaluatedSolutionsParameter.ActualValue.Value < MaximumEvaluatedSolutionsParameter.ActualValue.Value) &&
                 (selectionPressure.Value < maxSelPress) &&
                 (currentSuccessRatio.Value < successRatio)) ||
                ((population.Count + virtual_population.Count) < populationSize))
            {
                // more children required -> reduce left and start children generation again
                scope.SubScopes.Remove(parents);
                scope.SubScopes.Remove(offspring);
                while (parents.SubScopes.Count > 0)
                {
                    IScope parent = parents.SubScopes[0];
                    parents.SubScopes.RemoveAt(0); // TODO: repeated call of RemoveAt(0) is inefficient?
                    scope.SubScopes.Add(parent);   // order of subscopes is reversed
                }

                IOperator offspringCreator = OffspringCreatorParameter.ActualValue as IOperator;
                if (offspringCreator == null)
                {
                    throw new InvalidOperationException(Name + ": More offspring are required, but no operator specified for creating them.");
                }
                return(ExecutionContext.CreateOperation(offspringCreator)); // this assumes that this operator will be called again indirectly or directly
            }
            else
            {
                // enough children generated
                var fitnessComparer = new FitnessComparer(QualityParameter.TranslatedName, MaximizationParameter.ActualValue.Value);
                population.Sort(fitnessComparer); // sort individuals by descending fitness

                // keeps only the best successRatio * populationSize solutions in the population (the remaining ones are added to the virtual population)
                int removed = 0;
                for (int i = 0; i < population.Count; i++)
                {
                    double tmpSuccessRatio = i / (double)populationSize;
                    if (tmpSuccessRatio > successRatio)
                    {
                        virtual_population.Add(population[i]);
                        removed++;
                    }
                }
                population.RemoveRange(population.Count - removed, removed);

                //fill up population with best remaining children (successful or unsuccessful)
                virtual_population.Sort(fitnessComparer);
                int offspringNeeded = populationSize - population.Count;
                for (int i = 0; i < offspringNeeded && i < virtual_population.Count; i++)
                {
                    population.Add(virtual_population[i]); // children are sorted by descending fitness
                }

                offspring.SubScopes.Clear();
                offspring.SubScopes.AddRange(population);

                scope.Variables.Remove(OffspringPopulationParameter.TranslatedName);
                scope.Variables.Remove(OffspringVirtualPopulationParameter.TranslatedName);
                scope.Variables.Remove(OffspringPopulationWinnersParameter.TranslatedName);
                return(base.Apply());
            }
        }
Ejemplo n.º 36
0
 private TabuSearchMainLoop FindMainLoop(IOperator start) {
   IOperator mainLoop = start;
   while (mainLoop != null && !(mainLoop is TabuSearchMainLoop))
     mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
   if (mainLoop == null) return null;
   else return (TabuSearchMainLoop)mainLoop;
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Core implementation of the visitor functionality.
 /// </summary>
 /// <param name="node">Node to apply the visitor to.</param>
 protected virtual void VisitCore(IOperator node)
 {
 }
Ejemplo n.º 38
0
 public TD_InStorageController(ITD_InStorageBusiness tD_InStorageBus, IOperator op, IServiceProvider svcProvider)
 {
     _tD_InStorageBus = tD_InStorageBus;
     _Op = op;
     this.serviceProvider = svcProvider;
 }
Ejemplo n.º 39
0
 public HomeBusiness(IOperator theOperator)
 {
     _theOperator = theOperator;
 }
Ejemplo n.º 40
0
 public Context(IOperator _operator)
 {
     this._operator = _operator;
 }
Ejemplo n.º 41
0
 public override void applyBeforeSolving(IOperator o, Vector v)
 {
     return;
 }
Ejemplo n.º 42
0
 internal PrefixTerm(IOperator source, string prefix)
     : base(SearchConditionNodeType.Prefix, source)
 {
     ArgumentValidator.EnsureArgumentNotNullOrEmptyOrWhiteSpace(prefix, "prefix");
     Prefix = prefix;
 }
Ejemplo n.º 43
0
        static async Task <int> Main(string[] args)
        {
            IOperator dynamicOperator = null;

            // Setup logging
            using var loggerFactory = SetupLogging(args);
            var logger = loggerFactory.CreateLogger <Program>();

            try
            {
                logger.LogDebug($"Environment variables: {JsonConvert.SerializeObject(Environment.GetEnvironmentVariables())}");

                // Setup termination handlers
                SetupSignalHandlers();

                // Setup the Kubernetes client
                using var client = SetupClient(args);

                // Setup the operator
                var configuration = GetOperatorConfiguration();
                dynamicOperator = new Operator(configuration, client, loggerFactory);
                dynamicOperator.AddControllerOfType <MyDynamicResourceController>();

                // Start the operator
                return(await dynamicOperator.StartAsync());
            }
            catch (Exception exception)
            {
                logger.LogError(exception, "Operator error");
                return(1);
            }

            IKubernetes SetupClient(string[] args)
            {
                // Load the Kubernetes configuration
                KubernetesClientConfiguration config = null;

                if (KubernetesClientConfiguration.IsInCluster())
                {
                    logger.LogDebug("Loading cluster configuration");
                    config = KubernetesClientConfiguration.InClusterConfig();
                }
                else
                {
                    logger.LogDebug("Loading local configuration");
                    config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
                }

                if (logger.IsEnabled(LogLevel.Debug))
                {
                    logger.LogDebug($"Client configuration: {JsonConvert.SerializeObject(config)}");
                }

                return(new Kubernetes(config));
            }

            ILoggerFactory SetupLogging(string[] args)
            {
                if (!System.Enum.TryParse <LogLevel>(Environment.GetEnvironmentVariable("LOG_LEVEL"), true, out LogLevel logLevel))
                {
                    logLevel = LogLevel.Debug;
                }

                var loggerFactory = LoggerFactory.Create(builder => builder
                                                         .AddConsole(options => options.Format = ConsoleLoggerFormat.Systemd)
                                                         .SetMinimumLevel(logLevel)
                                                         );

                // Enable Kubernetes client logging if level = DEBUG
                ServiceClientTracing.IsEnabled = logLevel <= LogLevel.Debug;
                ServiceClientTracing.AddTracingInterceptor(new ConsoleTracingInterceptor());

                return(loggerFactory);
            }

            void SetupSignalHandlers()
            {
                // SIGTERM: signal the operator to shut down gracefully
                AppDomain.CurrentDomain.ProcessExit += (s, e) =>
                {
                    logger.LogDebug("Received SIGTERM");
                    dynamicOperator?.Stop();
                };

                // SIGINT: try to shut down gracefully on the first attempt
                Console.CancelKeyPress += (s, e) =>
                {
                    bool isFirstSignal = !dynamicOperator.IsDisposing;
                    logger.LogDebug($"Received SIGINT, first signal: {isFirstSignal}");
                    if (isFirstSignal)
                    {
                        e.Cancel = true;
                        Environment.Exit(0);
                    }
                };
            }
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Gets the heuristic value for the given node.
 /// </summary>
 /// <param name="node">Node to be evaluated.</param>
 /// <param name="predecessor">Preceding node.</param>
 /// <param name="appliedOperator">Applied operator from the preceding node.</param>
 /// <returns>Heuristic value for the specified node.</returns>
 public double GetValue(ISearchNode node, ISearchNode predecessor, IOperator appliedOperator)
 {
     // at the moment, specific for states only!
     System.Diagnostics.Debug.Assert(node is IState && predecessor is IState);
     return(GetValue((IState)node, (IState)predecessor, appliedOperator));
 }
Ejemplo n.º 45
0
 public void AcceptOperator(IOperator op)
 => op.Operate(this);
 public F_ShopInfoBusiness(IRepository repository, IOperator op)
     : base(repository)
 {
     operate = op;
 }
 public SystemMenuManage(IOperator @operator, IPermissionManage permissionManage)
 {
     _operator         = @operator;
     _permissionManage = permissionManage;
 }
Ejemplo n.º 48
0
        /// <summary>
        /// Starts the search procedure.
        /// </summary>
        /// <param name="type">Type of search.</param>
        /// <returns>Result of the search.</returns>
        public override ResultStatus Start(SearchType type = SearchType.Forward)
        {
            InitSearch(type);

            List <IOperator> transitionCandidates = new List <IOperator>();

            ISearchNode currentNode = GetInitialNode();

            while (!Problem.IsGoalNode(currentNode))
            {
                if (IsTimeLimitExceeded())
                {
                    return(FinishSearch(ResultStatus.TimeLimitExceeded));
                }

                if (IsMemoryLimitExceeded())
                {
                    return(FinishSearch(ResultStatus.MemoryLimitExceeded));
                }

                LogSearchStatistics();

                transitionCandidates.Clear();
                double    bestCost = double.MaxValue;
                IOperator bestCostOperator;

                foreach (var transition in Problem.GetTransitions(currentNode))
                {
                    IOperator   appliedOperator = transition.GetAppliedOperator();
                    ISearchNode node            = transition.GetTransitionResult();

                    double transitionCost = appliedOperator.GetCost() + Heuristic.GetValue(node);
                    if (transitionCost < bestCost)
                    {
                        bestCost = transitionCost;
                        transitionCandidates.Clear();
                        transitionCandidates.Add(appliedOperator);
                    }
                    else if (transitionCost.Equals(bestCost))
                    {
                        transitionCandidates.Add(appliedOperator);
                    }
                }

                if (transitionCandidates.Count == 0)
                {
                    return(FinishSearch(ResultStatus.NoSolutionFound)); // dead-end reached
                }
                else if (transitionCandidates.Count == 1)
                {
                    bestCostOperator = transitionCandidates[0];
                }
                else
                {
                    bestCostOperator = transitionCandidates[RandomNumberGenerator.Next(transitionCandidates.Count)];
                }

                SolutionPlan.Add(bestCostOperator);
                SolutionCost += bestCostOperator.GetCost();

                currentNode = Apply(currentNode, bestCostOperator);
                ++ProcessedStatesCount;
            }

            if (SearchType != SearchType.Forward)
            {
                SolutionPlan.Reverse();
            }

            return(FinishSearch(ResultStatus.SolutionFound, currentNode));
        }
Ejemplo n.º 49
0
 public TimelineDecomposition(string name, List <ITerm> terms, IOperator init, IOperator dummy, List <IPredicate> Preconditions, List <IPredicate> Effects, int ID)
     : base(name, terms, init, dummy, Preconditions, Effects, ID)
 {
 }
Ejemplo n.º 50
0
        // interface

        /*! This method modifies an operator \f$ L \f$ before it is
         *  applied to an array \f$ u \f$ so that \f$ v = Lu \f$ will
         *  satisfy the given condition. */
        public virtual void applyBeforeApplying(IOperator o)
        {
            throw new NotSupportedException();
        }
Ejemplo n.º 51
0
        private ITextRange GetIndexerOrFunctionErrorRange(ParseContext context, IOperator operatorNode) {
            ITextRange range = null;
            if (operatorNode is Indexer) {
                range = ((Indexer)operatorNode).LeftBrackets;
            } else if (operatorNode is FunctionCall) {
                range = ((FunctionCall)operatorNode).OpenBrace;
            }

            if (range == null) {
                range = context.Tokens.FirstOrDefault((x) => x.Start >= operatorNode.End);
            }

            if (range == null) {
                range = operatorNode;
            }

            return range;
        }
Ejemplo n.º 52
0
 public TimelineDecomposition(IOperator core, List <IPredicate> literals, List <IPlanStep> substeps, List <Tuple <IPlanStep, IPlanStep> > suborderings, List <CausalLink <IPlanStep> > sublinks)
     : base(core, literals, substeps, suborderings, sublinks)
 {
 }
Ejemplo n.º 53
0
        private ParseErrorType ProcessHigherPrecendenceOperators(ParseContext context, IOperator currentOperator) {
            Debug.Assert(_operators.Count > 1);
            ParseErrorType errorType = ParseErrorType.None;
            Association association = currentOperator.Association;

            // At least one operator above sentinel is on the stack.
            do {
                errorType = MakeNode(context);
                if (errorType == ParseErrorType.None) {
                    IOperator nextOperatorNode = _operators.Peek();

                    if (association == Association.Left && nextOperatorNode.Precedence <= currentOperator.Precedence) {
                        break;
                    }

                    if (association == Association.Right && nextOperatorNode.Precedence < currentOperator.Precedence) {
                        break;
                    }
                }
            } while (_operators.Count > 1 && errorType == ParseErrorType.None);

            return errorType;
        }
Ejemplo n.º 54
0
 internal bool TryGetOperator(string operatorName, out IOperator value)
 {
     return(this.registeredOperators.TryGetValue(operatorName, out value));
 }
Ejemplo n.º 55
0
 public Expression(double arg1, double arg2, IOperator o)
 {
     _arg1 = arg1;
     _arg2 = arg2;
     _o = o;
 }
Ejemplo n.º 56
0
 private void graphTreeView_AfterSelect(object sender, TreeViewEventArgs e)
 {
     SelectedOperator = graphTreeView.SelectedNode == null ? null : GetOperatorTag(graphTreeView.SelectedNode);
 }
Ejemplo n.º 57
0
 private void ParameterizeStochasticOperator(IOperator op) {
   if (op is IStochasticOperator) {
     IStochasticOperator stOp = (IStochasticOperator)op;
     stOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
     stOp.RandomParameter.Hidden = true;
   }
 }
Ejemplo n.º 58
0
        private void breakpointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IOperator op = (IOperator)breakpointToolStripMenuItem.Tag;

            op.Breakpoint = breakpointToolStripMenuItem.Checked;
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Obtains a reflection wrapper for an operator.
        /// </summary>
        /// <param name="target">The method, or null if none.</param>
        /// <returns>The reflection wrapper, or null if none.</returns>
        public StaticMethodWrapper Wrap(IOperator target)
        {
            if (target == null)
                return null;

            StaticDeclaredTypeWrapper declaringType = MakeDeclaredTypeWithoutSubstitution(target.GetContainingType());
            return new StaticMethodWrapper(this, target, declaringType, declaringType, declaringType.Substitution);
        }
Ejemplo n.º 60
0
        public override IOperation Apply()
        {
            double maxSelPress  = MaximumSelectionPressureParameter.ActualValue.Value;
            double successRatio = SuccessRatioParameter.ActualValue.Value;
            bool   fillPopulationWithParents = false;

            if (FillPopulationWithParentsParameter.ActualValue != null)
            {
                fillPopulationWithParents = FillPopulationWithParentsParameter.ActualValue.Value;
            }
            IScope scope          = ExecutionContext.Scope;
            IScope parents        = scope.SubScopes[0];
            IScope offspring      = scope.SubScopes[1];
            int    populationSize = parents.SubScopes.Count;

            // retrieve actual selection pressure and success ratio
            DoubleValue selectionPressure = SelectionPressureParameter.ActualValue;

            if (selectionPressure == null)
            {
                selectionPressure = new DoubleValue(0);
                SelectionPressureParameter.ActualValue = selectionPressure;
            }
            DoubleValue currentSuccessRatio = CurrentSuccessRatioParameter.ActualValue;

            if (currentSuccessRatio == null)
            {
                currentSuccessRatio = new DoubleValue(0);
                CurrentSuccessRatioParameter.ActualValue = currentSuccessRatio;
            }

            // retrieve next population
            ItemList <IScope> population = OffspringPopulationParameter.ActualValue;
            IntValue          successfulOffspring;

            if (population == null)
            {
                population = new ItemList <IScope>();
                OffspringPopulationParameter.ActualValue = population;
                selectionPressure.Value   = 0; // initialize selection pressure for this round
                currentSuccessRatio.Value = 0; // initialize current success ratio for this round
                successfulOffspring       = new IntValue(0);
                OffspringPopulationWinnersParameter.ActualValue = successfulOffspring;
            }
            else
            {
                successfulOffspring = OffspringPopulationWinnersParameter.ActualValue;
            }

            int worseOffspringNeeded     = (int)((1 - successRatio) * populationSize) - (population.Count - successfulOffspring.Value);
            int successfulOffspringAdded = 0;

            // implement the ActualValue fetch here - otherwise the parent scope would also be included, given that there may be 1000 or more parents, this is quite unnecessary
            string tname = SuccessfulOffspringParameter.TranslatedName;
            double tmpSelPress = selectionPressure.Value, tmpSelPressInc = 1.0 / populationSize;

            for (int i = 0; i < offspring.SubScopes.Count; i++)
            {
                // fetch value
                IVariable tmpVar;
                if (!offspring.SubScopes[i].Variables.TryGetValue(tname, out tmpVar))
                {
                    throw new InvalidOperationException(Name + ": Could not determine if an offspring was successful or not.");
                }
                BoolValue tmp = (tmpVar.Value as BoolValue);
                if (tmp == null)
                {
                    throw new InvalidOperationException(Name + ": The variable that indicates whether an offspring is successful or not must contain a BoolValue.");
                }

                // add to population
                if (tmp.Value)
                {
                    IScope currentOffspring = offspring.SubScopes[i];
                    offspring.SubScopes.Remove(currentOffspring);
                    i--;
                    population.Add(currentOffspring);
                    successfulOffspringAdded++;
                }
                else if (worseOffspringNeeded > 0 || tmpSelPress >= maxSelPress)
                {
                    IScope currentOffspring;
                    if (!fillPopulationWithParents || worseOffspringNeeded > 0)
                    {
                        currentOffspring = offspring.SubScopes[i];
                        offspring.SubScopes.Remove(currentOffspring);
                        i--;
                        worseOffspringNeeded--;
                    }
                    else
                    {
                        currentOffspring = parents.SubScopes[i];
                    }
                    population.Add(currentOffspring);
                }
                tmpSelPress += tmpSelPressInc;
                if (population.Count == populationSize)
                {
                    break;
                }
            }
            successfulOffspring.Value += successfulOffspringAdded;

            // calculate actual selection pressure and success ratio
            selectionPressure.Value   = tmpSelPress;
            currentSuccessRatio.Value = successfulOffspring.Value / ((double)populationSize);

            // check if enough children have been generated
            if (((selectionPressure.Value < maxSelPress) && (currentSuccessRatio.Value < successRatio)) ||
                (population.Count < populationSize))
            {
                // more children required -> reduce left and start children generation again
                scope.SubScopes.Remove(parents);
                scope.SubScopes.Remove(offspring);
                while (parents.SubScopes.Count > 0)
                {
                    IScope parent = parents.SubScopes[0];
                    parents.SubScopes.RemoveAt(0);
                    scope.SubScopes.Add(parent);
                }

                IOperator moreOffspring = OffspringCreatorParameter.ActualValue as IOperator;
                if (moreOffspring == null)
                {
                    throw new InvalidOperationException(Name + ": More offspring are required, but no operator specified for creating them.");
                }
                return(ExecutionContext.CreateOperation(moreOffspring));
            }
            else
            {
                // enough children generated
                offspring.SubScopes.Clear();
                offspring.SubScopes.AddRange(population);

                scope.Variables.Remove(OffspringPopulationParameter.TranslatedName);
                scope.Variables.Remove(OffspringPopulationWinnersParameter.TranslatedName);
                return(base.Apply());
            }
        }