private List <LinguisticVariable> PrepareLinguisticVariables()
        {
            // Water variable
            MembershipFunctionList firstMembershipFunctionList = new MembershipFunctionList
            {
                new TrapezoidalMembershipFunction("Cold", 0, 20, 20, 30),
                new TrapezoidalMembershipFunction("Hot", 50, 60, 60, 80)
            };
            LinguisticVariable firstLinguisticVariable =
                new LinguisticVariable("Water", firstMembershipFunctionList, isInitialData: true);

            // Pressure vatiable
            MembershipFunctionList secondsMembershipFunctionList = new MembershipFunctionList
            {
                new TrapezoidalMembershipFunction("Low", 20, 50, 50, 60),
                new TrapezoidalMembershipFunction("Medium", 60, 65, 65, 80),
                new TrapezoidalMembershipFunction("High", 80, 100, 100, 150)
            };
            LinguisticVariable secondLinguisticVariable =
                new LinguisticVariable("Pressure", secondsMembershipFunctionList, isInitialData: false);

            List <LinguisticVariable> variables = new List <LinguisticVariable>
            {
                firstLinguisticVariable, secondLinguisticVariable
            };

            return(variables);
        }
Beispiel #2
0
        private void Initialize()
        {
            _fVariable = new LinguisticVariable(Name, _range.Min, _range.Max);
            foreach (FuzzySet label in _sets)
            {
                _fVariable.AddLabel(label);
            }

            _chartArea = _chart.ChartAreas[0];
            _chartArea.AxisY.Maximum = 1;
            _chartArea.AxisY.Minimum = 0;

            _chartArea.AxisX.LabelStyle.Format   = "{0}";
            _chartArea.AxisX.LabelStyle.Interval = 2;
            _chartArea.AxisY.LabelStyle.Format   = "{0.0}";
            _chartArea.AxisY.LabelStyle.Interval = 0.5;

            //_chart = System.Windows.Forms.DockStyle.Bottom;
            _chart.Legends.ToList().ForEach(x => x.Docking = Docking.Bottom);

            if (Type == VariableType.Input)
            {
                InitialSelectLine();
            }
        }
        public AddTermWindow(LinguisticVariable linguisticVariable)
        {
            InitializeComponent();

            mCurrentVariable = linguisticVariable;
            InitializeListBox();
        }
Beispiel #4
0
        private void SetUpFisII()
        {
            //Input
            var impact = new LinguisticVariable("Impact", 0, 100);

            new List <FuzzySet>()
            {
                new FuzzySet("Low", new TrapezoidalFunction(0, 5, 25, 30)),
                new FuzzySet("Medium", new TrapezoidalFunction(20, 25, 55, 60)),
                new FuzzySet("High", new TrapezoidalFunction(50, 55, 95, 100))
            }.ForEach(x => impact.AddLabel(x));


            var onGround = new LinguisticVariable("On_ground", -0.5f, 1.5f);

            new List <FuzzySet>()
            {
                new FuzzySet("Low", new TrapezoidalFunction(-0.5f, -0.2f, 0.2f, 0.5f)),
                new FuzzySet("Medium", new TrapezoidalFunction(0.1f, 0.5f, 0.5f, 0.9f)),
                new FuzzySet("High", new TrapezoidalFunction(0.5f, 0.8f, 1.2f, 1.5f))
            }.ForEach(x => onGround.AddLabel(x));


            var timeOnGround = new LinguisticVariable("Time_on_ground", -1, 901);

            new List <FuzzySet>()
            {
                new FuzzySet("Brief", new TrapezoidalFunction(-1, 1, 1, 2)),
                new FuzzySet("Short", new TrapezoidalFunction(1, 5, 10, 15)),
                new FuzzySet("Moderate", new TrapezoidalFunction(10, 120, 480, 720)),
                new FuzzySet("Long", new TrapezoidalFunction(480, 900, 900, 901))
            }.ForEach(x => timeOnGround.AddLabel(x));


            //Output
            var fallWearable = new LinguisticVariable("Fall_wearable", -0.5f, 1.5f);

            new List <FuzzySet>()
            {
                new FuzzySet("Low", new TrapezoidalFunction(-0.5f, -0.2f, 0.2f, 0.5f)),
                new FuzzySet("Medium", new TrapezoidalFunction(0.1f, 0.5f, 0.5f, 0.9f)),
                new FuzzySet("High", new TrapezoidalFunction(0.5f, 0.8f, 1.2f, 1.5f))
            }.ForEach(x => fallWearable.AddLabel(x));

            var db = new Database();

            db.AddVariable(impact);
            db.AddVariable(onGround);
            db.AddVariable(timeOnGround);
            db.AddVariable(fallWearable);


            fisII = new InferenceSystem(db, new CentroidDefuzzifier(1000));

            fisII.NewRule("Rule 1", "IF Impact IS High AND On_ground IS High AND Time_on_ground IS Long THEN Fall_wearable IS High");
            fisII.NewRule("Rule 2", "IF Impact IS Medium AND On_ground IS High AND Time_on_ground IS Long THEN Fall_wearable IS High");
            fisII.NewRule("Rule 3", "IF Impact IS Low AND On_ground IS Low AND (Time_on_ground IS Short OR Time_on_ground IS Brief) THEN Fall_wearable IS Low");
            fisII.NewRule("Rule 4", "IF Impact IS Medium AND On_ground IS Medium AND Time_on_ground IS Moderate THEN Fall_wearable IS Medium");
            fisII.NewRule("Rule 5", "IF Impact IS High AND On_ground IS Medium AND (Time_on_ground IS Short OR Time_on_ground IS Brief) THEN Fall_wearable IS Medium");
        }
