public static FGUISystem createFGUISystem(FuzzySystem system)
 {
     GameObject go = (GameObject)Instantiate(prefabFGUISystem);
     FGUISystem gui = go.GetComponent<FGUISystem>();
     gui.setSystem(system);
     return gui;
 }
Exemple #2
0
        private void TypeBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If Mamdani/Larsen selected
            if ((FuzzyType)e.AddedItems[0] == FuzzyType.Mamdani || (FuzzyType)e.AddedItems[0] == FuzzyType.Larsen)
            {
                if (FuzzySystem.StringToImpMethod(ImpBox.Text) == ImpMethodType.prod)
                {
                    ImpBox.SelectedItem = ImpMethodType.min;
                }
                if (FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text) == DefuzzMethodType.wtaver || FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text) == DefuzzMethodType.wtsum)
                {
                    DefuzzBox.SelectedItem = DefuzzMethodType.COG;
                }
            }

            // If Sugeno selected
            if ((FuzzyType)e.AddedItems[0] == FuzzyType.Sugeno)
            {
                if (FuzzySystem.StringToImpMethod(ImpBox.Text) == ImpMethodType.min || FuzzySystem.StringToImpMethod(ImpBox.Text) == ImpMethodType.max)
                {
                    ImpBox.SelectedItem = ImpMethodType.prod;
                }
                if (FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text) == DefuzzMethodType.COA || FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text) == DefuzzMethodType.COG || FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text) == DefuzzMethodType.MOM || FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text) == DefuzzMethodType.LOM || FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text) == DefuzzMethodType.SOM)
                {
                    DefuzzBox.SelectedItem = DefuzzMethodType.wtaver;
                }
            }
        }
Exemple #3
0
        private void CalculateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FuzzySystem fuzzy = FuzzyReader.GetFuzzySystemFromFile(FuzzySystemText.Text);
                fuzzy.LoadInputsAndSaveOutputs(InputValuesText.Text, "FuzzySystemTemporaryTestOutputFile.temp.del");
                float MSE = FuzzySystem.GetOutputFilesMSE(OutputValuesText.Text, "FuzzySystemTemporaryTestOutputFile.temp.del");
                if (File.Exists("FuzzySystemTemporaryTestOutputFile.temp.del"))
                {
                    File.Delete("FuzzySystemTemporaryTestOutputFile.temp.del");
                }

                MSEText.Text   = MSE.ToString(CultureInfo.InvariantCulture);
                RMSEText.Text  = Math.Sqrt(MSE).ToString(CultureInfo.InvariantCulture);
                RMSEPText.Text = (Math.Sqrt(MSE) / (fuzzy.Outputs[0].Range[1] - fuzzy.Outputs[0].Range[0]) * 100.0f).ToString(CultureInfo.InvariantCulture);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                if (File.Exists("FuzzySystemTemporaryTestOutputFile.temp.del"))
                {
                    File.Delete("FuzzySystemTemporaryTestOutputFile.temp.del");
                }
                return;
            }
        }
Exemple #4
0
        private double FitnessFunctionMSE(ArrayList ActualParameters)
        {
            FuzzySystem tempFuz = GetModifiedFuzzySystem(ActualParameters);

            float MSE        = 0.0f;
            bool  readFailed = false;

            Dispatcher.Invoke(() =>
            {
                try
                {
                    tempFuz.LoadInputsAndSaveOutputs(InputFileTextBox.Text, OutputFileTextBox.Text.Replace(".txt", ".generated.txt"));
                    MSE = FuzzySystem.GetOutputFilesMSE(OutputFileTextBox.Text, OutputFileTextBox.Text.Replace(".txt", ".generated.txt"));
                }
                catch (Exception exc)
                {
                    readFailed     = true;
                    Optimizer.Stop = true;
                    MessageBox.Show(exc.Message, "Error", MessageBoxButton.OK);
                }
            });

            if (readFailed)
            {
                return(double.NaN);
            }

            //return (double)Math.Sqrt((double)MSE);
            return((double)MSE);
        }
Exemple #5
0
    public FuzzyRule(string ruleStr, FuzzySystem fuzzySystem)
    {
        // To Uppercase
        ruleStr = ruleStr.ToUpper();

        // Split premises and conclusion
        String[] rule = ruleStr.Split(new String[] { " THEN " }, StringSplitOptions.RemoveEmptyEntries);
        if (rule.Length == 2)
        {
            // Compute and add premises
            rule[0] = rule[0].Remove(0, 2); // On enlève "IF"
            String[] prem = rule[0].Trim().Split(new String[] { " AND " }, StringSplitOptions.RemoveEmptyEntries);
            Premises = new List <FuzzyExpression>();
            foreach (String exp in prem)
            {
                String[] res = exp.Split(new String[] { " IS " }, StringSplitOptions.RemoveEmptyEntries);
                if (res.Length == 2)
                {
                    FuzzyExpression fexp = new FuzzyExpression(fuzzySystem.LinguisticVariableByName(res[0]), res[1]);
                    Premises.Add(fexp);
                }
            }
            // Add conclusion
            String[] conclu = rule[1].Split(new String[] { " IS " }, StringSplitOptions.RemoveEmptyEntries);
            if (conclu.Length == 2)
            {
                Conclusion = new FuzzyExpression(fuzzySystem.LinguisticVariableByName(conclu[0]), conclu[1]);
            }
        }
    }
Exemple #6
0
        // <DELAYER>

        /*private int delayer()
         * {
         *  System.Threading.Thread.Sleep(15000);
         *  return 0;
         * }*/
        // </DELAYER>

        private void OnNewGeneration(object sender, ArrayList Antibodies, double[] affinities)
        {
            // Update output window text
            string text = "";

            for (int i = 0; i < Antibodies.Count; i++)
            {
                text += ("Parameters: " + List(((IElement)Antibodies[i]).Position) + " \tFitness: " + affinities[i].ToString() + "\r\n");
            }
            ProgressWindow.UpdateText(text);
            ProgressWindow.UpdateImage(affinities[0]);

            // Update graphical windows
            FuzzySystem tempFuz = GetModifiedFuzzySystem(((IElement)Antibodies[0]).Position);

            for (int i = 0; i < tempFuz.Inputs.Length; i++)
            {
                IoputMfWindows[i].ShowNewIoput(tempFuz.Inputs[i]);
            }
            for (int i = 0; i < tempFuz.Outputs.Length; i++)
            {
                IoputMfWindows[tempFuz.Inputs.Length + i].ShowNewIoput(tempFuz.Outputs[i]);
            }

            float RMSEP = (float)affinities[0] / (tempFuz.Outputs[0].Range[1] - tempFuz.Outputs[0].Range[0]) * 100.0f;
        }
Exemple #7
0
    private Dictionary<string, FuzzyVariable> variables; // TODO: maybe put this in the Fuzzy system?

    #endregion Fields

    #region Methods

    public void Start()
    {
        this.system = new FuzzySystem("TestFuzzySystem");
        this.variables = new Dictionary<string, FuzzyVariable>();

        testRead();

        testGUI();

        //testFuzzy();

        //testWrite();
    }
