Skip to content

Commit

Permalink
Fixed expression server-side validation. Before it was only accepting…
Browse files Browse the repository at this point in the history
… equivalence when expressions were *structural* equivalent as well.
  • Loading branch information
arielfayol37 committed Aug 19, 2023
1 parent 03ba020 commit 29005be
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 23 deletions.
Binary file modified db.sqlite3
Binary file not shown.
Binary file modified deimos/__pycache__/views.cpython-311.pyc
Binary file not shown.
9 changes: 5 additions & 4 deletions deimos/static/deimos/js/answer_input.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ document.addEventListener('DOMContentLoaded', ()=> {

submitBtn.addEventListener('click', (event)=>{
event.preventDefault();
if (questionType.value==='structural'){
if (questionType.value==='structural' && screen.value.length > 0){
fetch(`/${validateAnswerActionURL}`, {
method: 'POST',
headers: { 'X-CSRFToken': getCookie('csrftoken') },
body: JSON.stringify({
answer: screen.value,
answer: math.simplify(processString(screen.value)).toString(),
questionType: questionType.value
})
})
Expand All @@ -31,6 +31,7 @@ document.addEventListener('DOMContentLoaded', ()=> {
console.log(result.correct);
});
} else if( questionType.value ==='mcq'){
// TODO make sure some mcqs are selected as true.
fetch(`/${validateAnswerActionURL}`, {
method: 'POST',
headers: { 'X-CSRFToken': getCookie('csrftoken') },
Expand Down Expand Up @@ -103,7 +104,7 @@ displayLatex();
MathJax.typesetPromise().then(() => {
try {

const userInputNode = math.parse(processString(screen.value));
const userInputNode = math.simplify(processString(screen.value));
var userInputLatex = userInputNode.toTex();
const formattedAnswer = MathJax.tex2chtml(userInputLatex + '\\phantom{}');
formattedAnswerDiv.innerHTML = '';
Expand All @@ -123,7 +124,7 @@ displayLatex();
form.addEventListener('submit', (event)=>{
event.preventDefault();
if (!(screen === null)){
const userInputNode = math.parse(screen.value);
const userInputNode = math.simplify(processString(screen.value));
var userInputString = userInputNode.toString();
screen.value = userInputString;
}
Expand Down
42 changes: 30 additions & 12 deletions deimos/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
from django.middleware import csrf
from django.utils.timesince import timesince
from phobos.models import QuestionChoices
import random
from sympy import symbols, simplify, Eq
import random, re
from sympy import symbols, simplify

# Create your views here.
@login_required(login_url='astros:login')
Expand Down Expand Up @@ -284,7 +284,7 @@ def register(request):
student.save()
except IntegrityError:
return render(request, "astros/register.html", {
"message": "Username already taken."
"message": "Username/email already taken."
})
login(request, student)
return HttpResponseRedirect(reverse("deimos:index"))
Expand All @@ -302,17 +302,35 @@ def is_student_enrolled(student_id, course_id):
is_enrolled = Enrollment.objects.filter(student=student, course=course).exists()

return is_enrolled
def extract_numbers(text):
# Regular expression pattern to match floats and ints
pattern = r'[-+]?\d*\.\d+|\d+'

# Find all matches using the pattern
matches = re.findall(pattern, text)

# Convert matches to floats or ints
numbers = [str(match) if '.' in match else str(match) for match in matches]

return numbers

def compare_expressions(e1, e2):
""" Given two strings e1 and e2,
returns True if they are algebraically equivalent,
returns False otherwise
"""
su = set(e1) | set(e2)
so = symbols(' '.join(su))
sym_e1 = simplify(e1, symbols=so)
sym_e2 = simplify(e2, symbols=so)
same = Eq(sym_e1, sym_e2)
return True if same==True else False
Given two strings e1 and e2,
returns True if they are algebraically equivalent,
returns False otherwise.
"""
if not (isinstance(e1, str) and isinstance(e2, str)):
raise ValueError("Both inputs should be strings")

symbols_union = set(e1) | set(e2) # Combined set of symbols from both expressions
symbols_union.update(extract_numbers(e1 + e2)) # Update with extracted numbers
symbls = symbols(' '.join(symbols_union))
sym_e1 = simplify(e1, symbols=symbls)
sym_e2 = simplify(e2, symbols=symbls)
difference = (simplify(sym_e1 - sym_e2, symbols=symbls))
return True if difference == 0 else False


def compare_floats(f1, f2, margin_error=0.0):
"""
Expand Down
Binary file added media/phobos/images/course_covers/newton.webp
Binary file not shown.
12 changes: 6 additions & 6 deletions phobos/static/phobos/js/answer_input.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ document.addEventListener('DOMContentLoaded', () => {
MathJax.typesetPromise().then(() => {
try {

const userInputNode = math.parse(processString(screen.value));
const userInputNode = math.simplify(processString(screen.value));
var userInputLatex = userInputNode.toTex();
const formattedAnswer = MathJax.tex2chtml(userInputLatex + '\\phantom{}');
formattedAnswerDiv.innerHTML = '';
Expand All @@ -270,15 +270,15 @@ document.addEventListener('DOMContentLoaded', () => {
form.addEventListener('submit', (event) => {

if (mode==='e-answer'){
const userInputNode = math.parse(screen.value);
const userInputNode = math.simplify(processString(screen.value));
var userInputString = userInputNode.toString();
//var userInputString = math.simplify(userInputNode, {}, {context: math.simplify.realContext}).toString()
screen.value = userInputString;
}
else if(
mode==='f-answer'
) {
const userInputNode = math.parse(screen.value);
const userInputNode = math.simplify(processString(screen.value));
var userInputString = userInputNode.evaluate();
screen.value = userInputString;

Expand Down Expand Up @@ -319,7 +319,7 @@ function create_inputed_mcq_div(answer_value, answer_type) {
switch (answer_type) {
case 'f-answer':
display_value = answer_value;
answer_value = math.parse(answer_value).evaluate();
answer_value = math.simplify(processString(answer_value)).evaluate();
answer_info_encoding = rep(answer_info_encoding, 1, '1');
break;
case 't-answer':
Expand All @@ -331,7 +331,7 @@ function create_inputed_mcq_div(answer_value, answer_type) {
answer_info_encoding = rep(answer_info_encoding, 1, '2');
break;
case 'e-answer':
answer_value = math.parse(answer_value).toString();
answer_value = math.simplify(processString(answer_value)).toString();
display_value = answer_value;
answer_info_encoding = rep(answer_info_encoding, 1, '0');
break;
Expand All @@ -350,7 +350,7 @@ function create_inputed_mcq_div(answer_value, answer_type) {
formatted_answer.innerHTML = userInputLatex;
}
else{
const userInputNode = math.parse(processString(display_value));
const userInputNode = math.simplify(processString(display_value));
userInputLatex = userInputNode.toTex();
formatted_answer = MathJax.tex2chtml(userInputLatex + '\\phantom{}');
}
Expand Down
2 changes: 1 addition & 1 deletion phobos/static/phobos/js/calci.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const specialBtns = document.querySelectorAll('.special');

const replacementDict = {
'π':'pi',
'√':'sqrt'
'√':'sqrt',
}

const specialBtnsTextDict ={
Expand Down

0 comments on commit 29005be

Please sign in to comment.