Beispiel #5
0
    void Start()
    {
        rigidbody = GetComponent <Rigidbody>();
        // Here we need to setup the Fuzzy Inference System
        distance = new LinguisticVariable("distance");
        var farRight = distance.MembershipFunctions.AddTrapezoid("farRight", -100, -100, -60, -45);
        var right    = distance.MembershipFunctions.AddTrapezoid("right", -50, -50, -7, -0.05f);
        var none     = distance.MembershipFunctions.AddTrapezoid("none", -7, -0.5, 0.5, 7);
        var left     = distance.MembershipFunctions.AddTrapezoid("left", 0.05f, 7, 50, 50);
        var farLeft  = distance.MembershipFunctions.AddTrapezoid("farLeft", 45, 60, 100, 100);

        direction = new LinguisticVariable("direction");
        var farRightD = direction.MembershipFunctions.AddTrapezoid("farRight", -100, -100, -60, -45);
        var rightD    = direction.MembershipFunctions.AddTrapezoid("right", -50, -50, -7, -0.05f);
        var noneD     = direction.MembershipFunctions.AddTrapezoid("none", -7, -0.5, 0.5, 7);
        var leftD     = direction.MembershipFunctions.AddTrapezoid("left", 0.05f, 7, 50, 50);
        var farLeftD  = direction.MembershipFunctions.AddTrapezoid("farLeft", 45, 60, 100, 100);

        engine = new FuzzyEngineFactory().Default();
        var rule0 = Rule.If(distance.Is(farRight)).Then(direction.Is(farLeftD));
        var rule1 = Rule.If(distance.Is(right)).Then(direction.Is(leftD));
        var rule2 = Rule.If(distance.Is(left)).Then(direction.Is(rightD));
        var rule3 = Rule.If(distance.Is(none)).Then(distance.Is(noneD));
        var rule4 = Rule.If(distance.Is(farLeft)).Then(direction.Is(farRightD));

        engine.Rules.Add(rule0, rule1, rule2, rule3, rule4);
    }
        public FuzzyRoamState(Monster pawn) : base(pawn)
        {
            engine_wallDetection   = new FuzzyEngineFactory().Default();
            engine_playerDetection = new FuzzyEngineFactory().Default();

            distanceToWall = new LinguisticVariable("distanceToWall");
            var farDistance  = distanceToWall.MembershipFunctions.AddTrapezoid("WallFar", 70, 70, 90, 120);
            var midDistance  = distanceToWall.MembershipFunctions.AddTrapezoid("WallMid", 50, 60, 70, 80);
            var nearDistance = distanceToWall.MembershipFunctions.AddTrapezoid("WallNear", 0, 20, 50, 70);

            turnStrength = new LinguisticVariable("turnStrength");
            var weak   = turnStrength.MembershipFunctions.AddTrapezoid("Weak", 1, 4, 8, 12);
            var medium = turnStrength.MembershipFunctions.AddTrapezoid("Medium", 6, 12, 18, 24);
            var strong = turnStrength.MembershipFunctions.AddTrapezoid("Strong", 15, 30, 60, 80);

            playerDetected = new LinguisticVariable("playerDetected");
            var detected    = playerDetected.MembershipFunctions.AddRectangle("Detected", 0, 1);
            var notDetected = playerDetected.MembershipFunctions.AddRectangle("NotDetected", -1, 0);

            playerDistance = new LinguisticVariable("playerDistance");
            var playerNear = playerDistance.MembershipFunctions.AddTrapezoid("PlayerNear", 0, 10, 25, 30);
            var playerMid  = playerDistance.MembershipFunctions.AddTrapezoid("PlayerMid", 20, 30, 40, 50);
            var playerFar  = playerDistance.MembershipFunctions.AddTrapezoid("PlayerFar", 40, 50, 60, 70);

            var wallDetection_rule1 = Rule.If(distanceToWall.Is(farDistance)).Then(turnStrength.Is(weak));
            var wallDetection_rule2 = Rule.If(distanceToWall.Is(midDistance)).Then(turnStrength.Is(medium));
            var wallDetection_rule3 = Rule.If(distanceToWall.Is(nearDistance)).Then(turnStrength.Is(strong));

            var playerDetection_rule1 = Rule.If(playerDistance.Is(playerNear).Or(playerDistance.Is(playerMid))).Then(playerDetected.Is(detected));
            var playerDetection_rule2 = Rule.If(playerDistance.Is(playerFar)).Then(playerDetected.Is(notDetected));

            engine_wallDetection.Rules.Add(wallDetection_rule1, wallDetection_rule2, wallDetection_rule3);
            engine_playerDetection.Rules.Add(playerDetection_rule1, playerDetection_rule2);
        }
Beispiel #7
0
        private void SetUpFisI()
        {
            //Input
            var treshhold = new LinguisticVariable("Threshold", 0, 100);

            new List <FuzzySet>()
            {
                new FuzzySet("Low", new TrapezoidalFunction(0, 5, 25, 30)),
                new FuzzySet("Medium", new TrapezoidalFunction(20, 25, 55, 60)),
                new FuzzySet("High", new TrapezoidalFunction(50, 55, 95, 100))
            }.ForEach(x => treshhold.AddLabel(x));

            //Output
            var impact = new LinguisticVariable("Impact", 0, 100);

            new List <FuzzySet>()
            {
                new FuzzySet("Low", new TrapezoidalFunction(0, 5, 25, 30)),
                new FuzzySet("Medium", new TrapezoidalFunction(20, 25, 55, 60)),
                new FuzzySet("High", new TrapezoidalFunction(50, 55, 95, 100))
            }.ForEach(x => impact.AddLabel(x));

            var db = new Database();

            db.AddVariable(treshhold);
            db.AddVariable(impact);


            fisI = new InferenceSystem(db, new CentroidDefuzzifier(1000));

            fisI.NewRule("Rule 1", "IF Threshold IS Low THEN Impact IS Low");
            fisI.NewRule("Rule 2", "IF Threshold IS Medium THEN Impact IS Medium");
            fisI.NewRule("Rule 3", "IF Threshold IS High THEN Impact IS High");
        }
