예제 #1
0
        // Método que realiza o monitoramento e executa as tarefas pendentes autorizadas
        public void monitorAndExecute(System.Diagnostics.EventLog log)
        {
            //string authToken = "uQLhVpS2kx2%2b95sRUwiq1uh8iRycp%2bWro6efT7eNTFM%3d";
            string authToken = "T%2bVgaQPEbcfz%2bMbQPMd38d2pU7wL678T4nHb%2b%2fQjNI8WeISiIPYYh%2f62AqV3Uo0%2b";
            List <AutomaticTask> tarefasAutorizadas = new Business.AutomaticTaskExecution().automaticTaskExecutionList();

            // Se tem tarefas autorizadas
            if (tarefasAutorizadas.Count > 0)
            {
                foreach (AutomaticTask at in tarefasAutorizadas)
                {
                    // Para cada tarefa autorizada por um usuário, verificar a existência destas tarefas em pendência de
                    // execução sob a responsabilidade do usuário que autorizou

                    // Chama query que consulta tarefas pendentes com o codTask e na responsabilidade do usuário em questão
                    List <Data.Task> pendingTasks = new Business.Task().getPendingTasks(at.CodUser, at.CodTask);

                    // Tem dessa tarefa em andamento?
                    // Se sim, // Chamar o apoio à decisão para a tarefa, assim chama uma vez só para várias
                    // Se não tem tarefa pendente, não há por que chamar trecho de apoio à decisão e nem de finalizar
                    if (pendingTasks.Count > 0)
                    {
                        // Número total de execuções da tarefa
                        int totalExecutions = getTotalExecutions(at.CodTask);

                        // Lista de resultados da tarefa
                        List <string> DsFlowResults = getTaskResults(at.CodTask);

                        // Número de possíveis resultados para a tarefa sendo analisada
                        int classCount = DsFlowResults.Count;

                        // Chama a árvore de decisão // TODO: Usar árvore serializada
                        Data.DecisionTree dTree = runDecisionSupport(at.CodTask, totalExecutions, classCount);

                        // Para cada tarefa autorizada e pendente com o usuário, chama o apoio a decisão e depois finaliza a tarefa
                        foreach (Data.Task t in pendingTasks)
                        {
                            // Pegar a sugestão de ação para a tarefa
                            string action = getActionSuggestion(dTree, t.CodFlowExecute);

                            // Cria o objeto de referência ao webservice
                            Instance.Instance inst = new Instance.Instance();
                            //FinalizeTask02 - Finaliza a tarefa
                            XmlNode xml = inst.FinalizeTask02(authToken, t.CodFlowExecuteTask, action, "");

                            if (log != null && xml.Name == "success")
                            {
                                log.WriteEntry("A Tarefa " + t.DsTask + " do processo " + t.CodFlowExecute.ToString() + " foi finalizada automaticamente com a opção " + action + ".");
                            }

                            if (xml.Name == "success")
                            {
                                // Notificar o usuário sobre a conclusão da tarefa
                                new Business.AutomaticTaskExecution().notifyAutomaticExecution(at.CodTask, at.CodUser, t.CodFlowExecute);
                            }
                        }
                    }
                }
            }
        }
예제 #2
0
        /**
         * <summary> Converts discrete attributes of a single instance to binary discrete version using 1-of-L encoding. For example, if
         * an attribute has values red, green, blue; this attribute will be converted to 3 binary attributes where
         * red will have the value true false false, green will have the value false true false, and blue will have the value false false true.</summary>
         *
         * <param name="instance">The instance to be converted.</param>
         */
        protected override void ConvertInstance(Instance.Instance instance)
        {
            var size = instance.AttributeSize();

            for (var i = 0; i < size; i++)
            {
                if (attributeDistributions[i].Count > 0)
                {
                    var index = attributeDistributions[i].GetIndex(instance.GetAttribute(i).ToString());
                    for (var j = 0; j < attributeDistributions[i].Count; j++)
                    {
                        if (j != index)
                        {
                            instance.AddAttribute(new BinaryAttribute(false));
                        }
                        else
                        {
                            instance.AddAttribute(new BinaryAttribute(true));
                        }
                    }
                }
            }

            RemoveDiscreteAttributes(instance, size);
        }
