~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/worksheet/utils.py

  • Committer: David Coles
  • Date: 2009-12-10 01:18:36 UTC
  • Revision ID: coles.david@gmail.com-20091210011836-6kk2omcmr9hvphj0
Correct documentation's system diagram (console communication goes via Application Slaves)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2009 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Author: Matt Giuca
 
19
 
 
20
"""
 
21
Worksheet Utility Functions
 
22
 
 
23
This module provides functions for tutorial and worksheet computations.
 
24
"""
 
25
 
 
26
from storm.locals import And, Asc, Desc, Store
 
27
import genshi
 
28
 
 
29
import ivle.database
 
30
from ivle.database import ExerciseAttempt, ExerciseSave, Worksheet, \
 
31
                          WorksheetExercise, Exercise
 
32
 
 
33
__all__ = ['ExerciseNotFound', 'get_exercise_status',
 
34
           'get_exercise_stored_text', 'get_exercise_attempts',
 
35
           'get_exercise_attempt',
 
36
          ]
 
37
 
 
38
class ExerciseNotFound(Exception):
 
39
    pass
 
40
 
 
41
def get_exercise_status(store, user, worksheet_exercise, as_of=None):
 
42
    """Given a storm.store, User and Exercise, returns information about
 
43
    the user's performance on that problem.
 
44
    @param store: A storm.store
 
45
    @param user: A User.
 
46
    @param worksheet_exercise: An Exercise.
 
47
    @param as_of: Optional datetime. If supplied, gets the status as of as_of.
 
48
    Returns a tuple of:
 
49
        - A boolean, whether they have successfully passed this exercise.
 
50
        - An int, the number of attempts they have made up to and
 
51
          including the first successful attempt (or the total number of
 
52
          attempts, if not yet successful).
 
53
    """
 
54
    # A Storm expression denoting all active attempts by this user for this
 
55
    # exercise.
 
56
    is_relevant = ((ExerciseAttempt.user_id == user.id) &
 
57
            (ExerciseAttempt.ws_ex_id == worksheet_exercise.id) &
 
58
            (ExerciseAttempt.active == True))
 
59
    if as_of is not None:
 
60
        is_relevant &= ExerciseAttempt.date <= as_of
 
61
 
 
62
    # Get the first successful active attempt, or None if no success yet.
 
63
    # (For this user, for this exercise).
 
64
    first_success = store.find(ExerciseAttempt, is_relevant,
 
65
            ExerciseAttempt.complete == True
 
66
        ).order_by(Asc(ExerciseAttempt.date)).first()
 
67
 
 
68
    if first_success is not None:
 
69
        # Get the total number of active attempts up to and including the
 
70
        # first successful attempt.
 
71
        # (Subsequent attempts don't count, because the user had already
 
72
        # succeeded by then).
 
73
        num_attempts = store.find(ExerciseAttempt, is_relevant,
 
74
                ExerciseAttempt.date <= first_success.date).count()
 
75
    else:
 
76
        # User has not yet succeeded.
 
77
        # Get the total number of active attempts.
 
78
        num_attempts = store.find(ExerciseAttempt, is_relevant).count()
 
79
 
 
80
    return first_success is not None, num_attempts
 
81
 
 
82
def get_exercise_stored_text(store, user, worksheet_exercise):
 
83
    """Given a storm.store, User and WorksheetExercise, returns an
 
84
    ivle.database.ExerciseSave object for the last saved/submitted attempt for
 
85
    this question (note that ExerciseAttempt is a subclass of ExerciseSave).
 
86
    Returns None if the user has not saved or made an attempt on this
 
87
    problem.
 
88
    If the user has both saved and submitted, it returns whichever was
 
89
    made last.
 
90
    """
 
91
 
 
92
    # Get the saved text, or None
 
93
    saved = store.find(ExerciseSave,
 
94
                ExerciseSave.user_id == user.id,
 
95
                ExerciseSave.ws_ex_id == worksheet_exercise.id).one()
 
96
 
 
97
    # Get the most recent attempt, or None
 
98
    attempt = store.find(ExerciseAttempt,
 
99
            ExerciseAttempt.user_id == user.id,
 
100
            ExerciseAttempt.active == True,
 
101
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id
 
102
        ).order_by(Asc(ExerciseAttempt.date)).last()
 