Beispiel #8
0
 private void button_deleteLV_Click(object sender, EventArgs e)
 {
     if (dataGridViewLV.SelectedRows.Count > 0)
     {
         if (MessageBox.Show("Вы действительно хотите удалить эту лингвистическую переменную?", "Подтверждение удаления",
                             MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
         {
             try
             {
                 LinguisticVariable lv = dbConnection.Get <LinguisticVariable>(dataGridViewLV.SelectedRows[0].Cells["LVId"].Value);
                 lv.deleted = 1;
                 dbConnection.Update(lv);
                 refreshLinguisticTable();
             }
             catch (Exception ex)
             {
                 //Exception may occur when dbConnection is null
                 MessageBox.Show("Произошла ошибка при работе с базой данных: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
     }
     else
     {
         MessageBox.Show("Необходимо выбрать лингвистическую переменную", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
     }
 }
Beispiel #9
0
    void Start()
    {
        darahAwal   = darah;
        hpbar       = transform.Find("darahbar");
        hpbarobj    = hpbar.gameObject;
        posisiAwal  = transform.position;
        maju_kiri   = true;
        areaPatroli = 7;
        anim        = GetComponent <Animator>();
        patrol      = true;
        player      = GameObject.Find("utama");
        player_anim = player.GetComponent <Animator>();

        //Fuzzy
        fuzzyEngine = new FuzzyEngine();
        //Fuzzy Tambah Fungsi Keanggotaan HP
        HealthPoint = new LinguisticVariable("HealthPoint");
        HealthPoint.MembershipFunctionCollection.Add(new MembershipFunction("SangatRendah", 0, 0, 0, 20));
        HealthPoint.MembershipFunctionCollection.Add(new MembershipFunction("Rendah", 15, 30, 30, 45));
        HealthPoint.MembershipFunctionCollection.Add(new MembershipFunction("Setengah", 35, 50, 50, 65));
        HealthPoint.MembershipFunctionCollection.Add(new MembershipFunction("Tinggi", 55, 70, 70, 85));
        HealthPoint.MembershipFunctionCollection.Add(new MembershipFunction("SangatTinggi", 80, 100, 100, 100));
        //Fuzzy Tambah Fungsi Keanggotaan Jarak
        Jarak = new LinguisticVariable("Jarak");
        Jarak.MembershipFunctionCollection.Add(new MembershipFunction("SangatDekat", 0, 0, 0, 20));
        Jarak.MembershipFunctionCollection.Add(new MembershipFunction("Dekat", 15, 30, 30, 50));
        Jarak.MembershipFunctionCollection.Add(new MembershipFunction("Jauh", 40, 60, 60, 80));
        Jarak.MembershipFunctionCollection.Add(new MembershipFunction("SangatJauh", 70, 100, 100, 100));
        //Fuzzy Tambah Fungsi Keanggotaan Aksi
        Aksi = new LinguisticVariable("Aksi");
        Aksi.MembershipFunctionCollection.Add(new MembershipFunction("PanggilAnak", 0, 0, 0, 25));
        Aksi.MembershipFunctionCollection.Add(new MembershipFunction("Lempar", 20, 50, 50, 70));
        Aksi.MembershipFunctionCollection.Add(new MembershipFunction("Attack", 60, 80, 80, 100));

        fuzzyEngine.LinguisticVariableCollection.Add(HealthPoint);
        fuzzyEngine.LinguisticVariableCollection.Add(Jarak);
        fuzzyEngine.LinguisticVariableCollection.Add(Aksi);
        fuzzyEngine.Consequent = "Aksi";
        //Fuzzy Rule
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatRendah) AND (Jarak IS SangatDekat) THEN Aksi IS PanggilAnak"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatRendah) AND (Jarak IS Dekat) THEN Aksi IS PanggilAnak"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatRendah) AND (Jarak IS Jauh) THEN Aksi IS PanggilAnak"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatRendah) AND (Jarak IS SangatJauh) THEN Aksi IS PanggilAnak"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Rendah) AND (Jarak IS SangatDekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Rendah) AND (Jarak IS Dekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Rendah) AND (Jarak IS Jauh) THEN Aksi IS Lempar"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Rendah) AND (Jarak IS SangatJauh) THEN Aksi IS Lempar"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Setengah) AND (Jarak IS SangatDekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Setengah) AND (Jarak IS Dekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Setengah) AND (Jarak IS Jauh) THEN Aksi IS Lempar"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Setengah) AND (Jarak IS SangatJauh) THEN Aksi IS Lempar"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Tinggi) AND (Jarak IS SangatDekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Tinggi) AND (Jarak IS Dekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Tinggi) AND (Jarak IS Jauh) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS Tinggi) AND (Jarak IS SangatJauh) THEN Aksi IS Lempar"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatTinggi) AND (Jarak IS SangatDekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatTinggi) AND (Jarak IS Dekat) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatTinggi) AND (Jarak IS Jauh) THEN Aksi IS Attack"));
        fuzzyEngine.FuzzyRuleCollection.Add(new FuzzyRule("IF (HealthPoint IS SangatTinggi) AND (Jarak IS SangatJauh) THEN Aksi IS Lempar"));
    }
Beispiel #10
0
        public void T3RangeCalibration()
        {
            LinguisticVariable =
                LinguisticVariable.fromJson(JsonLingVar);
            LinguisticVariable.RangeCalibration(1, 0.01);
            string LogMsg = "{Range Calibration Test Result]\n";

            LogMsg += string.Format(
                "{0,-15}\t| {1,-15}{2,-15}\t| {3,-15}{4,-15}\n",
                "Linguistic",
                "Start",
                "",
                "length",
                ""
                );
            LogMsg += "=============== <Before> / <After> ===============\n";
            foreach (MembershipFunction MF in LinguisticVariable.membershipFunctions)
            {
                MembershipFunction PreCalib = MFs.Find(
                    x =>
                    x.membershipValue.linguistic == MF.membershipValue.linguistic);
                LogMsg += string.Format(
                    "{0,-15}\t| {1,15} / {2,-15}\t| {3,15} / {4,-15}\n",
                    MF.membershipValue.linguistic,
                    PreCalib.start,
                    MF.start,
                    PreCalib.length,
                    MF.length
                    );
            }
            Debug.Log(LogMsg);
        }
Beispiel #11
0
        public void T6Implicate()
        {
            double axis = 0;

            LinguisticVariable =
                LinguisticVariable.fromJson(JsonLingVar);
            LinguisticVariable.RangeCalibration(1, 0.01);
            ExternalLVSetUp();
            string LogMsg = "[Implicate Test Result]\n==================================\n";
            string TmpLog;

            LinguisticVariable.ApplyRule(LingVars);
            LinguisticVariable.Implicate(1);
            foreach (LinguisticRule rule in LinguisticVariable.linguisticRules)
            {
                TmpLog  = "Linguistic : " + rule.membershipValue.linguistic + "\n";
                TmpLog += "Implication Method : " + FuzzyImplication.nameOf(rule.implicationM) + "\n";
                TmpLog += "Axis\t| Implication\n";
                axis    = rule.implData.StartAxis;
                foreach (double implRes in rule.implData.data)
                {
                    TmpLog += axis + "\t| " + implRes + "\n";
                    axis   += rule.implData.spacing;
                }
                LogMsg += TmpLog + "==================================\n";
                TmpLog  = "";
            }
            Debug.Log(LogMsg);
        }
Beispiel #12
0
        public static void ReadFromXLS(string path) // Function for reading data from the file .xls
        {
            HSSFWorkbook hssfwb;

            using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))  // Data2
            {
                hssfwb = new HSSFWorkbook(file);
            }
            ISheet        sheet = hssfwb.GetSheet("FirstList");
            List <string> Elements = new List <string>();
            int           column = 1, Row = 1;

            countColumnData = 0;
            Elements.Clear();

            for (column = 1; sheet.GetRow(0).GetCell(column) != null; column++) // подсчет количества колонок в файле, а также запись названия ЛП
            {
                List <Term> t = new List <Term>();
                NameOfLinguisticVariables.Add(string.Format("{0: 0.0}", sheet.GetRow(0).GetCell(column)));
                LinguisticVariable LP = new LinguisticVariable(new Guid(), string.Format("{0: 0.0}", sheet.GetRow(0).GetCell(column)), t, 0, 1);
                //FKB.ListVar.Add(LP);
                countColumnData += 1;
            }

            if (counterFoRowDataFromFile == 0)
            {
                for (Row = 1; sheet.GetRow(Row) != null && sheet.GetRow(Row).GetCell(0) != null; Row++)  // подсчет количества строк в файле
                {
                    counterFoRowDataFromFile++;
                }
            }
            column         = 1;
            ElementsMatrix = new double[counterFoRowDataFromFile, countColumnData];
            for (int row = 1; row <= counterFoRowDataFromFile; row++)  // запись построчно с файла данных в список ElementsMulti -MultiDimensionalVector-
            {
                MultiDimensionalVector h = new MultiDimensionalVector();
                while (sheet.GetRow(row).GetCell(column) != null)
                {
                    Elements.Add(string.Format("{0: 0.0}", sheet.GetRow(row).GetCell(column)));
                    column += 1;
                }
                List <double> result  = Elements.Select(x => double.Parse(x)).ToList();
                int           integer = 0;
                foreach (double x in result)
                {
                    var newVector = x;
                    h.Add(newVector);
                    ElementsMatrix[row - 1, integer] = x;
                    integer++;
                }
                ElementsMulti.Add(h);
                column = 1;
                Elements.Clear();
            }
            ClusterCount = (counterFoRowDataFromFile / 2) + 3;
            if (ClusterCount > 10)
            {
                ClusterCount = 7;
            }
        }
