Search in sources :

Example 66 with ExerciseGroup

use of de.tum.in.www1.artemis.domain.exam.ExerciseGroup in project ArTEMiS by ls1intum.

the class ExamService method calculateExamScores.

/**
 * Puts students, result and exerciseGroups together for ExamScoresDTO
 *
 * @param examId the id of the exam
 * @return return ExamScoresDTO with students, scores and exerciseGroups for exam
 */
public ExamScoresDTO calculateExamScores(Long examId) {
    Exam exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException("Exam", examId));
    // without test run participations
    List<StudentParticipation> studentParticipations = studentParticipationRepository.findByExamIdWithSubmissionRelevantResult(examId);
    // Adding exam information to DTO
    ExamScoresDTO scores = new ExamScoresDTO(exam.getId(), exam.getTitle(), exam.getMaxPoints());
    // setting multiplicity of correction rounds
    scores.hasSecondCorrectionAndStarted = false;
    // Counts how many participants each exercise has
    Map<Long, Long> exerciseIdToNumberParticipations = studentParticipations.stream().collect(Collectors.groupingBy(studentParticipation -> studentParticipation.getExercise().getId(), Collectors.counting()));
    // Adding exercise group information to DTO
    for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {
        // Find the maximum points for this exercise group
        OptionalDouble optionalMaxPointsGroup = exerciseGroup.getExercises().stream().mapToDouble(Exercise::getMaxPoints).max();
        Double maxPointsGroup = optionalMaxPointsGroup.orElse(0);
        // Counter for exerciseGroup participations. Is calculated by summing up the number of exercise participations
        long numberOfExerciseGroupParticipants = 0;
        // Add information about exercise groups and exercises
        var exerciseGroupDTO = new ExamScoresDTO.ExerciseGroup(exerciseGroup.getId(), exerciseGroup.getTitle(), maxPointsGroup);
        for (Exercise exercise : exerciseGroup.getExercises()) {
            Long participantsForExercise = exerciseIdToNumberParticipations.get(exercise.getId());
            // If no participation exists for an exercise then no entry exists in the map
            if (participantsForExercise == null) {
                participantsForExercise = 0L;
            }
            numberOfExerciseGroupParticipants += participantsForExercise;
            exerciseGroupDTO.containedExercises.add(new ExamScoresDTO.ExerciseGroup.ExerciseInfo(exercise.getId(), exercise.getTitle(), exercise.getMaxPoints(), participantsForExercise, exercise.getClass().getSimpleName()));
        }
        exerciseGroupDTO.numberOfParticipants = numberOfExerciseGroupParticipants;
        scores.exerciseGroups.add(exerciseGroupDTO);
    }
    // Adding registered student information to DTO
    // fetched without test runs
    Set<StudentExam> studentExams = studentExamRepository.findByExamId(examId);
    ObjectMapper objectMapper = new ObjectMapper();
    for (StudentExam studentExam : studentExams) {
        User user = studentExam.getUser();
        var studentResult = new ExamScoresDTO.StudentResult(user.getId(), user.getName(), user.getEmail(), user.getLogin(), user.getRegistrationNumber(), studentExam.isSubmitted());
        // Adding student results information to DTO
        List<StudentParticipation> participationsOfStudent = studentParticipations.stream().filter(studentParticipation -> studentParticipation.getStudent().get().getId().equals(studentResult.userId)).toList();
        studentResult.overallPointsAchieved = 0.0;
        studentResult.overallPointsAchievedInFirstCorrection = 0.0;
        for (StudentParticipation studentParticipation : participationsOfStudent) {
            Exercise exercise = studentParticipation.getExercise();
            // Relevant Result is already calculated
            if (studentParticipation.getResults() != null && !studentParticipation.getResults().isEmpty()) {
                Result relevantResult = studentParticipation.getResults().iterator().next();
                // Note: It is important that we round on the individual exercise level first and then sum up.
                // This is necessary so that the student arrives at the same overall result when doing his own recalculation.
                // Let's assume that the student achieved 1.05 points in each of 5 exercises.
                // In the client, these are now displayed rounded as 1.1 points.
                // If the student adds up the displayed points, he gets a total of 5.5 points.
                // In order to get the same total result as the student, we have to round before summing.
                double achievedPoints = roundScoreSpecifiedByCourseSettings(relevantResult.getScore() / 100.0 * exercise.getMaxPoints(), exam.getCourse());
                // points earned in NOT_INCLUDED exercises do not count towards the students result in the exam
                if (!exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED)) {
                    studentResult.overallPointsAchieved += achievedPoints;
                }
                // collect points of first correction, if a second correction exists
                if (exam.getNumberOfCorrectionRoundsInExam() == 2 && !exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED)) {
                    Optional<Submission> latestSubmission = studentParticipation.findLatestSubmission();
                    if (latestSubmission.isPresent()) {
                        Submission submission = latestSubmission.get();
                        // Check if second correction already started
                        if (submission.getManualResults().size() > 1) {
                            if (!scores.hasSecondCorrectionAndStarted) {
                                scores.hasSecondCorrectionAndStarted = true;
                            }
                            Result firstManualResult = submission.getFirstManualResult();
                            double achievedPointsInFirstCorrection = 0.0;
                            if (firstManualResult != null) {
                                Double resultScore = firstManualResult.getScore();
                                achievedPointsInFirstCorrection = resultScore != null ? roundScoreSpecifiedByCourseSettings(resultScore / 100.0 * exercise.getMaxPoints(), exam.getCourse()) : 0.0;
                            }
                            studentResult.overallPointsAchievedInFirstCorrection += achievedPointsInFirstCorrection;
                        }
                    }
                }
                // Check whether the student attempted to solve the exercise
                boolean hasNonEmptySubmission = hasNonEmptySubmission(studentParticipation.getSubmissions(), exercise, objectMapper);
                studentResult.exerciseGroupIdToExerciseResult.put(exercise.getExerciseGroup().getId(), new ExamScoresDTO.ExerciseResult(exercise.getId(), exercise.getTitle(), exercise.getMaxPoints(), relevantResult.getScore(), achievedPoints, hasNonEmptySubmission));
            }
        }
        if (scores.maxPoints != null) {
            studentResult.overallScoreAchieved = (studentResult.overallPointsAchieved / scores.maxPoints) * 100.0;
            var overallScoreAchievedInFirstCorrection = (studentResult.overallPointsAchievedInFirstCorrection / scores.maxPoints) * 100.0;
            // Sets grading scale related properties for exam scores
            Optional<GradingScale> gradingScale = gradingScaleRepository.findByExamId(examId);
            if (gradingScale.isPresent()) {
                // Calculate current student grade
                GradeStep studentGrade = gradingScaleRepository.matchPercentageToGradeStep(studentResult.overallScoreAchieved, gradingScale.get().getId());
                GradeStep studentGradeInFirstCorrection = gradingScaleRepository.matchPercentageToGradeStep(overallScoreAchievedInFirstCorrection, gradingScale.get().getId());
                studentResult.overallGrade = studentGrade.getGradeName();
                studentResult.overallGradeInFirstCorrection = studentGradeInFirstCorrection.getGradeName();
                studentResult.hasPassed = studentGrade.getIsPassingGrade();
            }
        }
        scores.studentResults.add(studentResult);
    }
    // Updating exam information in DTO
    double sumOverallPoints = scores.studentResults.stream().mapToDouble(studentResult -> studentResult.overallPointsAchieved).sum();
    int numberOfStudentResults = scores.studentResults.size();
    if (numberOfStudentResults != 0) {
        scores.averagePointsAchieved = sumOverallPoints / numberOfStudentResults;
    }
    return scores;
}
Also used : Async(org.springframework.scheduling.annotation.Async) java.util(java.util) SecurityUtils(de.tum.in.www1.artemis.security.SecurityUtils) de.tum.in.www1.artemis.repository(de.tum.in.www1.artemis.repository) TimeLogUtil(de.tum.in.www1.artemis.service.util.TimeLogUtil) BadRequestAlertException(de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException) ZonedDateTime(java.time.ZonedDateTime) LoggerFactory(org.slf4j.LoggerFactory) GitService(de.tum.in.www1.artemis.service.connectors.GitService) StudentExam(de.tum.in.www1.artemis.domain.exam.StudentExam) InstanceMessageSendService(de.tum.in.www1.artemis.service.messaging.InstanceMessageSendService) RoundingUtil.roundScoreSpecifiedByCourseSettings(de.tum.in.www1.artemis.service.util.RoundingUtil.roundScoreSpecifiedByCourseSettings) Value(org.springframework.beans.factory.annotation.Value) ExerciseGroup(de.tum.in.www1.artemis.domain.exam.ExerciseGroup) AuditEvent(org.springframework.boot.actuate.audit.AuditEvent) Service(org.springframework.stereotype.Service) ModelingSubmission(de.tum.in.www1.artemis.domain.modeling.ModelingSubmission) GroupNotificationService(de.tum.in.www1.artemis.service.notifications.GroupNotificationService) Path(java.nio.file.Path) Exam(de.tum.in.www1.artemis.domain.exam.Exam) de.tum.in.www1.artemis.service(de.tum.in.www1.artemis.service) Logger(org.slf4j.Logger) QuizExercise(de.tum.in.www1.artemis.domain.quiz.QuizExercise) AuditEventRepository(org.springframework.boot.actuate.audit.AuditEventRepository) Files(java.nio.file.Files) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) QuizSubmission(de.tum.in.www1.artemis.domain.quiz.QuizSubmission) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Constants(de.tum.in.www1.artemis.config.Constants) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) de.tum.in.www1.artemis.domain(de.tum.in.www1.artemis.domain) de.tum.in.www1.artemis.web.rest.dto(de.tum.in.www1.artemis.web.rest.dto) StudentParticipation(de.tum.in.www1.artemis.domain.participation.StudentParticipation) ModelingExercise(de.tum.in.www1.artemis.domain.modeling.ModelingExercise) de.tum.in.www1.artemis.domain.enumeration(de.tum.in.www1.artemis.domain.enumeration) StudentParticipation(de.tum.in.www1.artemis.domain.participation.StudentParticipation) QuizExercise(de.tum.in.www1.artemis.domain.quiz.QuizExercise) ModelingExercise(de.tum.in.www1.artemis.domain.modeling.ModelingExercise) ExerciseGroup(de.tum.in.www1.artemis.domain.exam.ExerciseGroup) StudentExam(de.tum.in.www1.artemis.domain.exam.StudentExam) Exam(de.tum.in.www1.artemis.domain.exam.Exam) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ModelingSubmission(de.tum.in.www1.artemis.domain.modeling.ModelingSubmission) QuizSubmission(de.tum.in.www1.artemis.domain.quiz.QuizSubmission) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) StudentExam(de.tum.in.www1.artemis.domain.exam.StudentExam)

