/// <summary> /// Defuzzifies the specified relation returning a crisp value for the specified inputs. /// </summary> /// <param name="relation">Fuzzy Relation to defuzzify</param> /// <param name="inputs">Set of specified values for particular dimensions. There must be exactly one dimesion missing. This dimension will be used as the output dimension.</param> public Defuzzification(FuzzyRelation relation, Dictionary<IDimension, System.Decimal> inputs) { _relation = relation; if (inputs.Count < _relation.Dimensions.Length - 1) throw new ArgumentException(String.Format("Number of dimensions must be bigger than n-1, where n={0} is the total number of dimensions used in the relation.", relation.Dimensions.Length), "inputs"); List<IDimension> dims = _relation.Dimensions.ToList<IDimension>(); foreach (KeyValuePair<IDimension, System.Decimal> input in inputs) { //if (!dims.Contains(input.Key)) // throw new ArgumentException(String.Format("Dimension \"{0}\" does not exists in this relation.", input.Key), "inputs"); if (dims.Contains(input.Key)) dims.Remove(input.Key); } if (dims.Count > 1) throw new ArgumentException("There is more than one unspecified dimension left.", "inputs"); if (dims.Count == 0) throw new ArgumentException("There are no unspecified dimensions left. The output function would be a constanct which can be obtained easier using the IsMember() method.", "inputs"); _inputs = inputs; _outputDimension = dims[0]; if (_outputDimension is IDiscreteDimension) throw new ArgumentException(String.Format("Continuous dimension expected as output dimension. Dimension \"{0}\" is discrete.", _outputDimension.Name)); }
/// <summary> /// Creates new instance of the TreeSource for the specifed relation /// </summary> /// <param name="deffuzification">Relation wrapped in a deffuzification. In this case, the hierarchy will also contain information about applied deffuzification.</param> public TreeSource(Defuzzification deffuzification) { _relation = deffuzification.Relation; _deffuzification = deffuzification; _inputs = deffuzification.Inputs; _variableDimension = deffuzification.OutputDimension; }
internal RSS(FuzzyRelation subrelation1, FuzzyRelation subrelation2) { _subrelation1 = subrelation1; _subrelation2 = subrelation2; _rssDescendantCount = 2; if (_subrelation1 is NodeFuzzyRelation && ((NodeFuzzyRelation)_subrelation1).Operator is RSS) { _operand1Power = false; //powers have been created in subrelation _rssDescendantCount += ((RSS)((NodeFuzzyRelation)_subrelation1).Operator).RssDescendantCount - 1; } else { _operand1Power = true; } if (_subrelation2 is NodeFuzzyRelation && ((NodeFuzzyRelation)_subrelation2).Operator is RSS) { _operand2Power = false; //powers have been created in subrelation _rssDescendantCount += ((RSS)((NodeFuzzyRelation)_subrelation2).Operator).RssDescendantCount - 1; } else { _operand2Power = true; } }
/// <summary> /// Creates new instance of the TreeSource for the specifed relation /// </summary> /// <param name="relation">Fuzzy relation to represent as a hierarchical list</param> /// <param name="inputs">Set of specified values for particular dimensions.</param> /// <param name="variableDimension">Dimension which should be put on the x-axis. Null if we don't want to display graphs, or if we only want to display graphs for single-diemnsional sets.</param> public TreeSource(FuzzyRelation relation, Dictionary<IDimension, System.Decimal> inputs, IDimension variableDimension) { _relation = relation; _inputs = inputs; _variableDimension = variableDimension; treeView_AfterSelect_EventHandler = new TreeViewEventHandler(treeView_AfterSelect); }
/// <summary> /// Creates new instance of the TreeSource for the specifed relation /// </summary> /// <param name="relation">Fuzzy relation to represent as a hierarchical list</param> /// <param name="inputs">Set of specified values for particular dimensions.</param> /// <param name="variableDimension">Dimension which should be put on the x-axis. Null if we don't want to display graphs, or if we only want to display graphs for single-diemnsional sets.</param> public TreeSource(FuzzyRelation relation, Dictionary <IDimension, System.Decimal> inputs, IDimension variableDimension) { _relation = relation; _inputs = inputs; _variableDimension = variableDimension; treeView_AfterSelect_EventHandler = new TreeViewEventHandler(treeView_AfterSelect); }
/// <summary> /// Creates new instance of image just to display a single-dimensional fuzzy set without any values specified. /// </summary> /// <param name="singleDimensionalSet">Single-dimensional set to display</param> public RelationImage(FuzzySet singleDimensionalSet) { _inputs = new Dictionary<IDimension, decimal> { }; _relation = singleDimensionalSet; _variableDimension = singleDimensionalSet.Dimensions[0]; _fullySpecified = false; _specifiedMembership = null; }
/// <summary> /// Creates new instance of the TreeSource for the specifed relation /// </summary> /// <param name="deffuzification">Relation wrapped in a deffuzification. In this case, the hierarchy will also contain information about applied deffuzification.</param> public TreeSource(FuzzyFramework.Defuzzification.Defuzzification deffuzification) { _relation = deffuzification.Relation; _deffuzification = deffuzification; _inputs = deffuzification.Inputs; _variableDimension = deffuzification.OutputDimension; treeView_AfterSelect_EventHandler = new TreeViewEventHandler(treeView_AfterSelect); }
/// <summary> /// Creates new instance of image just to display a single-dimensional fuzzy set without any values specified. /// </summary> /// <param name="singleDimensionalSet">Single-dimensional set to display</param> public RelationImage(FuzzySet singleDimensionalSet) { _inputs = new Dictionary <IDimension, decimal> { }; _relation = singleDimensionalSet; _variableDimension = singleDimensionalSet.Dimensions[0]; _fullySpecified = false; _specifiedMembership = null; }
private void Awake() { m_Car = GetComponent <CarController>(); inputSpeed = new ContinuousDimension("", "", "", -100, 180); backwardSpeed = new RightQuadraticSet(inputSpeed, "", -100, -10, 0); zeroSpeed = new BellSet(inputSpeed, "", 0, 5, 10); lowSpeed = new QuadraticSet(inputSpeed, "", 10, 40, 0, 50, 5, 45); //private FuzzySet medSpeed; highSpeed = new LeftQuadraticSet(inputSpeed, "", 40, 45, 50); inputSideBoundDistance = new ContinuousDimension("", "", "", -10, 10); dangerousRight = new LeftQuadraticSet(inputSideBoundDistance, "", 0, 9, 10); dangerousLeft = new RightQuadraticSet(inputSideBoundDistance, "", -10, -9, 0); safe = new TrapezoidalSet(inputSideBoundDistance, "", -5, 5, -7, 7); inputFrontBoundDistance = new ContinuousDimension("", "", "", 0, 150); far = new LeftLinearSet(inputFrontBoundDistance, "", 20, 40); close = new TrapezoidalSet(inputFrontBoundDistance, "", 15, 20, 10, 25); dangerousClose = new RightLinearSet(inputFrontBoundDistance, "", 10, 15); outputGas = new ContinuousDimension("", "", "", -100, 100); pedalToMetal = new LeftQuadraticSet(outputGas, "", 0, 80, 100); clutch = new SingletonSet(outputGas, "", 0); brake = new RightLinearSet(outputGas, "", -100, 0); outputBrakes = new ContinuousDimension("", "", "", 0, 1); outputAction = new DiscreteDimension("", ""); outputSteeringWheel = new ContinuousDimension("", "", "", -100, 100); turnLeft = new RightLinearSet(outputSteeringWheel, "", -100, 0); turnRight = new LeftLinearSet(outputSteeringWheel, "", 0, 100); forward = new TriangularSet(outputSteeringWheel, "", 0, -10, 10); simpleSteeringRules = (dangerousLeft & turnRight) | (dangerousRight & turnLeft) | (safe & forward); simpleGasRules = (far & pedalToMetal) | ((close & lowSpeed) & clutch) | ((close & highSpeed) & brake) | ((close & zeroSpeed) & brake) | (dangerousClose & brake); }
void Calc() { #region Definitions //Definition of dimensions on which we will measure the input values ContinuousDimension height = new ContinuousDimension("Height", "Personal height", "cm", 100, 250); ContinuousDimension weight = new ContinuousDimension("Weight", "Personal weight", "kg", 30, 200); //Definition of dimension for output value ContinuousDimension consequent = new ContinuousDimension("Suitability for basket ball", "0 = not good, 5 = very good", "grade", 0, 5); //Definition of basic fuzzy sets with which we will work // input sets: FuzzySet tall = new LeftLinearSet(height, "Tall person", 170, 185); FuzzySet weighty = new LeftLinearSet(weight, "Weighty person", 80, 100); // output set: FuzzySet goodForBasket = new LeftLinearSet(consequent, "Good in basket ball", 0, 5); //Definition of antedescent FuzzyRelation lanky = tall & !weighty; //Implication FuzzyRelation term = (lanky & goodForBasket) | (!lanky & !goodForBasket); #endregion #region Input values //Console.Write("Enter your height in cm:"); //decimal inputHeight = decimal.Parse(Console.ReadLine()); decimal inputHeight = _inputHeight; //Console.Write("Enter your weight in kg:"); //decimal inputWeight = decimal.Parse(Console.ReadLine()); decimal inputWeight = _inputWeight; #endregion #region Deffuzification of the output set Defuzzification result = new MeanOfMaximum( term, new Dictionary <IDimension, decimal> { { height, inputHeight }, { weight, inputWeight } } ); //Console.WriteLine(String.Format("Your disposition to be a basketball player is {0:F3} out of <0,...,5>", result.CrispValue)); // Debug.Log("Your disposition to be a basketball player is {0:F3} out of <0,...,5>" + result.CrispValue); ans = (double)result.CrispValue; text.text = ans.ToString(); //Console.WriteLine("Press any key to exit"); //Console.ReadKey(); #endregion }
/// <summary> /// Creates new instance of image depicting the specified relation. /// </summary> /// <param name="relation">Relation to draw</param> /// <param name="inputs">Set of specified values for particular dimensions. There can be one dimesion missing. This dimension will be used as the variable dimension on the X-axis. If all dimensions specified, variable dimension needs to be specifed as explicit parameter</param> public RelationImage(FuzzyRelation relation, Dictionary <IDimension, System.Decimal> inputs, IDimension variableDimension) { _relation = relation; if (inputs.Count < _relation.Dimensions.Length - 1) { throw new ArgumentException(String.Format("Number of dimensions must at least n-1, where n={0} is the total number of dimensions used in the relation.", relation.Dimensions.Length), "inputs"); } List <IDimension> dims = _relation.Dimensions.ToList <IDimension>(); foreach (KeyValuePair <IDimension, System.Decimal> input in inputs) { //if (!dims.Contains(input.Key)) // throw new ArgumentException(String.Format("Dimension \"{0}\" does not exists in this relation.", input.Key), "inputs"); if (dims.Contains(input.Key)) { dims.Remove(input.Key); } } if (dims.Count > 1) { throw new ArgumentException("There is more than one unspecified dimension left.", "inputs"); } _inputs = inputs; if (dims.Count == 1) { _variableDimension = dims[0]; if (variableDimension != null && variableDimension != _variableDimension) { throw new ArgumentException("Variable dimension missing in inputs does not match the dimension specified by parameter variableDimension.", "variableDimension"); } _fullySpecified = false; } else { if (variableDimension == null) { throw new ArgumentException("Variable dimension has to be defined explicitly if all variables specified in parameter inputs.", "variableDimension"); } _variableDimension = variableDimension; _fullySpecified = true; _specifiedValue = new decimal?(_inputs[_variableDimension]); _specifiedMembership = new Nullable <double>(this.isMember(_specifiedValue.Value)); } }
void Start() { _rigidbody = GetComponent <Rigidbody>(); altitude = new ContinuousDimension("Altitude", "Altitude", "units", -100, 100); velocity = new ContinuousDimension("Velocity", "Velocity", "units/s", -50, 50); Adim = new ContinuousDimension("", "", "", 0, 10); Bdim = new ContinuousDimension("", "", "", 0, 10); Cdim = new ContinuousDimension("", "", "", 0, 10); A = new TriangularSet(Adim, "", 2, 0, 4); B = new TriangularSet(Bdim, "", 4, 3, 5); C = new TriangularSet(Cdim, "", 5, 0, 10); AlarsB = (A & B) / C; var projection = AlarsB.Project(new Dictionary <IDimension, decimal> { { Adim, 3 }, { Bdim, 4 } }); for (decimal i = 0; i < 10; i += 1) { Debug.Log(i + " " + projection.IsMember(i)); } upSpeed = new LeftLinearSet(velocity, "up speed", 5, 30); downSpeed = new RightLinearSet(velocity, "down speed", -30, -5); noSpeed = new TriangularSet(velocity, "no speed", 0, -10, 10); high = new LeftLinearSet(altitude, "high", 5, 20); low = new RightLinearSet(altitude, "l", -20, -5); mid = new TriangularSet(altitude, "l", 0, -10, 10); term = (high / downSpeed) % (low / upSpeed) % (mid / noSpeed); /* * lowUp = (low * upSpeed); * highDown = (high * downSpeed); * midno = mid * noSpeed; * * for (decimal x = -30; x<= 30; x++) { * for (decimal y = -30; y <= 30 ; y++) { * Debug.Log("low(" + x + ") && upSpeed(" + y + ") = " + lowUp.IsMember(new Dictionary<IDimension, decimal> { {altitude, x}, {velocity, y} })); * } * * } */ }
/// <summary> /// Construct instance of a defuzzification wrapper which wrappes a fuzzy relation to deffuzify. /// </summary> /// <param name="relation">Fuzzy Relation to defuzzify</param> /// <param name="inputs">Set of specified values for particular dimensions. There must be exactly one dimesion missing. This dimension will be used as the output dimension.</param> /// <param name="method">Deffuzification method to apply</param> /// <returns></returns> public static Defuzzification GetDefuzzification(FuzzyRelation relation, Dictionary<IDimension, System.Decimal> inputs, DefuzzificationMethod method) { switch (method) { case DefuzzificationMethod.CenterOfGravity: return new CenterOfGravity(relation, inputs); case DefuzzificationMethod.CenterOfMaximum: return new CenterOfMaximum(relation, inputs); case DefuzzificationMethod.LeftOfMaximum: return new LeftOfMaximum(relation, inputs); case DefuzzificationMethod.RightOfMaximum: return new RightOfMaximum(relation, inputs); case DefuzzificationMethod.MeanOfMaximum: return new MeanOfMaximum(relation, inputs); default: throw new NotImplementedException("Unknown defuuzification method."); } }
private float ComputeGas(float distanceToFrontBound, FuzzyRelation relation) { decimal distance = (decimal)Mathf.Clamp(distanceToFrontBound, 0.0f, 150.0f); if (displayGui) { memberDangerouslyClose = (float)dangerousClose.IsMember(distance); memberClose = (float)close.IsMember(distance); memberFar = (float)far.IsMember(distance); memberZeroSpeed = (float)zeroSpeed.IsMember((decimal)m_Car.CurrentSpeed); memberLowSpeed = (float)lowSpeed.IsMember((decimal)m_Car.CurrentSpeed); memberHighSpeed = (float)highSpeed.IsMember((decimal)m_Car.CurrentSpeed); } /* * FuzzySet projection = simpleSteeringRules.Project(new Dictionary<IDimension, decimal>() * { * {inputSideBoundDistance, distance } * }); * * string str = ""; * * for (decimal i = -100; i <= 100; i += 20) { * str += i + ": " + projection.IsMember(i) + ", "; * } * Debug.Log(str); */ Defuzzification result = new CenterOfGravity(relation, new Dictionary <IDimension, decimal>() { { inputFrontBoundDistance, distance }, { inputSpeed, (decimal)m_Car.CurrentSpeed } }); //Debug.Log("distance: " + distance + ", gas: " + result.CrispValue); crispGas = (float)result.CrispValue; return((float)result.CrispValue); }
/// <summary> /// Defuzzifies the specified relation returning a crisp value for the specified inputs. /// </summary> /// <param name="relation">Fuzzy Relation to defuzzify</param> /// <param name="inputs">Set of specified values for particular dimensions. There must be exactly one dimesion missing. This dimension will be used as the output dimension.</param> public Defuzzification(FuzzyRelation relation, Dictionary <IDimension, System.Decimal> inputs) { _relation = relation; if (inputs.Count < _relation.Dimensions.Length - 1) { throw new ArgumentException(String.Format("Number of dimensions must be bigger than n-1, where n={0} is the total number of dimensions used in the relation.", relation.Dimensions.Length), "inputs"); } List <IDimension> dims = _relation.Dimensions.ToList <IDimension>(); foreach (KeyValuePair <IDimension, System.Decimal> input in inputs) { //if (!dims.Contains(input.Key)) // throw new ArgumentException(String.Format("Dimension \"{0}\" does not exists in this relation.", input.Key), "inputs"); if (dims.Contains(input.Key)) { dims.Remove(input.Key); } } if (dims.Count > 1) { throw new ArgumentException("There is more than one unspecified dimension left.", "inputs"); } if (dims.Count == 0) { throw new ArgumentException("There are no unspecified dimensions left. The output function would be a constanct which can be obtained easier using the IsMember() method.", "inputs"); } _inputs = inputs; _outputDimension = dims[0]; if (_outputDimension is IDiscreteDimension) { throw new ArgumentException(String.Format("Continuous dimension expected as output dimension. Dimension \"{0}\" is discrete.", _outputDimension.Name)); } }
protected bool allInputDimensionsAvailable(FuzzyRelation relation) { if (relation.Dimensions.Count() == 1) { return(true); } if (_variableDimension == null) { return(false); } foreach (IDimension dimension in relation.Dimensions) { if (!_inputs.ContainsKey(dimension) && dimension != _variableDimension) { return(false); } } return(true); }
/// <summary> /// Creates new instance of image depicting the specified relation. /// </summary> /// <param name="relation">Relation to draw</param> /// <param name="inputs">Set of specified values for particular dimensions. There can be one dimesion missing. This dimension will be used as the variable dimension on the X-axis. If all dimensions specified, variable dimension needs to be specifed as explicit parameter</param> public RelationImage(FuzzyRelation relation, Dictionary<IDimension, System.Decimal> inputs, IDimension variableDimension) { _relation = relation; if (inputs.Count < _relation.Dimensions.Length - 1) throw new ArgumentException(String.Format("Number of dimensions must at least n-1, where n={0} is the total number of dimensions used in the relation.", relation.Dimensions.Length), "inputs"); List<IDimension> dims = _relation.Dimensions.ToList<IDimension>(); foreach (KeyValuePair<IDimension, System.Decimal> input in inputs) { //if (!dims.Contains(input.Key)) // throw new ArgumentException(String.Format("Dimension \"{0}\" does not exists in this relation.", input.Key), "inputs"); if (dims.Contains(input.Key)) dims.Remove(input.Key); } if (dims.Count > 1) throw new ArgumentException("There is more than one unspecified dimension left.", "inputs"); _inputs = inputs; if (dims.Count == 1) { _variableDimension = dims[0]; if (variableDimension != null && variableDimension != _variableDimension) throw new ArgumentException("Variable dimension missing in inputs does not match the dimension specified by parameter variableDimension.", "variableDimension"); _fullySpecified = false; } else { if (variableDimension == null) throw new ArgumentException("Variable dimension has to be defined explicitly if all variables specified in parameter inputs.", "variableDimension"); _variableDimension = variableDimension; _fullySpecified = true; _specifiedValue = new decimal?(_inputs[_variableDimension]); _specifiedMembership = new Nullable<double>( this.isMember(_specifiedValue.Value) ); } }
/// <summary> /// Construct instance of a defuzzification wrapper which wrappes a fuzzy relation to deffuzify. /// </summary> /// <param name="relation">Fuzzy Relation to defuzzify</param> /// <param name="inputs">Set of specified values for particular dimensions. There must be exactly one dimesion missing. This dimension will be used as the output dimension.</param> /// <param name="method">Deffuzification method to apply</param> /// <returns></returns> public static Defuzzification GetDefuzzification(FuzzyRelation relation, Dictionary <IDimension, System.Decimal> inputs, DefuzzificationMethod method) { switch (method) { case DefuzzificationMethod.CenterOfGravity: return(new CenterOfGravity(relation, inputs)); case DefuzzificationMethod.CenterOfMaximum: return(new CenterOfMaximum(relation, inputs)); case DefuzzificationMethod.LeftOfMaximum: return(new LeftOfMaximum(relation, inputs)); case DefuzzificationMethod.RightOfMaximum: return(new RightOfMaximum(relation, inputs)); case DefuzzificationMethod.MeanOfMaximum: return(new MeanOfMaximum(relation, inputs)); default: throw new NotImplementedException("Unknown defuuzification method."); } }
private float ComputeSteering(float distToLeftBound, float distToRightBound, FuzzyRelation relation) { float r = Mathf.Clamp(distToRightBound, 0.0f, 20.0f); float l = Mathf.Clamp(distToLeftBound, 0.0f, 20.0f); float middle = (l + r) / 2; float fCarPosition; if (r < middle) { fCarPosition = 10.0f - (r / middle) * 10.0f; } else { fCarPosition = -10.0f + (l / middle) * 10.0f; } decimal carPosition = (decimal)fCarPosition; if (displayGui) { memberLeft = (float)dangerousLeft.IsMember(carPosition); memberRight = (float)dangerousRight.IsMember(carPosition); memberCenter = (float)safe.IsMember(carPosition); } Defuzzification result = new CenterOfGravity(relation, new Dictionary <IDimension, decimal>() { { inputSideBoundDistance, carPosition } }); crispSteeringWheel = (float)result.CrispValue; return((float)result.CrispValue); }
/// <summary> /// Method to be invoked recursively to build the whole tree /// </summary> /// <param name="nodeCollection"></param> /// <param name="pictureBox"></param> /// <param name="label"></param> protected void buildSubTree(FuzzyRelation subrelation, TreeNodeCollection nodeCollection, PictureBox pictureBox, Label label) { TreeNode tnThis; if (subrelation is FuzzySet) { FuzzySet fs = (FuzzySet)subrelation; tnThis = new TreeNode(); if (!String.IsNullOrEmpty(fs.Caption)) { tnThis.Text = fs.Caption; } else { tnThis.Text = "Fuzzy Set"; tnThis.ForeColor = UnnamedNodeFontColor; } tnThis.ImageKey = "fuzzySet"; tnThis.SelectedImageKey = "fuzzySet"; TreeNode tnDimType = new TreeNode("Type: " + (fs.Dimensions[0] is IContinuousDimension ? "Continuous" : "Discrete")); tnDimType.ImageKey = "dimensionType"; tnDimType.SelectedImageKey = "dimensionType"; tnThis.Nodes.Add(tnDimType); } else { NodeFuzzyRelation nfr = (NodeFuzzyRelation)subrelation; tnThis = new TreeNode("Multidimensional Relation"); tnThis.ForeColor = UnnamedNodeFontColor; tnThis.ImageKey = "nodeFuzzyRelation"; tnThis.SelectedImageKey = "nodeFuzzyRelation"; TreeNode tnSubrelations = new TreeNode(nfr.Operator.Caption); tnSubrelations.ImageKey = "subrelations"; tnSubrelations.SelectedImageKey = "subrelations"; tnSubrelations.ForeColor = OperatorFontColor; tnThis.Nodes.Add(tnSubrelations); //Find all operands. Several commutative operands of same type from different nested levels will be displayed together List <FuzzyRelation> nestedSubrelations = new List <FuzzyRelation>(); findNestedOperands(nfr, nestedSubrelations); foreach (FuzzyRelation nestedSubrelation in nestedSubrelations) { buildSubTree(nestedSubrelation, tnSubrelations.Nodes, pictureBox, label); } } #region Dimensions; TreeNode tnDimensions = new TreeNode("Dimension" + ((subrelation.Dimensions.Count() > 1) ? "s" : "")); tnDimensions.ImageKey = "dimensions"; tnDimensions.SelectedImageKey = "dimensions"; tnThis.Nodes.Add(tnDimensions); foreach (IDimension dimension in subrelation.Dimensions) { bool blnKnown = _inputs.ContainsKey(dimension); bool blnContinuous = dimension is IContinuousDimension; Color fontColor; string strDimCaption = String.IsNullOrEmpty(dimension.Name) ? "Dimension" : dimension.Name; if (blnKnown) { if (blnContinuous) { strDimCaption += String.Format("={0:F5} {1}", _inputs[dimension], ((IContinuousDimension)dimension).Unit); } else { IDiscreteDimension discreteDim = (IDiscreteDimension)dimension; if (discreteDim.DefaultSet != null) { strDimCaption += "=" + discreteDim.DefaultSet.GetMember(_inputs[dimension]); } else { strDimCaption += String.Format("=#{0:F0}", _inputs[dimension]); } } fontColor = SpecifiedDimensionFontColor; } else { fontColor = UnspecifiedDimensionFontColor; } if (dimension == _variableDimension) { fontColor = VariableDimensionFontColor; } string imageKey = String.Format("dimension{0}{1}", blnContinuous ? "Continuous" : "Discrete", blnKnown ? "Known" : "Unknown"); TreeNode tnDimension = new TreeNode(strDimCaption); tnDimension.ImageKey = imageKey; tnDimension.SelectedImageKey = imageKey; tnDimension.ForeColor = fontColor; addToolTip(tnDimension, dimension.Description); tnDimensions.Nodes.Add(tnDimension); } #endregion #region Function #endregion nodeCollection.Add(tnThis); }
/// <summary> /// Method to be invoked recursively to build the whole tree /// </summary> /// <param name="nodeCollection"></param> /// <param name="pictureBox"></param> /// <param name="label"></param> protected void buildSubTree(FuzzyRelation subrelation, TreeNodeCollection nodeCollection, PictureBox pictureBox, Label label) { TreeNode tnThis; if (subrelation is FuzzySet) { FuzzySet fs = (FuzzySet)subrelation; tnThis = new TreeNode(); if (!String.IsNullOrEmpty(fs.Caption)) { tnThis.Text = fs.Caption; } else { tnThis.Text = "Fuzzy Set"; } tnThis.ImageKey = "fuzzySet"; tnThis.SelectedImageKey = "fuzzySet"; TreeNode tnDimType = new TreeNode("Type: " + (fs.Dimensions[0] is IContinuousDimension ? "Continuous" : "Discrete")); tnDimType.ImageKey = "dimensionType"; tnDimType.SelectedImageKey = "dimensionType"; tnThis.Nodes.Add(tnDimType); } else { NodeFuzzyRelation nfr = (NodeFuzzyRelation)subrelation; tnThis = new TreeNode("Multidimensional Relation"); tnThis.ImageKey = "nodeFuzzyRelation"; tnThis.SelectedImageKey = "nodeFuzzyRelation"; TreeNode tnSubrelations = new TreeNode(nfr.Operator.Caption); tnSubrelations.ImageKey = "subrelations"; tnSubrelations.SelectedImageKey = "subrelations"; tnSubrelations.ForeColor = OperatorFontColor; tnThis.Nodes.Add(tnSubrelations); //Find all operands. Several commutative operands of same type from different nested levels will be displayed together List<FuzzyRelation> nestedSubrelations = new List<FuzzyRelation>(); findNestedOperands(nfr, nestedSubrelations); foreach(FuzzyRelation nestedSubrelation in nestedSubrelations) { buildSubTree(nestedSubrelation, tnSubrelations.Nodes, pictureBox, label); } } #region Dimensions TreeNode tnDimensions = new TreeNode("Dimension" + ((subrelation.Dimensions.Count() > 1) ? "s" : "") ); tnDimensions.ImageKey = "dimensions"; tnDimensions.SelectedImageKey = "dimensions"; tnThis.Nodes.Add(tnDimensions); foreach(IDimension dimension in subrelation.Dimensions) { bool blnKnown = _inputs.ContainsKey(dimension); bool blnContinuous = dimension is IContinuousDimension; Color fontColor; string strDimCaption = String.IsNullOrEmpty(dimension.Name) ? "Dimension" : dimension.Name; if (blnKnown) { if (blnContinuous) { strDimCaption += String.Format("={0:F5} {1}", _inputs[dimension], ((IContinuousDimension)dimension).Unit); } else { IDiscreteDimension discreteDim = (IDiscreteDimension)dimension; if (discreteDim.DefaultSet != null) strDimCaption += "=" + discreteDim.DefaultSet.GetMember(_inputs[dimension]).Caption; else strDimCaption += String.Format("=#{0:F0}", _inputs[dimension]); } fontColor = SpecifiedDimensionFontColor; } else fontColor = UnspecifiedDimensionFontColor; if (dimension == _variableDimension) fontColor = VariableDimensionFontColor; string imageKey = String.Format("dimension{0}{1}", blnContinuous ? "Continuous" : "Discrete", blnKnown ? "Known" : "Unknown"); TreeNode tnDimension = new TreeNode(strDimCaption); tnDimension.ImageKey = imageKey; tnDimension.SelectedImageKey = imageKey; tnDimension.ForeColor = fontColor; addToolTip(tnDimension, dimension.Description); tnDimensions.Nodes.Add(tnDimension); } #endregion #region Function if (allInputDimensionsAvailable(subrelation)) { IDimension realVariableDimension; if (subrelation.Dimensions.Count() == 1) realVariableDimension = subrelation.Dimensions[0]; else realVariableDimension = _variableDimension; Dictionary<IDimension, decimal> copyInputs = new Dictionary<IDimension,decimal>( _inputs ); foreach (KeyValuePair<IDimension, decimal> item in _inputs) if (!subrelation.Dimensions.Contains(item.Key)) copyInputs.Remove(item.Key); if (copyInputs.ContainsKey(realVariableDimension)) copyInputs.Remove(realVariableDimension); if (subrelation.Dimensions.Count() > copyInputs.Count()) { IntervalSet intervals = subrelation.GetFunction(copyInputs); string strIntervals = intervals.ToString(); string[] arrLines = strIntervals.Split(new char[] { '\n' }); TreeNode tnFunction = new TreeNode("Function"); tnFunction.ImageKey = "function"; tnFunction.SelectedImageKey = "function"; foreach (string line in arrLines) { if (!String.IsNullOrWhiteSpace(line)) { TreeNode tnLine = new TreeNode(line); tnLine.ImageKey = "spacer"; tnLine.SelectedImageKey = "spacer"; tnFunction.Nodes.Add(tnLine); } } tnThis.Nodes.Add(tnFunction); } } #endregion tnThis.ForeColor = MainNodeFontColor; tnThis.Tag = subrelation; nodeCollection.Add(tnThis); }
protected bool allInputDimensionsAvailable(FuzzyRelation relation) { if (relation.Dimensions.Count() == 1) return true; if (_variableDimension == null) return false; foreach (IDimension dimension in relation.Dimensions) { if (!_inputs.ContainsKey( dimension) && dimension != _variableDimension) return false; } return true; }
/// <summary> /// Creates new instance of the TreeSource for the specifed relation /// </summary> /// <param name="relation">Fuzzy relation to represent as a hierarchical list</param> /// <param name="inputs">Set of specified values for particular dimensions.</param> /// <param name="variableDimension">Dimension which should be put on the x-axis</param> public TreeSource(FuzzyRelation relation, Dictionary <IDimension, System.Decimal> inputs, IDimension variableDimension) { _relation = relation; _inputs = inputs; _variableDimension = variableDimension; }
/// <summary> /// Creates new instance of the TreeSource for the specifed relation /// </summary> /// <param name="relation">Fuzzy relation to represent as a hierarchical list</param> /// <param name="inputs">Set of specified values for particular dimensions.</param> /// <param name="variableDimension">Dimension which should be put on the x-axis</param> public TreeSource(FuzzyRelation relation, Dictionary<IDimension, System.Decimal> inputs, IDimension variableDimension) { _relation = relation; _inputs = inputs; _variableDimension = variableDimension; }
/// <summary> /// Method to be invoked recursively to build the whole tree /// </summary> /// <param name="nodeCollection"></param> /// <param name="pictureBox"></param> /// <param name="label"></param> protected void buildSubTree(FuzzyRelation subrelation, TreeNodeCollection nodeCollection, PictureBox pictureBox, Label label) { TreeNode tnThis; if (subrelation is FuzzySet) { FuzzySet fs = (FuzzySet)subrelation; tnThis = new TreeNode(); if (!String.IsNullOrEmpty(fs.Caption)) { tnThis.Text = fs.Caption; } else { tnThis.Text = "Fuzzy Set"; tnThis.ForeColor = UnnamedNodeFontColor; } tnThis.ImageKey = "fuzzySet"; tnThis.SelectedImageKey = "fuzzySet"; TreeNode tnDimType = new TreeNode("Type: " + (fs.Dimensions[0] is IContinuousDimension ? "Continuous" : "Discrete")); tnDimType.ImageKey = "dimensionType"; tnDimType.SelectedImageKey = "dimensionType"; tnThis.Nodes.Add(tnDimType); } else { NodeFuzzyRelation nfr = (NodeFuzzyRelation)subrelation; tnThis = new TreeNode("Multidimensional Relation"); tnThis.ForeColor = UnnamedNodeFontColor; tnThis.ImageKey = "nodeFuzzyRelation"; tnThis.SelectedImageKey = "nodeFuzzyRelation"; TreeNode tnSubrelations = new TreeNode(nfr.Operator.Caption); tnSubrelations.ImageKey = "subrelations"; tnSubrelations.SelectedImageKey = "subrelations"; tnSubrelations.ForeColor = OperatorFontColor; tnThis.Nodes.Add(tnSubrelations); //Find all operands. Several commutative operands of same type from different nested levels will be displayed together List<FuzzyRelation> nestedSubrelations = new List<FuzzyRelation>(); findNestedOperands(nfr, nestedSubrelations); foreach(FuzzyRelation nestedSubrelation in nestedSubrelations) { buildSubTree(nestedSubrelation, tnSubrelations.Nodes, pictureBox, label); } } #region Dimensions; TreeNode tnDimensions = new TreeNode("Dimension" + ((subrelation.Dimensions.Count() > 1) ? "s" : "") ); tnDimensions.ImageKey = "dimensions"; tnDimensions.SelectedImageKey = "dimensions"; tnThis.Nodes.Add(tnDimensions); foreach(IDimension dimension in subrelation.Dimensions) { bool blnKnown = _inputs.ContainsKey(dimension); bool blnContinuous = dimension is IContinuousDimension; Color fontColor; string strDimCaption = String.IsNullOrEmpty(dimension.Name) ? "Dimension" : dimension.Name; if (blnKnown) { if (blnContinuous) { strDimCaption += String.Format("={0:F5} {1}", _inputs[dimension], ((IContinuousDimension)dimension).Unit); } else { IDiscreteDimension discreteDim = (IDiscreteDimension)dimension; if (discreteDim.DefaultSet != null) strDimCaption += "=" + discreteDim.DefaultSet.GetMember(_inputs[dimension]); else strDimCaption += String.Format("=#{0:F0}", _inputs[dimension]); } fontColor = SpecifiedDimensionFontColor; } else fontColor = UnspecifiedDimensionFontColor; if (dimension == _variableDimension) fontColor = VariableDimensionFontColor; string imageKey = String.Format("dimension{0}{1}", blnContinuous ? "Continuous" : "Discrete", blnKnown ? "Known" : "Unknown"); TreeNode tnDimension = new TreeNode(strDimCaption); tnDimension.ImageKey = imageKey; tnDimension.SelectedImageKey = imageKey; tnDimension.ForeColor = fontColor; addToolTip(tnDimension, dimension.Description); tnDimensions.Nodes.Add(tnDimension); } #endregion #region Function #endregion nodeCollection.Add(tnThis); }
/// <summary> /// Method to be invoked recursively to build the whole tree /// </summary> /// <param name="nodeCollection"></param> /// <param name="pictureBox"></param> /// <param name="label"></param> protected void buildSubTree(FuzzyRelation subrelation, TreeNodeCollection nodeCollection, PictureBox pictureBox, Label label) { TreeNode tnThis; if (subrelation is FuzzySet) { FuzzySet fs = (FuzzySet)subrelation; tnThis = new TreeNode(); if (!String.IsNullOrEmpty(fs.Caption)) { tnThis.Text = fs.Caption; } else { tnThis.Text = "Fuzzy Set"; } tnThis.ImageKey = "fuzzySet"; tnThis.SelectedImageKey = "fuzzySet"; TreeNode tnDimType = new TreeNode("Type: " + (fs.Dimensions[0] is IContinuousDimension ? "Continuous" : "Discrete")); tnDimType.ImageKey = "dimensionType"; tnDimType.SelectedImageKey = "dimensionType"; tnThis.Nodes.Add(tnDimType); } else { NodeFuzzyRelation nfr = (NodeFuzzyRelation)subrelation; tnThis = new TreeNode("Multidimensional Relation"); tnThis.ImageKey = "nodeFuzzyRelation"; tnThis.SelectedImageKey = "nodeFuzzyRelation"; TreeNode tnSubrelations = new TreeNode(nfr.Operator.Caption); tnSubrelations.ImageKey = "subrelations"; tnSubrelations.SelectedImageKey = "subrelations"; tnSubrelations.ForeColor = OperatorFontColor; tnThis.Nodes.Add(tnSubrelations); //Find all operands. Several commutative operands of same type from different nested levels will be displayed together List <FuzzyRelation> nestedSubrelations = new List <FuzzyRelation>(); findNestedOperands(nfr, nestedSubrelations); foreach (FuzzyRelation nestedSubrelation in nestedSubrelations) { buildSubTree(nestedSubrelation, tnSubrelations.Nodes, pictureBox, label); } } #region Dimensions TreeNode tnDimensions = new TreeNode("Dimension" + ((subrelation.Dimensions.Count() > 1) ? "s" : "")); tnDimensions.ImageKey = "dimensions"; tnDimensions.SelectedImageKey = "dimensions"; tnThis.Nodes.Add(tnDimensions); foreach (IDimension dimension in subrelation.Dimensions) { bool blnKnown = _inputs.ContainsKey(dimension); bool blnContinuous = dimension is IContinuousDimension; Color fontColor; string strDimCaption = String.IsNullOrEmpty(dimension.Name) ? "Dimension" : dimension.Name; if (blnKnown) { if (blnContinuous) { strDimCaption += String.Format("={0:F5} {1}", _inputs[dimension], ((IContinuousDimension)dimension).Unit); } else { IDiscreteDimension discreteDim = (IDiscreteDimension)dimension; if (discreteDim.DefaultSet != null) { strDimCaption += "=" + discreteDim.DefaultSet.GetMember(_inputs[dimension]).Caption; } else { strDimCaption += String.Format("=#{0:F0}", _inputs[dimension]); } } fontColor = SpecifiedDimensionFontColor; } else { fontColor = UnspecifiedDimensionFontColor; } if (dimension == _variableDimension) { fontColor = VariableDimensionFontColor; } string imageKey = String.Format("dimension{0}{1}", blnContinuous ? "Continuous" : "Discrete", blnKnown ? "Known" : "Unknown"); TreeNode tnDimension = new TreeNode(strDimCaption); tnDimension.ImageKey = imageKey; tnDimension.SelectedImageKey = imageKey; tnDimension.ForeColor = fontColor; addToolTip(tnDimension, dimension.Description); tnDimensions.Nodes.Add(tnDimension); } #endregion #region Function if (allInputDimensionsAvailable(subrelation)) { IDimension realVariableDimension; if (subrelation.Dimensions.Count() == 1) { realVariableDimension = subrelation.Dimensions[0]; } else { realVariableDimension = _variableDimension; } Dictionary <IDimension, decimal> copyInputs = new Dictionary <IDimension, decimal>(_inputs); foreach (KeyValuePair <IDimension, decimal> item in _inputs) { if (!subrelation.Dimensions.Contains(item.Key)) { copyInputs.Remove(item.Key); } } if (copyInputs.ContainsKey(realVariableDimension)) { copyInputs.Remove(realVariableDimension); } if (subrelation.Dimensions.Count() > copyInputs.Count()) { IntervalSet intervals = subrelation.GetFunction(copyInputs); string strIntervals = intervals.ToString(); string[] arrLines = strIntervals.Split(new char[] { '\n' }); TreeNode tnFunction = new TreeNode("Function"); tnFunction.ImageKey = "function"; tnFunction.SelectedImageKey = "function"; foreach (string line in arrLines) { if (!String.IsNullOrWhiteSpace(line)) { TreeNode tnLine = new TreeNode(line); tnLine.ImageKey = "spacer"; tnLine.SelectedImageKey = "spacer"; tnFunction.Nodes.Add(tnLine); } } tnThis.Nodes.Add(tnFunction); } } #endregion tnThis.ForeColor = MainNodeFontColor; tnThis.Tag = subrelation; nodeCollection.Add(tnThis); }
public MeanOfMaximum(FuzzyRelation relation, Dictionary <IDimension, System.Decimal> inputs) : base(relation, inputs) { }
// public decimal Work(decimal rain, decimal visibility, decimal temperature, decimal hour) public Defuzzification Work(decimal rainValue, decimal temperatureValue, decimal fogValue /*, decimal darknessValue*/, DefuzzificationFactory.DefuzzificationMethod method) { FuzzySet zimno = _temperatureParam.NegativeSet; FuzzySet cieplo = _temperatureParam.PositiveSet; FuzzySet mokro = _rainParam.PositiveSet; FuzzySet sucho = _rainParam.NegativeSet; FuzzySet mgliscie = _fogParam.NegativeSet; FuzzySet przejrzyscie = _fogParam.PositiveSet; // FuzzySet ciemno = _darknessParam.PositiveSet; // FuzzySet jasno = _darknessParam.NegativeSet; //Definition of dimensions on which we will measure the input values //ContinuousDimension height = new ContinuousDimension("Height", "Personal height", "cm", 100, 250); //ContinuousDimension weight = new ContinuousDimension("Weight", "Personal weight", "kg", 30, 200); //Definition of dimension for output value ContinuousDimension consequent = new ContinuousDimension("", "0 = not good, 10 = very good", "grade", 0, 10); //Definition of basic fuzzy sets with which we will work // input sets: //FuzzySet tall = new LeftQuadraticSet(height, "Tall person", 150, 180, 200); //FuzzySet weighty = new LeftLinearSet(weight, "Weighty person", 80, 100); //_tall = new LeftQuadraticSet(height, "Tall person", 150, 180, 200); //_weighty = new LeftLinearSet(weight, "Weighty person", 80, 100); // output set: FuzzySet goodConditions = _resultParam.PositiveSet; //*/new LeftQuadraticSet(consequent, "Good conditions", 5, 7.5m, 10); FuzzySet badConditions = _resultParam.NegativeSet; //*/new RightQuadraticSet(consequent, "Bad conditions", 5, 7.5m, 10); //FuzzySet badConditions = new RightLinearSet(consequent, "Good in basket ball", 0, 10); //FuzzySet mediumConditions = new TrapezoidalSet(consequent, "", 4,6,2,8); //Implication //FuzzyRelation term =/* ((tall & !weighty) & goodForBasket); |*/ (!(tall & !weighty) & !goodForBasket); //FuzzyRelation term = ((_rainParam.PositiveSet & !_temperatureParam.PositiveSet) & goodForBasket) | ((!_rainParam.PositiveSet & _temperatureParam.PositiveSet) & !goodForBasket); FuzzyRelation term = //((zimno) & badConditions) | ((sucho & cieplo) & goodConditions) | ((zimno & mokro) & badConditions) | ((sucho & przejrzyscie) & goodConditions) | ((cieplo & przejrzyscie) & goodConditions) | ((mgliscie & zimno) & badConditions) | ((mgliscie & mokro) & badConditions); //((mglisto & mokro) & badConditions) | //((mglisto & mokro) & badConditions) | //((mglisto & mokro) & badConditions) | //((mglisto & mokro) & badConditions); //((zimno & deszcz & mgla & noc) & badConditions) | //((zimno & deszcz & brakMgly & dzien) & badConditions) | //((zimno & deszcz & brakMgly & noc) & badConditions) | //((cieplo & brakDeszczu & mgla & dzien) & goodConditions) | //((cieplo & brakDeszczu & mgla & noc) & mediumConditions) | //((cieplo & brakDeszczu & brakMgly & dzien) & goodConditions) | //((cieplo & brakDeszczu & brakMgly & noc) & goodConditions) | //((cieplo & deszcz & mgla & dzien) & mediumConditions) | //((cieplo & deszcz & mgla & noc) & mediumConditions) | //((cieplo & deszcz & brakMgly & dzien) & goodConditions) | //((cieplo & deszcz & brakMgly & noc) & goodConditions); var result = DefuzzificationFactory.GetDefuzzification(term, new Dictionary <IDimension, decimal> { { _rainParam.Dimension, rainValue }, { _temperatureParam.Dimension, temperatureValue }, { _fogParam.Dimension, fogValue }, // { _darknessParam.Dimension, darknessValue }, }, method); //Defuzzification result = new MeanOfMaximum( // term, // new Dictionary<IDimension, decimal>{ // { _rainParam.Dimension, rainValue }, // { _temperatureParam.Dimension, temperatureValue }, // { _fogParam.Dimension, fogValue }, // // { _darknessParam.Dimension, darknessValue }, // } //); return(result); }
void Start() { if (fs == null) { fs = this; } #region Definitions //Definition of dimensions on which we will measure the input values volume = new ContinuousDimension("Volume", "Vehicle per hour", "veh/hr", 0, 1200); queue = new ContinuousDimension("Weight", "Vehicle lenth on proper direction", "veh", 0, 30); //Definition of dimension for output value greenLight = new ContinuousDimension("Green Time", "green phase duration of Traffic Light", "s", 5, 60); //Definition of basic fuzzy sets with which we will work // input sets: Volume_small = new RightLinearSet(volume, "Small", 100, 300); Volume_middle = new TrapezoidalSet(volume, "Middle", 300, 400, 100, 600); Volume_large = new TrapezoidalSet(volume, "Large", 600, 700, 400, 900); Volume_extraLarge = new LeftLinearSet(volume, "Extra Large", 700, 900); Queue_small = new RightLinearSet(queue, "Small", 0, 7); Queue_middle = new TriangularSet(queue, "Middle", 10, 14); Queue_large = new TriangularSet(queue, "Large", 17, 14); Queue_extraLarge = new LeftLinearSet(queue, "Extra Large", 17, 23); // output set: Time_veryShort = new RightLinearSet(greenLight, "veryshort", 7, 15); Time_short = new TrapezoidalSet(greenLight, "short", 15, 23, 7, 30); Time_middle = new TrapezoidalSet(greenLight, "middle", 30, 38, 23, 45); Time_long = new TrapezoidalSet(greenLight, "long", 45, 53, 38, 60); Time_veryLong = new LeftLinearSet(greenLight, "verylong", 53, 60); //Definition of antedescent //relation = // ((Volume_small & Queue_small) & Time_veryShort) | // ((Volume_small & Queue_middle) & Time_short) | // ((Volume_small & Queue_large) & Time_short) | // ((Volume_small & Queue_extraLarge) & Time_middle) | // ((Volume_middle & Queue_small) & Time_short) | // ((Volume_middle & Queue_middle) & Time_middle) | // ((Volume_middle & Queue_large) & Time_middle) | // ((Volume_middle & Queue_extraLarge) & Time_long) | // ((Volume_large & Queue_small) & Time_middle) | // ((Volume_large & Queue_middle) & Time_long) | // ((Volume_large & Queue_large) & Time_long) | // ((Volume_large & Queue_extraLarge) & Time_veryLong) | // ((Volume_extraLarge & Queue_small) & Time_middle) | // ((Volume_extraLarge & Queue_middle) & Time_long) | // ((Volume_extraLarge & Queue_large) & Time_veryLong) | // ((Volume_extraLarge & Queue_extraLarge) & Time_veryLong); relation = ((Volume_small & Queue_small) & Time_veryShort) | ((Volume_small & Queue_middle) & Time_short) | ((Volume_small & Queue_large) & Time_short) | ((Volume_small & Queue_extraLarge) & Time_middle) | ((Volume_middle & Queue_small) & Time_veryShort) | ((Volume_middle & Queue_middle) & Time_short) | ((Volume_middle & Queue_large) & Time_middle) | ((Volume_middle & Queue_extraLarge) & Time_long) | ((Volume_large & Queue_small) & Time_short) | ((Volume_large & Queue_middle) & Time_middle) | ((Volume_large & Queue_large) & Time_long) | ((Volume_large & Queue_extraLarge) & Time_veryLong) | ((Volume_extraLarge & Queue_small) & Time_middle) | ((Volume_extraLarge & Queue_middle) & Time_long) | ((Volume_extraLarge & Queue_large) & Time_veryLong) | ((Volume_extraLarge & Queue_extraLarge) & Time_veryLong); #endregion //for (int iv = 0; iv < 110; iv++) //{ // for (int iq = 0; iq < 25; iq++) // { // Instantiate(haha, new Vector3((float)iv * 0.25f, Calc((float)(iv * 10), (float)(iq)) * 0.5f, (float)iq), Quaternion.identity); // Debug.Log("=!="); // } //} //Debug.Log("=)"); }
/// <summary> /// Defuzzifies the output set using defuzzifioncation method Center-Of-Gravity /// </summary> public CenterOfGravity(FuzzyRelation relation, Dictionary <IDimension, System.Decimal> inputs) : base(relation, inputs) { }
static void Main(string[] args) { #region Definitions //Definition of dimensions on which we will measure the input values ContinuousDimension height = new ContinuousDimension("Height", "Personal height", "cm", 100, 250); ContinuousDimension weight = new ContinuousDimension("Weight", "Personal weight", "kg", 30, 200); //Definition of dimension for output value ContinuousDimension consequent = new ContinuousDimension("Suitability for basket ball", "0 = not good, 5 = very good", "grade", 0, 5); //Definition of basic fuzzy sets with which we will work // input sets: FuzzySet tall = new LeftLinearSet(height, "Tall person", 170, 185); FuzzySet weighty = new LeftLinearSet(weight, "Weighty person", 80, 100); // output set: FuzzySet goodForBasket = new LeftLinearSet(consequent, "Good in basket ball", 0, 5); //Definition of antedescent FuzzyRelation lanky = tall & !weighty; //Implication FuzzyRelation term = (lanky & goodForBasket) | (!lanky & !goodForBasket); #endregion #region Input values Console.Write("Enter your height in cm:"); decimal inputHeight = decimal.Parse(Console.ReadLine()); Console.Write("Enter your weight in kg:"); decimal inputWeight = decimal.Parse(Console.ReadLine()); #endregion #region Auxiliary messages; just for better understanding and not necessary for the final defuzzification double isLanky = lanky.IsMember( new Dictionary <IDimension, decimal> { { height, inputHeight }, { weight, inputWeight } } ); System.Console.WriteLine(String.Format("You are lanky to the {0:F3} degree out of range <0,1>.", isLanky)); System.Console.WriteLine("Membership distribution in the output set for given inputs:"); for (decimal i = 0; i <= 5; i++) { double membership = term.IsMember( new Dictionary <IDimension, decimal> { { height, inputHeight }, { weight, inputWeight }, { consequent, i } } ); System.Console.WriteLine(String.Format("µrelation(height={0:F0},weight={1:F0},consequent={2:F0}) = {3:F3}", inputHeight, inputWeight, i, membership)); } System.Console.WriteLine(); #endregion #region Deffuzification of the output set Defuzzification result = new MeanOfMaximum( term, new Dictionary <IDimension, decimal> { { height, inputHeight }, { weight, inputWeight } } ); Console.WriteLine(String.Format("Your disposition to be a basketball player is {0:F3} out of <0,...,5>", result.CrispValue)); Console.WriteLine("Press any key to exit"); Console.ReadKey(); #endregion }
void treeView_AfterSelect(object sender, TreeViewEventArgs e) { if (_pictureBox != null && _label != null) { //Find nearest relation upper in the hierarchy TreeNode tn = e.Node; while (tn.Tag == null && !(tn.Tag is FuzzyRelation) && !(tn.Tag is Defuzzification.Defuzzification)) { if (tn.Parent == null) { //We are at the top _label.Text = ""; _pictureBox.Image = null; tn = null; break; } tn = tn.Parent; } if (tn != null) { if (tn.Tag is Defuzzification.Defuzzification) { Defuzzification.Defuzzification deffuz = (Defuzzification.Defuzzification)tn.Tag; if (allInputDimensionsAvailable(deffuz.Relation)) { Dictionary <IDimension, System.Decimal> inputsCopy = new Dictionary <IDimension, System.Decimal>(_inputs); if (!inputsCopy.ContainsKey(deffuz.OutputDimension)) { inputsCopy.Add(deffuz.OutputDimension, deffuz.CrispValue); } else { inputsCopy[deffuz.OutputDimension] = deffuz.CrispValue; } RelationImage img = new RelationImage(deffuz.Relation, inputsCopy, deffuz.OutputDimension); img.SupportOnly = _supportOnly; Bitmap bmp = new Bitmap(_pictureBox.Width, _pictureBox.Height); img.DrawImage(System.Drawing.Graphics.FromImage(bmp)); _pictureBox.Image = bmp; _label.Text = String.Format("{0} deffuzification yields {1}={2:F5} {3}", deffuz.GetType().Name, deffuz.OutputDimension.Name, deffuz.CrispValue, deffuz.OutputDimension is IContinuousDimension ? ((IContinuousDimension)deffuz.OutputDimension).Unit : "" ); } else { reportTooManyDimensions(); } } else { FuzzyRelation relation = (FuzzyRelation)tn.Tag; if (allInputDimensionsAvailable(relation)) { RelationImage img = null; if (relation.Dimensions.Count() == 1) { img = new RelationImage(relation, _inputs, relation.Dimensions[0]); } else if (_variableDimension != null) { img = new RelationImage(relation, _inputs, _variableDimension); } if (img == null) { _label.Text = ""; _pictureBox.Image = null; } else { string lblText = ""; img.SupportOnly = _supportOnly; Bitmap bmp = new Bitmap(_pictureBox.Width, _pictureBox.Height); img.DrawImage(System.Drawing.Graphics.FromImage(bmp)); _pictureBox.Image = bmp; IDimension realVariableDimension; if (relation.Dimensions.Count() == 1) { lblText = String.Format("Fuzzy set for dimension {0}.", relation.Dimensions[0].Name); realVariableDimension = relation.Dimensions[0]; } else { StringBuilder sb = new StringBuilder(); foreach (IDimension dim in relation.Dimensions) { if (sb.Length != 0) { sb.Append(" x "); } sb.Append(dim.Name); } lblText = String.Format("Fuzzy relation for dimensions ({0}) where {1} is variable.", sb.ToString(), _variableDimension.Name); realVariableDimension = _variableDimension; } if (_inputs.ContainsKey(realVariableDimension)) { string value; if (realVariableDimension is IContinuousDimension) { IContinuousDimension dim = (IContinuousDimension)realVariableDimension; value = _inputs[realVariableDimension].ToString("F5"); if (!String.IsNullOrEmpty(dim.Unit)) { value += " " + dim.Unit; } } else { IDiscreteDimension dim = (IDiscreteDimension)realVariableDimension; if (dim.DefaultSet != null) { value = dim.DefaultSet.GetMember(_inputs[realVariableDimension]).Caption; } else { value = "#" + _inputs[realVariableDimension].ToString("F0"); } } lblText += String.Format("\r\nµ{1}(x)={0:F2} for x={2}.", relation.IsMember(_inputs), realVariableDimension.Name, value ); } _label.Text = lblText; } } } } } }
public CenterOfMaximum(FuzzyRelation relation, Dictionary<IDimension, System.Decimal> inputs) : base(relation, inputs) { }
protected void buildRelationNow(bool initial) { if (!_ready) { return; } _waitingForBuild = false; _building = true; bool _expressionChanged = false; decimal inputProduct = ddlProduct.SelectedIndex + 1; decimal inputPrice = txtPrice.Value; #region Realtime expression evaluation by means of C# parser string strExpression = txtExpression.Text; prependFullName(ref strExpression, "cheap"); prependFullName(ref strExpression, "fruits"); prependFullName(ref strExpression, "buyIt"); object obj = Evaluator.Eval(strExpression); if (obj != null) { if (!(obj is FuzzyRelation)) { MessageBox.Show(String.Format("ERROR: Object of type FuzzyRelation expected as the result of the expression.\r\nThis object is type {0}.", obj.GetType().FullName), "Error evaluating expression", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { _relation = (FuzzyRelation)obj; if (_expression != txtExpression.Text) { _expressionChanged = true; } _expression = txtExpression.Text; } } #endregion #region Defuzzification DefuzzificationFactory.DefuzzificationMethod method = (DefuzzificationFactory.DefuzzificationMethod)ddlDefuzMethod.SelectedIndex; _defuzzification = DefuzzificationFactory.GetDefuzzification( _relation, new Dictionary <IDimension, decimal> { { product, inputProduct }, { price, inputPrice } }, method ); _defuzzMethod = method; #endregion #region Output value string unit = ((IContinuousDimension)_defuzzification.OutputDimension).Unit; lblOutput.Text = _defuzzification.CrispValue.ToString("F5") + (string.IsNullOrEmpty(unit) ? "" : " " + unit); #endregion Cursor.Current = Cursors.WaitCursor; #region storing TreeView selection //Store information about currenlty selected node. It will become handy //when selecting the same node after the refresh (if applicable) List <int> selectedNodePath = new List <int>(); if (treeViewRelation.SelectedNode != null) { TreeNode pointer = treeViewRelation.SelectedNode; while (pointer != null) { selectedNodePath.Add(pointer.Index); pointer = pointer.Parent; } } else if (initial) { selectedNodePath.Add(0); } #endregion TreeSource ts = new TreeSource(_defuzzification); ts.DrawImageOnNodeSelect = false; ts.BuildTree(treeViewRelation, pictureBoxGraph, lblGraphCaption); //Cursor.Current = Cursors.Default; #region restoring TreeView selection if ((!_expressionChanged || initial) && selectedNodePath.Count() > 0 && selectedNodePath[selectedNodePath.Count() - 1] < treeViewRelation.Nodes.Count) { //We will now try to restore the selection TreeNode pointer = treeViewRelation.Nodes[selectedNodePath[selectedNodePath.Count() - 1]]; for (int i = selectedNodePath.Count() - 2; i >= 0; i--) { if (selectedNodePath[i] >= pointer.Nodes.Count) { pointer = null; break; } pointer = pointer.Nodes[selectedNodePath[i]]; } if (pointer != null) { treeViewRelation.SelectedNode = pointer; ts.DrawDetailImage(pointer); } } Cursor.Current = Cursors.Default; ts.DrawImageOnNodeSelect = true; #endregion _building = false; }