Beispiel #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Conclusion"/> class.
 /// </summary>
 /// <param name="variable">
 /// The linguistic variable.
 /// </param>
 /// <param name="evaluator">
 /// The evaluation operator.
 /// </param>
 /// <param name="state">
 /// The fuzzy state.
 /// </param>
 public Conclusion(
     LinguisticVariable variable,
     IEvaluationOperator evaluator,
     FuzzyState state)
     : base(variable, evaluator, state)
 {
 }
Beispiel #14
0
        /// <summary>
        /// Returns the mouse speed given the hand movement variation.
        /// </summary>
        /// <param name="value">variation of movement</param>
        /// <returns></returns>
        public double Get(float value)
        {
            //create fuzzy engine
            fuzzyEngine = new FuzzyEngineFactory().Default();

            // movement fuzzy sets
            var variation = new LinguisticVariable("Variation");
            var litle     = variation.MembershipFunctions.AddTrapezoid("Litle", 0, 0, 40, 80);
            var medium    = variation.MembershipFunctions.AddTriangle("Medium", 30, 90, 110);
            var big       = variation.MembershipFunctions.AddTrapezoid("Big", 75, 110, 400, 400);

            // speed fuzzy sets
            var speed  = new LinguisticVariable("Speed");
            var slow   = speed.MembershipFunctions.AddTrapezoid("slow", 0, 0, 5, 10);
            var normal = speed.MembershipFunctions.AddTrapezoid("normal", 10, 20, 30, 40);
            var fast   = speed.MembershipFunctions.AddTriangle("fast", 20, 70, 70);

            //fuzzy rules
            var rule1 = Rule.If(variation.Is(litle)).Then(speed.Is(slow));
            var rule2 = Rule.If(variation.Is(medium)).Then(speed.Is(normal));
            var rule3 = Rule.If(variation.Is(big)).Then(speed.Is(fast));

            // add rules
            fuzzyEngine.Rules.Add(rule1, rule2, rule3);

            //defuzify and return results
            return(fuzzyEngine.Defuzzify(new { variation = (int)value }));
        }
Beispiel #15
0
        public FuzzyChaseState(Monster pawn) : base(pawn)
        {
            engine_chaseSpeed   = new FuzzyEngineFactory().Default();
            engine_playerEscape = new FuzzyEngineFactory().Default();

            distanceToPlayer = new LinguisticVariable("distanceToPlayer");
            var near    = distanceToPlayer.MembershipFunctions.AddTrapezoid("Near", 0, 10, 25, 40);
            var mid     = distanceToPlayer.MembershipFunctions.AddTrapezoid("Mid", 25, 40, 55, 70);
            var far     = distanceToPlayer.MembershipFunctions.AddTrapezoid("Far", 55, 70, 85, 100);
            var veryfar = distanceToPlayer.MembershipFunctions.AddTrapezoid("VeryFar", 55, 90, 120, 160);

            chaseSpeed = new LinguisticVariable("chaseSpeed");
            var slow   = chaseSpeed.MembershipFunctions.AddTrapezoid("Slow", 0.5, 0.7, 0.9, 1.2);
            var normal = chaseSpeed.MembershipFunctions.AddTrapezoid("Normal", 0.8, 1.4, 1.8, 2.2);
            var fast   = chaseSpeed.MembershipFunctions.AddTrapezoid("Fast", 1.4, 2, 2.5, 4);

            lostPlayer = new LinguisticVariable("lostPlayer");
            var lost    = lostPlayer.MembershipFunctions.AddRectangle("Lost", 0, 1);
            var notLost = lostPlayer.MembershipFunctions.AddRectangle("NotLost", -1, 0);

            var chaseSpeed_rule1 = Rule.If(distanceToPlayer.Is(far)).Then(chaseSpeed.Is(fast));
            var chaseSpeed_rule2 = Rule.If(distanceToPlayer.Is(mid)).Then(chaseSpeed.Is(normal));
            var chaseSpeed_rule3 = Rule.If(distanceToPlayer.Is(near)).Then(chaseSpeed.Is(slow));

            var lostPlayer_rule1 = Rule.If(distanceToPlayer.Is(veryfar)).Then(lostPlayer.Is(lost));
            var lostPlayer_rule2 = Rule.If(distanceToPlayer.Is(far).Or(distanceToPlayer.Is(mid)).Or(distanceToPlayer.Is(near))).Then(lostPlayer.Is(notLost));

            engine_chaseSpeed.Rules.Add(chaseSpeed_rule1, chaseSpeed_rule2, chaseSpeed_rule3);
            engine_playerEscape.Rules.Add(lostPlayer_rule1, lostPlayer_rule2);
        }