Example 67 with ExerciseGroup

use of de.tum.in.www1.artemis.domain.exam.ExerciseGroup in project ArTEMiS by ls1intum.

the class ExamService method findByIdWithExerciseGroupsAndExercisesElseThrow.

/**
 * Get one exam by id with exercise groups and exercises.
 * Also fetches the template and solution participation for programming exercises and questions for quiz exercises.
 *
 * @param examId the id of the entity
 * @return the exam with exercise groups
 */
@NotNull
public Exam findByIdWithExerciseGroupsAndExercisesElseThrow(Long examId) {
    log.debug("Request to get exam with exercise groups : {}", examId);
    Exam exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException("Exam", examId));
    for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {
        for (Exercise exercise : exerciseGroup.getExercises()) {
            if (exercise instanceof ProgrammingExercise) {
                ProgrammingExercise exerciseWithTemplateAndSolutionParticipation = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationWithResultsElseThrow(exercise.getId());
                ((ProgrammingExercise) exercise).setTemplateParticipation(exerciseWithTemplateAndSolutionParticipation.getTemplateParticipation());
                ((ProgrammingExercise) exercise).setSolutionParticipation(exerciseWithTemplateAndSolutionParticipation.getSolutionParticipation());
            }
            if (exercise instanceof QuizExercise) {
                QuizExercise quizExercise = quizExerciseRepository.findByIdWithQuestionsElseThrow(exercise.getId());
                ((QuizExercise) exercise).setQuizQuestions(quizExercise.getQuizQuestions());
            }
        }
    }
    return exam;
}
Also used : QuizExercise(de.tum.in.www1.artemis.domain.quiz.QuizExercise) ModelingExercise(de.tum.in.www1.artemis.domain.modeling.ModelingExercise) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) ExerciseGroup(de.tum.in.www1.artemis.domain.exam.ExerciseGroup) StudentExam(de.tum.in.www1.artemis.domain.exam.StudentExam) Exam(de.tum.in.www1.artemis.domain.exam.Exam) QuizExercise(de.tum.in.www1.artemis.domain.quiz.QuizExercise) NotNull(javax.validation.constraints.NotNull)

