Skip to content

Commit

Permalink
Merge pull request #23 from IDSIA/dev
Browse files Browse the repository at this point in the history
Version 1.6.2
  • Loading branch information
cbonesana authored Apr 3, 2023
2 parents 06ea506 + 9df1eec commit 3db757d
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* Author: Claudio "Dna" Bonesana
Expand Down Expand Up @@ -61,6 +62,13 @@ public String results(@PathVariable String token, Model model) {
Collectors.toList()
));

final List<Question> questions = answers.keySet()
.stream()
.sorted(Comparator.comparing(
q -> answers.get(q).get(0).getCreation())
)
.collect(Collectors.toList());

final HttpStatus statusCode = resResult.getStatusCode();

if (statusCode.is4xxClientError()) {
Expand All @@ -72,6 +80,7 @@ public String results(@PathVariable String token, Model model) {

final ResponseResult r = resResult.getBody();
model.addAttribute("result", r);
model.addAttribute("questions", questions);
model.addAttribute("answers", answers);

return "results";
Expand Down Expand Up @@ -112,7 +121,7 @@ public String survey(
@RequestParam(required = false) Long questionId,
@RequestParam(required = false) Long answerId,
@RequestParam(value = "checkboxes", required = false) Long[] multipleAnswersId,
@RequestParam(required = false, defaultValue = "true") Boolean show,
@RequestParam(required = false, defaultValue = "false") Boolean show,
Model model,
HttpServletRequest request
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,18 @@
import ch.idsia.adaptive.backend.services.SurveyManagerService;
import ch.idsia.adaptive.backend.services.commons.SurveyException;
import ch.idsia.adaptive.backend.utils.Convert;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.representations.IDToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.security.Principal;
import java.util.*;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -119,7 +114,7 @@ public ResponseEntity<List<ResponseState>> getAllStatesForToken(@PathVariable("t

try {
final Session session = sessions.getSession(token);
final List<State> states = statuses.findAllBySessionOrderByCreationDesc(session);
final List<State> states = statuses.findAllBySessionOrderByCreationAsc(session);

if (states == null)
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public interface StatesRepository extends CrudRepository<State, Long> {

State findFirstBySessionOrderByCreationDesc(Session s);

List<State> findAllBySessionOrderByCreationDesc(Session s);
List<State> findAllBySessionOrderByCreationAsc(Session s);

List<State> findAllBySessionIn(List<Session> sessions);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,38 +57,45 @@ public void init(SurveyData data) {

final Long seed = data.getStartTime().toEpochSecond(OffsetDateTime.now().getOffset());

// TODO: allow also imprecise agents
final AgentGeneric<BayesianFactor> agent = getAgentForSurvey(survey, seed);
agent.setExecutor(es);

activeSurveys.put(data.getToken(), agent);
}

public static AgentGeneric<BayesianFactor> getAgentForSurvey(Survey survey, Long seed) {
final AgentGeneric<BayesianFactor> agent;

// TODO: allow also imprecise agents

if (survey.getIsAdaptive()) {
Scoring<BayesianFactor> scoring;

if (survey.getScoring().equals("mode")) {
logger.debug("using ScoringFunctionBayesianMode for {}", surveyId);
logger.debug("using ScoringFunctionBayesianMode for {}", survey.getId());
scoring = new ScoringFunctionBayesianMode();
} else {
logger.debug("using ScoringFunctionExpectedEntropy for {}", surveyId);
logger.debug("using ScoringFunctionExpectedEntropy for {}", survey.getId());
scoring = new ScoringFunctionExpectedEntropy();
}

if (survey.getIsStructural()) {
logger.debug("new AgentPreciseAdaptiveStructural for {}", surveyId);
logger.debug("new AgentPreciseAdaptiveStructural for {}", survey.getId());
agent = new AgentPreciseAdaptiveStructural(survey, seed, scoring);
} else if (survey.getIsSimple()) {
logger.debug("new AgentPreciseAdaptiveSimple for {}", surveyId);
logger.debug("new AgentPreciseAdaptiveSimple for {}", survey.getId());
agent = new AgentPreciseAdaptiveSimple(survey, seed, scoring);
} else {
logger.debug("new AgentPreciseAdaptiveSimple for {}", surveyId);
logger.debug("new AgentPreciseAdaptiveSimple for {}", survey.getId());
agent = new AgentPreciseAdaptive(survey, seed, scoring);
}

} else {
logger.debug("new AgentPreciseNonAdaptive for {}", surveyId);
logger.debug("new AgentPreciseNonAdaptive for {}", survey.getId());
agent = new AgentPreciseNonAdaptive(survey, seed);
}

agent.setExecutor(es);

activeSurveys.put(data.getToken(), agent);
return agent;
}

public Agent getSurvey(SurveyData data) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@


import ch.idsia.adaptive.backend.persistence.model.*;
import ch.idsia.adaptive.backend.services.commons.agents.AgentPreciseAdaptiveStructural;
import ch.idsia.adaptive.backend.services.SurveyManagerService;
import ch.idsia.adaptive.backend.services.commons.agents.AgentGeneric;
import ch.idsia.adaptive.backend.services.commons.profiles.Content;
import ch.idsia.adaptive.backend.services.commons.profiles.Profile;
import ch.idsia.adaptive.backend.services.commons.scoring.precise.ScoringFunctionExpectedEntropy;
import ch.idsia.crema.factor.bayesian.BayesianFactor;
import lombok.Getter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
Expand Down Expand Up @@ -221,7 +222,7 @@ public void run() throws InterruptedException, IOException {
.map(profile -> (Callable<Content>) () -> {
final Content content = new Content();
final ExecutorService e = Executors.newFixedThreadPool(nThread);
final AgentPreciseAdaptiveStructural agent = new AgentPreciseAdaptiveStructural(survey, 42L, new ScoringFunctionExpectedEntropy());
final AgentGeneric<BayesianFactor> agent = SurveyManagerService.getAgentForSurvey(survey, 42L);
agent.setExecutor(e);

try {
Expand Down Expand Up @@ -314,7 +315,7 @@ public void run() throws InterruptedException, IOException {
}

content.newLine();
content.add("" + profile.getName()); // profile
content.add(profile.getName()); // profile
content.add("TRUE"); // question
content.add(""); // answer
content.add(""); // answer given
Expand Down Expand Up @@ -342,8 +343,10 @@ public void run() throws InterruptedException, IOException {
resultFilename = "results." + filename;
final Path dst = Paths.get("", "data", "results", resultFilename);

try (FileOutputStream fos = new FileOutputStream(dst.toFile(), false)) {
final XSSFWorkbook workbook = new XSSFWorkbook();
try (
FileOutputStream fos = new FileOutputStream(dst.toFile(), false);
XSSFWorkbook workbook = new XSSFWorkbook()
) {
final XSSFSheet results = workbook.createSheet("results");

int r = 0;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
logging.level.ch.idsia=info
logging.level.ch.idsia=debug
logging.level.ch.idsia.adaptive.backend.services.templates=warn
logging.level.ch.idsia.adaptive.backend.services.InitializationService=warn
logging.level.org.apache.catalina=warn
Expand Down
15 changes: 8 additions & 7 deletions AdapQuestBackend/src/main/resources/static/js/charts.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ d3.json('/survey/states/' + token)
.then((data) => {
const entropies = []

data.sort((a, b) => a.totalAnswers - b.totalAnswers)
.forEach(d => {
entropies.push({'answers': d.totalAnswers, 'value': d.scoreAverage})
});
data.forEach(d => {
entropies.push({
'answers': d.totalAnswers, 'value': d.scoreAverage.toFixed(2)
})
});

return entropies;
})
.then(data => {
.then((data) => {
const svg = d3.select('#chart-entropy')
.append('svg')
.attr('width', width + margin.left + margin.right)
Expand Down Expand Up @@ -115,7 +116,7 @@ d3.json('/survey/state/' + token)
const svg = d3.select('#chart-distribution')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.attr('height', 1.7*height + margin.top + margin.bottom)
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);

Expand All @@ -129,7 +130,7 @@ d3.json('/survey/state/' + token)
.attr('transform', `translate(0, ${height})`)
.call(d3.axisBottom(x))
.selectAll('text')
.attr('transform', 'translate(-10,0)rotate(-35)')
.attr('transform', 'translate(-12,+10)rotate(-90)')
.style('text-anchor', 'end');

const y = d3.scaleLinear()
Expand Down
8 changes: 5 additions & 3 deletions AdapQuestBackend/src/main/resources/templates/results.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,14 @@
<div>
Answers:
<ul>
<li th:each="question : ${answers.keySet()}">
<li th:each="question : ${questions}">
<div>
<span style="font-weight: bold" th:text="${question.getQuestion()}"></span>
<span style="font-weight: bold" th:text="${question.name}"></span>
&nbsp;
<span style="font-weight: bold" th:text="${question.question}"></span>
</div>
<div th:each="answer : ${answers.get(question)}"
th:with="text=${answer.getQuestionAnswer().getText()}">
th:with="text=${answer.questionAnswer.text}">
<span th:if="${!text.equals('no')}" th:text="${text}"></span>
</div>
</li>
Expand Down
2 changes: 1 addition & 1 deletion AdapQuestBackend/src/main/resources/templates/survey.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<input th:name="questionId" th:value="${question.id}" type="hidden">
<div class="jumbotron">
<div>
<h3 th:text="'Q' + ${question.id}"></h3>
<h3 th:text="${question.name}"></h3>
<p th:text="${question.explanation}"></p>
<p th:text="${question.question}"></p>

Expand Down
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,19 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
<version>2.14.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.3</version>
<version>2.14.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.13.3</version>
<version>2.14.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
<dependency>
Expand Down

0 comments on commit 3db757d

Please sign in to comment.