Beispiel #16
0
        public LingVar(string name, int numTerms, float min, float max, float cross)
        {
            this.min = min;
            this.max = max;
            range    = Math.Abs(max - min);

            float left, right, center;

            terms = new FuzzySet[numTerms];
            lv    = new LinguisticVariable(name, min, max);

            center = min + 0 * range / (numTerms - 1) * (1 / cross);
            right  = min + (0 + 1) * range / (numTerms - 1) * (1 / cross);

            terms[0] = new FuzzySet(name + "-0", new TrapezoidalFunction(center, right, TrapezoidalFunction.EdgeType.Right));
            lv.AddLabel(terms[0]);

            for (int i = 1; i < numTerms - 1; i++)
            {
                left   = min + (i - 1) * range / (numTerms - 1) * (1 / cross);
                center = min + i * range / (numTerms - 1) * (1 / cross);
                right  = min + (i + 1) * range / (numTerms - 1) * (1 / cross);

                terms[i] = new FuzzySet(name + "-" + i.ToString(), new TrapezoidalFunction(left, center, right));

                lv.AddLabel(terms[i]);
            }

            left   = min + (numTerms - 1 - 1) * range / (numTerms - 1) * (1 / cross);
            center = min + (numTerms - 1) * range / (numTerms - 1) * (1 / cross);

            terms[numTerms - 1] = new FuzzySet(name + "-" + (numTerms - 1).ToString(), new TrapezoidalFunction(left, center, TrapezoidalFunction.EdgeType.Left));
            lv.AddLabel(terms[numTerms - 1]);
        }
        private KB.Rule GetRule12()
        {
            Antecedent antecedent;
            Judgment   consequent;

#pragma warning disable CS0168 // Переменная "other" объявлена, но ни разу не использована.
            Judgment other;
#pragma warning restore CS0168 // Переменная "other" объявлена, но ни разу не использована.

            antecedent = new Antecedent()
                         .OR(new Judgment(FactorTitle.Ua, FactorFuzzyValue.Maximum), new Judgment(FactorTitle.Ub, FactorFuzzyValue.Maximum), new Judgment(FactorTitle.Uc, FactorFuzzyValue.Maximum))
                         .OR(new Judgment(FactorTitle.Ua, FactorFuzzyValue.Maximum), new Judgment(FactorTitle.Ua, FactorFuzzyValue.Nominal))
                         .OR(new Judgment(FactorTitle.Ub, FactorFuzzyValue.Maximum), new Judgment(FactorTitle.Ua, FactorFuzzyValue.Nominal))
                         .OR(new Judgment(FactorTitle.Uc, FactorFuzzyValue.Maximum), new Judgment(FactorTitle.Ua, FactorFuzzyValue.Nominal))
                         .AND(new Judgment(FactorTitle.Weather, FactorFuzzyValue.Unsuccessful));
            consequent = new Judgment(FactorTitle.Uimp, FactorFuzzyValue.Maximum);

            LinguisticVariable linguistic = new LinguisticVariable(
                FactorTitle.Uimp,
                null,
                new List <FactorFuzzyValue> {
                FactorFuzzyValue.Nominal, FactorFuzzyValue.Maximum, FactorFuzzyValue.Exceeding
            },
                "Грозовые импульсные напряжения",
                "В"
                );
            return(new SimpleRule(linguistic, antecedent, consequent));
        }
        private KB.Rule GetRule03()
        {
            Antecedent antecedent;
            Judgment   consequent;

            antecedent = new Antecedent()
                         .OR(new Judgment(FactorTitle.Uimp, FactorFuzzyValue.Nominal))
                         .AND(new Judgment(FactorTitle.dUabc, FactorFuzzyValue.Nominal))
                         .AND(new Judgment(FactorTitle.Uns, FactorFuzzyValue.Nominal))
                         .AND(new Judgment(FactorTitle.K2U, FactorFuzzyValue.Nominal))
                         .AND(new Judgment(FactorTitle.K2Ui, FactorFuzzyValue.Successful))
                         .AND(new Judgment(FactorTitle.dt, FactorFuzzyValue.Successful));
            consequent = new Judgment(FactorTitle.ServiceabilityEquipment, FactorFuzzyValue.Nominal);

            LinguisticVariable linguistic = new LinguisticVariable(
                FactorTitle.ServiceabilityEquipment,
                null,
                new List <FactorFuzzyValue> {
                FactorFuzzyValue.Nominal, FactorFuzzyValue.Maximum, FactorFuzzyValue.Exceeding
            },
                "Исправность технического состояния оборудования",
                null
                );

            return(new SimpleRule(linguistic, antecedent, consequent));
        }
Beispiel #19
0
    // Start is called before the first frame update
    void Start()
    {
        controller = GetComponent <CarController>();

        var acceleration = new LinguisticVariable("Acceleration");
        var accelerate   = acceleration.MembershipFunctions.AddTrapezoid("Accelerate", 1, 1.5, 2, 2);
        var coast        = acceleration.MembershipFunctions.AddTriangle("Coast", 0.5, 1, 1.5);
        var decelerate   = acceleration.MembershipFunctions.AddTrapezoid("Decelerate", 0, 0, 0.5, 1);

        var distance = new LinguisticVariable("Distance");
        var close    = distance.MembershipFunctions.AddTrapezoid("Close", 0, 0, 6, 10);
        var far      = distance.MembershipFunctions.AddTrapezoid("Far", 5, 20, 100, 100);

        var deltaToTargetDistance = new LinguisticVariable("DistanceDelta");
        var below   = deltaToTargetDistance.MembershipFunctions.AddTrapezoid("Below", 0, 0, 5, 10);
        var onPoint = deltaToTargetDistance.MembershipFunctions.AddTriangle("Middle", 5, 10, 15);
        var above   = deltaToTargetDistance.MembershipFunctions.AddTrapezoid("Above", 10, 15, 20, 20);

        var rule1 = Rule.If(deltaToTargetDistance.Is(below).Or(distance.Is(close))).Then(acceleration.Is(decelerate));
        var rule2 = Rule.If(deltaToTargetDistance.Is(above).And(distance.IsNot(close))).Then(acceleration.Is(accelerate));
        var rule3 = Rule.If(deltaToTargetDistance.Is(onPoint)).Then(acceleration.Is(coast));

        fuzzyEngine = new FuzzyEngineFactory().Default();

        fuzzyEngine.Rules.Add(rule1);
        fuzzyEngine.Rules.Add(rule2);

        StartCoroutine(AICycle());
    }
        public void CoG_Trap_Defuzzify2_Success(Int32 waterInputValue, Double expectedValue)
        {
            //Arrange
            LinguisticVariable water = new LinguisticVariable("Water");
            var cold = water.MembershipFunctions.AddTrapezoid("Cold", 0, 0, 40, 70);
            var warm = water.MembershipFunctions.AddTriangle("Warm", 40, 70, 100);
            var hot  = water.MembershipFunctions.AddTrapezoid("Hot", 70, 100, 120, 120);

            LinguisticVariable power = new LinguisticVariable("Power");
            var low  = power.MembershipFunctions.AddTriangle("Low", -50, 20, 50);
            var med  = power.MembershipFunctions.AddTriangle("Medium", 20, 50, 100);
            var high = power.MembershipFunctions.AddTriangle("High", 50, 100, 150);


            IFuzzyEngine fuzzyEngine = new FuzzyEngine(new TrapezoidCoGDefuzzification());

            fuzzyEngine.Rules.If(water.Is(cold)).Then(power.Is(high));
            fuzzyEngine.Rules.If(water.Is(warm)).Then(power.Is(med));
            fuzzyEngine.Rules.If(water.Is(hot)).Then(power.Is(low));

            //Act
            var result = fuzzyEngine.Defuzzify(new { water = waterInputValue });

            //Assert
            Assert.That(Math.Floor(result), Is.EqualTo(Math.Floor(expectedValue)));
        }