Example 68 with ExerciseGroup

use of de.tum.in.www1.artemis.domain.exam.ExerciseGroup in project ArTEMiS by ls1intum.

the class ExamService method getAllProgrammingExercisesForExam.

private Set<ProgrammingExercise> getAllProgrammingExercisesForExam(Long examId) {
    var exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException("Exam", examId));
    // Collect all programming exercises for the given exam
    Set<ProgrammingExercise> programmingExercises = new HashSet<>();
    for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {
        for (Exercise exercise : exerciseGroup.getExercises()) {
            if (exercise instanceof ProgrammingExercise) {
                programmingExercises.add((ProgrammingExercise) exercise);
            }
        }
    }
    return programmingExercises;
}
Also used : QuizExercise(de.tum.in.www1.artemis.domain.quiz.QuizExercise) ModelingExercise(de.tum.in.www1.artemis.domain.modeling.ModelingExercise) EntityNotFoundException(de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException) ExerciseGroup(de.tum.in.www1.artemis.domain.exam.ExerciseGroup)

Example 69 with ExerciseGroup

use of de.tum.in.www1.artemis.domain.exam.ExerciseGroup in project ArTEMiS by ls1intum.

the class BitbucketService method createProjectForExercise.

/**
 * Create a new project
 *
 * @param programmingExercise the programming exercise for which the Bitbucket Project should be created
 * @throws BitbucketException if the project could not be created
 */