예제 #3
0
        /**
         * <summary> The satisfy method takes an {@link Instance} as an input.
         * <p/>
         * If defined {@link Attribute} value is a {@link DiscreteIndexedAttribute} it compares the index of {@link Attribute} of instance at the
         * attributeIndex and the index of {@link Attribute} value and returns the result.
         * <p/>
         * If defined {@link Attribute} value is a {@link DiscreteAttribute} it compares the value of {@link Attribute} of instance at the
         * attributeIndex and the value of {@link Attribute} value and returns the result.
         * <p/>
         * If defined {@link Attribute} value is a {@link ContinuousAttribute} it compares the value of {@link Attribute} of instance at the
         * attributeIndex and the value of {@link Attribute} value and returns the result according to the comparison character whether it is
         * less than or greater than signs.</summary>
         *
         * <param name="instance">Instance to compare.</param>
         * <returns>True if gicen instance satisfies the conditions.</returns>
         */
        public bool Satisfy(Instance.Instance instance)
        {
            if (_value is DiscreteIndexedAttribute discreteIndexedAttribute)
            {
                if (discreteIndexedAttribute.GetIndex() != -1)
                {
                    return(((DiscreteIndexedAttribute)instance.GetAttribute(_attributeIndex)).GetIndex() ==
                           discreteIndexedAttribute.GetIndex());
                }

                return(true);
            }

            if (_value is DiscreteAttribute discreteAttribute)
            {
                return(((DiscreteAttribute)instance.GetAttribute(_attributeIndex)).GetValue()
                       == discreteAttribute.GetValue());
            }

            if (_value is ContinuousAttribute continuousAttribute)
            {
                if (_comparison == '<')
                {
                    return(((ContinuousAttribute)instance.GetAttribute(_attributeIndex)).GetValue() <=
                           continuousAttribute.GetValue());
                }

                if (_comparison == '>')
                {
                    return(((ContinuousAttribute)instance.GetAttribute(_attributeIndex)).GetValue() >
                           continuousAttribute.GetValue());
                }
            }
            return(false);
        }
        /**
         * <summary> Calculates Euclidian distance between two instances. For continuous features: \sum_{i=1}^d (x_i^(1) - x_i^(2))^2,
         * For discrete features: \sum_{i=1}^d 1(x_i^(1) == x_i^(2))</summary>
         *
         * <param name="instance1">First instance</param>
         * <param name="instance2">Second instance</param>
         * <returns>Euclidian distance between two instances.</returns>
         */
        public double Distance(Instance.Instance instance1, Instance.Instance instance2)
        {
            double result = 0;

            for (var i = 0; i < instance1.AttributeSize(); i++)
            {
                if (instance1.GetAttribute(i) is DiscreteAttribute && instance2.GetAttribute(i) is DiscreteAttribute)
                {
                    if (((DiscreteAttribute)instance1.GetAttribute(i)).GetValue() != null &&
                        string.Compare(((DiscreteAttribute)instance1.GetAttribute(i)).GetValue(),
                                       ((DiscreteAttribute)instance2.GetAttribute(i)).GetValue(), StringComparison.Ordinal) != 0)
                    {
                        result += 1;
                    }
                }
                else
                {
                    if (instance1.GetAttribute(i) is ContinuousAttribute && instance2.GetAttribute(i) is
                        ContinuousAttribute)
                    {
                        result += System.Math.Pow(
                            ((ContinuousAttribute)instance1.GetAttribute(i)).GetValue() -
                            ((ContinuousAttribute)instance2.GetAttribute(i)).GetValue(), 2);
                    }
                }
            }

            return(result);
        }