103
 
 
104
    # Pick the most recent of these two
 
105
    if saved is not None:
 
106
        if attempt is not None:
 
107
            return saved if saved.date > attempt.date else attempt
 
108
        else:
 
109
            return saved
 
110
    else:
 
111
        if attempt is not None:
 
112
            return attempt
 
113
        else:
 
114
            return None
 
115
 
 
116
def _get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
 
117
        allow_inactive=False):
 
118
    """Same as get_exercise_attempts, but doesn't convert Storm's iterator
 
119
    into a list."""
 
120
 
 
121
    # Get the most recent attempt before as_of, or None
 
122
    return store.find(ExerciseAttempt,
 
123
            ExerciseAttempt.user_id == user.id,
 
124
            ExerciseAttempt.ws_ex_id == worksheet_exercise.id,
 
125
            True if allow_inactive else ExerciseAttempt.active == True,
 
126
            True if as_of is None else ExerciseAttempt.date <= as_of,
 
127
        ).order_by(Desc(ExerciseAttempt.date))
 
128
 
 
129
def get_exercise_attempts(store, user, worksheet_exercise, as_of=None,
 
130
        allow_inactive=False):
 
131
    """Given a storm.store, User and Exercise, returns a list of
 
132
    ivle.database.ExerciseAttempt objects, one for each attempt made for the
 
133
    exercise, sorted from latest to earliest.
 
134
 
 
135
    as_of: Optional datetime.datetime object. If supplied, only returns
 
136
        attempts made before or at this time.
 
137
    allow_inactive: If True, will return disabled attempts.
 
138
    """
 
139
    return list(_get_exercise_attempts(store, user, worksheet_exercise, as_of,
 
140
        allow_inactive))
 
141
 
 
142
def get_exercise_attempt(store, user, worksheet_exercise, as_of=None,
 
143
        allow_inactive=False):
 
144
    """Given a storm.store, User and WorksheetExercise, returns an
 
145
    ivle.database.ExerciseAttempt object for the last submitted attempt for
 
146
    this question.
 
147
    Returns None if the user has not made an attempt on this
 
148
    problem.
 
149
 
 
150
    as_of: Optional datetime.datetime object. If supplied, only returns
 
151
        attempts made before or at this time.
 
152
    allow_inactive: If True, will return disabled attempts.
 
153
    """
 
154
    return _get_exercise_attempts(store, user, worksheet_exercise, as_of,
 
155
        allow_inactive).first()
 
156
 
 
157
def save_exercise(store, user, worksheet_exercise, text, date):
 
158
    """Save an exercise for a user.
 
159
 
 
160
    Given a store, User, WorksheetExercise, text and date, save the text to the
 
161
    database. This will create the ExerciseSave if needed.
 
162
    """
 
163
    saved = store.find(ivle.database.ExerciseSave,
 
164
                ivle.database.ExerciseSave.user_id == user.id,
 
165
                ivle.database.ExerciseSave.ws_ex_id == worksheet_exercise.id
 
166
                ).one()
 
167
    if saved is None:
 
168
        saved = ivle.database.ExerciseSave(user=user, 
 
169
                                        worksheet_exercise=worksheet_exercise)
 
170
        store.add(saved)
 
171
 
 
172
    saved.date = date
 
173
    saved.text = text
 
174
 
 
175
def calculate_score(store, user, worksheet, as_of=None):
 
176
    """
 
177
    Given a storm.store, User, Exercise and Worksheet, calculates a score for
 
178
    the user on the given worksheet.
 
179
    @param store: A storm.store
 
180
    @param user: A User.
 
181
    @param worksheet: A Worksheet.
 
182
    @param as_of: Optional datetime. If supplied, gets the score as of as_of.
 
183
    Returns a 4-tuple of ints, consisting of:
 
184
    (No. mandatory exercises completed,
 
185
     Total no. mandatory exercises,
 
186
     No. optional exercises completed,
 
187
     Total no. optional exercises)
 
188
    """
 
189
    mand_done = 0
 
190
    mand_total = 0
 
191
    opt_done = 0
 
192
    opt_total = 0
 
193
 
 
194
    # Get the student's pass/fail for each exercise in this worksheet
 
195
    for worksheet_exercise in worksheet.worksheet_exercises:
 
196
        exercise = worksheet_exercise.exercise
 
197
        worksheet = worksheet_exercise.worksheet
 