@Override
public void createProjectForExercise(ProgrammingExercise programmingExercise) throws BitbucketException {
    String projectKey = programmingExercise.getProjectKey();
    String projectName = programmingExercise.getProjectName();
    final var body = new BitbucketProjectDTO(projectKey, projectName);
    HttpEntity<?> entity = new HttpEntity<>(body, null);
    log.debug("Creating Bitbucket project {} with key {}", projectName, projectKey);
    try {
        // Get course over exerciseGroup in exam mode
        Course course = programmingExercise.getCourseViaExerciseGroupOrCourseMember();
        restTemplate.exchange(bitbucketServerUrl + "/rest/api/latest/projects", HttpMethod.POST, entity, Void.class);
        // admins get administrative permissions
        grantGroupPermissionToProject(projectKey, adminGroupName, BitbucketPermission.PROJECT_ADMIN);
        if (StringUtils.hasText(course.getInstructorGroupName())) {
            // instructors get administrative permissions
            grantGroupPermissionToProject(projectKey, course.getInstructorGroupName(), BitbucketPermission.PROJECT_ADMIN);
        }
        // editors get write permissions
        if (StringUtils.hasText(course.getEditorGroupName())) {
            grantGroupPermissionToProject(projectKey, course.getEditorGroupName(), BitbucketPermission.PROJECT_WRITE);
        }
        // tutors get read permissions
        if (StringUtils.hasText(course.getTeachingAssistantGroupName())) {
            grantGroupPermissionToProject(projectKey, course.getTeachingAssistantGroupName(), BitbucketPermission.PROJECT_READ);
        }
    } catch (HttpClientErrorException e) {
        log.error("Could not create Bitbucket project {} with key {}", projectName, projectKey, e);
        throw new BitbucketException("Error while creating Bitbucket project. Try a different name!");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) BitbucketException(de.tum.in.www1.artemis.exception.BitbucketException)

Example 70 with ExerciseGroup

use of de.tum.in.www1.artemis.domain.exam.ExerciseGroup in project ArTEMiS by ls1intum.

the class ProgrammingExerciseTestService method createProgrammingExerciseForExam_DatesSet.

// TEST
public void createProgrammingExerciseForExam_DatesSet() throws Exception {
    setupRepositoryMocks(examExercise, exerciseRepo, solutionRepo, testRepo, auxRepo);
    ExerciseGroup exerciseGroup = examExercise.getExerciseGroup();
    mockDelegate.mockConnectorRequestsForSetup(examExercise, false);
    ZonedDateTime someMoment = ZonedDateTime.of(2000, 06, 15, 0, 0, 0, 0, ZoneId.of("Z"));
    examExercise.setDueDate(someMoment);
    request.postWithResponseBody(ROOT + SETUP, examExercise, ProgrammingExercise.class, HttpStatus.BAD_REQUEST);
    assertThat(exerciseGroup.getExercises()).doesNotContain(examExercise);
}
Also used : ZonedDateTime(java.time.ZonedDateTime) ExerciseGroup(de.tum.in.www1.artemis.domain.exam.ExerciseGroup)

Aggregations

ExerciseGroup (de.tum.in.www1.artemis.domain.exam.ExerciseGroup)126 WithMockUser (org.springframework.security.test.context.support.WithMockUser)76 Test (org.junit.jupiter.api.Test)70 Exam (de.tum.in.www1.artemis.domain.exam.Exam)64 StudentExam (de.tum.in.www1.artemis.domain.exam.StudentExam)46 ModelingExercise (de.tum.in.www1.artemis.domain.modeling.ModelingExercise)46 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)24 QuizExercise (de.tum.in.www1.artemis.domain.quiz.QuizExercise)22 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)22 AbstractSpringIntegrationBambooBitbucketJiraTest (de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest)20 BadRequestAlertException (de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException)20 StudentParticipation (de.tum.in.www1.artemis.domain.participation.StudentParticipation)18 EntityNotFoundException (de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException)14 TextExercise (de.tum.in.www1.artemis.domain.TextExercise)12 ZonedDateTime (java.time.ZonedDateTime)12 de.tum.in.www1.artemis.domain (de.tum.in.www1.artemis.domain)10 de.tum.in.www1.artemis.repository (de.tum.in.www1.artemis.repository)10 Collectors (java.util.stream.Collectors)10 ModelingSubmission (de.tum.in.www1.artemis.domain.modeling.ModelingSubmission)8 Participation (de.tum.in.www1.artemis.domain.participation.Participation)8