예제 #5
0
        /**
         * <summary> Adds the attribute types according to given {@link Instance}. For instance, if the attribute type of given {@link Instance}
         * is a Discrete type, it than adds a discrete attribute type to the list of attribute types.</summary>
         *
         * <param name="instance">{@link Instance} input.</param>
         */
        private void SetDefinition(Instance.Instance instance)
        {
            var attributeTypes = new List <AttributeType>();

            for (var i = 0; i < instance.AttributeSize(); i++)
            {
                if (instance.GetAttribute(i) is BinaryAttribute)
                {
                    attributeTypes.Add(AttributeType.BINARY);
                }
                else
                {
                    if (instance.GetAttribute(i) is DiscreteIndexedAttribute)
                    {
                        attributeTypes.Add(AttributeType.DISCRETE_INDEXED);
                    }
                    else
                    {
                        if (instance.GetAttribute(i) is DiscreteAttribute)
                        {
                            attributeTypes.Add(AttributeType.DISCRETE);
                        }
                        else
                        {
                            if (instance.GetAttribute(i) is ContinuousAttribute)
                            {
                                attributeTypes.Add(AttributeType.CONTINUOUS);
                            }
                        }
                    }
                }
            }

            _definition = new DataDefinition(attributeTypes);
        }
        /**
         * <summary> The calculateMetric method takes an {@link Instance} and a String as inputs. It returns the dot product of given Instance
         * and wi plus w0i.</summary>
         *
         * <param name="instance">{@link Instance} input.</param>
         * <param name="Ci">      String input.</param>
         * <returns>The dot product of given Instance and wi plus w0i.</returns>
         */
        protected override double CalculateMetric(Instance.Instance instance, string ci)
        {
            var xi  = instance.ToVector();
            var wi  = w[ci];
            var w0i = w0[ci];

            return(wi.DotProduct(xi) + w0i);
        }
        /**
         * <summary> The calculateRMinusY method creates a new {@link java.util.Vector} with given Instance, then it multiplies given
         * input Vector with given weights Matrix. After normalizing the output, it return the difference between the newly created
         * Vector and normalized output.</summary>
         *
         * <param name="instance">Instance is used to get class labels.</param>
         * <param name="input">   Vector to multiply weights.</param>
         * <param name="weights"> Matrix of weights/</param>
         * <returns>Difference between newly created Vector and normalized output.</returns>
         */
        protected Vector CalculateRMinusY(Instance.Instance instance, Vector input, Matrix weights)
        {
            r = new Vector(K, classLabels.IndexOf(instance.GetClassLabel()), 1.0);
            var o = weights.MultiplyWithVectorFromRight(input);

            y = NormalizeOutput(o);
            return(r.Difference(y));
        }
예제 #8
0
        /**
         * <summary> The calculateMetric method takes an {@link Instance} and a String as inputs. It multiplies Matrix Wi with Vector xi
         * then calculates the dot product of it with xi. Then, again it finds the dot product of wi and xi and returns the summation with w0i.</summary>
         *
         * <param name="instance">{@link Instance} input.</param>
         * <param name="ci">      String input.</param>
         * <returns>The result of Wi.multiplyWithVectorFromLeft(xi).dotProduct(xi) + wi.dotProduct(xi) + w0i.</returns>
         */
        protected override double CalculateMetric(Instance.Instance instance, string ci)
        {
            var xi  = instance.ToVector();
            var Wi  = _W[ci];
            var wi  = w[ci];
            var w0i = w0[ci];

            return(Wi.MultiplyWithVectorFromLeft(xi).DotProduct(xi) + wi.DotProduct(xi) + w0i);
        }
        /**
         * <summary> The calculateMetric method takes an {@link Instance} and a String as inputs and it returns the log likelihood of</summary>
         * these inputs.
         *
         * <param name="instance">{@link Instance} input.</param>
         * <param name="ci">      String input.</param>
         * <returns>The log likelihood of inputs.</returns>
         */
        protected override double CalculateMetric(Instance.Instance instance, string ci)
        {
            if (_classAttributeDistributions == null)
            {
                return(LogLikelihoodContinuous(ci, instance));
            }

            return(LogLikelihoodDiscrete(ci, instance));
        }