Beispiel #21
0
        public void IsLinguisticVariableOutputExcpetionTest()
        {
            RulesService.Clear();
            LinguisticVariableService.Clear();

            LinguisticVariable inputVariable1 = new LinguisticVariable("var1", 1, 10);
            LinguisticVariable inputVariable2 = new LinguisticVariable("var2", 1, 10);
            LinguisticVariable inputVariable3 = new LinguisticVariable("var3", 1, 10);

            LinguisticVariable outputVariable = new LinguisticVariable("outputVar", 1, 10);

            Term term1 = TermsFactory.Instance.CreateTermForVariable("term1", inputVariable1, new TrapezoidalFunction());
            Term term2 = TermsFactory.Instance.CreateTermForVariable("term2", inputVariable2, new TrapezoidalFunction());
            Term term3 = TermsFactory.Instance.CreateTermForVariable("term3", inputVariable3, new TrapezoidalFunction());

            Term outputTerm = TermsFactory.Instance.CreateTermForVariable("outputTerm", outputVariable, new TrapezoidalFunction());

            LinguisticVariableService.Instance.Add(inputVariable1, LinguisticVariableType.Input);
            LinguisticVariableService.Instance.Add(inputVariable2, LinguisticVariableType.Input);
            LinguisticVariableService.Instance.Add(inputVariable3, LinguisticVariableType.Input);

            LinguisticVariableService.Instance.Add(outputVariable, LinguisticVariableType.Input);

            // TODO : Variable input/output checking
            RuleBuilder builder = RuleBuilder.CreateBuilder();
            Rule        rule    = builder
                                  .Conditions()
                                  .ConditionsOperation(OperationType.And)
                                  .Add(ConditionSign.Negation, term1)
                                  .Add(ConditionSign.Identity, term2)
                                  .Add(ConditionSign.Negation, term3)
                                  .And()
                                  .OutputTerm(outputTerm)
                                  .Build();
        }
Beispiel #22
0
        public void UsageExample_Success()
        {
            //Arrange
            LinguisticVariable water = new LinguisticVariable("Water");
            var cold = water.MembershipFunctions.AddTrapezoid("Cold", 0, 0, 20, 40);
            var warm = water.MembershipFunctions.AddTriangle("Warm", 30, 50, 70);
            var hot  = water.MembershipFunctions.AddTrapezoid("Hot", 50, 80, 100, 100);

            LinguisticVariable power = new LinguisticVariable("Power");
            var low  = power.MembershipFunctions.AddTriangle("Low", 0, 25, 50);
            var high = power.MembershipFunctions.AddTriangle("High", 25, 50, 75);

            IFuzzyEngine fuzzyEngine = new FuzzyEngineFactory().Default();

            var rule1 = Rule.If(water.Is(cold).Or(water.Is(warm))).Then(power.Is(high));
            var rule2 = Rule.If(water.Is(hot)).Then(power.Is(low));

            fuzzyEngine.Rules.Add(rule1, rule2);

            //Act
            var result = fuzzyEngine.Defuzzify(new { water = 60 });

            //Assert
            Assert.That(Math.Floor(result), Is.EqualTo(Math.Floor(40.0)));

            //Extra
            System.Diagnostics.Debug.WriteLine(result);
        }
Beispiel #23
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string          Name     = null;
            Interval        Interval = new Interval();
            List <FuzzySet> fSets    = new List <FuzzySet>();


            if (!DA.GetData(0, ref Name))
            {
                return;
            }
            if (!DA.GetData(1, ref Interval))
            {
                return;
            }
            if (!DA.GetDataList(2, fSets))
            {
                return;
            }

            LinguisticVariable lingVar = new LinguisticVariable(Name, (float)Interval.Min, (float)Interval.Max);

            foreach (object x in fSets)
            {
                FuzzySet func = (FuzzySet)x;
                lingVar.AddLabel(func);
            }

            DA.SetData(0, lingVar);
        }
        public void RulePremise_Single_Success()
        {
            //Arrange
            LinguisticVariable water = new LinguisticVariable("Water");
            var cold = water.MembershipFunctions.AddTrapezoid("Cold", 0, 0, 20, 40);
            var warm = water.MembershipFunctions.AddTrapezoid("Warm", 30, 50, 50, 70);
            var hot  = water.MembershipFunctions.AddTrapezoid("Hot", 50, 80, 100, 100);

            LinguisticVariable power = new LinguisticVariable("Power");
            var low  = power.MembershipFunctions.AddTrapezoid("Low", 0, 25, 25, 50);
            var high = power.MembershipFunctions.AddTrapezoid("High", 25, 50, 50, 75);

            //Act
            var rule   = new FuzzyRule().If(water.Is(cold)).Then(power.Is(high));
            var result = rule.Premise;

            //Assert
            Assert.That(result, Is.Not.Empty, "result");
            Assert.That(result.Count, Is.EqualTo(1), "result count");

            Assert.That(result[0].Variable.Name, Is.EqualTo("Water"), "0 - water");
            Assert.That(result[0].MembershipFunction.Name, Is.EqualTo("Cold"), "0 - cold");

            //extra
            //System.Diagnostics.Debug.WriteLine(rule.Text);
        }
        public void RuleConclusion_Success()
        {
            //Arrange
            LinguisticVariable water = new LinguisticVariable("Water");
            var cold = water.MembershipFunctions.AddTrapezoid("Cold", 0, 0, 20, 40);
            var warm = water.MembershipFunctions.AddTrapezoid("Warm", 30, 50, 50, 70);
            var hot  = water.MembershipFunctions.AddTrapezoid("Hot", 50, 80, 100, 100);

            LinguisticVariable power = new LinguisticVariable("Power");
            var low  = power.MembershipFunctions.AddTrapezoid("Low", 0, 25, 25, 50);
            var high = power.MembershipFunctions.AddTrapezoid("High", 25, 50, 50, 75);

            //Act
            var rule   = new FuzzyRule().If(water.Is(cold).Or(water.Is(warm))).Then(power.Is(high));
            var result = rule.Conclusion;

            //Assert
            Assert.That(result, Is.Not.Null, "result");
            Assert.That(result.Variable, Is.Not.Null, "result variable");
            Assert.That(result.Operator, Is.Not.Null, "result operator");
            Assert.That(result.MembershipFunction, Is.Not.Null, "result MembershipFunction");
            Assert.That(result.Variable.Name, Is.EqualTo("Power"), "result variable");
            Assert.That(result.Operator.Name, Is.EqualTo("IS"), "result operator");
            Assert.That(result.MembershipFunction.Name, Is.EqualTo("High"), "result MembershipFunction");

            //extra
            //System.Diagnostics.Debug.WriteLine(rule.Text);
        }
        public void RuleValid_Success()
        {
            //Arrange
            LinguisticVariable water = new LinguisticVariable("Water");
            var cold = water.MembershipFunctions.AddTrapezoid("Cold", 0, 0, 20, 40);
            var warm = water.MembershipFunctions.AddTrapezoid("Warm", 30, 50, 50, 70);
            var hot  = water.MembershipFunctions.AddTrapezoid("Hot", 50, 80, 100, 100);

            LinguisticVariable power = new LinguisticVariable("Power");
            var low  = power.MembershipFunctions.AddTrapezoid("Low", 0, 25, 25, 50);
            var high = power.MembershipFunctions.AddTrapezoid("High", 25, 50, 50, 75);

            //Act
            var rule1 = new FuzzyRule().If(water.Is(cold)).Then(power.Is(high));                                        //valid
            var rule2 = new FuzzyRule().If(water.IsNot(cold)).Then(power.Is(high));                                     //valid
            var rule3 = new FuzzyRule().If(water.Is(cold).Or(water.Is(warm))).Then(power.Is(high));                     //valid
            var rule4 = new FuzzyRule().If(water.Is(cold).Or(water.Is(warm)).And(water.Is(hot))).Then(power.Is(high));  //valid
            var rule5 = new FuzzyRule().If(water.Is(cold).And(water.Is(warm)).And(water.Is(hot))).Then(power.Is(high)); //valid
            var rule6 = new FuzzyRule().If(water.Is(cold).Or(water.Is(warm)).Or(water.Is(hot))).Then(power.Is(high));   //valid

            var result1 = rule1.IsValid();
            var result2 = rule2.IsValid();
            var result3 = rule3.IsValid();
            var result4 = rule4.IsValid();
            var result5 = rule3.IsValid();
            var result6 = rule4.IsValid();

            //Assert
            Assert.That(result1, Is.True, "result1");
            Assert.That(result2, Is.True, "result2");
            Assert.That(result3, Is.True, "result3");
            Assert.That(result4, Is.True, "result4");
            Assert.That(result5, Is.True, "result5");
            Assert.That(result6, Is.True, "result6");
        }
        public void RuleInvalid_Success()
        {
            //Arrange
            LinguisticVariable water = new LinguisticVariable("Water");
            var cold = water.MembershipFunctions.AddTrapezoid("Cold", 0, 0, 20, 40);
            var warm = water.MembershipFunctions.AddTrapezoid("Warm", 30, 50, 50, 70);
            var hot  = water.MembershipFunctions.AddTrapezoid("Hot", 50, 80, 100, 100);

            LinguisticVariable power = new LinguisticVariable("Power");
            var low  = power.MembershipFunctions.AddTrapezoid("Low", 0, 25, 25, 50);
            var high = power.MembershipFunctions.AddTrapezoid("High", 25, 50, 50, 75);

            //Act
            var rule4 = new FuzzyRule().If(water.Is(cold).Or(water.Is(warm)));                    //not
            var rule5 = new FuzzyRule().Then(power.Is(high));                                     //not
            var rule6 = new FuzzyRule().If(new List <FuzzyRuleCondition>()).Then(power.Is(high)); //not

            var result1 = rule4.IsValid();
            var result2 = rule5.IsValid();
            var result3 = rule6.IsValid();

            //Assert
            Assert.That(result1, Is.False, "result1");
            Assert.That(result2, Is.False, "result2");
            Assert.That(result3, Is.False, "result3");
        }