Exemple #8
0
        public void LoadFuzzyFile(string FileName)
        {
            StreamReader reader = new StreamReader(FileName);

            FuzzyBox.Text = reader.ReadToEnd();
            reader.Close();

            SaveButton.IsEnabled = true;
            UseButton.IsEnabled  = true;

            //fuzzySystem = new FuzzySystem();
            try
            {
                fuzzySystem = FuzzyReader.GetFuzzySystemFromFile(FileName);
            }
            catch (Exception exc)
            {
                fuzzySystem = null;
                MessageBox.Show("Failed to load fuzzy system.\r\n" + (exc != null ? exc.Message : ""), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            StringReader strRead = new StringReader(FuzzyBox.Text);
            string       str     = "";

            while ((str = strRead.ReadLine()) != null)
            {
                if (str.StartsWith("MF"))
                {
                    if (str.Contains("!"))
                    {
                        IncludeValuesCheckBox.IsChecked = true;
                    }
                    else
                    {
                        IncludeValuesCheckBox.IsChecked = false;
                    }
                    break;
                }
            }
            strRead.Close();

            CheckPreparation(null, null);
        }
Exemple #9
0
 // Start is called before the first frame update
 void Awake()
 {
     fuzzySystem = GetComponent <FuzzySystem>();
     fuzzySystem.FunctionCurve  = inputCurve;
     fuzzySystem.FuzzyRulesList = rulesList;
 }
Exemple #10
0
        private async void OptimizeButton_Click(object sender, RoutedEventArgs e)
        {
            /*if (fuzzySystem.Type == FuzzyType.Sugeno && CheckOutput.IsChecked == true)
             * {
             *  MessageBox.Show("Output optimization is not valid for Sugeno-type fuzzy systems.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
             *  return;
             * }*/

            // Disable the optimize button and the optimization parameters
            OptimizeButton.IsEnabled = false;
            UseButton.IsEnabled      = false;
            RadioBaseRatio.IsEnabled = false;
            RadioRefPoint.IsEnabled  = false;
            CheckInput.IsEnabled     = false;
            CheckOutput.IsEnabled    = false;
            // Initialize variables
            ArrayList initParams = new ArrayList();
            ArrayList lbp        = new ArrayList();
            ArrayList ubp        = new ArrayList();

            // Set up initial parameters
            if (CheckInput.IsChecked == true)
            {
                foreach (InputOutput input in fuzzySystem.Inputs)
                {
                    foreach (MembershipFunction MF in input.MFs)
                    {
                        if (RadioRefPoint.IsChecked == true)
                        {
                            initParams.Add((double)(MF.GetReferencePoint()));
                            lbp.Add((double)(input.Range[0]));
                            ubp.Add((double)(input.Range[1]));
                        }
                        if (RadioBaseRatio.IsChecked == true)
                        {
                            initParams.Add((double)(MF.GetTrapBaseRatio()));
                            lbp.Add(0.0);
                            ubp.Add(0.95);
                        }
                    }
                }
            }
            if (CheckOutput.IsChecked == true)
            {
                foreach (InputOutput output in fuzzySystem.Outputs)
                {
                    foreach (MembershipFunction MF in output.MFs)
                    {
                        if (RadioRefPoint.IsChecked == true)
                        {
                            initParams.Add((double)(MF.GetReferencePoint()));
                            lbp.Add((double)(output.Range[0]));
                            ubp.Add((double)(output.Range[1]));
                        }
                        if (RadioBaseRatio.IsChecked == true)
                        {
                            initParams.Add((double)(MF.GetTrapBaseRatio()));
                            lbp.Add(0.0);
                            ubp.Add(0.95);
                        }
                    }
                }
            }

            bool[] ints = new bool[initParams.Count];

            // Set up the optimizer object depending on the settings
            switch (MethodId)
            {
            case 0:     //Firework
                Optimizer = new Firework
                {
                    // Number of particles in the swarm.
                    NumberOfElements = NA,
                    m    = m,
                    ymax = double.MaxValue,
                    a    = a,
                    b    = b,
                    Amax = Amax,
                    mhat = mhat,
                    Slow = false
                };
                break;

            case 1:     //Particle Swarm
                Optimizer = new ParticleSwarm
                {
                    // Number of particles in the swarm.
                    NumberOfElements = NA,
                    c0 = c0,
                    // Multiplication factor for the distance to the personal best position.
                    cp = cp,
                    // Multiplication factor for the distance to the global best position.
                    cg   = cg,
                    Slow = false
                };
                break;

            case 2:     //Clonal generation
                if (cgn > NA)
                {
                    MessageBox.Show("Number of antibodies selected for cloning at the end of each generation greater than the number of antibodies.", "ERROR", MessageBoxButton.OK);
                    OptimizeButton.IsEnabled = true;
                    return;
                }
                Optimizer = new ClonalGeneration
                {
                    // Size of the antibody pool.
                    NumberOfElements = NA,
                    // Number of antibodies selected for cloning.
                    NumberSelectedForCloning = cgn,
                    // Parameter determining the number of clones created for an antibody that was selected for cloning. (0,1]
                    Beta = beta,
                    // Number of antibodies created with random parameters in each new generation.
                    RandomAntibodiesPerGeneration = d,
                    // Mutation coefficient (0,1].
                    Ro   = ro,
                    Slow = false
                };
                break;

            case 3:
                Optimizer = new GeneticAlgorithm
                {
                    // Size of the individual pool.
                    NumberOfElements = NA,
                    // Number of parents in each generation.
                    ParentsInEachGeneration = P,
                    // The probability of mutation.
                    MutationProbability = pm,
                    // The number of crossovers in each generation.
                    CrossoverPerGeneration = crossoverCount,
                    Slow = false
                };
                break;

            case 4:     //Clonal generation
                if (cgn > NA)
                {
                    MessageBox.Show("Number of antibodies selected for cloning at the end of each generation greater than the number of antibodies.", "ERROR", MessageBoxButton.OK);
                    OptimizeButton.IsEnabled = true;
                    return;
                }
                Optimizer = new ClonalGenerationLocal
                {
                    // Size of the antibody pool.
                    NumberOfElements = NA,
                    // Number of antibodies selected for cloning.
                    NumberSelectedForCloning = cgn,
                    // Parameter determining the number of clones created for an antibody that was selected for cloning. (0,1]
                    Beta = beta,
                    // Number of antibodies created with random parameters in each new generation.
                    RandomAntibodiesPerGeneration = d,
                    // Mutation coefficient (0,1].
                    Ro = ro,
                    // Local searches per generation
                    LocalSearchesPerGeneration = cgln,
                    Slow = false
                };
                break;
            }

            // Set common parameters
            Optimizer.InitialParameters = initParams;
            Optimizer.LowerParamBounds  = lbp;
            Optimizer.UpperParamBounds  = ubp;
            // Bounds are required before setting this value
            if (MethodId == 4)
            {
                ((ClonalGenerationLocal)Optimizer).StepSizeRelative = cglssr;
            }
            Optimizer.Integer                     = ints;
            Optimizer.FitnessFunction             = FitnessFunctionMSE;
            Optimizer.StoppingNumberOfGenerations = StopGenerationNumber;
            Optimizer.StoppingNumberOfEvaluations = StopAffinityEvaluation;
            Optimizer.StoppingFitnessTreshold     = StopFitnessTreshold;
            Optimizer.StoppingType                = StopType;

            // Output string
            string outstr = "Initial parameters: " + List(initParams) + "\r\n";

            // Open progress window and begin the optimization
            ProgressWindow           = new OptimizationProgressWindow();
            ProgressWindow.OptWindow = this;
            ProgressWindow.Show();
            if (IoputMfWindows != null)
            {
                foreach (MFsPreviewWindow window in IoputMfWindows)
                {
                    window.Close();
                }
            }
            IoputMfWindows = new List <MFsPreviewWindow>();
            foreach (InputOutput input in fuzzySystem.Inputs)
            {
                IoputMfWindows.Add(new MFsPreviewWindow(input));
                IoputMfWindows[IoputMfWindows.Count - 1].Show();
            }
            foreach (InputOutput output in fuzzySystem.Outputs)
            {
                IoputMfWindows.Add(new MFsPreviewWindow(output));
                IoputMfWindows[IoputMfWindows.Count - 1].Show();
            }
            Optimizer.GenerationCreated += OnNewGeneration;
            // <DELAYER>

            /*var z = Task.Run(() => (delayer()));
             * int y = await z;*/
            // </DELAYER>
            var x       = Task.Run(() => (Optimizer.Optimize()));
            var Results = await x;

            ProgressWindow.Close();

            // Add results to output string
            outstr += "Initial MSE: " + Results.InfoList[InfoTypes.InitialFitness] + "\r\n" +
                      "Final parameters: " + List(Results.OptimizedParameters) + "\r\n" +
                      "Final MSE: " + $"{Results.InfoList[InfoTypes.FinalFitness],10:F6}" + "\r\n" +
                      "Number of generations: " + Results.InfoList[InfoTypes.Generations] + "\r\n" +
                      "Number of fitness evaluations: " + Results.InfoList[InfoTypes.Evaluations] + "\r\n" +
                      "Best affinities in each generation: " + List((ArrayList)Results.InfoList[InfoTypes.Affinities]) + "\r\n" +
                      "Optimization time in milliseconds: " + Results.InfoList[InfoTypes.ExecutionTime];

            fuzzySystem   = GetModifiedFuzzySystem(Results.OptimizedParameters);
            FuzzyBox.Text = fuzzySystem.ToString();

            // Display results and reenable the optimize button
            MessageBox.Show(outstr, "Optimization finished", MessageBoxButton.OK);
            OptimizeButton.IsEnabled = true;
            UseButton.IsEnabled      = true;
            RadioBaseRatio.IsEnabled = true;
            RadioRefPoint.IsEnabled  = true;
            CheckInput.IsEnabled     = true;
            CheckOutput.IsEnabled    = true;
        }
Exemple #11
0
        private void InitializeFuzzySystem()
        {
            switch (FuzzySystem.StringToFuzzyType(TypeBox.Text))
            {
            case FuzzyType.Mamdani:
                fuzzySystem = new MamdaniFS();
                break;

            case FuzzyType.Larsen:
                fuzzySystem = new LarsenFS();
                break;

            case FuzzyType.Sugeno:
                fuzzySystem = new SugenoFS();
                break;

            case FuzzyType.Sparse:
                break;

            default:
                break;
            }
            //fuzzySystem = new FuzzySystem();

            // Load fuzzysystem data
            fuzzySystem.Name = NameBox.Text;
            //fuzzySystem.Type = FuzzySystem.StringToFuzzyType(TypeBox.Text);
            fuzzySystem.Version      = VersionBox.Text;
            fuzzySystem.AndMethod    = FuzzySystem.StringToAndMethod(AndBox.Text);
            fuzzySystem.OrMethod     = FuzzySystem.StringToOrMethod(OrBox.Text);
            fuzzySystem.AggMethod    = FuzzySystem.StringToAggMethod(AggBox.Text);
            fuzzySystem.ImpMethod    = FuzzySystem.StringToImpMethod(ImpBox.Text);
            fuzzySystem.DefuzzMethod = FuzzySystem.StringToDefuzzMethod(DefuzzBox.Text);

            // Set up the data and declare the arrays
            fuzzySystem.NumInputs = InputTemplates.Count;
            for (int i = 0; i < fuzzySystem.NumInputs; i++)
            {
                fuzzySystem.Inputs[i] = new InputOutput
                {
                    Name    = InputTemplates[i].Name,
                    IsInput = true,
                    Index   = i + 1
                };
            }
            fuzzySystem.NumOutputs = OutputTemplates.Count;
            for (int i = 0; i < fuzzySystem.NumOutputs; i++)
            {
                fuzzySystem.Outputs[i] = new InputOutput
                {
                    Name    = OutputTemplates[i].Name,
                    IsInput = false,
                    Index   = i + 1
                };
            }
            // Set the ranges and NumMF-s
            for (int inputId = 0; inputId < InputTemplates.Count; inputId++)
            {
                try
                {
                    fuzzySystem.Inputs[inputId].Range = new float[] { float.Parse(InputTemplates[inputId].RangeMin.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture), float.Parse(InputTemplates[inputId].RangeMax.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture) };
                }
                catch (Exception exc)
                {
                    if (exc != null)
                    {
                        throw exc;
                    }

                    throw new Exception("Failed to read range from" + fuzzySystem.Inputs[inputId].Name);
                }
                if (fuzzySystem.Inputs[inputId].Range[0] >= fuzzySystem.Inputs[inputId].Range[1])
                {
                    throw new Exception("Incorrect range for" + fuzzySystem.Inputs[inputId].Name);
                }
                fuzzySystem.Inputs[inputId].NumMFs = InputTemplates[inputId].NumMF;
            }
            for (int outputId = 0; outputId < OutputTemplates.Count; outputId++)
            {
                try
                {
                    fuzzySystem.Outputs[outputId].Range = new float[] { float.Parse(OutputTemplates[outputId].RangeMin.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture), float.Parse(OutputTemplates[outputId].RangeMax.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture) };
                }
                catch (Exception exc)
                {
                    if (exc != null)
                    {
                        throw exc;
                    }

                    throw new Exception("Failed to read range from" + fuzzySystem.Inputs[outputId].Name);
                }
                if (fuzzySystem.Outputs[outputId].Range[0] >= fuzzySystem.Outputs[outputId].Range[1])
                {
                    throw new Exception("Incorrect range for" + fuzzySystem.Inputs[outputId].Name);
                    //MessageBox.Show("Incorrect range for " + fuzzySystem.Outputs[outputId].Name, "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                fuzzySystem.Outputs[outputId].NumMFs = OutputTemplates[outputId].NumMF;
            }

            fuzzySystem.GenerateTrapezoidMFs(1.0f / 3.0f, true, fuzzySystem.Type != FuzzyType.Sugeno);
            //if (fuzzySystem.Type == FuzzyType.Sugeno)
            //fuzzySystem.GenerateConstantOutputMFs();
        }
Exemple #12
0
 public void setSystem(FuzzySystem system)
 {
     this.system = system;
     this.name = system.name;
 }
Exemple #13
0
        private FuzzySystem GetModifiedFuzzySystem(ArrayList ActualParameters)
        {
            // Clone fuzzysystem
            FuzzySystem tempFuz = (FuzzySystem)Activator.CreateInstance(fuzzySystem.GetType());

            tempFuz.CopyDataFrom(fuzzySystem);

            /*FuzzySystem tempFuz = null;
             * switch (fuzzySystem.Type)
             * {
             *  case FuzzyType.Mamdani:
             *      tempFuz = new MamdaniFS();
             *      break;
             *  case FuzzyType.Larsen:
             *      tempFuz = new LarsenFS();
             *      break;
             *  case FuzzyType.Sugeno:
             *      tempFuz = new SugenoFS();
             *      break;
             *  case FuzzyType.Sparse:
             *  default:
             *      throw new NotImplementedException();
             *      break;
             * }*/

            // Read settings
            bool In  = false;
            bool Out = false;
            bool RP  = false;

            Dispatcher.Invoke(() =>
            {
                In  = CheckInput.IsChecked == true;
                Out = CheckOutput.IsChecked == true;
                RP  = RadioRefPoint.IsChecked == true;
            });

            // Store the number of MFs handled by the optimization
            int finishedMfCount = 0;

            if (In)
            {
                for (int inputId = 0; inputId < tempFuz.Inputs.Length; inputId++)
                {
                    for (int mfId = 0; mfId < tempFuz.Inputs[inputId].MFs.Length; mfId++)
                    {
                        if (RP)
                        {
                            tempFuz.Inputs[inputId].MFs[mfId] = tempFuz.Inputs[inputId].MFs[mfId].GetAtRefPoint(
                                (float)((double)ActualParameters[finishedMfCount + mfId]));
                        }
                        else
                        {
                            tempFuz.Inputs[inputId].MFs[mfId] = MembershipFunction.CreateTrapezoid(
                                tempFuz.Inputs[inputId].MFs[mfId].GetTrapReferencePoint(),
                                tempFuz.Inputs[inputId].MFs[mfId].GetTrapBottomBase(),
                                tempFuz.Inputs[inputId].MFs[mfId].GetTrapBottomBase() * (float)((double)ActualParameters[finishedMfCount + mfId]));
                        }
                    }
                    finishedMfCount += tempFuz.Inputs[inputId].NumMFs;
                }
            }
            if (Out)
            {
                for (int outputId = 0; outputId < tempFuz.Outputs.Length; outputId++)
                {
                    for (int mfId = 0; mfId < tempFuz.Outputs[outputId].MFs.Length; mfId++)
                    {
                        if (RP)
                        {
                            tempFuz.Outputs[outputId].MFs[mfId] = tempFuz.Outputs[outputId].MFs[mfId].GetAtRefPoint(
                                (float)((double)ActualParameters[finishedMfCount + mfId]));
                        }
                        else
                        {
                            tempFuz.Outputs[outputId].MFs[mfId] = MembershipFunction.CreateTrapezoid(
                                tempFuz.Outputs[outputId].MFs[mfId].GetTrapReferencePoint(),
                                tempFuz.Outputs[outputId].MFs[mfId].GetTrapBottomBase(),
                                tempFuz.Outputs[outputId].MFs[mfId].GetTrapBottomBase() * (float)((double)ActualParameters[finishedMfCount + mfId]));
                        }
                    }
                    finishedMfCount += tempFuz.Outputs[outputId].NumMFs;
                }
            }

            return(tempFuz);
        }
Exemple #14
0
        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            InitializeFuzzySystem();

            // Make sure the selected values are compatible
            {
                bool invalid = true;

                if (fuzzySystem.Type == FuzzyType.Mamdani || fuzzySystem.Type == FuzzyType.Larsen)
                {
                    if (fuzzySystem.DefuzzMethod == DefuzzMethodType.COA || fuzzySystem.DefuzzMethod == DefuzzMethodType.COG || fuzzySystem.DefuzzMethod == DefuzzMethodType.MOM || fuzzySystem.DefuzzMethod == DefuzzMethodType.LOM || fuzzySystem.DefuzzMethod == DefuzzMethodType.SOM)
                    {
                        if (fuzzySystem.ImpMethod == ImpMethodType.min || fuzzySystem.ImpMethod == ImpMethodType.max)
                        {
                            invalid = false;
                        }
                    }
                }

                if (fuzzySystem.Type == FuzzyType.Sugeno)
                {
                    if (fuzzySystem.DefuzzMethod == DefuzzMethodType.wtaver || fuzzySystem.DefuzzMethod == DefuzzMethodType.wtsum)
                    {
                        if (fuzzySystem.ImpMethod == ImpMethodType.prod)
                        {
                            invalid = false;
                        }
                    }
                }

                if (invalid)
                {
                    MessageBox.Show("Incompatible fuzzy system type and defuzzification method.", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }

            var watch = System.Diagnostics.Stopwatch.StartNew();

            List <Rule> rules = new List <Rule>();

            // Generate the rules
            if (fuzzySystem.Type == FuzzyType.Sugeno)
            {
                // Get a list of inputMF-combinations
                int ruleCount = 1;
                for (int inputId = 0; inputId < fuzzySystem.Inputs.Length; inputId++)
                {
                    ruleCount *= fuzzySystem.Inputs[inputId].NumMFs;
                }

                for (int i = 0; i < ruleCount; i++)
                {
                    rules.Add(new Rule());
                    rules[rules.Count - 1].Inputs     = new int[fuzzySystem.Inputs.Length];
                    rules[rules.Count - 1].Inputs[0]  = -1; // Uninitialized rule indicator
                    rules[rules.Count - 1].Outputs    = new int[fuzzySystem.Outputs.Length];
                    rules[rules.Count - 1].Outputs[0] = i + 1;
                }

                // Prepare outputs
                fuzzySystem.Outputs[0].NumMFs = ruleCount;
                for (int mfId = 0; mfId < fuzzySystem.Outputs[0].NumMFs; mfId++)
                {
                    fuzzySystem.Outputs[0].MFs[mfId]      = new MembershipFunction();
                    fuzzySystem.Outputs[0].MFs[mfId].Type = MFtype.constant;
                }

                Random RNG = new Random();
                for (int ruleId = 0; ruleId < rules.Count; ruleId++)
                {
                    bool newRuleFound = true;
                    do
                    {
                        for (int i = 0; i < rules[ruleId].Inputs.Length; i++)
                        {
                            rules[ruleId].Inputs[i] = RNG.Next(fuzzySystem.Inputs[i].NumMFs) + 1;
                        }
                        newRuleFound = true;
                        for (int r = 0; r < ruleId; r++)
                        {
                            if (rules[r].SameInput(rules[ruleId]))
                            {
                                newRuleFound = false;
                            }
                        }
                    }while (!newRuleFound);

                    // For each input combination we calculate their weights at each of the given coordinates

                    List <int>   itrValues = new List <int>();
                    List <float> weights   = new List <float>();

                    for (int itr = 0; itr < InputCoords[0].Count; itr++)
                    {
                        float weight = 1.0f;
                        for (int inputId = 0; inputId < fuzzySystem.NumInputs; inputId++)
                        {
                            weight = Math.Min(weight, fuzzySystem.Inputs[inputId].MFs[rules[ruleId].Inputs[inputId] - 1].GetMembershipValue(InputCoords[inputId][itr]));
                        }

                        // If both weights are >0, we store these weigths (or their min/avg) and the itr value for this combination
                        if (weight > 0.0f)
                        {
                            weights.Add(weight);
                            itrValues.Add(itr);
                        }
                    }

                    // We get the weighed average of the outputs for each combination
                    // Add a new MF to the output with this value, and set the rule to it
                    float result = 0.0f;
                    for (int i = 0; i < weights.Count; i++)
                    {
                        result += weights[i] * OutputCoords[0][itrValues[i]];
                    }
                    result /= weights.Sum();

                    fuzzySystem.Outputs[0].MFs[ruleId].Params[0] = result;
                }

                // Remove invalid rules/outputs (NaN output -> no matching input-output values were found)
                // Make new lists of the valid entries
                List <Rule> validRules = new List <Rule>();
                List <MembershipFunction> validOutputMFs = new List <MembershipFunction>();
                for (int i = 0; i < ruleCount; i++)
                {
                    if (!float.IsNaN(fuzzySystem.Outputs[0].MFs[i].Params[0]))
                    {
                        validRules.Add(rules[i]);
                        validRules[validRules.Count - 1].Outputs[0] = validRules.Count;
                        validOutputMFs.Add(fuzzySystem.Outputs[0].MFs[i]);
                    }
                }
                // Overwrite original arrays with the new ones
                rules = validRules;
                fuzzySystem.Outputs[0].NumMFs = validOutputMFs.Count;
                fuzzySystem.Outputs[0].MFs    = validOutputMFs.ToArray();
            }
            else if (fuzzySystem.Type == FuzzyType.Mamdani || fuzzySystem.Type == FuzzyType.Larsen)
            {
                // for each input-output data we have (rows in the txt)
                for (int itr = 0; itr < InputCoords[0].Count; itr++)
                {
                    // Get the value of each input's MFs at the specified points
                    List <List <float> > MFvalues = new List <List <float> >();   //MFvalues[input id][MF id]
                    // Add a list foreach ioput
                    for (int i = 0; i < fuzzySystem.NumInputs + fuzzySystem.NumOutputs; i++)
                    {
                        MFvalues.Add(new List <float>());
                    }

                    // for each input
                    for (int inputId = 0; inputId < InputCoords.Count; inputId++)
                    {
                        // for each MF
                        for (int mfID = 0; mfID < fuzzySystem.Inputs[inputId].NumMFs; mfID++)
                        {
                            // Get the membership value at the given coordinate
                            MFvalues[inputId].Add(fuzzySystem.Inputs[inputId].MFs[mfID].GetMembershipValue(InputCoords[inputId][itr]));
                        }
                    }

                    // for each output
                    for (int outputId = 0; outputId < OutputCoords.Count; outputId++)
                    {
                        // for each MF
                        for (int mfID = 0; mfID < fuzzySystem.Outputs[outputId].NumMFs; mfID++)
                        {
                            // Get the membership value at the given coordinate
                            MFvalues[fuzzySystem.NumInputs + outputId].Add(fuzzySystem.Outputs[outputId].MFs[mfID].GetMembershipValue(OutputCoords[outputId][itr]));
                        }
                    }

                    // Check if we have a NaN
                    bool hasNaN = false;
                    foreach (List <float> MFlist in MFvalues)
                    {
                        foreach (float f in MFlist)
                        {
                            if (float.IsNaN(f))
                            {
                                hasNaN = true;
                            }
                        }
                    }
                    if (hasNaN)
                    {
                        continue;
                    }

                    // Get each input's MF where the membership was the highest (randomly chosen if equal)
                    int[] highestMF = new int[fuzzySystem.NumInputs + fuzzySystem.NumOutputs];
                    for (int k = 0; k < fuzzySystem.NumInputs; k++)
                    {
                        // Find highest membership value
                        float highestVal = MFvalues[k][0];
                        for (int l = 1; l < fuzzySystem.Inputs[k].NumMFs; l++)
                        {
                            highestVal = Math.Max(MFvalues[k][l], highestVal);
                        }
                        // Find MFs that have the highest membership value we just found
                        List <int> MFsWithHighestVal = new List <int>();
                        for (int l = 0; l < fuzzySystem.Inputs[k].NumMFs; l++)
                        {
                            if (MFvalues[k][l] == highestVal)
                            {
                                MFsWithHighestVal.Add(l);
                            }
                        }
                        // Choose a random one of them
                        highestMF[k] = MFsWithHighestVal[(new Random()).Next(MFsWithHighestVal.Count)];
                    }
                    // Get each output's highest MF index
                    for (int k = 0; k < fuzzySystem.NumOutputs; k++)
                    {
                        // Find highest membership value
                        float highestVal = MFvalues[fuzzySystem.NumInputs + k][0];
                        for (int l = 1; l < fuzzySystem.Outputs[k].NumMFs; l++)
                        {
                            highestVal = Math.Max(MFvalues[fuzzySystem.NumInputs + k][l], highestVal);
                        }
                        // Find MFs that have the highest membership value we just found
                        List <int> MFsWithHighestVal = new List <int>();
                        for (int l = 0; l < fuzzySystem.Outputs[0].NumMFs; l++)
                        {
                            if (MFvalues[fuzzySystem.NumInputs + k][l] == highestVal)
                            {
                                MFsWithHighestVal.Add(l);
                            }
                        }
                        // Choose a random one of them
                        highestMF[fuzzySystem.NumInputs + k] = MFsWithHighestVal[(new Random()).Next(MFsWithHighestVal.Count)];
                    }
                    // Create rule
                    Rule newRule = new Rule()
                    {
                        ConnectionType = 1,
                        Inputs         = new int[fuzzySystem.NumInputs],
                        Outputs        = new int[fuzzySystem.NumOutputs],
                        Weight         = 1.0f
                    };
                    for (int i = 0; i < fuzzySystem.NumInputs; i++)
                    {
                        newRule.Inputs[i] = highestMF[i] + 1;
                    }
                    for (int i = 0; i < fuzzySystem.NumOutputs; i++)
                    {
                        newRule.Outputs[i] = highestMF[fuzzySystem.NumInputs + i] + 1;
                    }

                    // Add to rule list if the inputs don't match any existing rule
                    bool isRuleNew = true;
                    foreach (Rule rule in rules)
                    {
                        if (rule.SameInput(newRule))
                        {
                            isRuleNew = false;
                            break;
                        }
                    }
                    if (isRuleNew)
                    {
                        rules.Add(newRule);
                    }
                }
            }

            foreach (Rule rule in rules)
            {
                rule.ConnectionType = 1;
                rule.Weight         = 1.0f;
            }
            fuzzySystem.Rules = rules.ToArray();

            watch.Stop();

            GeneratedFuzzyBox.Text = fuzzySystem.ToString(IncludeValuesCheckBox.IsChecked == true);

            SaveButton.IsEnabled     = true;
            OptimizeButton.IsEnabled = true;
            UseButton.IsEnabled      = true;

            float MSE;

            try
            {
                fuzzySystem.LoadInputsAndSaveOutputs(InputFileTextBox.Text, OutputFileTextBox.Text.Replace(".txt", ".generated.txt"));
                MSE = FuzzySystem.GetOutputFilesMSE(OutputFileTextBox.Text, OutputFileTextBox.Text.Replace(".txt", ".generated.txt"));
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Error", MessageBoxButton.OK);
                return;
            }

            MessageBox.Show("MSE: " + MSE.ToString(CultureInfo.InvariantCulture) + "\r\nRMSE: " + Math.Sqrt(MSE).ToString(CultureInfo.InvariantCulture) + "\r\nRMSEP: " + (Math.Sqrt(MSE) / (fuzzySystem.Outputs[0].Range[1] - fuzzySystem.Outputs[0].Range[0]) * 100.0f).ToString(CultureInfo.InvariantCulture) + "%\r\nGeneration time in milliseconds: " + watch.ElapsedMilliseconds, "Generation successful!", MessageBoxButton.OK);
        }
Exemple #15
0
    static void Main(string[] args)
    {
        // Création du système
        WriteLine("Gestion du zoom GPS", true);
        FuzzySystem system = new FuzzySystem("Gestion du zoom GPS");

        WriteLine("1) Ajout des variables", true);

        // Ajout de la variable linguistique "Distance" (de 0 à 500 000 m)
        WriteLine("Ajout de la variable Distance");
        LinguisticVariable distance = new LinguisticVariable("Distance", 0, 500000);

        distance.AddValue(new LinguisticValue("Faible", new LeftFuzzySet(0, 500000, 30, 50)));
        distance.AddValue(new LinguisticValue("Moyenne", new TrapezoidalFuzzySet(0, 500000, 40, 50, 100, 150)));
        distance.AddValue(new LinguisticValue("Grande", new RightFuzzySet(0, 500000, 100, 150)));
        system.addInputVariable(distance);

        // Ajout de la variable linguistique "Vitesse" (de 0 à 200)
        WriteLine("Ajout de la variable Vitesse");
        LinguisticVariable vitesse = new LinguisticVariable("Vitesse", 0, 200);

        vitesse.AddValue(new LinguisticValue("Lente", new LeftFuzzySet(0, 200, 20, 30)));
        vitesse.AddValue(new LinguisticValue("PeuRapide", new TrapezoidalFuzzySet(0, 200, 20, 30, 70, 80)));
        vitesse.AddValue(new LinguisticValue("Rapide", new TrapezoidalFuzzySet(0, 200, 70, 80, 90, 110)));
        vitesse.AddValue(new LinguisticValue("TresRapide", new RightFuzzySet(0, 200, 90, 110)));
        system.addInputVariable(vitesse);

        // Ajout de la variable linguistique "Zoom" (de 1 à 5)
        WriteLine("Ajout de la variable Zoom");
        LinguisticVariable zoom = new LinguisticVariable("Zoom", 0, 5);

        zoom.AddValue(new LinguisticValue("Petit", new LeftFuzzySet(0, 5, 1, 2)));
        zoom.AddValue(new LinguisticValue("Normal", new TrapezoidalFuzzySet(0, 5, 1, 2, 3, 4)));
        zoom.AddValue(new LinguisticValue("Gros", new RightFuzzySet(0, 5, 3, 4)));
        system.addOutputVariable(zoom);

        WriteLine("2) Ajout des règles", true);

        // Création des règles selon la matrice suivante :
        // Plus le zoom est petit, plus on voit loin (mais moins détaillé)
        // V \ D  || F | M | G |
        // Lent   || N | P | P |
        // Peu Ra || N | N | P |
        // Rapide || G | N | P |
        // Très R || G | G | P |
        system.addFuzzyRule("IF Distance IS Grande THEN Zoom IS Petit");
        system.addFuzzyRule("IF Distance IS Faible AND Vitesse IS Lente THEN Zoom IS Normal");
        system.addFuzzyRule("IF Distance IS Faible AND Vitesse IS PeuRapide THEN Zoom IS Normal");
        system.addFuzzyRule("IF Distance IS Faible AND Vitesse IS Rapide THEN Zoom IS Gros");
        system.addFuzzyRule("IF Distance IS Faible AND Vitesse IS TresRapide THEN Zoom IS Gros");
        system.addFuzzyRule("IF Distance IS Moyenne AND Vitesse IS Lente THEN Zoom IS Petit");
        system.addFuzzyRule("IF Distance IS Moyenne AND Vitesse IS PeuRapide THEN Zoom IS Normal");
        system.addFuzzyRule("IF Distance IS Moyenne AND Vitesse IS Rapide THEN Zoom IS Normal");
        system.addFuzzyRule("IF Distance IS Moyenne AND Vitesse IS TresRapide THEN Zoom IS Gros");
        WriteLine("9 règles ajoutées \n");

        WriteLine("3) Résolution de cas pratiques", true);
        // Cas pratique 1 : vitesse de 35 kms/h, et prochain changement de direction à 70m
        WriteLine("Cas 1 :", true);
        WriteLine("V = 35 (peu rapide)");
        WriteLine("D = 70 (moyenne)");
        system.SetInputVariable(vitesse, 35);
        system.SetInputVariable(distance, 70);
        WriteLine("Attendu : zoom normal, centroïde à 2.5");
        WriteLine("Résultat : " + system.Solve() + "\n");

        // Cas pratique 2 : vitesse de 25 kms/h, et prochain changement de direction à 70m
        system.ResetCase();
        WriteLine("Cas 2 :", true);
        WriteLine("V = 25 (50% lente, 50% peu rapide)");
        WriteLine("D = 70 (moyenne)");
        system.SetInputVariable(vitesse, 25);
        system.SetInputVariable(distance, 70);
        WriteLine("Attendu : zoom normal à 50% + zoom petit à 50%");
        WriteLine("Résultat : " + system.Solve() + "\n");

        // Cas pratique 3 : vitesse de 72.5 kms/h, et prochain changement de direction à 40m
        system.ResetCase();
        WriteLine("Cas 3 :", true);
        WriteLine("V = 72.5 (75% peu rapide + 25% rapide)");
        WriteLine("D = 40 (50% faible)");
        system.SetInputVariable(vitesse, 72.5);
        system.SetInputVariable(distance, 40);
        WriteLine("Attendu : zoom normal à 50% + zoom gros à 25%");
        WriteLine("Résultat : " + system.Solve() + "\n");

        // Cas pratique 4 : vitesse de 100 kms/h, et prochain changement de direction à 110m
        system.ResetCase();
        WriteLine("Cas 4 :", true);
        WriteLine("V = 100 (50% rapide + 50% très rapide)");
        WriteLine("D = 110 (80% moyenne, 20% grande)");
        system.SetInputVariable(vitesse, 100);
        system.SetInputVariable(distance, 110);
        WriteLine("Attendu : zoom petit à 20% + zoom normal à 50% + zoom gros à 50%");
        WriteLine("Résultat : " + system.Solve() + "\n");

        // Cas pratique 5 : vitesse de 45 kms/h, et prochain changement de direction à 160m
        system.ResetCase();
        WriteLine("Cas 5 :", true);
        WriteLine("V = 45 (100% peu rapide)");
        WriteLine("D = 160 (100% grande)");
        system.SetInputVariable(vitesse, 45);
        system.SetInputVariable(distance, 160);
        WriteLine("Attendu : zoom petit à 100%");
        WriteLine("Résultat : " + system.Solve() + "\n");

        while (true)
        {
            ;
        }
    }
Exemple #16
0
        void Update()
        {
            distanciaCentro = Vector3.Distance(centro.position, playerPosition.position);
            if (tiempoRest > 0)
            {
                tiempoRest -= Time.deltaTime;
            }

            // Creación del sistema
            WriteLine("Gestión de la velocidad de los enemigos", true);
            FuzzySystem system = new FuzzySystem("Gestión de la velocidad de los enemigos");

            WriteLine("1) Agregar las variables", true);

            // Agregar la variable lingüística "Proximidad" (de 0 a 95 m)
            WriteLine("Agregar la variable Proximidad");
            LinguisticVariable proximidad = new LinguisticVariable("Proximidad", 0, 95);

            proximidad.AddValue(new LinguisticValue("Cerca", new LeftFuzzySet(0, 95, 0, 30)));
            proximidad.AddValue(new LinguisticValue("Media", new TrapezoidalFuzzySet(0, 95, 0, 30, 20, 50)));
            proximidad.AddValue(new LinguisticValue("Lejos", new RightFuzzySet(0, 95, 40, 65)));
            system.addInputVariable(proximidad);

            // Agregar la variable lingüística "Tiempo" (de 0 a 200 s)
            WriteLine("Agregar la variable Tiempo");
            LinguisticVariable tiempo = new LinguisticVariable("Tiempo", 0, 200);

            tiempo.AddValue(new LinguisticValue("Muy Poco", new LeftFuzzySet(0, 200, 40, 60)));
            tiempo.AddValue(new LinguisticValue("Poco", new TrapezoidalFuzzySet(0, 200, 40, 60, 90, 110)));
            tiempo.AddValue(new LinguisticValue("Mitad", new TrapezoidalFuzzySet(0, 200, 90, 110, 140, 160)));
            tiempo.AddValue(new LinguisticValue("Mucho", new RightFuzzySet(0, 200, 140, 160)));
            system.addInputVariable(tiempo);

            // Agregar la variable lingüística "Velocidad" (de 500 a 5000)
            WriteLine("Agregar la variable Velocidad");
            LinguisticVariable velocidad = new LinguisticVariable("Velocidad", 500, 5000);

            velocidad.AddValue(new LinguisticValue("Lenta", new LeftFuzzySet(500, 5000, 1000, 2000)));
            velocidad.AddValue(new LinguisticValue("Normal", new TrapezoidalFuzzySet(500, 5000, 1000, 2000, 3000, 4000)));
            velocidad.AddValue(new LinguisticValue("Rápida", new RightFuzzySet(500, 5000, 3000, 4000)));
            system.addOutputVariable(velocidad);

            WriteLine("2) Agregar las reglas", true);

            // Creación de las reglas en función de la matriz siguiente:
            // Cuanto mayor sea la Proximidad y menor sea el Tiempo, más Velocidad tendrán.
            // P \ T    || L | M | C |
            // Muy Poco || N | R | R |
            // Poco     || N | N | R |
            // Mitad    || L | N | N |
            // Mucho    || L | L | N |
            system.addFuzzyRule("IF Proximidad IS Lejos AND Tiempo IS Muy Poco THEN Velocidad IS Normal");
            system.addFuzzyRule("IF Proximidad IS Lejos AND Tiempo IS Poco THEN Velocidad IS Normal");
            system.addFuzzyRule("IF Proximidad IS Lejos AND Tiempo IS Mitad THEN Velocidad IS Lenta");
            system.addFuzzyRule("IF Proximidad IS Lejos AND Tiempo IS Mucho THEN Velocidad IS Lenta");
            system.addFuzzyRule("IF Proximidad IS Media AND Tiempo IS Muy Poco THEN Velocidad IS Rápida");
            system.addFuzzyRule("IF Proximidad IS Media AND Tiempo IS Poco THEN Velocidad IS Normal");
            system.addFuzzyRule("IF Proximidad IS Media AND Tiempo IS Mitad THEN Velocidad IS Normal");
            system.addFuzzyRule("IF Proximidad IS Media AND Tiempo IS Mucho THEN Velocidad IS Lenta");
            system.addFuzzyRule("IF Proximidad IS Cerca AND Tiempo IS Muy Poco THEN Velocidad IS Rápida");
            system.addFuzzyRule("IF Proximidad IS Cerca AND Tiempo IS Poco THEN Velocidad IS Rápida");
            system.addFuzzyRule("IF Proximidad IS Cerca AND Tiempo IS Mitad THEN Velocidad IS Normal");
            system.addFuzzyRule("IF Proximidad IS Cerca AND Tiempo IS Mucho THEN Velocidad IS Normal");
            WriteLine("12 reglas agregadas \n");

            WriteLine("3) Resolución de casos prácticos", true);
            WriteLine("Caso 1:", true);
            WriteLine("T = 30 (Muy Poco)");
            WriteLine("P = 800 (Cerca)");
            system.SetInputVariable(tiempo, tiempoRest);
            system.SetInputVariable(proximidad, distanciaCentro);
            WriteLine("Resultado: " + system.Solve() + "\n");
            enemyVelocity = system.Solve();
            system.ResetCase();

            //// Caso práctico 2: Tiempo de 180s, proximidad a la meta de 280m
            //system.ResetCase();
            //WriteLine("Caso 2:", true);
            //WriteLine("T = 180 (Mucho)");
            //WriteLine("P = 280 (Lejos)");
            //system.SetInputVariable(tiempo, 180);
            //system.SetInputVariable(proximidad, 280);
            //WriteLine("Resultado: " + system.Solve() + "\n");

            //// Caso práctico 3: Tiempo de 70s, proximidad a la meta de 530m
            //system.ResetCase();
            //WriteLine("Caso 3:", true);
            //WriteLine("T = 70 (Poco)");
            //WriteLine("P = 530 (Media)");
            //system.SetInputVariable(tiempo, 70);
            //system.SetInputVariable(proximidad, 530);
            //WriteLine("Resultado: " + system.Solve() + "\n");

            //// Caso práctico 4: Tiempo de 120s, proximidad a la meta de 120m
            //system.ResetCase();
            //WriteLine("Caso 4:", true);
            //WriteLine("T = 120 (Mitad)");
            //WriteLine("P = 120 (Lejos)");
            //system.SetInputVariable(tiempo, 120);
            //system.SetInputVariable(proximidad, 120);
            //WriteLine("Resultado: " + system.Solve() + "\n");

            //// Caso práctico 5 : Tiempo de 10s, proximidad a la meta de 450m
            //system.ResetCase();
            //WriteLine("Caso 5:", true);
            //WriteLine("T = 10 (Muy Poco)");
            //WriteLine("P = 450 (Media)");
            //system.SetInputVariable(tiempo, 10);
            //system.SetInputVariable(proximidad, 450);
            //WriteLine("Resultado: " + system.Solve() + "\n");
        }
Exemple #17
0
        static void Main(string[] args)
        {
            //Point2D pt1 = new Point2D(0, 0);
            //Point2D pt2 = new Point2D(15, 0);
            //Point2D pt3 = new Point2D(17, 1);
            //Point2D pt4 = new Point2D(20, 1);
            //Point2D pt5 = new Point2D(25, 0);
            //Point2D pt6 = new Point2D(15, 0);


            //Console.WriteLine("Test Classe Point2D :");
            //Console.WriteLine("(15;0) == (15;0)" + (pt2 == pt6));
            //Console.WriteLine("(15;0) != (17;0)" + (pt2 != pt3));
            //Console.WriteLine("(15;0) > (17;1)" + (pt2 > pt3));
            //Console.WriteLine("(15;0) < (17;1)" + (pt2 < pt3));
            //Console.WriteLine("(15;0) > (15;0)" + (pt2 > pt6));
            //Console.WriteLine("(15;0) < (15;0)" + (pt2 < pt6));
            //Console.WriteLine("(15;0) >= (15;0)" + (pt2 >= pt6));
            //Console.WriteLine("(15;0) <= (15;1)" + (pt2 <= pt6));

            //Console.WriteLine("\nTest Classe FuzzySet :");
            //Point2D[] array = { pt5, pt2, pt6, pt4, pt1, pt3 };
            //FuzzySet fs = new FuzzySet(array);
            //Console.WriteLine("\n" + fs.ToString());

            //List<Point2D> list = new List<Point2D>();
            //list.Add(pt5);
            //list.Add(pt2);
            //list.Add(pt6);
            //list.Add(pt4);
            //list.Add(pt1);
            //list.Add(pt3);

            //FuzzySet fs2 = new FuzzySet(list);
            //fs2.Max = 53;
            //Console.WriteLine("\n" + fs2.ToString());
            //fs2.AddPoint(-9, 0.98);
            //fs2.Min = -8;
            //Console.WriteLine("\n" + fs2.ToString());
            //Console.WriteLine("Egalité des 2 ensembles flous ? " + (fs == fs2));
            //Console.WriteLine("Différence entre les 2 ensembles flous ? " + (fs != fs2));

            //FuzzySet fs3 = fs * 0.5;
            //FuzzySet fs4 = 0.5 * fs;
            //Console.WriteLine("Multiplication par 0.5 de fs : " + fs3.ToString());
            //Console.WriteLine("Multiplication par 0.5 de fs (autre sens) : " + fs4.ToString());
            //FuzzySet fs5 = !fs;
            //Console.WriteLine("Opération NON flou sur fs : " + fs5.ToString());
            //Console.WriteLine("Valeur d'appartenance de fs à x=15,5 (0,25 normalement) : " + fs.DegreeAtValue(15.5));
            //Console.WriteLine("Calcul du barycentre pour fs : " + fs.Barycenter);

            //RampFuzzySet rfs = new RampFuzzySet(11.54, 26.56);
            //Console.WriteLine("Test classe RampFuzzySet : \n" + rfs.ToString());
            //Console.WriteLine("Calcul du barycentre pour lfs : " + rfs.Barycenter);

            //TriangularFuzzySet tfs = new TriangularFuzzySet(52.25, 12.56, 25.89);
            //Console.WriteLine("Test classe TriangularFuzzySet : \n" + tfs.ToString());
            //Console.WriteLine("Calcul du barycentre pour tfs : " + tfs.Barycenter);

            //TrapezoidalFuzzySet trfs = new TrapezoidalFuzzySet(25.2, 5, 89.45, 39.45);
            //Console.WriteLine("Test classe TrapezoidalFuzzySet : \n" + trfs.ToString());
            //Console.WriteLine("Calcul du barycentre pour trfs : " + trfs.Barycenter);

            //Console.WriteLine("\nTest classe LinguisticVariable :");
            //LinguisticValue lv1 = new LinguisticValue("LV1", rfs);
            //LinguisticValue lv2 = new LinguisticValue("LV2", tfs);
            //LinguisticValue lv3 = new LinguisticValue("LV3", trfs);
            //List<LinguisticValue> listeLv1 = new List<LinguisticValue>();
            //listeLv1.Add(lv1);
            //listeLv1.Add(lv2);
            //listeLv1.Add(lv3);
            //LinguisticVariable lVar1 = new LinguisticVariable("Variable linguistique 1", listeLv1, 3.56, 141.25);
            //Console.WriteLine("MinValue = " + lVar1.MinValue + ", MaxValue = " + lVar1.MaxValue);


            // Test algorithme flou avec problème de gestion du zoom GPS
            // Définition variable linguistique 1 (Premisse)
            LinguisticVariable distance = new LinguisticVariable("Distance");

            distance.AddValue(new LinguisticValue("faible", new RampFuzzySet(30, 50, 0, 500000)));
            distance.AddValue(new LinguisticValue("moyenne", new TrapezoidalFuzzySet(40, 50, 100, 150, 0, 500000)));
            distance.AddValue(new LinguisticValue("grande", new RampFuzzySet(150, 100, 0, 500000)));
            Console.WriteLine("Contrôle de la variable linguistique distance : " + distance.MinValue + " " + distance.MaxValue);
            // Définition variable linguistique 2 (Premisse)
            LinguisticVariable vitesse = new LinguisticVariable("Vitesse");

            vitesse.AddValue(new LinguisticValue("lente", new RampFuzzySet(20, 30, 0, 200)));
            vitesse.AddValue(new LinguisticValue("peu rapide", new TrapezoidalFuzzySet(20, 30, 70, 80, 0, 200)));
            vitesse.AddValue(new LinguisticValue("rapide", new TrapezoidalFuzzySet(70, 80, 90, 110, 0, 200)));
            vitesse.AddValue(new LinguisticValue("très rapide", new RampFuzzySet(110, 90, 0, 200)));
            Console.WriteLine("Contrôle de la variable linguistique vitesse : " + vitesse.MinValue + " " + vitesse.MaxValue);
            // Définition variable linguistique 3 (Conclusion)
            LinguisticVariable zoom = new LinguisticVariable("Zoom");

            zoom.AddValue(new LinguisticValue("petit", new RampFuzzySet(1, 2, 0, 5)));
            zoom.AddValue(new LinguisticValue("normal", new TrapezoidalFuzzySet(1, 2, 3, 4, 0, 5)));
            zoom.AddValue(new LinguisticValue("gros", new RampFuzzySet(4, 3, 0, 5)));
            Console.WriteLine("Contrôle de la variable linguistique zoom : " + zoom.MinValue + " " + zoom.MaxValue);

            List <LinguisticVariable> listeLinguisticVariable = new List <LinguisticVariable>();

            listeLinguisticVariable.Add(distance);
            listeLinguisticVariable.Add(vitesse);

            // Définition des FuzzeExpression
            FuzzyExpression exp11 = new FuzzyExpression(distance, "faible");
            FuzzyExpression exp12 = new FuzzyExpression(distance, "moyenne");
            FuzzyExpression exp13 = new FuzzyExpression(distance, "grande");
            FuzzyExpression exp21 = new FuzzyExpression(vitesse, "lente");
            FuzzyExpression exp22 = new FuzzyExpression(vitesse, "peu rapide");
            FuzzyExpression exp23 = new FuzzyExpression(vitesse, "rapide");
            FuzzyExpression exp24 = new FuzzyExpression(vitesse, "très rapide");
            FuzzyExpression exp31 = new FuzzyExpression(zoom, "petit");
            FuzzyExpression exp32 = new FuzzyExpression(zoom, "normal");
            FuzzyExpression exp33 = new FuzzyExpression(zoom, "gros");
            // Définition des règles
            List <FuzzyExpression> premises = new List <FuzzyExpression>();
            FuzzyExpression        conclusion;
            List <FuzzyRule>       rules = new List <FuzzyRule>();

            // Règle 1
            premises.Add(exp11);
            premises.Add(exp21);
            conclusion = exp32;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 2
            premises.Add(exp12);
            premises.Add(exp21);
            conclusion = exp31;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 3
            premises.Add(exp11);
            premises.Add(exp22);
            conclusion = exp32;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 4
            premises.Add(exp12);
            premises.Add(exp22);
            conclusion = exp32;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 5
            premises.Add(exp11);
            premises.Add(exp23);
            conclusion = exp33;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 6
            premises.Add(exp12);
            premises.Add(exp23);
            conclusion = exp32;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 7
            premises.Add(exp11);
            premises.Add(exp24);
            conclusion = exp33;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 8
            premises.Add(exp12);
            premises.Add(exp24);
            conclusion = exp33;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Règle 9
            premises.Add(exp13);
            conclusion = exp31;
            rules.Add(new FuzzyRule(new List <FuzzyExpression>(premises), conclusion));
            premises.Clear();

            // Création du FuzzySystem
            FuzzySystem system = new FuzzySystem("Gestion du zoom GPS", listeLinguisticVariable, zoom, rules);

            // Cas 1
            system.SetInputVariable(distance, 70);
            system.SetInputVariable(vitesse, 35);
            Console.WriteLine("GPS cas n°1 (70m et 35km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 2
            system.SetInputVariable(distance, 70);
            system.SetInputVariable(vitesse, 25);
            Console.WriteLine("GPS cas n°1 (70m et 25km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 3
            system.SetInputVariable(distance, 40);
            system.SetInputVariable(vitesse, 72.5);
            Console.WriteLine("GPS cas n°1 (40m et 72,5km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 4
            system.SetInputVariable(distance, 110);
            system.SetInputVariable(vitesse, 100);
            Console.WriteLine("GPS cas n°1 (110m et 100km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 5
            system.SetInputVariable(distance, 160);
            system.SetInputVariable(vitesse, 45);
            Console.WriteLine("GPS cas n°1 (160m et 45km/h) : " + system.Solve());
            system.ResetCase();


            // Test Parsin fichier XML
            Console.WriteLine("\n\nTEST PARSING FICHIER XML");
            XmlFuzzySystemParser parser = new XmlFuzzySystemParser();

            parser.CreateFuzzySystem("Fuzzy System - Gestion zoom GPS.xml");
            Console.WriteLine("Résultat parsing = " + parser.ErrorCode.ToString());
            List <LinguisticVariable> _inputs = parser.GetInputs();
            LinguisticVariable        _output = parser.GetOutput();
            List <FuzzyRule>          _rules  = parser.GetRules();

            // Création du FuzzySystem
            system = new FuzzySystem("Gestion du zoom GPS", _inputs, _output, _rules);
            // Cas 1
            system.SetInputVariable(_inputs[0], 70);
            system.SetInputVariable(_inputs[1], 35);
            Console.WriteLine("GPS cas n°1 (70m et 35km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 2
            system.SetInputVariable(_inputs[0], 70);
            system.SetInputVariable(_inputs[1], 25);
            Console.WriteLine("GPS cas n°1 (70m et 25km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 3
            system.SetInputVariable(_inputs[0], 40);
            system.SetInputVariable(_inputs[1], 72.5);
            Console.WriteLine("GPS cas n°1 (40m et 72,5km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 4
            system.SetInputVariable(_inputs[0], 110);
            system.SetInputVariable(_inputs[1], 100);
            Console.WriteLine("GPS cas n°1 (110m et 100km/h) : " + system.Solve());
            system.ResetCase();

            // Cas 5
            system.SetInputVariable(_inputs[0], 160);
            system.SetInputVariable(_inputs[1], 45);
            Console.WriteLine("GPS cas n°1 (160m et 45km/h) : " + system.Solve());
            system.ResetCase();



            Console.ReadKey();
        }
 private void CreateSystem()
 {
     system = new FuzzySystem("Enemy Damage");
     SetLinguisticValues();
     SetRules();
 }