#74 -- add new library, create middle service

This commit is contained in:
Anton Romanov 2022-10-25 14:44:27 +04:00
parent 374415e154
commit f2f53b1980
9 changed files with 194 additions and 121 deletions

View File

@ -69,6 +69,7 @@ dependencies {
implementation group: 'com.ibm.icu', name: 'icu4j', version: '63.1' implementation group: 'com.ibm.icu', name: 'icu4j', version: '63.1'
implementation group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: '5.9.0.202009080501-r' implementation group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: '5.9.0.202009080501-r'
implementation group: 'net.sourceforge.jFuzzyLogic', name: 'jFuzzyLogic', version: '1.2.1' implementation group: 'net.sourceforge.jFuzzyLogic', name: 'jFuzzyLogic', version: '1.2.1'
implementation group: 'com.fuzzylite', name: 'jfuzzylite', version: '6.0.1'
implementation group: 'org.webjars', name: 'jquery', version: '3.6.0' implementation group: 'org.webjars', name: 'jquery', version: '3.6.0'
implementation group: 'org.webjars', name: 'bootstrap', version: '4.6.0' implementation group: 'org.webjars', name: 'bootstrap', version: '4.6.0'

View File

@ -1,16 +1,88 @@
package ru.ulstu.extractor; package ru.ulstu.extractor;
import com.fuzzylite.Engine;
import com.fuzzylite.FuzzyLite;
import com.fuzzylite.Op;
import com.fuzzylite.activation.Highest;
import com.fuzzylite.defuzzifier.Centroid;
import com.fuzzylite.norm.s.Maximum;
import com.fuzzylite.norm.t.AlgebraicProduct;
import com.fuzzylite.rule.Rule;
import com.fuzzylite.rule.RuleBlock;
import com.fuzzylite.term.Trapezoid;
import com.fuzzylite.variable.InputVariable;
import com.fuzzylite.variable.OutputVariable;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.EnableScheduling;
import ru.ulstu.extractor.rule.service.FuzzyInference;
@SpringBootApplication @SpringBootApplication
@EnableScheduling @EnableScheduling
public class GitExtractorApplication { public class GitExtractorApplication {
public static void main(String[] args) { public static void main(String[] args) {
Engine engine = new Engine();
engine.setName("Git rules");
engine.setDescription("");
new FuzzyInference().run(); InputVariable obstacle = new InputVariable();
obstacle.setName("obstacle");
obstacle.setDescription("");
obstacle.setEnabled(true);
obstacle.setRange(0.000, 1.000);
obstacle.setLockValueInRange(false);
obstacle.addTerm(new Trapezoid("left", 0.000, 0.700));
obstacle.addTerm(new Trapezoid("right", 0.400, 1.000));
engine.addInputVariable(obstacle);
OutputVariable mSteer = new OutputVariable();
mSteer.setName("mSteer");
mSteer.setDescription("");
mSteer.setEnabled(true);
mSteer.setRange(0.000, 1.000);
mSteer.setLockValueInRange(false);
mSteer.setAggregation(new Maximum());
mSteer.setDefuzzifier(new Centroid(100));
mSteer.setDefaultValue(Double.NaN);
mSteer.setLockPreviousValue(false);
mSteer.addTerm(new Trapezoid("left", 0.000, 0.700));
mSteer.addTerm(new Trapezoid("right", 0.400, 1.000));
engine.addOutputVariable(mSteer);
RuleBlock mamdani = new RuleBlock();
mamdani.setName("mamdani");
mamdani.setDescription("");
mamdani.setEnabled(true);
mamdani.setConjunction(null);
mamdani.setDisjunction(null);
mamdani.setImplication(new AlgebraicProduct());
mamdani.setActivation(new Highest());
mamdani.addRule(Rule.parse("if obstacle is left then mSteer is right", engine));
mamdani.addRule(Rule.parse("if obstacle is right then mSteer is left", engine));
engine.addRuleBlock(mamdani);
StringBuilder status = new StringBuilder();
if (!engine.isReady(status))
throw new RuntimeException("[engine error] engine is not ready:n" + status);
InputVariable obstacle1 = engine.getInputVariable("obstacle");
OutputVariable steer = engine.getOutputVariable("mSteer");
for (int i = 10; i <= 50; ++i) {
double location = obstacle1.getMinimum() + i * (obstacle1.range() / 50);
obstacle1.setValue(location);
engine.process();
if (Double.isNaN(steer.getValue())) {
System.out.println("no decision");
continue;
}
FuzzyLite.logger().info(String.format(
"obstacle.input = %s -> steer.output = %s",
Op.str(location), Op.str(steer.getValue())));
FuzzyLite.logger().info(String.format(
"obstacle.input = %s -> steer.output = %s",
Op.str(location), steer.highestMembership(steer.getValue()).getSecond().getName()));
}
SpringApplication.run(GitExtractorApplication.class, args); SpringApplication.run(GitExtractorApplication.class, args);
} }
} }

View File

@ -7,9 +7,11 @@ import javax.persistence.Entity;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity @Entity
public class Rule extends BaseEntity { @Table(name = "rule")
public class DbRule extends BaseEntity {
@ManyToOne @ManyToOne
private AntecedentValue firstAntecedentValue; private AntecedentValue firstAntecedentValue;
@ -24,10 +26,10 @@ public class Rule extends BaseEntity {
private String consequent; private String consequent;
public Rule() { public DbRule() {
} }
public Rule(AntecedentValue firstAntecedentValue, public DbRule(AntecedentValue firstAntecedentValue,
TimeSeriesType firstAntecedent, TimeSeriesType firstAntecedent,
AntecedentValue secondAntecedentValue, AntecedentValue secondAntecedentValue,
TimeSeriesType secondAntecedent, TimeSeriesType secondAntecedent,

View File

@ -1,7 +1,7 @@
package ru.ulstu.extractor.rule.repository; package ru.ulstu.extractor.rule.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.extractor.rule.model.Rule; import ru.ulstu.extractor.rule.model.DbRule;
public interface RuleRepository extends JpaRepository<Rule, Integer> { public interface RuleRepository extends JpaRepository<DbRule, Integer> {
} }

View File

@ -1,99 +0,0 @@
package ru.ulstu.extractor.rule.service;
import net.sourceforge.jFuzzyLogic.defuzzifier.DefuzzifierCenterOfGravity;
import net.sourceforge.jFuzzyLogic.membership.MembershipFunctionTriangular;
import net.sourceforge.jFuzzyLogic.rule.FuzzyRule;
import net.sourceforge.jFuzzyLogic.rule.FuzzyRuleExpression;
import net.sourceforge.jFuzzyLogic.rule.FuzzyRuleSet;
import net.sourceforge.jFuzzyLogic.rule.FuzzyRuleTerm;
import net.sourceforge.jFuzzyLogic.rule.LinguisticTerm;
import net.sourceforge.jFuzzyLogic.rule.Variable;
import net.sourceforge.jFuzzyLogic.ruleConnection.RuleConnectionMethodAndMin;
import net.sourceforge.jFuzzyLogic.ruleImplication.RuleImplicationMethodMin;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class FuzzyInference {
public void run() {
FuzzyRule fuzzyRule1 = new FuzzyRule("rule 1");
FuzzyRule fuzzyRule2 = new FuzzyRule("rule 2");
FuzzyRule fuzzyRule3 = new FuzzyRule("rule 3");
Variable weather = new Variable("Погода");
weather.getLinguisticTerms().put("солнечно",
new LinguisticTerm("солнечно", new MembershipFunctionTriangular(0, 20, 30)));
weather.getLinguisticTerms().put("мороз",
new LinguisticTerm("мороз", new MembershipFunctionTriangular(-50, -10, 10)));
weather.setDefuzzifier(new DefuzzifierCenterOfGravity(weather));
Variable suit = new Variable("Одежда");
suit.getLinguisticTerms().put("легко одет",
new LinguisticTerm("легко одет", new MembershipFunctionTriangular(0, 5, 10)));
suit.getLinguisticTerms().put("тепло одет",
new LinguisticTerm("тепло одет", new MembershipFunctionTriangular(5, 10, 20)));
suit.setDefuzzifier(new DefuzzifierCenterOfGravity(suit));
Variable feel = new Variable("Ощущение");
feel.getLinguisticTerms().put("Холодно",
new LinguisticTerm("Холодно", new MembershipFunctionTriangular(0, 5, 10)));
feel.getLinguisticTerms().put("Жарко",
new LinguisticTerm("Жарко", new MembershipFunctionTriangular(5, 10, 20)));
feel.setDefuzzifier(new DefuzzifierCenterOfGravity(feel));
FuzzyRuleTerm weatherTerm1 = new FuzzyRuleTerm(weather, "солнечно", false);
FuzzyRuleTerm weatherTerm2 = new FuzzyRuleTerm(weather, "мороз", false);
FuzzyRuleTerm suitTerm1 = new FuzzyRuleTerm(suit, "легко одет", false);
FuzzyRuleTerm suitTerm2 = new FuzzyRuleTerm(suit, "тепло одет", false);
FuzzyRuleTerm feelCold = new FuzzyRuleTerm(feel, "Холодно", false);
FuzzyRuleTerm feelWarm = new FuzzyRuleTerm(feel, "Жарко", false);
FuzzyRuleExpression expression1 = new FuzzyRuleExpression(weatherTerm1, suitTerm2, new RuleConnectionMethodAndMin());
fuzzyRule1.setAntecedents(expression1);
fuzzyRule1.setConsequents(new LinkedList<>(Collections.singleton(feelWarm)));
FuzzyRuleExpression expression2 = new FuzzyRuleExpression(weatherTerm2, suitTerm1, new RuleConnectionMethodAndMin());
fuzzyRule2.setAntecedents(expression2);
fuzzyRule2.setConsequents(new LinkedList<>(Collections.singleton(feelCold)));
FuzzyRuleExpression expression3 = new FuzzyRuleExpression(weatherTerm1, suitTerm1, new RuleConnectionMethodAndMin());
fuzzyRule3.setAntecedents(expression3);
fuzzyRule3.setConsequents(new LinkedList<>(Collections.singleton(feelCold)));
fuzzyRule1.evaluate(new RuleImplicationMethodMin());
fuzzyRule2.evaluate(new RuleImplicationMethodMin());
//fuzzyRule3.evaluate(new RuleImplicationMethodMin());
FuzzyRuleSet set = new FuzzyRuleSet();
set.add(fuzzyRule1);
set.add(fuzzyRule2);
set.add(fuzzyRule3);
set.evaluate();
set.setVariable("Погода", 25);
set.setVariable("Одежда", 7);
// Evaluate fuzzy set
set.evaluate();
// Show output variable's chart
//set.getVariable("Ощущение").chartDefuzzifier(true);
System.out.println(set.getVariable("Ощущение").getLatestDefuzzifiedValue());
System.out.println(set);
System.out.println(set.getVariable("Ощущение"));
System.out.println(
feel.getLinguisticTerms()
.entrySet()
.stream()
.max(Comparator.comparing(e -> e.getValue()
.getMembershipFunction()
.membership(set.getVariable("Ощущение").getLatestDefuzzifiedValue())))
.get()
.getValue().getTermName()
);
set.getVariable("Ощущение").chartDefuzzifier(true);
}
}

View File

@ -0,0 +1,97 @@
package ru.ulstu.extractor.rule.service;
import com.fuzzylite.Engine;
import com.fuzzylite.activation.Highest;
import com.fuzzylite.norm.t.AlgebraicProduct;
import com.fuzzylite.rule.Rule;
import com.fuzzylite.rule.RuleBlock;
import com.fuzzylite.term.Triangle;
import com.fuzzylite.variable.InputVariable;
import com.fuzzylite.variable.OutputVariable;
import org.springframework.stereotype.Service;
import ru.ulstu.extractor.rule.model.AntecedentValue;
import ru.ulstu.extractor.rule.model.DbRule;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class FuzzyInferenceService {
private final static String RULE_TEMPLATE = "if %s is %s AND %s is %s then state is %s";
private final RuleService ruleService;
private final AntecedentValueService antecedentValueService;
public FuzzyInferenceService(RuleService ruleService,
AntecedentValueService antecedentValueService) {
this.ruleService = ruleService;
this.antecedentValueService = antecedentValueService;
}
public List<String> getRulesFromDb() {
List<DbRule> dbDbRules = ruleService.getList();
return dbDbRules.stream().map(this::getFuzzyRule).collect(Collectors.toList());
}
private String getFuzzyRule(DbRule dbRule) {
return String.format(RULE_TEMPLATE,
dbRule.getFirstAntecedent().name(),
dbRule.getFirstAntecedentValue().getAntecedentValue(),
dbRule.getSecondAntecedent().name(),
dbRule.getSecondAntecedentValue().getAntecedentValue(),
dbRule.getConsequent());
}
private RuleBlock getRuleBlock(Engine engine, Map<String, Double> variableValues, List<AntecedentValue> antecedentValues) {
variableValues.forEach((key, value) -> {
InputVariable input = new InputVariable();
input.setName(key);
input.setDescription("");
input.setEnabled(true);
input.setRange(0.000, 1.000);
input.setLockValueInRange(false);
for (int i = 0; i < antecedentValues.size(); i++) {
input.addTerm(new Triangle(antecedentValues.get(i).getAntecedentValue(), i, i + 2));
}
engine.addInputVariable(input);
});
RuleBlock mamdani = new RuleBlock();
mamdani.setName("mamdani");
mamdani.setDescription("");
mamdani.setEnabled(true);
mamdani.setConjunction(null);
mamdani.setDisjunction(null);
mamdani.setImplication(new AlgebraicProduct());
mamdani.setActivation(new Highest());
getRulesFromDb().forEach(r -> mamdani.addRule(Rule.parse(r, engine)));
return mamdani;
}
private Engine getFuzzyEngine() {
Engine engine = new Engine();
engine.setName("Git rules");
engine.setDescription("");
return engine;
}
public String run() {
Engine engine = getFuzzyEngine();
List<AntecedentValue> antecedentValues = antecedentValueService.getList();
Map<String, Double> variableValues = new HashMap<>();
engine.addRuleBlock(getRuleBlock(engine, variableValues, antecedentValues));
return getConsequent(engine, variableValues);
}
private String getConsequent(Engine engine, Map<String, Double> variableValues) {
OutputVariable outputVariable = engine.getOutputVariable("state");
for (Map.Entry<String, Double> variableValue : variableValues.entrySet()) {
InputVariable inputVariable = engine.getInputVariable(variableValue.getKey());
inputVariable.setValue(variableValue.getValue());
}
engine.process();
return outputVariable.highestMembership(outputVariable.getValue()).getSecond().getName();
}
}

View File

@ -2,7 +2,7 @@ package ru.ulstu.extractor.rule.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import ru.ulstu.extractor.rule.model.AddRuleForm; import ru.ulstu.extractor.rule.model.AddRuleForm;
import ru.ulstu.extractor.rule.model.Rule; import ru.ulstu.extractor.rule.model.DbRule;
import ru.ulstu.extractor.rule.repository.RuleRepository; import ru.ulstu.extractor.rule.repository.RuleRepository;
import ru.ulstu.extractor.ts.model.TimeSeriesType; import ru.ulstu.extractor.ts.model.TimeSeriesType;
import ru.ulstu.extractor.ts.service.TimeSeriesService; import ru.ulstu.extractor.ts.service.TimeSeriesService;
@ -23,12 +23,12 @@ public class RuleService {
this.antecedentValueService = antecedentValueService; this.antecedentValueService = antecedentValueService;
} }
public List<Rule> getList() { public List<DbRule> getList() {
return ruleRepository.findAll(); return ruleRepository.findAll();
} }
public void saveRule(AddRuleForm addRuleForm) { public void saveRule(AddRuleForm addRuleForm) {
ruleRepository.save(new Rule(antecedentValueService.getById(addRuleForm.getFirstAntecedentValueId()), ruleRepository.save(new DbRule(antecedentValueService.getById(addRuleForm.getFirstAntecedentValueId()),
TimeSeriesType.valueOf(addRuleForm.getFirstAntecedentId()), TimeSeriesType.valueOf(addRuleForm.getFirstAntecedentId()),
antecedentValueService.getById(addRuleForm.getSecondAntecedentValueId()), antecedentValueService.getById(addRuleForm.getSecondAntecedentValueId()),
TimeSeriesType.valueOf(addRuleForm.getSecondAntecedentId()), TimeSeriesType.valueOf(addRuleForm.getSecondAntecedentId()),

File diff suppressed because one or more lines are too long

View File

@ -14,15 +14,15 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr th:each="rule: ${rules}"> <tr th:each="dbRule: ${rules}">
<td><span class="badge badge-info">Если</span></td> <td><span class="badge badge-info">Если</span></td>
<td><span class="badge badge-success" th:text="${rule.firstAntecedent.description}"></span></td> <td><span class="badge badge-success" th:text="${dbRule.firstAntecedent.description}"></span></td>
<td><span class="badge badge-success" th:text="${rule.firstAntecedentValue.antecedentValue}"></span></td> <td><span class="badge badge-success" th:text="${dbRule.firstAntecedentValue.antecedentValue}"></span></td>
<td><span class="badge badge-info">и</span></td> <td><span class="badge badge-info">и</span></td>
<td><span class="badge badge-success" th:text="${rule.secondAntecedent.description }"></span></td> <td><span class="badge badge-success" th:text="${dbRule.secondAntecedent.description }"></span></td>
<td><span class="badge badge-success" th:text="${rule.secondAntecedentValue.antecedentValue}"></span></td> <td><span class="badge badge-success" th:text="${dbRule.secondAntecedentValue.antecedentValue}"></span></td>
<td><span class="badge badge-info">то</span></td> <td><span class="badge badge-info">то</span></td>
<td><span class="badge badge-warning" th:text="${rule.consequent}"></span></td> <td><span class="badge badge-warning" th:text="${dbRule.consequent}"></span></td>
</tr> </tr>
</tbody> </tbody>
</table> </table>