198
        optional = worksheet_exercise.optional
 
199
 
 
200
        done, _ = get_exercise_status(store, user, worksheet_exercise, as_of)
 
201
        # done is a bool, whether this student has completed that problem
 
202
        if optional:
 
203
            opt_total += 1
 
204
            if done: opt_done += 1
 
205
        else:
 
206
            mand_total += 1
 
207
            if done: mand_done += 1
 
208
 
 
209
    return mand_done, mand_total, opt_done, opt_total
 
210
 
 
211
def calculate_mark(mand_done, mand_total):
 
212
    """Calculate a subject mark, given the result of all worksheets.
 
213
    @param mand_done: The total number of mandatory exercises completed by
 
214
        some student, across all worksheets.
 
215
    @param mand_total: The total number of mandatory exercises across all
 
216
        worksheets in the offering.
 
217
    @return: (percent, mark, mark_total)
 
218
        percent: The percentage of exercises the student has completed, as an
 
219
            integer between 0 and 100 inclusive.
 
220
        mark: The mark the student has received, based on the percentage.
 
221
        mark_total: The total number of marks available (currently hard-coded
 
222
            as 5).
 
223
    """
 
224
    # We want to display a students mark out of 5. However, they are
 
225
    # allowed to skip 1 in 5 questions and still get 'full marks'.
 
226
    # Hence we divide by 16, essentially making 16 percent worth
 
227
    # 1 star, and 80 or above worth 5.
 
228
    if mand_total > 0:
 
229
        percent_int = (100 * mand_done) // mand_total
 
230
    else:
 
231
        # Avoid Div0, just give everyone 0 marks if there are none available
 
232
        percent_int = 0
 
233
    # percent / 16, rounded down, with a maximum mark of 5
 
234
    max_mark = 5
 
235
    mark = min(percent_int // 16, max_mark)
 
236
    return (percent_int, mark, max_mark)
 
237
 
 
238
def update_exerciselist(worksheet):
 
239
    """Runs through the worksheetstream, generating the appropriate
 
240
    WorksheetExercises, and de-activating the old ones."""
 
241
    exercises = []
 
242
    # Turns the worksheet into an xml stream, and then finds all the 
 
243
    # exercise nodes in the stream.
 
244
    worksheetdata = genshi.XML(worksheet.get_xml())
 
245
    for kind, data, pos in worksheetdata:
 
246
        if kind is genshi.core.START:
 
247
            # Data is a tuple of tag name and a list of name->value tuples
 
248
            if data[0] == 'exercise':
 
249
                src = ""
 
250
                optional = False
 
251
                for attr in data[1]:
 
252
                    if attr[0] == 'src':
 
253
                        src = attr[1]
 
254
                    if attr[0] == 'optional':
 
255
                        optional = attr[1] == 'true'
 
256
                if src != "":
 
257
                    exercises.append((src, optional))
 
258
    ex_num = 0
 
259
    # Set all current worksheet_exercises to be inactive
 
260
    db_worksheet_exercises = Store.of(worksheet).find(WorksheetExercise,
 
261
        WorksheetExercise.worksheet_id == worksheet.id)
 
262
    for worksheet_exercise in db_worksheet_exercises:
 
263
        worksheet_exercise.active = False
 
264
    
 
265
    for exerciseid, optional in exercises:
 
266
        worksheet_exercise = Store.of(worksheet).find(WorksheetExercise,
 
267
            WorksheetExercise.worksheet_id == worksheet.id,
 
268
            Exercise.id == WorksheetExercise.exercise_id,
 
269
            Exercise.id == exerciseid).one()
 
270
        if worksheet_exercise is None:
 
271
            exercise = Store.of(worksheet).find(Exercise,
 
272
                Exercise.id == exerciseid
 
273
            ).one()
 
274
            if exercise is None:
 
275
                raise ExerciseNotFound(exerciseid)
 
276
            worksheet_exercise = WorksheetExercise()
 
277
            worksheet_exercise.worksheet_id = worksheet.id
 
278
            worksheet_exercise.exercise_id = exercise.id
 
279
            Store.of(worksheet).add(worksheet_exercise)
 
280
        worksheet_exercise.active = True
 
281
        worksheet_exercise.seq_no = ex_num
 
282
        worksheet_exercise.optional = optional
 
283