Beispiel #28
0
Datei: Need.cs Projekt: Quotas/AI
    public Need(string name, Func <ProcessState> task, Utility u, float min, float max, float scale = 1)
    {
        state = new StateMachine <State, Trigger>(State.Fufilled);
        InternalNeedMethod = task;

        state.Configure(State.Fufilled)
        .Permit(Trigger.OnMinValueReached, State.Unfufilled);

        state.Configure(State.Unfufilled)
        .OnEntry(t => ActionPriorityList.Add(InternalNeedMethod))
        .Permit(Trigger.OnMaxValueReached, State.Fufilled);


        _minValue = min;
        _maxValue = max;
        _scale    = scale;

        utility = u;

        Value    = max;
        Name     = name;
        Priority = 0;

        fuzzyengine = new FuzzyEngine();


        LinguisticVariable priority = new LinguisticVariable("Priority");

        priority.MembershipFunctionCollection.Add(new MembershipFunction("High", 0, 25, 25, 50));
        priority.MembershipFunctionCollection.Add(new MembershipFunction("Low", 50, 75, 75, 100));


        fuzzyengine.LinguisticVariableCollection.Add(priority);
        fuzzyengine.Consequent = "Priority";
    }
Beispiel #29
0
        /// <summary>
        /// Parses an XML FuzzyExpression element
        /// </summary>
        /// <param name="a_expression">XML FuzzyExpression element</param>
        /// <param name="a_isPremise">Corresponding FuzzyExpression object or null if parsing is unsuccessful</param>
        /// <returns></returns>
        private FuzzyExpression ParseFuzzyExpression(XElement a_expression, bool a_isPremise)
        {
            LinguisticVariable linguisticVariable = null;
            string             variableName       = a_expression.Descendants("LinguisticVariableName").FirstOrDefault().Value;
            string             valueName          = a_expression.Descendants("LinguisticValueName").FirstOrDefault().Value;

            if (variableName != null && variableName != string.Empty && valueName != null && valueName != string.Empty)
            {
                if (a_isPremise)
                {
                    foreach (var variable in inputs)
                    {
                        if (variable.Name == variableName)
                        {
                            linguisticVariable = variable;
                        }
                    }
                }
                else
                {
                    if (output.Name == variableName)
                    {
                        linguisticVariable = output;
                    }
                }
            }
            if (linguisticVariable != null && linguisticVariable.Values.Where(x => x.Name == valueName).Count() != 0)
            {
                return(new FuzzyExpression(linguisticVariable, valueName));
            }
            else
            {
                return(null);
            }
        }
        protected LinguisticVariable CreateLinguisticVariable()
        {
            var result = new LinguisticVariable();

            DefaultSettingsOfCodeEntityHelper.SetUpLinguisticVariable(result, CurrentDefaultSetings);
            return(result);
        }
