FuzzySwift provides basic tools to solve many different problems by using fuzzy logic with a handy syntax.
A fuzzy set can be defined just by implementing the FuzzySet procotol.
public enum Velocity: FuzzySet {
case slow
case normal
case fast
public static var sets: [FuzzySet] {
return _sets
}
private static var _sets: [Velocity] {
return [.slow, .normal, .fast]
}
public var function: FuzzyFunction {
switch self {
case .slow:
return TrapetzoidalFunction(0, 40, 60, upperSide: .left)
case .normal:
return TrapetzoidalFunction(40, 60, 80, 100)
case .fast:
return TrapetzoidalFunction(80, 100, 140, upperSide: .right)
}
}
public var name: String {
switch self {
case .slow:
return "Slow"
case .normal:
return "Normal"
case .fast:
return "Fast"
}
}
}
###FuzzyVariable In the same way, it's possible to create a FuzzyVariable and assign the corresponding [FuzzySet]
public struct Speed : FuzzyVariable {
public init() { }
public var name: String {
return "Speed"
}
public var sets: [FuzzySet] {
return Velocity.sets
}
}
FuzzyRuleset will contain all the rules to set up the fuzzy logic.
public struct SpeedRuleSet : FuzzyRuleset {
public var name: String {
return "SpeedRuleSet"
}
public let speed = Speed()
public let rightDistance = Distance.right
public let leftDistance = Distance.left
public let frontalDistance = Distance.frontal
public init() { }
public var rules: [Rule] {
return [
Rule(name: "Movement 1",
if: frontalDistance == Nearness.far, then: speed => Velocity.fast),
Rule(name: "Movement 2",
if: frontalDistance == Nearness.medium, then: speed => Velocity.normal),
Rule(name: "Movement 3",
if: frontalDistance == Nearness.close, then: speed => Velocity.slow),
Rule(name: "Movement 4",
if: leftDistance == Nearness.close && rightDistance == Nearness.close, then: speed => Velocity.slow)
]
}
public var variables: [FuzzyVariable] {
return [
speed,
rightDistance,
leftDistance,
frontalDistance
]
}
}
InferenceManager can evaluate data for given variable inputs.
let ruleset = SpeedRuleSet()
let system = InferenceManager(ruleSets: [ruleset])
system.set(input: 10, for: ruleset.frontalDistance)
let evaluated = system.evaluate(variable: ruleset.speed)