Merge pull request 'demo' (#9) from 8-demo into master

Reviewed-on: #9
This commit is contained in:
romanov73 2023-09-07 18:17:10 +04:00
commit f3710b6680
6 changed files with 245 additions and 87 deletions

View File

@ -11,17 +11,16 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration @Configuration
public class MvcConfiguration implements WebMvcConfigurer { public class MvcConfiguration implements WebMvcConfigurer {
@Override // @Override
public void addViewControllers(ViewControllerRegistry registry) { // public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index"); // registry.addViewController("/index");
} // }
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {

View File

@ -0,0 +1,54 @@
package ru.ulstu.fc.rule.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.ulstu.fc.rule.model.Antecedent;
import ru.ulstu.fc.rule.model.InferenceForm;
import ru.ulstu.fc.rule.service.FuzzyInferenceService;
import java.util.Arrays;
import java.util.List;
@Controller
public class InferenceMvcController {
private final FuzzyInferenceService fuzzyInferenceService;
public InferenceMvcController(FuzzyInferenceService fuzzyInferenceService) {
this.fuzzyInferenceService = fuzzyInferenceService;
}
@GetMapping("/")
public String initInference(Model model) {
model.addAttribute("ageAntecedents", getAgeAntecedents());
model.addAttribute("incomeAntecedents", getIncomeAntecedents());
model.addAttribute("inferenceForm", new InferenceForm());
return "index";
}
@RequestMapping(value = "get-inference", method = RequestMethod.POST)
public String getInference(@ModelAttribute InferenceForm inferenceForm, Model model) {
model.addAttribute("ageAntecedents", getAgeAntecedents());
model.addAttribute("incomeAntecedents", getIncomeAntecedents());
model.addAttribute("inferenceForm", inferenceForm);
model.addAttribute("response", fuzzyInferenceService.getFuzzyInference());
return "index";
}
private List<Antecedent> getAgeAntecedents() {
return Arrays.asList(
new Antecedent("молодой", "young"),
new Antecedent("средний", "average"),
new Antecedent("старый", "old"));
}
private List<Antecedent> getIncomeAntecedents() {
return Arrays.asList(
new Antecedent("малый", "small"),
new Antecedent("средний", "average"),
new Antecedent("высокий", "high"));
}
}

View File

@ -0,0 +1,19 @@
package ru.ulstu.fc.rule.model;
public class Antecedent {
private String value;
private String description;
public Antecedent(String description, String value) {
this.description = description;
this.value = value;
}
public String getValue() {
return value;
}
public String getDescription() {
return description;
}
}

View File

@ -0,0 +1,22 @@
package ru.ulstu.fc.rule.model;
public class InferenceForm {
private String ageAntecedent;
private String incomeAntecedent;
public String getAgeAntecedent() {
return ageAntecedent;
}
public void setAgeAntecedent(String ageAntecedent) {
this.ageAntecedent = ageAntecedent;
}
public String getIncomeAntecedent() {
return incomeAntecedent;
}
public void setIncomeAntecedent(String incomeAntecedent) {
this.incomeAntecedent = incomeAntecedent;
}
}

View File

@ -1,84 +1,116 @@
package ru.ulstu.fc.rule.service; package ru.ulstu.fc.rule.service;
import com.fuzzylite.Engine; import com.fuzzylite.Engine;
import com.fuzzylite.activation.General;
import com.fuzzylite.defuzzifier.Centroid;
import com.fuzzylite.norm.s.Maximum;
import com.fuzzylite.norm.t.AlgebraicProduct;
import com.fuzzylite.norm.t.Minimum;
import com.fuzzylite.rule.Rule;
import com.fuzzylite.rule.RuleBlock;
import com.fuzzylite.term.Activated; import com.fuzzylite.term.Activated;
import com.fuzzylite.term.Triangle;
import com.fuzzylite.variable.InputVariable; import com.fuzzylite.variable.InputVariable;
import com.fuzzylite.variable.OutputVariable; import com.fuzzylite.variable.OutputVariable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Service @Service
public class FuzzyInferenceService { public class FuzzyInferenceService {
private final static Logger LOG = LoggerFactory.getLogger(FuzzyInferenceService.class); private final static Logger LOG = LoggerFactory.getLogger(FuzzyInferenceService.class);
private final static String OUTPUT_VARIABLE_NAME = "state"; private final static String OUTPUT_VARIABLE_NAME = "кредит";
private final static String RULE_TEMPLATE = "if %s is %s and %s is %s then " private final static String RULE_TEMPLATE = "if %s is %s and %s is %s then "
+ OUTPUT_VARIABLE_NAME + OUTPUT_VARIABLE_NAME
+ " is %s"; + " is %s";
private final static String NO_RESULT = "Нет результата"; private final static String NO_RESULT = "Нет результата";
// private List<String> mapRulesToString(List<DbRule> dbRules) { private Map<String, List<Entry<String, Integer>>> inputFuzzyTerms = Map.of(
// return dbRules.stream().map(this::getFuzzyRule).collect(Collectors.toList()); "возраст",
// } List.of(
new AbstractMap.SimpleEntry("молодой", 35),
new AbstractMap.SimpleEntry("средний", 60),
new AbstractMap.SimpleEntry("старый", 100)),
"доход",
List.of(
new AbstractMap.SimpleEntry("небольшой", 35000),
new AbstractMap.SimpleEntry("средний", 100000),
new AbstractMap.SimpleEntry("высокий", 500000)));
// private String getFuzzyRule(DbRule dbRule) { private Map<String, List<Entry<String, Integer>>> outputFuzzyTerms = Map.of(
// return format(RULE_TEMPLATE, "кредит", List.of(new AbstractMap.SimpleEntry("небольшой", 20000),
// dbRule.getFirstAntecedent().name(), new AbstractMap.SimpleEntry("средний", 100000),
// dbRule.getFirstAntecedentValue().getAntecedentValue(), new AbstractMap.SimpleEntry("большой", 1000000)));
// dbRule.getSecondAntecedent().name(),
// dbRule.getSecondAntecedentValue().getAntecedentValue(),
// dbRule.getId());
// }
// private RuleBlock getRuleBlock(Engine engine, private List<String> getDemoRules() {
// List<DbRule> dbRules, return List.of(
// Map<String, Double> variableValues, String.format(RULE_TEMPLATE, "возраст", "молодой", "доход", "высокий", "большой"),
// List<AntecedentValue> antecedentValues, String.format(RULE_TEMPLATE, "возраст", "средний", "доход", "высокий", "средний"),
// List<Integer> consequentValues) { String.format(RULE_TEMPLATE, "возраст", "старый", "доход", "высокий", "средний")
// variableValues.forEach((key, value) -> { );
// InputVariable input = new InputVariable(); }
// input.setName(key);
// input.setDescription(""); private List<InputVariable> getInputVariables() {
// input.setEnabled(true); return List.of(getInputVariable("возраст", inputFuzzyTerms.get("возраст")),
// input.setRange(-1, 1); getInputVariable("доход", inputFuzzyTerms.get("доход")));
// input.setLockValueInRange(false); }
// input.addTerm(new Triangle("спад", -1, 0));
// input.addTerm(new Triangle("стабильно", -0.1, 0.1)); private InputVariable getInputVariable(String name, List<Entry<String, Integer>> terms) {
// input.addTerm(new Triangle("рост", 0, 1)); final InputVariable input = new InputVariable();
// engine.addInputVariable(input); input.setName(name);
// }); input.setDescription("");
// input.setRange(0, terms.get(terms.size() - 1).getValue());
// OutputVariable output = new OutputVariable(); input.setEnabled(true);
// output.setName(OUTPUT_VARIABLE_NAME); input.setLockValueInRange(false);
// output.setDescription(""); double prev = 0;
// output.setEnabled(true); for (int i = 0; i < terms.size(); i++) {
// output.setRange(0, consequentValues.size() + 0.1); Triangle term = new Triangle(terms.get(i).getKey(), prev, terms.get(i).getValue());
// output.setAggregation(new Maximum()); prev = term.getVertexB();
// output.setDefuzzifier(new Centroid(10)); input.addTerm(term);
// output.setDefaultValue(Double.NaN); }
// output.setLockValueInRange(false); return input;
// for (int i = 0; i < consequentValues.size(); i++) { }
// output.addTerm(new Triangle(consequentValues.get(i).toString(), i, i + 1));
// } private <T extends Enum<T>> OutputVariable getOutputVariable(String name, List<Entry<String, Integer>> terms) {
// engine.addOutputVariable(output); final OutputVariable output = new OutputVariable();
// output.setName(name);
// RuleBlock mamdani = new RuleBlock(); output.setDescription("");
// mamdani.setName("mamdani"); output.setRange(0, terms.get(terms.size() - 1).getValue());
// mamdani.setDescription(""); output.setEnabled(true);
// mamdani.setEnabled(true); output.setAggregation(new Maximum());
// mamdani.setConjunction(new Minimum()); output.setDefuzzifier(new Centroid(terms.get(terms.size() - 1).getValue()));
// //mamdani.setDisjunction(null); output.setDefaultValue(Double.NaN);
// mamdani.setImplication(new AlgebraicProduct()); output.setLockValueInRange(false);
// mamdani.setActivation(new General()); double prev = 0;
// mapRulesToString(dbRules).forEach(r -> { for (int i = 0; i < terms.size(); i++) {
// LOG.info(r); Triangle term = new Triangle(terms.get(i).getKey(), prev, terms.get(i).getValue());
// mamdani.addRule(Rule.parse(r, engine)); prev = term.getVertexB();
// }); output.addTerm(term);
// return mamdani; }
// } return output;
}
private RuleBlock getRuleBlock(Engine engine,
List<String> rules) {
getInputVariables().forEach(engine::addInputVariable);
engine.addOutputVariable(getOutputVariable("кредит", outputFuzzyTerms.get("кредит")));
RuleBlock mamdani = new RuleBlock();
mamdani.setName("mamdani");
mamdani.setDescription("");
mamdani.setEnabled(true);
mamdani.setConjunction(new Minimum());
mamdani.setImplication(new AlgebraicProduct());
mamdani.setActivation(new General());
rules.forEach(r -> mamdani.addRule(Rule.parse(r, engine)));
return mamdani;
}
private Engine getFuzzyEngine() { private Engine getFuzzyEngine() {
Engine engine = new Engine(); Engine engine = new Engine();
@ -87,29 +119,6 @@ public class FuzzyInferenceService {
return engine; return engine;
} }
// public List<Assessment> getFuzzyInference(List<DbRule> dbRules,
// List<AntecedentValue> antecedentValues,
// Map<String, Double> variableValues) {
// validateVariables(variableValues, dbRules);
// variableValues.entrySet().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
// Engine engine = getFuzzyEngine();
// List<Integer> consequentValues = dbRules.stream().map(DbRule::getId).collect(Collectors.toList());
// engine.addRuleBlock(getRuleBlock(engine, dbRules, variableValues, antecedentValues, consequentValues));
// Map<String, Double> consequents = getConsequent(engine, variableValues);
// if (consequents.containsKey(NO_RESULT)) {
// return new ArrayList<>();
// }
// List<Assessment> assessments = new ArrayList<>();
// for (Map.Entry<String, Double> consequent : consequents.entrySet()) {
// for (DbRule dbRule : dbRules) {
// if (dbRule.getId().equals(Integer.valueOf(consequent.getKey()))) {
// assessments.add(new Assessment(dbRule, consequent.getValue()));
// }
// }
// }
// return assessments;
// }
private Map<String, Double> getConsequent(Engine engine, Map<String, Double> variableValues) { private Map<String, Double> getConsequent(Engine engine, Map<String, Double> variableValues) {
OutputVariable outputVariable = engine.getOutputVariable(OUTPUT_VARIABLE_NAME); OutputVariable outputVariable = engine.getOutputVariable(OUTPUT_VARIABLE_NAME);
for (Map.Entry<String, Double> variableValue : variableValues.entrySet()) { for (Map.Entry<String, Double> variableValue : variableValues.entrySet()) {
@ -124,4 +133,11 @@ public class FuzzyInferenceService {
? Map.of(NO_RESULT, 0.0) ? Map.of(NO_RESULT, 0.0)
: outputVariable.fuzzyOutput().getTerms().stream().collect(Collectors.toMap(t -> t.getTerm().getName(), Activated::getDegree)); : outputVariable.fuzzyOutput().getTerms().stream().collect(Collectors.toMap(t -> t.getTerm().getName(), Activated::getDegree));
} }
public Map<String, Double> getFuzzyInference() {
Engine engine = getFuzzyEngine();
engine.addRuleBlock(getRuleBlock(engine, getDemoRules()));
return getConsequent(engine, Map.of("возраст", 20.0, "доход", 250000.0));
}
} }

View File

@ -3,6 +3,54 @@
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}"> layout:decorate="~{default}">
<div class="container" layout:fragment="content"> <div class="container" layout:fragment="content">
Индекс <form action="/get-inference" th:object="${inferenceForm}" method="post">
<div class="row">
Пример вывода по набору нечетких правил:
</div>
<div class="row">
если возраст средний и доход высокий то размер кредита большой
</div>
<div class="row">
если возраст молодой и доход высокий то размер кредита средний
</div>
<div class="row">
если возраст старый и доход средний то размер кредита средний
</div>
<div class="row">
Выберите значения:
</div>
<div class="row">
<div class="col-md-2 col-sm-12">
Возраст
</div>
<div class="col-md-6 col-sm-12">
<select id="select-age-antecedent" class="selectpicker m-2" data-live-search="true"
th:field="*{ageAntecedent}"
data-width="90%">
<option th:each="ageAntecedent : ${ageAntecedents}"
th:value="${ageAntecedent.value}"
th:utext="${ageAntecedent.description}">
</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-2 col-sm-12">
Доход
</div>
<div class="col-md-6 col-sm-12">
<select id="select-income-antecedent" class="selectpicker m-2" data-live-search="true"
th:field="*{incomeAntecedent}"
data-width="90%">
<option th:each="incomeAntecedent : ${incomeAntecedents}"
th:value="${incomeAntecedent.value}"
th:utext="${incomeAntecedent.description}">
</option>
</select>
</div>
</div>
<input type="submit" class="btn btn-outline-success m-2" value="Получить результат вывода"/>
<div class="row" th:text="${response}"></div>
</form>
</div> </div>
</html> </html>