Beispiel #31
0
        public void Test1()
        {
            LinguisticVariable water = new LinguisticVariable("Water");
            var cold = water.MembershipFunctions.AddTrapezoid("Cold", 0, 0, 20, 40);
            var warm = water.MembershipFunctions.AddTriangle("Warm", 30, 50, 70);
            var hot = water.MembershipFunctions.AddTrapezoid("Hot", 50, 80, 100, 100);

            LinguisticVariable power = new LinguisticVariable("Power");
            var low = power.MembershipFunctions.AddTriangle("Low", 0, 25, 50);
            var high = power.MembershipFunctions.AddTriangle("High", 25, 50, 75);

            IFuzzyEngine fuzzyEngine = new FuzzyEngineFactory().Default();

            fuzzyEngine.Rules.If(water.Is(cold).Or(water.Is(warm))).Then(power.Is(high));
            fuzzyEngine.Rules.If(water.Is(hot)).Then(power.Is(low));

            var result = fuzzyEngine.Defuzzify(new { water = 60 });
        }
        public static double CalcularPoliza(double inputEnfermedadesActuales, double inputEnfermedadesHistoricas, double inputEstiloDeVida, double inputOcupacion)
        {
            LinguisticVariable enfermedadesActuales = new LinguisticVariable("EnfermedadesActuales");
            var sano = enfermedadesActuales.MembershipFunctions.AddTrapezoid("Sano", 0, 0, 20, 40);
            var regular = enfermedadesActuales.MembershipFunctions.AddTriangle("Regular", 30, 50, 70);
            var malo = enfermedadesActuales.MembershipFunctions.AddTrapezoid("Malo", 60, 80, 100, 100);

            LinguisticVariable enfermedadesHistoricas = new LinguisticVariable("EnfermedadesHistoricas");
            var bajas = enfermedadesHistoricas.MembershipFunctions.AddTrapezoid("Bajas", 0, 0, 20, 40);
            var normales = enfermedadesHistoricas.MembershipFunctions.AddTriangle("Normales", 30, 50, 70);
            var altas = enfermedadesHistoricas.MembershipFunctions.AddTrapezoid("Altas", 60, 80, 100, 100);

            LinguisticVariable estiloVida = new LinguisticVariable("EstiloVida");
            var tranquilo = estiloVida.MembershipFunctions.AddTrapezoid("Tranquilo", 0, 0, 20, 40);
            var moderado = estiloVida.MembershipFunctions.AddTriangle("Moderado", 30, 50, 70);
            var reisgozo = estiloVida.MembershipFunctions.AddTrapezoid("Riesgozo", 60, 80, 100, 100);

            LinguisticVariable ocupacion = new LinguisticVariable("Ocupacion");
            var ocupacionNormal = ocupacion.MembershipFunctions.AddTrapezoid("Normal", 0, 0, 20, 40);
            var ocupacionBajoRiezgo = ocupacion.MembershipFunctions.AddTriangle("Riesgoza", 30, 50, 70);
            var ocupacionAltoRiezgo = ocupacion.MembershipFunctions.AddTrapezoid("AltoRiezgo", 60, 80, 100, 100);

            LinguisticVariable estadoAseguramiento = new LinguisticVariable("EstadoAseguramiento");
            var coberturaTotal = estadoAseguramiento.MembershipFunctions.AddTrapezoid("Total", 0, 0, 17.5, 30);
            var coberturaModerada = estadoAseguramiento.MembershipFunctions.AddTriangle("Moderada", 20, 37.5, 55);
            var coberturaBaja = estadoAseguramiento.MembershipFunctions.AddTriangle("Baja", 45, 62.5, 80);
            var coberturaNula = estadoAseguramiento.MembershipFunctions.AddTrapezoid("Nula", 70, 87.5, 100, 100);

            IFuzzyEngine fuzzyEngine = new FuzzyEngineFactory().Create(new CoGDefuzzification());

            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(malo).Or(enfermedadesHistoricas.Is(altas)))
                .If(estiloVida.Is(reisgozo).Or(ocupacion.Is(ocupacionAltoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaNula));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(malo).Or(enfermedadesHistoricas.Is(altas)))
                .If(estiloVida.Is(reisgozo).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaNula));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(malo).Or(enfermedadesHistoricas.Is(altas)))
                .If(estiloVida.Is(moderado).And(ocupacion.Is(ocupacionAltoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaNula));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(malo).Or(enfermedadesHistoricas.Is(altas)))
                .If(estiloVida.Is(moderado).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaBaja));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(malo).Or(enfermedadesHistoricas.Is(altas)))
                .If(estiloVida.Is(moderado).And(ocupacion.Is(ocupacionNormal)))
                .Then(estadoAseguramiento.Is(coberturaBaja));
            fuzzyEngine.Rules
                  .If(enfermedadesActuales.Is(malo).Or(enfermedadesHistoricas.Is(altas)))
                  .If(estiloVida.Is(tranquilo).And(ocupacion.Is(ocupacionBajoRiezgo)))
                  .Then(estadoAseguramiento.Is(coberturaBaja));
            fuzzyEngine.Rules
                  .If(enfermedadesActuales.Is(malo).Or(enfermedadesHistoricas.Is(altas)))
                  .If(estiloVida.Is(tranquilo).And(ocupacion.Is(ocupacionNormal)))
                  .Then(estadoAseguramiento.Is(coberturaModerada));

            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(regular).Or(enfermedadesHistoricas.Is(normales)).And(estiloVida.Is(reisgozo)).And(ocupacion.Is(ocupacionAltoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaNula));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(regular).Or(enfermedadesHistoricas.Is(normales)).And(estiloVida.Is(moderado)).And(ocupacion.Is(ocupacionAltoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaBaja));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(regular).Or(enfermedadesHistoricas.Is(normales)).And(estiloVida.Is(reisgozo)).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaBaja));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(regular).Or(enfermedadesHistoricas.Is(normales)).And(estiloVida.Is(moderado)).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaModerada));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(regular).Or(enfermedadesHistoricas.Is(normales)).And(estiloVida.Is(tranquilo)).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaModerada));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(regular).Or(enfermedadesHistoricas.Is(normales)).And(estiloVida.Is(moderado)).And(ocupacion.Is(ocupacionNormal)))
                .Then(estadoAseguramiento.Is(coberturaModerada));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(regular).Or(enfermedadesHistoricas.Is(normales)).And(estiloVida.Is(tranquilo)).And(ocupacion.Is(ocupacionNormal)))
                .Then(estadoAseguramiento.Is(coberturaTotal));

            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(sano).Or(enfermedadesHistoricas.Is(bajas)).And(estiloVida.Is(reisgozo)).And(ocupacion.Is(ocupacionAltoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaBaja));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(sano).Or(enfermedadesHistoricas.Is(bajas)).And(estiloVida.Is(moderado)).And(ocupacion.Is(ocupacionAltoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaModerada));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(sano).Or(enfermedadesHistoricas.Is(bajas)).And(estiloVida.Is(reisgozo)).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaModerada));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(sano).Or(enfermedadesHistoricas.Is(bajas)).And(estiloVida.Is(moderado)).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaTotal));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(sano).Or(enfermedadesHistoricas.Is(bajas)).And(estiloVida.Is(tranquilo)).And(ocupacion.Is(ocupacionBajoRiezgo)))
                .Then(estadoAseguramiento.Is(coberturaTotal));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(sano).Or(enfermedadesHistoricas.Is(bajas)).And(estiloVida.Is(moderado)).And(ocupacion.Is(ocupacionNormal)))
                .Then(estadoAseguramiento.Is(coberturaTotal));
            fuzzyEngine.Rules
                .If(enfermedadesActuales.Is(sano).Or(enfermedadesHistoricas.Is(bajas)))
                .If(estiloVida.Is(tranquilo).And(ocupacion.Is(ocupacionNormal)))
                .Then(estadoAseguramiento.Is(coberturaTotal));

            var result = fuzzyEngine.Defuzzify(new {
                enfermedadesActuales = inputEnfermedadesActuales,
                enfermedadesHistoricas = inputEnfermedadesHistoricas,
                estiloVida = inputEstiloDeVida,
                ocupacion = inputOcupacion
            });

            return result;
        }