예제 #10
0
        /**
         * <summary> The predict method takes an {@link Instance} as an input and finds the nearest neighbors of given instance. Then
         * it returns the first possible class label as the predicted class.</summary>
         *
         * <param name="instance">{@link Instance} to make prediction.</param>
         * <returns>The first possible class label as the predicted class.</returns>
         */
        public override string Predict(Instance.Instance instance)
        {
            var    nearestNeighbors = NearestNeighbors(instance);
            string predictedClass;

            if (instance is CompositeInstance compositeInstance && nearestNeighbors.Size() == 0)
            {
                predictedClass = compositeInstance.GetPossibleClassLabels()[0];
            }
예제 #11
0
        /**
         * <summary> The predict method  performs prediction on the root node of given instance, and if it is null, it returns the possible class labels.
         * Otherwise it returns the returned class labels.</summary>
         *
         * <param name="instance">Instance make prediction.</param>
         * <returns>Possible class labels.</returns>
         */
        public override string Predict(Instance.Instance instance)
        {
            var predictedClass = _root.Predict(instance);

            if (predictedClass == null && instance is CompositeInstance)
            {
                predictedClass = ((CompositeInstance)instance).GetPossibleClassLabels()[0];
            }
            return(predictedClass);
        }
예제 #12
0
        public override Dictionary <string, double> PredictProbability(Instance.Instance instance)
        {
            var distribution = new DiscreteDistribution();

            foreach (var tree in _forest)
            {
                distribution.AddItem(tree.Predict(instance));
            }
            return(distribution.GetProbabilityDistribution());
        }
예제 #13
0
        /**
         * <summary> The predict method takes an {@link Instance} as an input and loops through the {@link ArrayList} of {@link DecisionTree}s.
         * Makes prediction for the items of that ArrayList and returns the maximum item of that ArrayList.</summary>
         *
         * <param name="instance">Instance to make prediction.</param>
         * <returns>The maximum prediction of a given Instance.</returns>
         */
        public override string Predict(Instance.Instance instance)
        {
            var distribution = new DiscreteDistribution();

            foreach (var tree in _forest)
            {
                distribution.AddItem(tree.Predict(instance));
            }
            return(distribution.GetMaxItem());
        }
예제 #14
0
        /**
         * <summary> The convertInstance method takes an {@link Instance} as an input and creates a {@link java.util.Vector} attributes from continuousAttributes.
         * After removing all attributes of given instance, it then adds new {@link ContinuousAttribute} by using the dot
         * product of attributes Vector and the eigenvectors.</summary>
         *
         * <param name="instance">Instance that will be converted to {@link ContinuousAttribute} by using eigenvectors.</param>
         */
        protected override void ConvertInstance(Instance.Instance instance)
        {
            var attributes = new Vector(instance.ContinuousAttributes());

            instance.RemoveAllAttributes();
            foreach (var eigenvector in _eigenvectors)
            {
                instance.AddAttribute(new ContinuousAttribute(attributes.DotProduct(eigenvector)));
            }
        }
        /**
         * <summary> The predict method takes an Instance as an input and returns the entry of distribution which has the maximum value.</summary>
         *
         * <param name="instance">Instance to make prediction.</param>
         * <returns>The entry of distribution which has the maximum value.</returns>
         */
        public override string Predict(Instance.Instance instance)
        {
            if (instance is CompositeInstance compositeInstance)
            {
                var possibleClassLabels = compositeInstance.GetPossibleClassLabels();
                return(_distribution.GetMaxItem(possibleClassLabels));
            }

            return(_distribution.GetMaxItem());
        }
        /**
         * <summary> Calculates Mahalanobis distance between two instances. (x^(1) - x^(2)) S (x^(1) - x^(2))^T</summary>
         *
         * <param name="instance1">First instance.</param>
         * <param name="instance2">Second instance.</param>
         * <returns>Mahalanobis distance between two instances.</returns>
         */
        public double Distance(Instance.Instance instance1, Instance.Instance instance2)
        {
            var v1 = instance1.ToVector();
            var v2 = instance2.ToVector();

            v1.Subtract(v2);
            var v3 = _covarianceInverse.MultiplyWithVectorFromLeft(v1);

            return(v3.DotProduct(v1));
        }
예제 #17
0
        /**
         * <summary> Returns the standard deviation of attributes for instances.</summary>
         *
         * <returns>Standard deviation of attributes for instances.</returns>
         */
        public Instance.Instance StandardDeviation()
        {
            var result = new Instance.Instance(_list[0].GetClassLabel());

            for (var i = 0; i < _list[0].AttributeSize(); i++)
            {
                result.AddAttribute(AttributeStandardDeviation(i));
            }

            return(result);
        }
예제 #18
0
        public override Dictionary <string, double> PredictProbability(Instance.Instance instance)
        {
            var result = new Dictionary <string, double>();

            foreach (string classLabel in _classLabels)
            {
                result[classLabel] = 1.0 / _classLabels.Count;
            }

            return(result);
        }
        /**
         * <summary> The calculateMetric method takes an {@link Instance} and a String as inputs. It loops through the class means, if
         * the corresponding class label is same as the given String it returns the negated distance between given instance and the
         * current item of class means. Otherwise it returns the smallest negative number.</summary>
         *
         * <param name="instance">{@link Instance} input.</param>
         * <param name="Ci">      String input.</param>
         * <returns>The negated distance between given instance and the current item of class means.</returns>
         */
        protected override double CalculateMetric(Instance.Instance instance, string ci)
        {
            for (var i = 0; i < _classMeans.Size(); i++)
            {
                if (_classMeans.Get(i).GetClassLabel() == ci)
                {
                    return(-_distanceMetric.Distance(instance, _classMeans.Get(i)));
                }
            }

            return(double.MinValue);
        }
        /**
         * <summary> The predict method takes an {@link Instance} as an input, converts it to a Vector and calculates the {@link Matrix} y by
         * multiplying Matrix W with {@link Vector} x. Then it returns the class label which has the maximum y value.</summary>
         *
         * <param name="instance">Instance to predict.</param>
         * <returns>The class label which has the maximum y.</returns>
         */
        public override string Predict(Instance.Instance instance)
        {
            CreateInputVector(instance);

            CalculateOutput();
            if (instance is CompositeInstance compositeInstance)
            {
                return(PredictWithCompositeInstance(compositeInstance.GetPossibleClassLabels()));
            }

            return(classLabels[y.MaxIndex()]);
        }
        /**
         * <summary> The logLikelihoodDiscrete method takes an {@link Instance} and a class label as inputs. First it gets the logarithm</summary>
         * of given class label's probability via prior distribution as logLikelihood and gets the class attribute distribution of given class label.
         * Then it loops times of given instance attribute size, and accumulates the logLikelihood by calculating the logarithm of
         * corresponding attribute distribution's smoothed probability by using laplace smoothing on xi.
         *
         * <param name="classLabel">String input class label.</param>
         * <param name="instance">  {@link Instance} input.</param>
         * <returns>The log likelihood of given class label and {@link Instance}.</returns>
         */
        private double LogLikelihoodDiscrete(string classLabel, Instance.Instance instance)
        {
            var logLikelihood          = System.Math.Log(priorDistribution.GetProbability(classLabel));
            var attributeDistributions = _classAttributeDistributions[classLabel];

            for (var i = 0; i < instance.AttributeSize(); i++)
            {
                var xi = ((DiscreteAttribute)instance.GetAttribute(i)).GetValue();
                logLikelihood += System.Math.Log(attributeDistributions[i].GetProbabilityLaplaceSmoothing(xi));
            }

            return(logLikelihood);
        }
예제 #22
0
        /**
         * <summary> Checks given instance's attribute and returns true if it is a discrete indexed attribute, false otherwise.</summary>
         *
         * <param name="instance">Instance to check.</param>
         * <returns>True if instance is a discrete indexed attribute, false otherwise.</returns>
         */
        public bool DiscreteCheck(Instance.Instance instance)
        {
            for (var i = 0; i < instance.AttributeSize(); i++)
            {
                if (instance.GetAttribute(i) is DiscreteAttribute && !(instance.GetAttribute(i) is
                                                                       DiscreteIndexedAttribute))
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #23
0
 /**
  * <summary> Normalizes the continuous attributes of a single instance. For all i, new x_i = (x_i - m_i) / s_i.</summary>
  *
  * <param name="instance">Instance whose attributes will be normalized.</param>
  */
 protected override void ConvertInstance(Instance.Instance instance)
 {
     for (var i = 0; i < instance.AttributeSize(); i++)
     {
         if (instance.GetAttribute(i) is ContinuousAttribute)
         {
             var xi = (ContinuousAttribute)instance.GetAttribute(i);
             var mi = (ContinuousAttribute)_averageInstance.GetAttribute(i);
             var si = (ContinuousAttribute)_standardDeviationInstance.GetAttribute(i);
             xi.SetValue((xi.GetValue() - mi.GetValue()) / si.GetValue());
         }
     }
 }
        /**
         * <summary> The logLikelihoodContinuous method takes an {@link Instance} and a class label as inputs. First it gets the logarithm</summary>
         * of given class label's probability via prior distribution as logLikelihood. Then it loops times of given instance attribute size, and accumulates the
         * logLikelihood by calculating -0.5 * ((xi - mi) / si )** 2).
         *
         * <param name="classLabel">String input class label.</param>
         * <param name="instance">  {@link Instance} input.</param>
         * <returns>The log likelihood of given class label and {@link Instance}.</returns>
         */
        private double LogLikelihoodContinuous(string classLabel, Instance.Instance instance)
        {
            var logLikelihood = System.Math.Log(priorDistribution.GetProbability(classLabel));

            for (var i = 0; i < instance.AttributeSize(); i++)
            {
                var xi = ((ContinuousAttribute)instance.GetAttribute(i)).GetValue();
                var mi = _classMeans[classLabel].GetValue(i);
                var si = _classDeviations[classLabel].GetValue(i);
                logLikelihood += -0.5 * System.Math.Pow((xi - mi) / si, 2);
            }

            return(logLikelihood);
        }
        public override Dictionary <string, double> PredictProbability(Instance.Instance instance)
        {
            CreateInputVector(instance);

            CalculateOutput();
            var result = new Dictionary <string, double>();

            for (var i = 0; i < classLabels.Count; i++)
            {
                result[classLabels[i]] = y.GetValue(i);
            }

            return(result);
        }
예제 #26
0
 /**
  * <summary> Adds a new instance to the {@link InstanceList}.</summary>
  *
  * <param name="current">{@link Instance} to add.</param>
  */
 public void AddInstance(Instance.Instance current)
 {
     if (_definition == null)
     {
         SetDefinition(current);
         _instances.Add(current);
     }
     else
     {
         if (CheckDefinition(current))
         {
             _instances.Add(current);
         }
     }
 }
        /**
         * <summary> The removeDiscreteAttributes method takes an {@link Instance} as an input, and removes the discrete attributes from
         * given instance.</summary>
         *
         * <param name="instance">Instance to removes attributes from.</param>
         * <param name="size">    Size of the given instance.</param>
         */
        protected void RemoveDiscreteAttributes(Instance.Instance instance, int size)
        {
            var k = 0;

            for (var i = 0; i < size; i++)
            {
                if (attributeDistributions[i].Count > 0)
                {
                    instance.RemoveAttribute(k);
                }
                else
                {
                    k++;
                }
            }
        }
예제 #28
0
 /**
  * <summary> The predict method gets an Instance as an input and retrieves the possible class labels as an List. Then selects a
  * random number as an index and returns the class label at this selected index.</summary>
  *
  * <param name="instance">{@link Instance} to make prediction.</param>
  * <returns>The class label at the randomly selected index.</returns>
  */
 public override string Predict(Instance.Instance instance)
 {
     if (instance is CompositeInstance compositeInstance)
     {
         var possibleClassLabels = compositeInstance.GetPossibleClassLabels();
         var size  = possibleClassLabels.Count;
         var index = random.Next(size);
         return(possibleClassLabels[index]);
     }
     else
     {
         var size  = _classLabels.Count;
         var index = random.Next(size);
         return(_classLabels[index]);
     }
 }
        /**
         * <summary> Converts discrete attributes of a single instance to indexed version.</summary>
         *
         * <param name="instance">The instance to be converted.</param>
         */
        protected override void ConvertInstance(Instance.Instance instance)
        {
            var size = instance.AttributeSize();

            for (var i = 0; i < size; i++)
            {
                if (attributeDistributions[i].Count > 0)
                {
                    var index = attributeDistributions[i].GetIndex(instance.GetAttribute(i).ToString());
                    instance.AddAttribute(new DiscreteIndexedAttribute(instance.GetAttribute(i).ToString(), index,
                                                                       attributeDistributions[i].Count));
                }
            }

            RemoveDiscreteAttributes(instance, size);
        }
        public Dictionary <string, double> PredictProbabilityDistribution(Instance.Instance instance)
        {
            if (_leaf)
            {
                return(_data.ClassDistribution().GetProbabilityDistribution());
            }

            foreach (var node in _children)
            {
                if (node._condition.Satisfy(instance))
                {
                    return(node.PredictProbabilityDistribution(instance));
                }
            }

            return(_data.ClassDistribution().GetProbabilityDistribution());
        }