+ %endif
+
+
%endfor
From c30f57022b3066185cd57f8e3041912f4d6f9212 Mon Sep 17 00:00:00 2001
From: Victor Shnayder
Date: Mon, 8 Oct 2012 16:44:54 -0400
Subject: [PATCH 10/65] Move more tests around, start prep for inputtype
refactor
---
common/lib/capa/capa/inputtypes.py | 8 +-
common/lib/capa/capa/tests/__init__.py | 4 +-
common/lib/capa/capa/tests/test_inputtypes.py | 383 +----------------
.../lib/capa/capa/tests/test_responsetypes.py | 384 ++++++++++++++++++
4 files changed, 410 insertions(+), 369 deletions(-)
create mode 100644 common/lib/capa/capa/tests/test_responsetypes.py
diff --git a/common/lib/capa/capa/inputtypes.py b/common/lib/capa/capa/inputtypes.py
index 466adcbf01..2858b2171f 100644
--- a/common/lib/capa/capa/inputtypes.py
+++ b/common/lib/capa/capa/inputtypes.py
@@ -124,8 +124,8 @@ def register_render_function(fn, names=None, cls=SimpleInput):
else:
raise NotImplementedError
- def wrapped():
- return fn
+ def wrapped(*args, **kwargs):
+ return fn(*args, **kwargs)
return wrapped
#-----------------------------------------------------------------------------
@@ -146,12 +146,14 @@ def optioninput(element, value, status, render_template, msg=''):
raise Exception(
"[courseware.capa.inputtypes.optioninput] Missing options specification in "
+ etree.tostring(element))
+
+ # parse the set of possible options
oset = shlex.shlex(options[1:-1])
oset.quotes = "'"
oset.whitespace = ","
oset = [x[1:-1] for x in list(oset)]
- # make ordered list with (key,value) same
+ # make ordered list with (key, value) same
osetdict = [(oset[x], oset[x]) for x in range(len(oset))]
# TODO: allow ordering to be randomized
diff --git a/common/lib/capa/capa/tests/__init__.py b/common/lib/capa/capa/tests/__init__.py
index ebbfe16a29..c72d2a1538 100644
--- a/common/lib/capa/capa/tests/__init__.py
+++ b/common/lib/capa/capa/tests/__init__.py
@@ -4,6 +4,8 @@ import os
from mock import Mock
+TEST_DIR = os.path.dirname(os.path.realpath(__file__))
+
test_system = Mock(
ajax_url='courses/course_id/modx/a_location',
track_function=Mock(),
@@ -11,7 +13,7 @@ test_system = Mock(
render_template=Mock(),
replace_urls=Mock(),
user=Mock(),
- filestore=fs.osfs.OSFS(os.path.dirname(os.path.realpath(__file__))+"/test_files"),
+ filestore=fs.osfs.OSFS(os.path.join(TEST_DIR, "test_files")),
debug=True,
xqueue={'interface':None, 'callback_url':'/', 'default_queuename': 'testqueue', 'waittime': 10},
node_path=os.environ.get("NODE_PATH", "/usr/local/lib/node_modules"),
diff --git a/common/lib/capa/capa/tests/test_inputtypes.py b/common/lib/capa/capa/tests/test_inputtypes.py
index af3d1e87a7..8451f963d5 100644
--- a/common/lib/capa/capa/tests/test_inputtypes.py
+++ b/common/lib/capa/capa/tests/test_inputtypes.py
@@ -10,375 +10,28 @@ import os
import unittest
from . import test_system
+from capa import inputtypes
-import capa.capa_problem as lcp
-from capa.correctmap import CorrectMap
-from capa.util import convert_files_to_filenames
-from capa.xqueue_interface import dateformat
+from lxml import etree
-class MultiChoiceTest(unittest.TestCase):
- def test_MC_grade(self):
- multichoice_file = os.path.dirname(__file__) + "/test_files/multichoice.xml"
- test_lcp = lcp.LoncapaProblem(open(multichoice_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': 'choice_foil3'}
- self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
- false_answers = {'1_2_1': 'choice_foil2'}
- self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
-
- def test_MC_bare_grades(self):
- multichoice_file = os.path.dirname(__file__) + "/test_files/multi_bare.xml"
- test_lcp = lcp.LoncapaProblem(open(multichoice_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': 'choice_2'}
- self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
- false_answers = {'1_2_1': 'choice_1'}
- self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
-
- def test_TF_grade(self):
- truefalse_file = os.path.dirname(__file__) + "/test_files/truefalse.xml"
- test_lcp = lcp.LoncapaProblem(open(truefalse_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': ['choice_foil2', 'choice_foil1']}
- self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
- false_answers = {'1_2_1': ['choice_foil1']}
- self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
- false_answers = {'1_2_1': ['choice_foil1', 'choice_foil3']}
- self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
- false_answers = {'1_2_1': ['choice_foil3']}
- self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
- false_answers = {'1_2_1': ['choice_foil1', 'choice_foil2', 'choice_foil3']}
- self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
-
-
-class ImageResponseTest(unittest.TestCase):
- def test_ir_grade(self):
- imageresponse_file = os.path.dirname(__file__) + "/test_files/imageresponse.xml"
- test_lcp = lcp.LoncapaProblem(open(imageresponse_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': '(490,11)-(556,98)',
- '1_2_2': '(242,202)-(296,276)'}
- test_answers = {'1_2_1': '[500,20]',
- '1_2_2': '[250,300]',
- }
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_2'), 'incorrect')
-
-
-class SymbolicResponseTest(unittest.TestCase):
- def test_sr_grade(self):
- raise SkipTest() # This test fails due to dependencies on a local copy of snuggletex-webapp. Until we have figured that out, we'll just skip this test
- symbolicresponse_file = os.path.dirname(__file__) + "/test_files/symbolicresponse.xml"
- test_lcp = lcp.LoncapaProblem(open(symbolicresponse_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': 'cos(theta)*[[1,0],[0,1]] + i*sin(theta)*[[0,1],[1,0]]',
- '1_2_1_dynamath': '''
-
-''',
- }
- wrong_answers = {'1_2_1': '2',
- '1_2_1_dynamath': '''
- ''',
- }
- self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
- self.assertEquals(test_lcp.grade_answers(wrong_answers).get_correctness('1_2_1'), 'incorrect')
-
-
-class OptionResponseTest(unittest.TestCase):
+class OptionInputTest(unittest.TestCase):
'''
- Run this with
-
- python manage.py test courseware.OptionResponseTest
+ Make sure option inputs work
'''
- def test_or_grade(self):
- optionresponse_file = os.path.dirname(__file__) + "/test_files/optionresponse.xml"
- test_lcp = lcp.LoncapaProblem(open(optionresponse_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': 'True',
- '1_2_2': 'False'}
- test_answers = {'1_2_1': 'True',
- '1_2_2': 'True',
- }
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_2'), 'incorrect')
+ def test_rendering(self):
+ xml = """"""
+ element = etree.fromstring(xml)
+
+ value = 'Down'
+ status = 'incorrect'
+ rendered_element = inputtypes.optioninput(element, value, status, test_system.render_template)
+ rendered_str = etree.tostring(rendered_element)
+ print rendered_str
+ self.assertTrue(False)
-class FormulaResponseWithHintTest(unittest.TestCase):
- '''
- Test Formula response problem with a hint
- This problem also uses calc.
- '''
- def test_or_grade(self):
- problem_file = os.path.dirname(__file__) + "/test_files/formularesponse_with_hint.xml"
- test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': '2.5*x-5.0'}
- test_answers = {'1_2_1': '0.4*x-5.0'}
- self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
- cmap = test_lcp.grade_answers(test_answers)
- self.assertEquals(cmap.get_correctness('1_2_1'), 'incorrect')
- self.assertTrue('You have inverted' in cmap.get_hint('1_2_1'))
-
-
-class StringResponseWithHintTest(unittest.TestCase):
- '''
- Test String response problem with a hint
- '''
- def test_or_grade(self):
- problem_file = os.path.dirname(__file__) + "/test_files/stringresponse_with_hint.xml"
- test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': 'Michigan'}
- test_answers = {'1_2_1': 'Minnesota'}
- self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
- cmap = test_lcp.grade_answers(test_answers)
- self.assertEquals(cmap.get_correctness('1_2_1'), 'incorrect')
- self.assertTrue('St. Paul' in cmap.get_hint('1_2_1'))
-
-
-class CodeResponseTest(unittest.TestCase):
- '''
- Test CodeResponse
- TODO: Add tests for external grader messages
- '''
- @staticmethod
- def make_queuestate(key, time):
- timestr = datetime.strftime(time, dateformat)
- return {'key': key, 'time': timestr}
-
- def test_is_queued(self):
- """
- Simple test of whether LoncapaProblem knows when it's been queued
- """
- problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
- with open(problem_file) as input_file:
- test_lcp = lcp.LoncapaProblem(input_file.read(), '1', system=test_system)
-
- answer_ids = sorted(test_lcp.get_question_answers())
-
- # CodeResponse requires internal CorrectMap state. Build it now in the unqueued state
- cmap = CorrectMap()
- for answer_id in answer_ids:
- cmap.update(CorrectMap(answer_id=answer_id, queuestate=None))
- test_lcp.correct_map.update(cmap)
-
- self.assertEquals(test_lcp.is_queued(), False)
-
- # Now we queue the LCP
- cmap = CorrectMap()
- for i, answer_id in enumerate(answer_ids):
- queuestate = CodeResponseTest.make_queuestate(i, datetime.now())
- cmap.update(CorrectMap(answer_id=answer_ids[i], queuestate=queuestate))
- test_lcp.correct_map.update(cmap)
-
- self.assertEquals(test_lcp.is_queued(), True)
-
-
- def test_update_score(self):
- '''
- Test whether LoncapaProblem.update_score can deliver queued result to the right subproblem
- '''
- problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
- with open(problem_file) as input_file:
- test_lcp = lcp.LoncapaProblem(input_file.read(), '1', system=test_system)
-
- answer_ids = sorted(test_lcp.get_question_answers())
-
- # CodeResponse requires internal CorrectMap state. Build it now in the queued state
- old_cmap = CorrectMap()
- for i, answer_id in enumerate(answer_ids):
- queuekey = 1000 + i
- queuestate = CodeResponseTest.make_queuestate(1000+i, datetime.now())
- old_cmap.update(CorrectMap(answer_id=answer_ids[i], queuestate=queuestate))
-
- # Message format common to external graders
- grader_msg = 'MESSAGE' # Must be valid XML
- correct_score_msg = json.dumps({'correct':True, 'score':1, 'msg': grader_msg})
- incorrect_score_msg = json.dumps({'correct':False, 'score':0, 'msg': grader_msg})
-
- xserver_msgs = {'correct': correct_score_msg,
- 'incorrect': incorrect_score_msg,}
-
- # Incorrect queuekey, state should not be updated
- for correctness in ['correct', 'incorrect']:
- test_lcp.correct_map = CorrectMap()
- test_lcp.correct_map.update(old_cmap) # Deep copy
-
- test_lcp.update_score(xserver_msgs[correctness], queuekey=0)
- self.assertEquals(test_lcp.correct_map.get_dict(), old_cmap.get_dict()) # Deep comparison
-
- for answer_id in answer_ids:
- self.assertTrue(test_lcp.correct_map.is_queued(answer_id)) # Should be still queued, since message undelivered
-
- # Correct queuekey, state should be updated
- for correctness in ['correct', 'incorrect']:
- for i, answer_id in enumerate(answer_ids):
- test_lcp.correct_map = CorrectMap()
- test_lcp.correct_map.update(old_cmap)
-
- new_cmap = CorrectMap()
- new_cmap.update(old_cmap)
- npoints = 1 if correctness=='correct' else 0
- new_cmap.set(answer_id=answer_id, npoints=npoints, correctness=correctness, msg=grader_msg, queuestate=None)
-
- test_lcp.update_score(xserver_msgs[correctness], queuekey=1000 + i)
- self.assertEquals(test_lcp.correct_map.get_dict(), new_cmap.get_dict())
-
- for j, test_id in enumerate(answer_ids):
- if j == i:
- self.assertFalse(test_lcp.correct_map.is_queued(test_id)) # Should be dequeued, message delivered
- else:
- self.assertTrue(test_lcp.correct_map.is_queued(test_id)) # Should be queued, message undelivered
-
-
- def test_recentmost_queuetime(self):
- '''
- Test whether the LoncapaProblem knows about the time of queue requests
- '''
- problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
- with open(problem_file) as input_file:
- test_lcp = lcp.LoncapaProblem(input_file.read(), '1', system=test_system)
-
- answer_ids = sorted(test_lcp.get_question_answers())
-
- # CodeResponse requires internal CorrectMap state. Build it now in the unqueued state
- cmap = CorrectMap()
- for answer_id in answer_ids:
- cmap.update(CorrectMap(answer_id=answer_id, queuestate=None))
- test_lcp.correct_map.update(cmap)
-
- self.assertEquals(test_lcp.get_recentmost_queuetime(), None)
-
- # CodeResponse requires internal CorrectMap state. Build it now in the queued state
- cmap = CorrectMap()
- for i, answer_id in enumerate(answer_ids):
- queuekey = 1000 + i
- latest_timestamp = datetime.now()
- queuestate = CodeResponseTest.make_queuestate(1000+i, latest_timestamp)
- cmap.update(CorrectMap(answer_id=answer_id, queuestate=queuestate))
- test_lcp.correct_map.update(cmap)
-
- # Queue state only tracks up to second
- latest_timestamp = datetime.strptime(datetime.strftime(latest_timestamp, dateformat), dateformat)
-
- self.assertEquals(test_lcp.get_recentmost_queuetime(), latest_timestamp)
-
- def test_convert_files_to_filenames(self):
- '''
- Test whether file objects are converted to filenames without altering other structures
- '''
- problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
- with open(problem_file) as fp:
- answers_with_file = {'1_2_1': 'String-based answer',
- '1_3_1': ['answer1', 'answer2', 'answer3'],
- '1_4_1': [fp, fp]}
- answers_converted = convert_files_to_filenames(answers_with_file)
- self.assertEquals(answers_converted['1_2_1'], 'String-based answer')
- self.assertEquals(answers_converted['1_3_1'], ['answer1', 'answer2', 'answer3'])
- self.assertEquals(answers_converted['1_4_1'], [fp.name, fp.name])
-
-
-class ChoiceResponseTest(unittest.TestCase):
-
- def test_cr_rb_grade(self):
- problem_file = os.path.dirname(__file__) + "/test_files/choiceresponse_radio.xml"
- test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': 'choice_2',
- '1_3_1': ['choice_2', 'choice_3']}
- test_answers = {'1_2_1': 'choice_2',
- '1_3_1': 'choice_2',
- }
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_3_1'), 'incorrect')
-
- def test_cr_cb_grade(self):
- problem_file = os.path.dirname(__file__) + "/test_files/choiceresponse_checkbox.xml"
- test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': 'choice_2',
- '1_3_1': ['choice_2', 'choice_3'],
- '1_4_1': ['choice_2', 'choice_3']}
- test_answers = {'1_2_1': 'choice_2',
- '1_3_1': 'choice_2',
- '1_4_1': ['choice_2', 'choice_3'],
- }
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_3_1'), 'incorrect')
- self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_4_1'), 'correct')
-
-class JavascriptResponseTest(unittest.TestCase):
-
- def test_jr_grade(self):
- problem_file = os.path.dirname(__file__) + "/test_files/javascriptresponse.xml"
- coffee_file_path = os.path.dirname(__file__) + "/test_files/js/*.coffee"
- os.system("coffee -c %s" % (coffee_file_path))
- test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
- correct_answers = {'1_2_1': json.dumps({0: 4})}
- incorrect_answers = {'1_2_1': json.dumps({0: 5})}
-
- self.assertEquals(test_lcp.grade_answers(incorrect_answers).get_correctness('1_2_1'), 'incorrect')
- self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+ # TODO: split each inputtype into a get_render_context function and a
+ # template property, and have the rendering done in one place. (and be
+ # able to test the logic without dealing with xml at least on the output
+ # end)
diff --git a/common/lib/capa/capa/tests/test_responsetypes.py b/common/lib/capa/capa/tests/test_responsetypes.py
new file mode 100644
index 0000000000..f2fa873080
--- /dev/null
+++ b/common/lib/capa/capa/tests/test_responsetypes.py
@@ -0,0 +1,384 @@
+"""
+Tests of responsetypes
+"""
+
+
+from datetime import datetime
+import json
+from nose.plugins.skip import SkipTest
+import os
+import unittest
+
+from . import test_system
+
+import capa.capa_problem as lcp
+from capa.correctmap import CorrectMap
+from capa.util import convert_files_to_filenames
+from capa.xqueue_interface import dateformat
+
+class MultiChoiceTest(unittest.TestCase):
+ def test_MC_grade(self):
+ multichoice_file = os.path.dirname(__file__) + "/test_files/multichoice.xml"
+ test_lcp = lcp.LoncapaProblem(open(multichoice_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': 'choice_foil3'}
+ self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+ false_answers = {'1_2_1': 'choice_foil2'}
+ self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
+
+ def test_MC_bare_grades(self):
+ multichoice_file = os.path.dirname(__file__) + "/test_files/multi_bare.xml"
+ test_lcp = lcp.LoncapaProblem(open(multichoice_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': 'choice_2'}
+ self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+ false_answers = {'1_2_1': 'choice_1'}
+ self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
+
+ def test_TF_grade(self):
+ truefalse_file = os.path.dirname(__file__) + "/test_files/truefalse.xml"
+ test_lcp = lcp.LoncapaProblem(open(truefalse_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': ['choice_foil2', 'choice_foil1']}
+ self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+ false_answers = {'1_2_1': ['choice_foil1']}
+ self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
+ false_answers = {'1_2_1': ['choice_foil1', 'choice_foil3']}
+ self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
+ false_answers = {'1_2_1': ['choice_foil3']}
+ self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
+ false_answers = {'1_2_1': ['choice_foil1', 'choice_foil2', 'choice_foil3']}
+ self.assertEquals(test_lcp.grade_answers(false_answers).get_correctness('1_2_1'), 'incorrect')
+
+
+class ImageResponseTest(unittest.TestCase):
+ def test_ir_grade(self):
+ imageresponse_file = os.path.dirname(__file__) + "/test_files/imageresponse.xml"
+ test_lcp = lcp.LoncapaProblem(open(imageresponse_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': '(490,11)-(556,98)',
+ '1_2_2': '(242,202)-(296,276)'}
+ test_answers = {'1_2_1': '[500,20]',
+ '1_2_2': '[250,300]',
+ }
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_2'), 'incorrect')
+
+
+class SymbolicResponseTest(unittest.TestCase):
+ def test_sr_grade(self):
+ raise SkipTest() # This test fails due to dependencies on a local copy of snuggletex-webapp. Until we have figured that out, we'll just skip this test
+ symbolicresponse_file = os.path.dirname(__file__) + "/test_files/symbolicresponse.xml"
+ test_lcp = lcp.LoncapaProblem(open(symbolicresponse_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': 'cos(theta)*[[1,0],[0,1]] + i*sin(theta)*[[0,1],[1,0]]',
+ '1_2_1_dynamath': '''
+
+''',
+ }
+ wrong_answers = {'1_2_1': '2',
+ '1_2_1_dynamath': '''
+ ''',
+ }
+ self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+ self.assertEquals(test_lcp.grade_answers(wrong_answers).get_correctness('1_2_1'), 'incorrect')
+
+
+class OptionResponseTest(unittest.TestCase):
+ '''
+ Run this with
+
+ python manage.py test courseware.OptionResponseTest
+ '''
+ def test_or_grade(self):
+ optionresponse_file = os.path.dirname(__file__) + "/test_files/optionresponse.xml"
+ test_lcp = lcp.LoncapaProblem(open(optionresponse_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': 'True',
+ '1_2_2': 'False'}
+ test_answers = {'1_2_1': 'True',
+ '1_2_2': 'True',
+ }
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_2'), 'incorrect')
+
+
+class FormulaResponseWithHintTest(unittest.TestCase):
+ '''
+ Test Formula response problem with a hint
+ This problem also uses calc.
+ '''
+ def test_or_grade(self):
+ problem_file = os.path.dirname(__file__) + "/test_files/formularesponse_with_hint.xml"
+ test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': '2.5*x-5.0'}
+ test_answers = {'1_2_1': '0.4*x-5.0'}
+ self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+ cmap = test_lcp.grade_answers(test_answers)
+ self.assertEquals(cmap.get_correctness('1_2_1'), 'incorrect')
+ self.assertTrue('You have inverted' in cmap.get_hint('1_2_1'))
+
+
+class StringResponseWithHintTest(unittest.TestCase):
+ '''
+ Test String response problem with a hint
+ '''
+ def test_or_grade(self):
+ problem_file = os.path.dirname(__file__) + "/test_files/stringresponse_with_hint.xml"
+ test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': 'Michigan'}
+ test_answers = {'1_2_1': 'Minnesota'}
+ self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+ cmap = test_lcp.grade_answers(test_answers)
+ self.assertEquals(cmap.get_correctness('1_2_1'), 'incorrect')
+ self.assertTrue('St. Paul' in cmap.get_hint('1_2_1'))
+
+
+class CodeResponseTest(unittest.TestCase):
+ '''
+ Test CodeResponse
+ TODO: Add tests for external grader messages
+ '''
+ @staticmethod
+ def make_queuestate(key, time):
+ timestr = datetime.strftime(time, dateformat)
+ return {'key': key, 'time': timestr}
+
+ def test_is_queued(self):
+ """
+ Simple test of whether LoncapaProblem knows when it's been queued
+ """
+ problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
+ with open(problem_file) as input_file:
+ test_lcp = lcp.LoncapaProblem(input_file.read(), '1', system=test_system)
+
+ answer_ids = sorted(test_lcp.get_question_answers())
+
+ # CodeResponse requires internal CorrectMap state. Build it now in the unqueued state
+ cmap = CorrectMap()
+ for answer_id in answer_ids:
+ cmap.update(CorrectMap(answer_id=answer_id, queuestate=None))
+ test_lcp.correct_map.update(cmap)
+
+ self.assertEquals(test_lcp.is_queued(), False)
+
+ # Now we queue the LCP
+ cmap = CorrectMap()
+ for i, answer_id in enumerate(answer_ids):
+ queuestate = CodeResponseTest.make_queuestate(i, datetime.now())
+ cmap.update(CorrectMap(answer_id=answer_ids[i], queuestate=queuestate))
+ test_lcp.correct_map.update(cmap)
+
+ self.assertEquals(test_lcp.is_queued(), True)
+
+
+ def test_update_score(self):
+ '''
+ Test whether LoncapaProblem.update_score can deliver queued result to the right subproblem
+ '''
+ problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
+ with open(problem_file) as input_file:
+ test_lcp = lcp.LoncapaProblem(input_file.read(), '1', system=test_system)
+
+ answer_ids = sorted(test_lcp.get_question_answers())
+
+ # CodeResponse requires internal CorrectMap state. Build it now in the queued state
+ old_cmap = CorrectMap()
+ for i, answer_id in enumerate(answer_ids):
+ queuekey = 1000 + i
+ queuestate = CodeResponseTest.make_queuestate(1000+i, datetime.now())
+ old_cmap.update(CorrectMap(answer_id=answer_ids[i], queuestate=queuestate))
+
+ # Message format common to external graders
+ grader_msg = 'MESSAGE' # Must be valid XML
+ correct_score_msg = json.dumps({'correct':True, 'score':1, 'msg': grader_msg})
+ incorrect_score_msg = json.dumps({'correct':False, 'score':0, 'msg': grader_msg})
+
+ xserver_msgs = {'correct': correct_score_msg,
+ 'incorrect': incorrect_score_msg,}
+
+ # Incorrect queuekey, state should not be updated
+ for correctness in ['correct', 'incorrect']:
+ test_lcp.correct_map = CorrectMap()
+ test_lcp.correct_map.update(old_cmap) # Deep copy
+
+ test_lcp.update_score(xserver_msgs[correctness], queuekey=0)
+ self.assertEquals(test_lcp.correct_map.get_dict(), old_cmap.get_dict()) # Deep comparison
+
+ for answer_id in answer_ids:
+ self.assertTrue(test_lcp.correct_map.is_queued(answer_id)) # Should be still queued, since message undelivered
+
+ # Correct queuekey, state should be updated
+ for correctness in ['correct', 'incorrect']:
+ for i, answer_id in enumerate(answer_ids):
+ test_lcp.correct_map = CorrectMap()
+ test_lcp.correct_map.update(old_cmap)
+
+ new_cmap = CorrectMap()
+ new_cmap.update(old_cmap)
+ npoints = 1 if correctness=='correct' else 0
+ new_cmap.set(answer_id=answer_id, npoints=npoints, correctness=correctness, msg=grader_msg, queuestate=None)
+
+ test_lcp.update_score(xserver_msgs[correctness], queuekey=1000 + i)
+ self.assertEquals(test_lcp.correct_map.get_dict(), new_cmap.get_dict())
+
+ for j, test_id in enumerate(answer_ids):
+ if j == i:
+ self.assertFalse(test_lcp.correct_map.is_queued(test_id)) # Should be dequeued, message delivered
+ else:
+ self.assertTrue(test_lcp.correct_map.is_queued(test_id)) # Should be queued, message undelivered
+
+
+ def test_recentmost_queuetime(self):
+ '''
+ Test whether the LoncapaProblem knows about the time of queue requests
+ '''
+ problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
+ with open(problem_file) as input_file:
+ test_lcp = lcp.LoncapaProblem(input_file.read(), '1', system=test_system)
+
+ answer_ids = sorted(test_lcp.get_question_answers())
+
+ # CodeResponse requires internal CorrectMap state. Build it now in the unqueued state
+ cmap = CorrectMap()
+ for answer_id in answer_ids:
+ cmap.update(CorrectMap(answer_id=answer_id, queuestate=None))
+ test_lcp.correct_map.update(cmap)
+
+ self.assertEquals(test_lcp.get_recentmost_queuetime(), None)
+
+ # CodeResponse requires internal CorrectMap state. Build it now in the queued state
+ cmap = CorrectMap()
+ for i, answer_id in enumerate(answer_ids):
+ queuekey = 1000 + i
+ latest_timestamp = datetime.now()
+ queuestate = CodeResponseTest.make_queuestate(1000+i, latest_timestamp)
+ cmap.update(CorrectMap(answer_id=answer_id, queuestate=queuestate))
+ test_lcp.correct_map.update(cmap)
+
+ # Queue state only tracks up to second
+ latest_timestamp = datetime.strptime(datetime.strftime(latest_timestamp, dateformat), dateformat)
+
+ self.assertEquals(test_lcp.get_recentmost_queuetime(), latest_timestamp)
+
+ def test_convert_files_to_filenames(self):
+ '''
+ Test whether file objects are converted to filenames without altering other structures
+ '''
+ problem_file = os.path.join(os.path.dirname(__file__), "test_files/coderesponse.xml")
+ with open(problem_file) as fp:
+ answers_with_file = {'1_2_1': 'String-based answer',
+ '1_3_1': ['answer1', 'answer2', 'answer3'],
+ '1_4_1': [fp, fp]}
+ answers_converted = convert_files_to_filenames(answers_with_file)
+ self.assertEquals(answers_converted['1_2_1'], 'String-based answer')
+ self.assertEquals(answers_converted['1_3_1'], ['answer1', 'answer2', 'answer3'])
+ self.assertEquals(answers_converted['1_4_1'], [fp.name, fp.name])
+
+
+class ChoiceResponseTest(unittest.TestCase):
+
+ def test_cr_rb_grade(self):
+ problem_file = os.path.dirname(__file__) + "/test_files/choiceresponse_radio.xml"
+ test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': 'choice_2',
+ '1_3_1': ['choice_2', 'choice_3']}
+ test_answers = {'1_2_1': 'choice_2',
+ '1_3_1': 'choice_2',
+ }
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_3_1'), 'incorrect')
+
+ def test_cr_cb_grade(self):
+ problem_file = os.path.dirname(__file__) + "/test_files/choiceresponse_checkbox.xml"
+ test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': 'choice_2',
+ '1_3_1': ['choice_2', 'choice_3'],
+ '1_4_1': ['choice_2', 'choice_3']}
+ test_answers = {'1_2_1': 'choice_2',
+ '1_3_1': 'choice_2',
+ '1_4_1': ['choice_2', 'choice_3'],
+ }
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_2_1'), 'correct')
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_3_1'), 'incorrect')
+ self.assertEquals(test_lcp.grade_answers(test_answers).get_correctness('1_4_1'), 'correct')
+
+class JavascriptResponseTest(unittest.TestCase):
+
+ def test_jr_grade(self):
+ problem_file = os.path.dirname(__file__) + "/test_files/javascriptresponse.xml"
+ coffee_file_path = os.path.dirname(__file__) + "/test_files/js/*.coffee"
+ os.system("coffee -c %s" % (coffee_file_path))
+ test_lcp = lcp.LoncapaProblem(open(problem_file).read(), '1', system=test_system)
+ correct_answers = {'1_2_1': json.dumps({0: 4})}
+ incorrect_answers = {'1_2_1': json.dumps({0: 5})}
+
+ self.assertEquals(test_lcp.grade_answers(incorrect_answers).get_correctness('1_2_1'), 'incorrect')
+ self.assertEquals(test_lcp.grade_answers(correct_answers).get_correctness('1_2_1'), 'correct')
+
From d10b568c13a6adc099ab2c84a27a5899ec9b52e9 Mon Sep 17 00:00:00 2001
From: Victor Shnayder
Date: Mon, 8 Oct 2012 20:08:48 -0400
Subject: [PATCH 11/65] Add chemcalc to capa package, to context for
customresponse
---
common/lib/capa/capa/capa_problem.py | 7 +-
common/lib/capa/capa/chem/__init__.py | 1 +
common/lib/capa/capa/chem/chemcalc.py | 540 ++++++++++++++++++++++++++
3 files changed, 546 insertions(+), 2 deletions(-)
create mode 100644 common/lib/capa/capa/chem/__init__.py
create mode 100644 common/lib/capa/capa/chem/chemcalc.py
diff --git a/common/lib/capa/capa/capa_problem.py b/common/lib/capa/capa/capa_problem.py
index 9a5a15a696..29e9b7eb97 100644
--- a/common/lib/capa/capa/capa_problem.py
+++ b/common/lib/capa/capa/capa_problem.py
@@ -30,6 +30,8 @@ import sys
from lxml import etree
from xml.sax.saxutils import unescape
+import chem
+import chem.chemcalc
import calc
from correctmap import CorrectMap
import eia
@@ -72,7 +74,8 @@ global_context = {'random': random,
'math': math,
'scipy': scipy,
'calc': calc,
- 'eia': eia}
+ 'eia': eia,
+ 'chemcalc': chem.chemcalc}
# These should be removed from HTML output, including all subelements
html_problem_semantics = ["codeparam", "responseparam", "answer", "script", "hintgroup"]
@@ -436,7 +439,7 @@ class LoncapaProblem(object):
sys.path = original_path + self._extract_system_path(script)
stype = script.get('type')
-
+
if stype:
if 'javascript' in stype:
continue # skip javascript
diff --git a/common/lib/capa/capa/chem/__init__.py b/common/lib/capa/capa/chem/__init__.py
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/common/lib/capa/capa/chem/__init__.py
@@ -0,0 +1 @@
+
diff --git a/common/lib/capa/capa/chem/chemcalc.py b/common/lib/capa/capa/chem/chemcalc.py
new file mode 100644
index 0000000000..65d1887d2e
--- /dev/null
+++ b/common/lib/capa/capa/chem/chemcalc.py
@@ -0,0 +1,540 @@
+from __future__ import division
+import copy
+import logging
+import math
+import operator
+import re
+import unittest
+import numpy
+import numbers
+import scipy.constants
+
+from pyparsing import Literal, Keyword, Word, nums, StringEnd, Optional, Forward, OneOrMore
+from pyparsing import ParseException
+import nltk
+from nltk.tree import Tree
+
+local_debug = None
+
+
+def log(s, output_type=None):
+ if local_debug:
+ print s
+ if output_type == 'html':
+ f.write(s + '\n \n')
+
+## Defines a simple pyparsing tokenizer for chemical equations
+elements = ['Ac','Ag','Al','Am','Ar','As','At','Au','B','Ba','Be',
+ 'Bh','Bi','Bk','Br','C','Ca','Cd','Ce','Cf','Cl','Cm',
+ 'Cn','Co','Cr','Cs','Cu','Db','Ds','Dy','Er','Es','Eu',
+ 'F','Fe','Fl','Fm','Fr','Ga','Gd','Ge','H','He','Hf',
+ 'Hg','Ho','Hs','I','In','Ir','K','Kr','La','Li','Lr',
+ 'Lu','Lv','Md','Mg','Mn','Mo','Mt','N','Na','Nb','Nd',
+ 'Ne','Ni','No','Np','O','Os','P','Pa','Pb','Pd','Pm',
+ 'Po','Pr','Pt','Pu','Ra','Rb','Re','Rf','Rg','Rh','Rn',
+ 'Ru','S','Sb','Sc','Se','Sg','Si','Sm','Sn','Sr','Ta',
+ 'Tb','Tc','Te','Th','Ti','Tl','Tm','U','Uuo','Uup',
+ 'Uus','Uut','V','W','Xe','Y','Yb','Zn','Zr']
+digits = map(str, range(10))
+symbols = list("[](){}^+-/")
+phases = ["(s)", "(l)", "(g)", "(aq)"]
+tokens = reduce(lambda a, b: a ^ b, map(Literal, elements + digits + symbols + phases))
+tokenizer = OneOrMore(tokens) + StringEnd()
+
+
+def orjoin(l):
+ return "'" + "' | '".join(l) + "'"
+
+## Defines an NLTK parser for tokenized equations
+grammar = """
+ S -> multimolecule | multimolecule '+' S
+ multimolecule -> count molecule | molecule
+ count -> number | number '/' number
+ molecule -> unphased | unphased phase
+ unphased -> group | paren_group_round | paren_group_square
+ element -> """ + orjoin(elements) + """
+ digit -> """ + orjoin(digits) + """
+ phase -> """ + orjoin(phases) + """
+ number -> digit | digit number
+ group -> suffixed | suffixed group
+ paren_group_round -> '(' group ')'
+ paren_group_square -> '[' group ']'
+ plus_minus -> '+' | '-'
+ number_suffix -> number
+ ion_suffix -> '^' number plus_minus | '^' plus_minus
+ suffix -> number_suffix | number_suffix ion_suffix | ion_suffix
+ unsuffixed -> element | paren_group_round | paren_group_square
+
+ suffixed -> unsuffixed | unsuffixed suffix
+"""
+parser = nltk.ChartParser(nltk.parse_cfg(grammar))
+
+
+def clean_parse_tree(tree):
+ ''' The parse tree contains a lot of redundant
+ nodes. E.g. paren_groups have groups as children, etc. This will
+ clean up the tree.
+ '''
+ def unparse_number(n):
+ ''' Go from a number parse tree to a number '''
+ if len(n) == 1:
+ rv = n[0][0]
+ else:
+ rv = n[0][0] + unparse_number(n[1])
+ return rv
+
+ def null_tag(n):
+ ''' Remove a tag '''
+ return n[0]
+
+ def ion_suffix(n):
+ '''1. "if" part handles special case
+ 2. "else" part is general behaviour '''
+
+ if n[1:][0].node == 'number' and n[1:][0][0][0] == '1':
+ # if suffix is explicitly 1, like ^1-
+ # strip 1, leave only sign: ^-
+ return nltk.tree.Tree(n.node, n[2:])
+ else:
+ return nltk.tree.Tree(n.node, n[1:])
+
+ dispatch = {'number': lambda x: nltk.tree.Tree("number", [unparse_number(x)]),
+ 'unphased': null_tag,
+ 'unsuffixed': null_tag,
+ 'number_suffix': lambda x: nltk.tree.Tree('number_suffix', [unparse_number(x[0])]),
+ 'suffixed': lambda x: len(x) > 1 and x or x[0],
+ 'ion_suffix': ion_suffix,
+ 'paren_group_square': lambda x: nltk.tree.Tree(x.node, x[1]),
+ 'paren_group_round': lambda x: nltk.tree.Tree(x.node, x[1])}
+
+ if type(tree) == str:
+ return tree
+
+ old_node = None
+ ## This loop means that if a node is processed, and returns a child,
+ ## the child will be processed.
+ while tree.node in dispatch and tree.node != old_node:
+ old_node = tree.node
+ tree = dispatch[tree.node](tree)
+
+ children = []
+ for child in tree:
+ child = clean_parse_tree(child)
+ children.append(child)
+
+ tree = nltk.tree.Tree(tree.node, children)
+
+ return tree
+
+
+def merge_children(tree, tags):
+ ''' nltk, by documentation, cannot do arbitrary length
+ groups. Instead of:
+ (group 1 2 3 4)
+ It has to handle this recursively:
+ (group 1 (group 2 (group 3 (group 4))))
+ We do the cleanup of converting from the latter to the former (as a
+ '''
+ if type(tree) == str:
+ return tree
+
+ merged_children = []
+ done = False
+ #print '00000', tree
+ ## Merge current tag
+ while not done:
+ done = True
+ for child in tree:
+ if type(child) == nltk.tree.Tree and child.node == tree.node and tree.node in tags:
+ merged_children = merged_children + list(child)
+ done = False
+ else:
+ merged_children = merged_children + [child]
+ tree = nltk.tree.Tree(tree.node, merged_children)
+ merged_children = []
+ #print '======',tree
+
+ # And recurse
+ children = []
+ for child in tree:
+ children.append(merge_children(child, tags))
+
+ #return tree
+ return nltk.tree.Tree(tree.node, children)
+
+
+def render_to_html(tree):
+ ''' Renders a cleaned tree to HTML '''
+
+ def molecule_count(tree, children):
+ # If an integer, return that integer
+ if len(tree) == 1:
+ return tree[0][0]
+ # If a fraction, return the fraction
+ if len(tree) == 3:
+ return " {num}⁄{den} ".format(num=tree[0][0], den=tree[2][0])
+ return "Error"
+
+ def subscript(tree, children):
+ return "{sub}".format(sub=children)
+
+ def superscript(tree, children):
+ return "{sup}".format(sup=children)
+
+ def round_brackets(tree, children):
+ return "({insider})".format(insider=children)
+
+ def square_brackets(tree, children):
+ return "[{insider}]".format(insider=children)
+
+ dispatch = {'count': molecule_count,
+ 'number_suffix': subscript,
+ 'ion_suffix': superscript,
+ 'paren_group_round': round_brackets,
+ 'paren_group_square': square_brackets}
+
+ if type(tree) == str:
+ return tree
+ else:
+ children = "".join(map(render_to_html, tree))
+ if tree.node in dispatch:
+ return dispatch[tree.node](tree, children)
+ else:
+ return children.replace(' ', '')
+
+
+def clean_and_render_to_html(s):
+ ''' render a string to html '''
+ status = render_to_html(get_finale_tree(s))
+ return status
+
+
+def get_finale_tree(s):
+ ''' return final tree after merge and clean '''
+ tokenized = tokenizer.parseString(s)
+ parsed = parser.parse(tokenized)
+ merged = merge_children(parsed, {'S','group'})
+ final = clean_parse_tree(merged)
+ return final
+
+
+def check_equality(tuple1, tuple2):
+ ''' return True if tuples of multimolecules are equal '''
+ list1 = list(tuple1)
+ list2 = list(tuple2)
+
+ # Hypo: trees where are levels count+molecule vs just molecule
+ # cannot be sorted properly (tested on test_complex_additivity)
+ # But without factors and phases sorting seems to work.
+
+ # Also for lists of multimolecules without factors and phases
+ # sorting seems to work fine.
+ list1.sort()
+ list2.sort()
+ return list1 == list2
+
+
+def compare_chemical_expression(s1, s2, ignore_state=False):
+ ''' It does comparison between two equations.
+ It uses divide_chemical_expression and check if division is 1
+ '''
+ return divide_chemical_expression(s1, s2, ignore_state) == 1
+
+
+def divide_chemical_expression(s1, s2, ignore_state=False):
+ ''' Compare chemical equations for difference
+ in factors. Ideas:
+ - extract factors and phases to standalone lists,
+ - compare equations without factors and phases,
+ - divide lists of factors for each other and check
+ for equality of every element in list,
+ - return result of factor division '''
+
+ # parsed final trees
+ treedic = {}
+ treedic['1'] = get_finale_tree(s1)
+ treedic['2'] = get_finale_tree(s2)
+
+ # strip phases and factors
+ # collect factors in list
+ for i in ('1', '2'):
+ treedic[i + ' cleaned_mm_list'] = []
+ treedic[i + ' factors'] = []
+ treedic[i + ' phases'] = []
+ for el in treedic[i].subtrees(filter=lambda t: t.node == 'multimolecule'):
+ count_subtree = [t for t in el.subtrees() if t.node == 'count']
+ group_subtree = [t for t in el.subtrees() if t.node == 'group']
+ phase_subtree = [t for t in el.subtrees() if t.node == 'phase']
+ if count_subtree:
+ if len(count_subtree[0]) > 1:
+ treedic[i + ' factors'].append(
+ int(count_subtree[0][0][0]) /
+ int(count_subtree[0][2][0]))
+ else:
+ treedic[i + ' factors'].append(int(count_subtree[0][0][0]))
+ else:
+ treedic[i + ' factors'].append(1.0)
+ if phase_subtree:
+ treedic[i + ' phases'].append(phase_subtree[0][0])
+ else:
+ treedic[i + ' phases'].append(' ')
+ treedic[i + ' cleaned_mm_list'].append(
+ Tree('multimolecule', [Tree('molecule', group_subtree)]))
+
+ # order of factors and phases must mirror the order of multimolecules,
+ # use 'decorate, sort, undecorate' pattern
+ treedic['1 cleaned_mm_list'], treedic['1 factors'], treedic['1 phases'] = zip(
+ *sorted(zip(treedic['1 cleaned_mm_list'], treedic['1 factors'], treedic['1 phases'])))
+
+ treedic['2 cleaned_mm_list'], treedic['2 factors'], treedic['2 phases'] = zip(
+ *sorted(zip(treedic['2 cleaned_mm_list'], treedic['2 factors'], treedic['2 phases'])))
+
+ # check if equations are correct without factors
+ if not check_equality(treedic['1 cleaned_mm_list'], treedic['2 cleaned_mm_list']):
+ return False
+
+ # phases are ruled by ingore_state flag
+ if not ignore_state: # phases matters
+ if treedic['1 phases'] != treedic['2 phases']:
+ return False
+
+ if any(map(lambda x, y: x / y - treedic['1 factors'][0] / treedic['2 factors'][0],
+ treedic['1 factors'], treedic['2 factors'])):
+ log('factors are not proportional')
+ return False
+ else: # return ratio
+ return int(max(treedic['1 factors'][0] / treedic['2 factors'][0],
+ treedic['2 factors'][0] / treedic['1 factors'][0]))
+
+
+class Test_Compare_Equations(unittest.TestCase):
+
+ def test_compare_incorrect_order_of_atoms_in_molecule(self):
+ self.assertFalse(compare_chemical_expression("H2O + CO2", "O2C + OH2"))
+
+ def test_compare_same_order_no_phases_no_factors_no_ions(self):
+ self.assertTrue(compare_chemical_expression("H2O + CO2", "CO2+H2O"))
+
+ def test_compare_different_order_no_phases_no_factors_no_ions(self):
+ self.assertTrue(compare_chemical_expression("H2O + CO2", "CO2 + H2O"))
+
+ def test_compare_different_order_three_multimolecule(self):
+ self.assertTrue(compare_chemical_expression("H2O + Fe(OH)3 + CO2", "CO2 + H2O + Fe(OH)3"))
+
+ def test_compare_same_factors(self):
+ self.assertTrue(compare_chemical_expression("3H2O + 2CO2", "2CO2 + 3H2O "))
+
+ def test_compare_different_factors(self):
+ self.assertFalse(compare_chemical_expression("2H2O + 3CO2", "2CO2 + 3H2O "))
+
+ def test_compare_correct_ions(self):
+ self.assertTrue(compare_chemical_expression("H^+ + OH^-", " OH^- + H^+ "))
+
+ def test_compare_wrong_ions(self):
+ self.assertFalse(compare_chemical_expression("H^+ + OH^-", " OH^- + H^- "))
+
+ def test_compare_parent_groups_ions(self):
+ self.assertTrue(compare_chemical_expression("Fe(OH)^2- + (OH)^-", " (OH)^- + Fe(OH)^2- "))
+
+ def test_compare_correct_factors_ions_and_one(self):
+ self.assertTrue(compare_chemical_expression("3H^+ + 2OH^-", " 2OH^- + 3H^+ "))
+
+ def test_compare_wrong_factors_ions(self):
+ self.assertFalse(compare_chemical_expression("2H^+ + 3OH^-", " 2OH^- + 3H^+ "))
+
+ def test_compare_float_factors(self):
+ self.assertTrue(compare_chemical_expression("7/2H^+ + 3/5OH^-", " 3/5OH^- + 7/2H^+ "))
+
+ # Phases tests
+ def test_compare_phases_ignored(self):
+ self.assertTrue(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O+CO2", ignore_state=True))
+
+ def test_compare_phases_not_ignored_explicitly(self):
+ self.assertFalse(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O+CO2", ignore_state=False))
+
+ def test_compare_phases_not_ignored(self): # same as previous
+ self.assertFalse(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O+CO2"))
+
+ def test_compare_phases_not_ignored_explicitly(self):
+ self.assertTrue(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O(s)+CO2", ignore_state=False))
+
+ # all in one cases
+ def test_complex_additivity(self):
+ self.assertTrue(compare_chemical_expression(
+ "5(H1H212)^70010- + 2H20 + 7/2HCl + H2O",
+ "7/2HCl + 2H20 + H2O + 5(H1H212)^70010-"))
+
+ def test_complex_additivity_wrong(self):
+ self.assertFalse(compare_chemical_expression(
+ "5(H1H212)^70010- + 2H20 + 7/2HCl + H2O",
+ "2H20 + 7/2HCl + H2O + 5(H1H212)^70011-"))
+
+ def test_complex_all_grammar(self):
+ self.assertTrue(compare_chemical_expression(
+ "5[Ni(NH3)4]^2+ + 5/2SO4^2-",
+ "5/2SO4^2- + 5[Ni(NH3)4]^2+"))
+
+ # special cases
+
+ def test_compare_one_superscript_explicitly_set(self):
+ self.assertTrue(compare_chemical_expression("H^+ + OH^1-", " OH^- + H^+ "))
+
+ def test_compare_equal_factors_differently_set(self):
+ self.assertTrue(compare_chemical_expression("6/2H^+ + OH^-", " OH^- + 3H^+ "))
+
+ def test_compare_one_subscript_explicitly_set(self):
+ self.assertFalse(compare_chemical_expression("H2 + CO2", "H2 + C102"))
+
+
+class Test_Divide_Equations(unittest.TestCase):
+ ''' as compare_ use divide_,
+ tests here must consider different
+ division (not equality) cases '''
+
+ def test_divide_wrong_factors(self):
+ self.assertFalse(divide_chemical_expression(
+ "5(H1H212)^70010- + 10H2O", "5H2O + 10(H1H212)^70010-"))
+
+ def test_divide_right(self):
+ self.assertEqual(divide_chemical_expression(
+ "5(H1H212)^70010- + 10H2O", "10H2O + 5(H1H212)^70010-"), 1)
+
+ def test_divide_wrong_reagents(self):
+ self.assertFalse(divide_chemical_expression(
+ "H2O + CO2", "CO2"))
+
+ def test_divide_right_simple(self):
+ self.assertEqual(divide_chemical_expression(
+ "H2O + CO2", "H2O+CO2"), 1)
+
+ def test_divide_right_phases(self):
+ self.assertEqual(divide_chemical_expression(
+ "H2O(s) + CO2", "2H2O(s)+2CO2"), 2)
+
+ def test_divide_wrong_phases(self):
+ self.assertFalse(divide_chemical_expression(
+ "H2O(s) + CO2", "2H2O+2CO2(s)"))
+
+ def test_divide_wrong_phases_but_phases_ignored(self):
+ self.assertEqual(divide_chemical_expression(
+ "H2O(s) + CO2", "2H2O+2CO2(s)", ignore_state=True), 2)
+
+ def test_divide_order(self):
+ self.assertEqual(divide_chemical_expression(
+ "2CO2 + H2O", "2H2O+4CO2"), 2)
+
+ def test_divide_fract_to_int(self):
+ self.assertEqual(divide_chemical_expression(
+ "3/2CO2 + H2O", "2H2O+3CO2"), 2)
+
+ def test_divide_fract_to_frac(self):
+ self.assertEqual(divide_chemical_expression(
+ "3/4CO2 + H2O", "2H2O+9/6CO2"), 2)
+
+ def test_divide_fract_to_frac_wrog(self):
+ self.assertFalse(divide_chemical_expression(
+ "6/2CO2 + H2O", "2H2O+9/6CO2"), 2)
+
+
+class Test_Render_Equations(unittest.TestCase):
+
+ def test_render1(self):
+ s = "H2O + CO2"
+ out = clean_and_render_to_html(s)
+ correct = "H2O+CO2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render_uncorrect_reaction(self):
+ s = "O2C + OH2"
+ out = clean_and_render_to_html(s)
+ correct = "O2C+OH2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render2(self):
+ s = "CO2 + H2O + Fe(OH)3"
+ out = clean_and_render_to_html(s)
+ correct = "CO2+H2O+Fe(OH)3"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render3(self):
+ s = "3H2O + 2CO2"
+ out = clean_and_render_to_html(s)
+ correct = "3H2O+2CO2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render4(self):
+ s = "H^+ + OH^-"
+ out = clean_and_render_to_html(s)
+ correct = "H++OH-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render5(self):
+ s = "Fe(OH)^2- + (OH)^-"
+ out = clean_and_render_to_html(s)
+ correct = "Fe(OH)2-+(OH)-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render6(self):
+ s = "7/2H^+ + 3/5OH^-"
+ out = clean_and_render_to_html(s)
+ correct = "7⁄2H++3⁄5OH-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render7(self):
+ s = "5(H1H212)^70010- + 2H2O + 7/2HCl + H2O"
+ out = clean_and_render_to_html(s)
+ correct = "5(H1H212)70010-+2H2O+7⁄2HCl+H2O"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render8(self):
+ s = "H2O(s) + CO2"
+ out = clean_and_render_to_html(s)
+ correct = "H2O(s)+CO2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render9(self):
+ s = "5[Ni(NH3)4]^2+ + 5/2SO4^2-"
+ #import ipdb; ipdb.set_trace()
+ out = clean_and_render_to_html(s)
+ correct = "5[Ni(NH3)4]2++5⁄2SO42-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render_error(self):
+ s = "5.2H20"
+ self.assertRaises(ParseException, clean_and_render_to_html, s)
+
+ def test_render_simple_brackets(self):
+ s = "(Ar)"
+ out = clean_and_render_to_html(s)
+ correct = "(Ar)"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+
+def suite():
+
+ testcases = [Test_Compare_Equations, Test_Divide_Equations, Test_Render_Equations]
+ suites = []
+ for testcase in testcases:
+ suites.append(unittest.TestLoader().loadTestsFromTestCase(testcase))
+ return unittest.TestSuite(suites)
+
+if __name__ == "__main__":
+ local_debug = True
+ with open('render.html', 'w') as f:
+ unittest.TextTestRunner(verbosity=2).run(suite())
+ # open render.html to look at rendered equations
From db175807103172d2f7f91e5e72f1fae2c3ebca16 Mon Sep 17 00:00:00 2001
From: Victor Shnayder
Date: Tue, 9 Oct 2012 18:47:32 -0400
Subject: [PATCH 12/65] Chemcalc refactor, improvement
* Move tests into a separate file
* add a chemical_equations_equal function to compare equations, not expressions
* rename some internal functions with a leading _
---
common/lib/capa/capa/chem/chemcalc.py | 340 ++++++--------------------
common/lib/capa/capa/chem/tests.py | 296 ++++++++++++++++++++++
2 files changed, 377 insertions(+), 259 deletions(-)
create mode 100644 common/lib/capa/capa/chem/tests.py
diff --git a/common/lib/capa/capa/chem/chemcalc.py b/common/lib/capa/capa/chem/chemcalc.py
index 65d1887d2e..b2198b5537 100644
--- a/common/lib/capa/capa/chem/chemcalc.py
+++ b/common/lib/capa/capa/chem/chemcalc.py
@@ -1,27 +1,19 @@
from __future__ import division
import copy
+from fractions import Fraction
import logging
import math
import operator
import re
-import unittest
import numpy
import numbers
import scipy.constants
-from pyparsing import Literal, Keyword, Word, nums, StringEnd, Optional, Forward, OneOrMore
-from pyparsing import ParseException
+from pyparsing import (Literal, Keyword, Word, nums, StringEnd, Optional,
+ Forward, OneOrMore, ParseException)
import nltk
from nltk.tree import Tree
-local_debug = None
-
-
-def log(s, output_type=None):
- if local_debug:
- print s
- if output_type == 'html':
- f.write(s + '\n \n')
## Defines a simple pyparsing tokenizer for chemical equations
elements = ['Ac','Ag','Al','Am','Ar','As','At','Au','B','Ba','Be',
@@ -42,19 +34,19 @@ tokens = reduce(lambda a, b: a ^ b, map(Literal, elements + digits + symbols + p
tokenizer = OneOrMore(tokens) + StringEnd()
-def orjoin(l):
+def _orjoin(l):
return "'" + "' | '".join(l) + "'"
-## Defines an NLTK parser for tokenized equations
+## Defines an NLTK parser for tokenized expressions
grammar = """
S -> multimolecule | multimolecule '+' S
multimolecule -> count molecule | molecule
count -> number | number '/' number
molecule -> unphased | unphased phase
unphased -> group | paren_group_round | paren_group_square
- element -> """ + orjoin(elements) + """
- digit -> """ + orjoin(digits) + """
- phase -> """ + orjoin(phases) + """
+ element -> """ + _orjoin(elements) + """
+ digit -> """ + _orjoin(digits) + """
+ phase -> """ + _orjoin(phases) + """
number -> digit | digit number
group -> suffixed | suffixed group
paren_group_round -> '(' group ')'
@@ -70,7 +62,7 @@ grammar = """
parser = nltk.ChartParser(nltk.parse_cfg(grammar))
-def clean_parse_tree(tree):
+def _clean_parse_tree(tree):
''' The parse tree contains a lot of redundant
nodes. E.g. paren_groups have groups as children, etc. This will
clean up the tree.
@@ -119,7 +111,7 @@ def clean_parse_tree(tree):
children = []
for child in tree:
- child = clean_parse_tree(child)
+ child = _clean_parse_tree(child)
children.append(child)
tree = nltk.tree.Tree(tree.node, children)
@@ -127,7 +119,7 @@ def clean_parse_tree(tree):
return tree
-def merge_children(tree, tags):
+def _merge_children(tree, tags):
''' nltk, by documentation, cannot do arbitrary length
groups. Instead of:
(group 1 2 3 4)
@@ -157,13 +149,13 @@ def merge_children(tree, tags):
# And recurse
children = []
for child in tree:
- children.append(merge_children(child, tags))
+ children.append(_merge_children(child, tags))
#return tree
return nltk.tree.Tree(tree.node, children)
-def render_to_html(tree):
+def _render_to_html(tree):
''' Renders a cleaned tree to HTML '''
def molecule_count(tree, children):
@@ -196,29 +188,29 @@ def render_to_html(tree):
if type(tree) == str:
return tree
else:
- children = "".join(map(render_to_html, tree))
+ children = "".join(map(_render_to_html, tree))
if tree.node in dispatch:
return dispatch[tree.node](tree, children)
else:
return children.replace(' ', '')
-def clean_and_render_to_html(s):
+def render_to_html(s):
''' render a string to html '''
- status = render_to_html(get_finale_tree(s))
+ status = _render_to_html(_get_final_tree(s))
return status
-def get_finale_tree(s):
+def _get_final_tree(s):
''' return final tree after merge and clean '''
tokenized = tokenizer.parseString(s)
parsed = parser.parse(tokenized)
- merged = merge_children(parsed, {'S','group'})
- final = clean_parse_tree(merged)
+ merged = _merge_children(parsed, {'S','group'})
+ final = _clean_parse_tree(merged)
return final
-def check_equality(tuple1, tuple2):
+def _check_equality(tuple1, tuple2):
''' return True if tuples of multimolecules are equal '''
list1 = list(tuple1)
list2 = list(tuple2)
@@ -242,18 +234,31 @@ def compare_chemical_expression(s1, s2, ignore_state=False):
def divide_chemical_expression(s1, s2, ignore_state=False):
- ''' Compare chemical equations for difference
- in factors. Ideas:
+ '''Compare two chemical equations for equivalence up to a multiplicative factor:
+
+ - If they are not the same chemicals, returns False.
+ - If they are the same, "divide" s1 by s2 to returns a factor x such that s1 / s2 == x as a Fraction object.
+ - if ignore_state is True, ignores phases when doing the comparison.
+
+ Examples:
+ divide_chemical_expression("H2O", "3H2O") -> Fraction(1,3)
+ divide_chemical_expression("3H2O", "H2O") -> 3 # actually Fraction(3, 1), but compares == to 3.
+ divide_chemical_expression("2H2O(s) + 2CO2", "H2O(s)+CO2") -> 2
+ divide_chemical_expression("H2O(s) + CO2", "3H2O(s)+2CO2") -> False
+
+ Implementation sketch:
- extract factors and phases to standalone lists,
- compare equations without factors and phases,
- divide lists of factors for each other and check
for equality of every element in list,
- - return result of factor division '''
+ - return result of factor division
+
+ '''
# parsed final trees
treedic = {}
- treedic['1'] = get_finale_tree(s1)
- treedic['2'] = get_finale_tree(s2)
+ treedic['1'] = _get_final_tree(s1)
+ treedic['2'] = _get_final_tree(s2)
# strip phases and factors
# collect factors in list
@@ -290,7 +295,7 @@ def divide_chemical_expression(s1, s2, ignore_state=False):
*sorted(zip(treedic['2 cleaned_mm_list'], treedic['2 factors'], treedic['2 phases'])))
# check if equations are correct without factors
- if not check_equality(treedic['1 cleaned_mm_list'], treedic['2 cleaned_mm_list']):
+ if not _check_equality(treedic['1 cleaned_mm_list'], treedic['2 cleaned_mm_list']):
return False
# phases are ruled by ingore_state flag
@@ -300,241 +305,58 @@ def divide_chemical_expression(s1, s2, ignore_state=False):
if any(map(lambda x, y: x / y - treedic['1 factors'][0] / treedic['2 factors'][0],
treedic['1 factors'], treedic['2 factors'])):
- log('factors are not proportional')
+ # factors are not proportional
return False
- else: # return ratio
- return int(max(treedic['1 factors'][0] / treedic['2 factors'][0],
- treedic['2 factors'][0] / treedic['1 factors'][0]))
+ else:
+ # return ratio
+ return Fraction(treedic['1 factors'][0] / treedic['2 factors'][0])
-class Test_Compare_Equations(unittest.TestCase):
+def chemical_equations_equal(eq1, eq2, ignoreFactor=True):
+ """
+ Check whether two chemical equations are the same. If ignoreFactor is True,
+ then they are considered equal if they differ by a constant factor.
- def test_compare_incorrect_order_of_atoms_in_molecule(self):
- self.assertFalse(compare_chemical_expression("H2O + CO2", "O2C + OH2"))
+ arrows matter: ->, and <-> are different.
- def test_compare_same_order_no_phases_no_factors_no_ions(self):
- self.assertTrue(compare_chemical_expression("H2O + CO2", "CO2+H2O"))
+ e.g.
+ chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + H2 -> H2O2') -> True
+ chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + 2H2 -> H2O2') -> False
- def test_compare_different_order_no_phases_no_factors_no_ions(self):
- self.assertTrue(compare_chemical_expression("H2O + CO2", "CO2 + H2O"))
+ chemical_equations_equal('H2 + O2 -> H2O2', 'O2 + H2 <-> H2O2') -> False
- def test_compare_different_order_three_multimolecule(self):
- self.assertTrue(compare_chemical_expression("H2O + Fe(OH)3 + CO2", "CO2 + H2O + Fe(OH)3"))
+ If there's a syntax error, we raise pyparsing.ParseException.
+ """
+ # for now, we do a manual parse for the arrow.
+ arrows = ('<->', '->') # order matters -- need to try <-> first
+ def split_on_arrow(s):
+ """Split a string on an arrow. Returns left, arrow, right, or raises ParseException if there isn't an arrow"""
+ for arrow in arrows:
+ left, a, right = s.partition(arrow)
+ if a != '':
+ return left, a, right
+ raise ParseException("Could not find arrow. Legal arrows: {0}".format(arrows))
- def test_compare_same_factors(self):
- self.assertTrue(compare_chemical_expression("3H2O + 2CO2", "2CO2 + 3H2O "))
+ left1, arrow1, right1 = split_on_arrow(eq1)
+ left2, arrow2, right2 = split_on_arrow(eq2)
- def test_compare_different_factors(self):
- self.assertFalse(compare_chemical_expression("2H2O + 3CO2", "2CO2 + 3H2O "))
+ # TODO: may want to be able to give student helpful feedback about why things didn't work.
+ if arrow1 != arrow2:
+ # arrows don't match
+ return False
- def test_compare_correct_ions(self):
- self.assertTrue(compare_chemical_expression("H^+ + OH^-", " OH^- + H^+ "))
+ factor_left = divide_chemical_expression(left1, left2)
+ if not factor_left:
+ # left sides don't match
+ return False
- def test_compare_wrong_ions(self):
- self.assertFalse(compare_chemical_expression("H^+ + OH^-", " OH^- + H^- "))
+ factor_right = divide_chemical_expression(right1, right2)
+ if not factor_right:
+ # right sides don't match
+ return False
- def test_compare_parent_groups_ions(self):
- self.assertTrue(compare_chemical_expression("Fe(OH)^2- + (OH)^-", " (OH)^- + Fe(OH)^2- "))
+ if factor_left != factor_right:
+ # factors don't match (molecule counts to add up)
+ return False
- def test_compare_correct_factors_ions_and_one(self):
- self.assertTrue(compare_chemical_expression("3H^+ + 2OH^-", " 2OH^- + 3H^+ "))
-
- def test_compare_wrong_factors_ions(self):
- self.assertFalse(compare_chemical_expression("2H^+ + 3OH^-", " 2OH^- + 3H^+ "))
-
- def test_compare_float_factors(self):
- self.assertTrue(compare_chemical_expression("7/2H^+ + 3/5OH^-", " 3/5OH^- + 7/2H^+ "))
-
- # Phases tests
- def test_compare_phases_ignored(self):
- self.assertTrue(compare_chemical_expression(
- "H2O(s) + CO2", "H2O+CO2", ignore_state=True))
-
- def test_compare_phases_not_ignored_explicitly(self):
- self.assertFalse(compare_chemical_expression(
- "H2O(s) + CO2", "H2O+CO2", ignore_state=False))
-
- def test_compare_phases_not_ignored(self): # same as previous
- self.assertFalse(compare_chemical_expression(
- "H2O(s) + CO2", "H2O+CO2"))
-
- def test_compare_phases_not_ignored_explicitly(self):
- self.assertTrue(compare_chemical_expression(
- "H2O(s) + CO2", "H2O(s)+CO2", ignore_state=False))
-
- # all in one cases
- def test_complex_additivity(self):
- self.assertTrue(compare_chemical_expression(
- "5(H1H212)^70010- + 2H20 + 7/2HCl + H2O",
- "7/2HCl + 2H20 + H2O + 5(H1H212)^70010-"))
-
- def test_complex_additivity_wrong(self):
- self.assertFalse(compare_chemical_expression(
- "5(H1H212)^70010- + 2H20 + 7/2HCl + H2O",
- "2H20 + 7/2HCl + H2O + 5(H1H212)^70011-"))
-
- def test_complex_all_grammar(self):
- self.assertTrue(compare_chemical_expression(
- "5[Ni(NH3)4]^2+ + 5/2SO4^2-",
- "5/2SO4^2- + 5[Ni(NH3)4]^2+"))
-
- # special cases
-
- def test_compare_one_superscript_explicitly_set(self):
- self.assertTrue(compare_chemical_expression("H^+ + OH^1-", " OH^- + H^+ "))
-
- def test_compare_equal_factors_differently_set(self):
- self.assertTrue(compare_chemical_expression("6/2H^+ + OH^-", " OH^- + 3H^+ "))
-
- def test_compare_one_subscript_explicitly_set(self):
- self.assertFalse(compare_chemical_expression("H2 + CO2", "H2 + C102"))
-
-
-class Test_Divide_Equations(unittest.TestCase):
- ''' as compare_ use divide_,
- tests here must consider different
- division (not equality) cases '''
-
- def test_divide_wrong_factors(self):
- self.assertFalse(divide_chemical_expression(
- "5(H1H212)^70010- + 10H2O", "5H2O + 10(H1H212)^70010-"))
-
- def test_divide_right(self):
- self.assertEqual(divide_chemical_expression(
- "5(H1H212)^70010- + 10H2O", "10H2O + 5(H1H212)^70010-"), 1)
-
- def test_divide_wrong_reagents(self):
- self.assertFalse(divide_chemical_expression(
- "H2O + CO2", "CO2"))
-
- def test_divide_right_simple(self):
- self.assertEqual(divide_chemical_expression(
- "H2O + CO2", "H2O+CO2"), 1)
-
- def test_divide_right_phases(self):
- self.assertEqual(divide_chemical_expression(
- "H2O(s) + CO2", "2H2O(s)+2CO2"), 2)
-
- def test_divide_wrong_phases(self):
- self.assertFalse(divide_chemical_expression(
- "H2O(s) + CO2", "2H2O+2CO2(s)"))
-
- def test_divide_wrong_phases_but_phases_ignored(self):
- self.assertEqual(divide_chemical_expression(
- "H2O(s) + CO2", "2H2O+2CO2(s)", ignore_state=True), 2)
-
- def test_divide_order(self):
- self.assertEqual(divide_chemical_expression(
- "2CO2 + H2O", "2H2O+4CO2"), 2)
-
- def test_divide_fract_to_int(self):
- self.assertEqual(divide_chemical_expression(
- "3/2CO2 + H2O", "2H2O+3CO2"), 2)
-
- def test_divide_fract_to_frac(self):
- self.assertEqual(divide_chemical_expression(
- "3/4CO2 + H2O", "2H2O+9/6CO2"), 2)
-
- def test_divide_fract_to_frac_wrog(self):
- self.assertFalse(divide_chemical_expression(
- "6/2CO2 + H2O", "2H2O+9/6CO2"), 2)
-
-
-class Test_Render_Equations(unittest.TestCase):
-
- def test_render1(self):
- s = "H2O + CO2"
- out = clean_and_render_to_html(s)
- correct = "H2O+CO2"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render_uncorrect_reaction(self):
- s = "O2C + OH2"
- out = clean_and_render_to_html(s)
- correct = "O2C+OH2"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render2(self):
- s = "CO2 + H2O + Fe(OH)3"
- out = clean_and_render_to_html(s)
- correct = "CO2+H2O+Fe(OH)3"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render3(self):
- s = "3H2O + 2CO2"
- out = clean_and_render_to_html(s)
- correct = "3H2O+2CO2"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render4(self):
- s = "H^+ + OH^-"
- out = clean_and_render_to_html(s)
- correct = "H++OH-"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render5(self):
- s = "Fe(OH)^2- + (OH)^-"
- out = clean_and_render_to_html(s)
- correct = "Fe(OH)2-+(OH)-"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render6(self):
- s = "7/2H^+ + 3/5OH^-"
- out = clean_and_render_to_html(s)
- correct = "7⁄2H++3⁄5OH-"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render7(self):
- s = "5(H1H212)^70010- + 2H2O + 7/2HCl + H2O"
- out = clean_and_render_to_html(s)
- correct = "5(H1H212)70010-+2H2O+7⁄2HCl+H2O"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render8(self):
- s = "H2O(s) + CO2"
- out = clean_and_render_to_html(s)
- correct = "H2O(s)+CO2"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render9(self):
- s = "5[Ni(NH3)4]^2+ + 5/2SO4^2-"
- #import ipdb; ipdb.set_trace()
- out = clean_and_render_to_html(s)
- correct = "5[Ni(NH3)4]2++5⁄2SO42-"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
- def test_render_error(self):
- s = "5.2H20"
- self.assertRaises(ParseException, clean_and_render_to_html, s)
-
- def test_render_simple_brackets(self):
- s = "(Ar)"
- out = clean_and_render_to_html(s)
- correct = "(Ar)"
- log(out + ' ------- ' + correct, 'html')
- self.assertEqual(out, correct)
-
-
-def suite():
-
- testcases = [Test_Compare_Equations, Test_Divide_Equations, Test_Render_Equations]
- suites = []
- for testcase in testcases:
- suites.append(unittest.TestLoader().loadTestsFromTestCase(testcase))
- return unittest.TestSuite(suites)
-
-if __name__ == "__main__":
- local_debug = True
- with open('render.html', 'w') as f:
- unittest.TextTestRunner(verbosity=2).run(suite())
- # open render.html to look at rendered equations
+ return True
diff --git a/common/lib/capa/capa/chem/tests.py b/common/lib/capa/capa/chem/tests.py
new file mode 100644
index 0000000000..433fe6feea
--- /dev/null
+++ b/common/lib/capa/capa/chem/tests.py
@@ -0,0 +1,296 @@
+from fractions import Fraction
+from pyparsing import ParseException
+import unittest
+
+from chemcalc import (compare_chemical_expression, divide_chemical_expression,
+ render_to_html, chemical_equations_equal)
+
+local_debug = None
+
+def log(s, output_type=None):
+ if local_debug:
+ print s
+ if output_type == 'html':
+ f.write(s + '\n \n')
+
+
+class Test_Compare_Equations(unittest.TestCase):
+ def test_simple_equation(self):
+ self.assertTrue(chemical_equations_equal('H2 + O2 -> H2O2',
+ 'O2 + H2 -> H2O2'))
+ # left sides don't match
+ self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2',
+ 'O2 + 2H2 -> H2O2'))
+ # right sides don't match
+ self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2',
+ 'O2 + H2 -> H2O'))
+
+ # factors don't match
+ self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2',
+ 'O2 + H2 -> 2H2O2'))
+
+ def test_different_factor(self):
+ self.assertTrue(chemical_equations_equal('H2 + O2 -> H2O2',
+ '2O2 + 2H2 -> 2H2O2'))
+
+ self.assertFalse(chemical_equations_equal('2H2 + O2 -> H2O2',
+ '2O2 + 2H2 -> 2H2O2'))
+
+
+ def test_different_arrows(self):
+ self.assertTrue(chemical_equations_equal('H2 + O2 -> H2O2',
+ '2O2 + 2H2 -> 2H2O2'))
+
+ self.assertFalse(chemical_equations_equal('H2 + O2 -> H2O2',
+ 'O2 + H2 <-> 2H2O2'))
+
+
+ def test_syntax_errors(self):
+ self.assertRaises(ParseException, chemical_equations_equal,
+ 'H2 + O2 a-> H2O2',
+ '2O2 + 2H2 -> 2H2O2')
+
+ self.assertRaises(ParseException, chemical_equations_equal,
+ 'H2 + O2 ==> H2O2', # strange arrow
+ '2O2 + 2H2 -> 2H2O2')
+
+
+class Test_Compare_Expressions(unittest.TestCase):
+
+ def test_compare_incorrect_order_of_atoms_in_molecule(self):
+ self.assertFalse(compare_chemical_expression("H2O + CO2", "O2C + OH2"))
+
+ def test_compare_same_order_no_phases_no_factors_no_ions(self):
+ self.assertTrue(compare_chemical_expression("H2O + CO2", "CO2+H2O"))
+
+ def test_compare_different_order_no_phases_no_factors_no_ions(self):
+ self.assertTrue(compare_chemical_expression("H2O + CO2", "CO2 + H2O"))
+
+ def test_compare_different_order_three_multimolecule(self):
+ self.assertTrue(compare_chemical_expression("H2O + Fe(OH)3 + CO2", "CO2 + H2O + Fe(OH)3"))
+
+ def test_compare_same_factors(self):
+ self.assertTrue(compare_chemical_expression("3H2O + 2CO2", "2CO2 + 3H2O "))
+
+ def test_compare_different_factors(self):
+ self.assertFalse(compare_chemical_expression("2H2O + 3CO2", "2CO2 + 3H2O "))
+
+ def test_compare_correct_ions(self):
+ self.assertTrue(compare_chemical_expression("H^+ + OH^-", " OH^- + H^+ "))
+
+ def test_compare_wrong_ions(self):
+ self.assertFalse(compare_chemical_expression("H^+ + OH^-", " OH^- + H^- "))
+
+ def test_compare_parent_groups_ions(self):
+ self.assertTrue(compare_chemical_expression("Fe(OH)^2- + (OH)^-", " (OH)^- + Fe(OH)^2- "))
+
+ def test_compare_correct_factors_ions_and_one(self):
+ self.assertTrue(compare_chemical_expression("3H^+ + 2OH^-", " 2OH^- + 3H^+ "))
+
+ def test_compare_wrong_factors_ions(self):
+ self.assertFalse(compare_chemical_expression("2H^+ + 3OH^-", " 2OH^- + 3H^+ "))
+
+ def test_compare_float_factors(self):
+ self.assertTrue(compare_chemical_expression("7/2H^+ + 3/5OH^-", " 3/5OH^- + 7/2H^+ "))
+
+ # Phases tests
+ def test_compare_phases_ignored(self):
+ self.assertTrue(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O+CO2", ignore_state=True))
+
+ def test_compare_phases_not_ignored_explicitly(self):
+ self.assertFalse(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O+CO2", ignore_state=False))
+
+ def test_compare_phases_not_ignored(self): # same as previous
+ self.assertFalse(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O+CO2"))
+
+ def test_compare_phases_not_ignored_explicitly(self):
+ self.assertTrue(compare_chemical_expression(
+ "H2O(s) + CO2", "H2O(s)+CO2", ignore_state=False))
+
+ # all in one cases
+ def test_complex_additivity(self):
+ self.assertTrue(compare_chemical_expression(
+ "5(H1H212)^70010- + 2H20 + 7/2HCl + H2O",
+ "7/2HCl + 2H20 + H2O + 5(H1H212)^70010-"))
+
+ def test_complex_additivity_wrong(self):
+ self.assertFalse(compare_chemical_expression(
+ "5(H1H212)^70010- + 2H20 + 7/2HCl + H2O",
+ "2H20 + 7/2HCl + H2O + 5(H1H212)^70011-"))
+
+ def test_complex_all_grammar(self):
+ self.assertTrue(compare_chemical_expression(
+ "5[Ni(NH3)4]^2+ + 5/2SO4^2-",
+ "5/2SO4^2- + 5[Ni(NH3)4]^2+"))
+
+ # special cases
+
+ def test_compare_one_superscript_explicitly_set(self):
+ self.assertTrue(compare_chemical_expression("H^+ + OH^1-", " OH^- + H^+ "))
+
+ def test_compare_equal_factors_differently_set(self):
+ self.assertTrue(compare_chemical_expression("6/2H^+ + OH^-", " OH^- + 3H^+ "))
+
+ def test_compare_one_subscript_explicitly_set(self):
+ self.assertFalse(compare_chemical_expression("H2 + CO2", "H2 + C102"))
+
+
+class Test_Divide_Expressions(unittest.TestCase):
+ ''' as compare_ use divide_,
+ tests here must consider different
+ division (not equality) cases '''
+
+ def test_divide_by_zero(self):
+ self.assertFalse(divide_chemical_expression(
+ "0H2O", "H2O"))
+
+ def test_divide_wrong_factors(self):
+ self.assertFalse(divide_chemical_expression(
+ "5(H1H212)^70010- + 10H2O", "5H2O + 10(H1H212)^70010-"))
+
+ def test_divide_right(self):
+ self.assertEqual(divide_chemical_expression(
+ "5(H1H212)^70010- + 10H2O", "10H2O + 5(H1H212)^70010-"), 1)
+
+ def test_divide_wrong_reagents(self):
+ self.assertFalse(divide_chemical_expression(
+ "H2O + CO2", "CO2"))
+
+ def test_divide_right_simple(self):
+ self.assertEqual(divide_chemical_expression(
+ "H2O + CO2", "H2O+CO2"), 1)
+
+ def test_divide_right_phases(self):
+ self.assertEqual(divide_chemical_expression(
+ "H2O(s) + CO2", "2H2O(s)+2CO2"), Fraction(1, 2))
+
+ def test_divide_right_phases_other_order(self):
+ self.assertEqual(divide_chemical_expression(
+ "2H2O(s) + 2CO2", "H2O(s)+CO2"), 2)
+
+ def test_divide_wrong_phases(self):
+ self.assertFalse(divide_chemical_expression(
+ "H2O(s) + CO2", "2H2O+2CO2(s)"))
+
+ def test_divide_wrong_phases_but_phases_ignored(self):
+ self.assertEqual(divide_chemical_expression(
+ "H2O(s) + CO2", "2H2O+2CO2(s)", ignore_state=True), Fraction(1, 2))
+
+ def test_divide_order(self):
+ self.assertEqual(divide_chemical_expression(
+ "2CO2 + H2O", "2H2O+4CO2"), Fraction(1, 2))
+
+ def test_divide_fract_to_int(self):
+ self.assertEqual(divide_chemical_expression(
+ "3/2CO2 + H2O", "2H2O+3CO2"), Fraction(1, 2))
+
+ def test_divide_fract_to_frac(self):
+ self.assertEqual(divide_chemical_expression(
+ "3/4CO2 + H2O", "2H2O+9/6CO2"), Fraction(1, 2))
+
+ def test_divide_fract_to_frac_wrog(self):
+ self.assertFalse(divide_chemical_expression(
+ "6/2CO2 + H2O", "2H2O+9/6CO2"), 2)
+
+
+class Test_Render_Equations(unittest.TestCase):
+
+ def test_render1(self):
+ s = "H2O + CO2"
+ out = render_to_html(s)
+ correct = "H2O+CO2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render_uncorrect_reaction(self):
+ s = "O2C + OH2"
+ out = render_to_html(s)
+ correct = "O2C+OH2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render2(self):
+ s = "CO2 + H2O + Fe(OH)3"
+ out = render_to_html(s)
+ correct = "CO2+H2O+Fe(OH)3"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render3(self):
+ s = "3H2O + 2CO2"
+ out = render_to_html(s)
+ correct = "3H2O+2CO2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render4(self):
+ s = "H^+ + OH^-"
+ out = render_to_html(s)
+ correct = "H++OH-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render5(self):
+ s = "Fe(OH)^2- + (OH)^-"
+ out = render_to_html(s)
+ correct = "Fe(OH)2-+(OH)-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render6(self):
+ s = "7/2H^+ + 3/5OH^-"
+ out = render_to_html(s)
+ correct = "7⁄2H++3⁄5OH-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render7(self):
+ s = "5(H1H212)^70010- + 2H2O + 7/2HCl + H2O"
+ out = render_to_html(s)
+ correct = "5(H1H212)70010-+2H2O+7⁄2HCl+H2O"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render8(self):
+ s = "H2O(s) + CO2"
+ out = render_to_html(s)
+ correct = "H2O(s)+CO2"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render9(self):
+ s = "5[Ni(NH3)4]^2+ + 5/2SO4^2-"
+ #import ipdb; ipdb.set_trace()
+ out = render_to_html(s)
+ correct = "5[Ni(NH3)4]2++5⁄2SO42-"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+ def test_render_error(self):
+ s = "5.2H20"
+ self.assertRaises(ParseException, render_to_html, s)
+
+ def test_render_simple_brackets(self):
+ s = "(Ar)"
+ out = render_to_html(s)
+ correct = "(Ar)"
+ log(out + ' ------- ' + correct, 'html')
+ self.assertEqual(out, correct)
+
+
+def suite():
+
+ testcases = [Test_Compare_Expressions, Test_Divide_Expressions, Test_Render_Equations]
+ suites = []
+ for testcase in testcases:
+ suites.append(unittest.TestLoader().loadTestsFromTestCase(testcase))
+ return unittest.TestSuite(suites)
+
+if __name__ == "__main__":
+ local_debug = True
+ with open('render.html', 'w') as f:
+ unittest.TextTestRunner(verbosity=2).run(suite())
+ # open render.html to look at rendered equations
From 6f60af71fd799f71ced3eb004ca2f1fca6a7d10a Mon Sep 17 00:00:00 2001
From: Tom Giannattasio
Date: Wed, 10 Oct 2012 16:14:32 -0400
Subject: [PATCH 13/65] tweaked collapsible selector to target the proper
section; functionality like this should have its own class to avoid selector
conflicts, but it may be too late to fix this now
---
common/lib/xmodule/xmodule/js/src/collapsible.coffee | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/common/lib/xmodule/xmodule/js/src/collapsible.coffee b/common/lib/xmodule/xmodule/js/src/collapsible.coffee
index 314e7ca868..2f4b84e253 100644
--- a/common/lib/xmodule/xmodule/js/src/collapsible.coffee
+++ b/common/lib/xmodule/xmodule/js/src/collapsible.coffee
@@ -11,7 +11,7 @@ class @Collapsible
###
el.find('.longform').hide()
el.find('.shortform').append('See full output')
- el.find('.collapsible section').hide()
+ el.find('.collapsible header + section').hide()
el.find('.full').click @toggleFull
el.find('.collapsible header a').click @toggleHint
From 00e2f093b9b3af578eb0509e026667558571dfeb Mon Sep 17 00:00:00 2001
From: Tom Giannattasio
Date: Wed, 10 Oct 2012 16:19:03 -0400
Subject: [PATCH 14/65] removed extra padding on nested sections
---
common/lib/xmodule/xmodule/css/capa/display.scss | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/common/lib/xmodule/xmodule/css/capa/display.scss b/common/lib/xmodule/xmodule/css/capa/display.scss
index aa3f96c2e7..fd67a3804e 100644
--- a/common/lib/xmodule/xmodule/css/capa/display.scss
+++ b/common/lib/xmodule/xmodule/css/capa/display.scss
@@ -572,7 +572,7 @@ section.problem {
}
}
- section {
+ > section {
padding: 9px;
}
}
From 58b0829b7975873c75e69a576a6db81a23aac931 Mon Sep 17 00:00:00 2001
From: Arjun Singh
Date: Thu, 11 Oct 2012 06:22:00 -0700
Subject: [PATCH 15/65] Fix some issues with integer ids in the discussion
forum
---
lms/templates/discussion/_underscore_templates.html | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/lms/templates/discussion/_underscore_templates.html b/lms/templates/discussion/_underscore_templates.html
index 0a691ac36f..d1d3f6db56 100644
--- a/lms/templates/discussion/_underscore_templates.html
+++ b/lms/templates/discussion/_underscore_templates.html
@@ -1,5 +1,5 @@
+
+
+
+
The University of Texas System joins edX
+
+
+
The University of Texas System joins Harvard, MIT and UC Berkeley in not-for-profit online learning collaborative
+
+
CAMBRIDGE, MA/AUSTIN, TX – October 15, 2012 — edX, the online non-profit learning initiative founded by Harvard University (Harvard) and the Massachusetts Institute of Technology (MIT) and launched in May, announced today the addition of The University of Texas (UT) System to its platform. The UT System, one of the largest public university systems in the United States with nine academic universities and six health institutions, will collaborate with edX to expand the group of participating “X Universities” – universities offering their courses on the edX platform.
+
+
The UT System includes the University of Texas at Austin, ranked 25th in the 2012-2013 Times Higher Education World University Rankings, UT Southwestern Medical Center, home to one of the nation's top 25 medical schools, and UT MD Anderson Cancer Center, the nation's No. 1-ranked cancer center. The system's institutions serve 212,000 students and employ 19,000 faculty members.
+
+
Through edX, the “X Universities” provide online interactive education wherever there is access to the Internet, with a goal to enhance teaching and learning through research about how students learn, and how technologies can facilitate effective teaching both on campus and online. The University of California, Berkeley (UC Berkeley) joined edX in July 2012. edX plans to add other “X Universities” from around the world to the edX platform in the coming months.
+
+
Francisco G. Cigarroa, Chancellor of The University of Texas System announced the partnership following a unanimous vote of approval by the UT System's Board of Regents on Monday.
+
+
“New technologies are positively impacting how professors teach and how course content is delivered,” Chancellor Cigarroa said. “The University of Texas System will help lead this revolution and fundamentally alter the direction of online education. We are excited about this partnership with edX and honored to be in the company of such exceptional institutions as MIT, Harvard and Berkeley. The mission of edX aligns perfectly with that of the UT System and keeps the learner as its central focus.”
+
+
The University of Texas System plans to offer at least four courses on edX within the next year.
+
+
In addition to serving a global community of online students, the UT System plans to redesign general education courses and traditional entry-level courses that are too often made up of several hundred students. Through its Institute for Transformational Learning, the UT System plans to give students more options by offering courses that are customized to student needs. For example, the UT System plans to offer courses that use a combination of technology and face-to-face interaction, courses that allow students to manage their own time by accelerating through sections they have already mastered or spending more time on areas they find challenging, and fully online courses so students are not limited by their location.
+
+
“As Texas' flagship university, UT Austin is committed not only to embracing breakthroughs in education, but helping create them,” said William Powers, Jr., President of UT Austin. “We're proud to be partnering with these top peer universities on edX.”
+
+
As part of a bold and innovative plan, the UT System also plans to offer courses through edX that will allow students to earn college credits toward a degree. “Our goal through our partnership with edX is to better meet the learning needs of a wide range of students, raise graduation rates and cut the cost of higher education, all while maintaining our commitment to education of the highest quality,” said Gene Powell, chairman of the UT System Board of Regents.
+
+
The UT System brings a large and diverse student body to the edX family. Its six health institutions offer a unique opportunity to provide groundbreaking health and medical courses via edX in the near future. The UT System also brings special expertise in analytics – assessing student learning, online course design and creating interactive learning environments.
+
+
edX courses are designed to provide students with a wealth of innovative resources, including interactive laboratories, virtual reality environments and access to online tutors and tutorials. Students who take UT System courses through edX won't work in isolation, but will have the opportunity to participate in online forums, network with instructors and fellow students and take part in exciting collaborative projects. “We are excited that The University of Texas System is joining edX's efforts to revolutionize learning,” said Anant Agarwal, President of edX. “The institutions within The University of Texas System bring a wide range of expertise to the edX mission, and with them edX is now positioned to continue to increase our offering of high-quality, online courses.”
+
+
edX was created by Harvard and MIT in May, with each university committing to contribute $30 million toward the online partnership.
+
+
“Today's announcement is another important step toward our shared objectives of expanding access to high quality educational content while enhancing teaching and learning online and in the classroom,” said Harvard President Drew Faust. “The addition of The University of Texas System to the edX platform will allow us to deepen our understanding of learning, develop new approaches to teaching that build on that knowledge, and strengthen both the on-campus and online learning experience.”
+
+
“At MIT, we are energetically exploring the ways that online instruction can help us reimagine our campus residential education even as it allows us to reach an unprecedented number of learners around the world,” said MIT President L. Rafael Reif. “It is thrilling to be joined by The University of Texas System in the pursuit of that dual goal.”
+
+
The edX classes to be offered by the UT System will be announced soon and will join other new edX courses planned for Spring, Summer and Fall 2013. As with all edX courses, online learners who obtain a passing grade in the UT System courses will receive a certificate of mastery. edX will also offer the option of proctored examinations for the UT System courses.
+
+
+
About edX
+
+
edX is a not-for-profit enterprise of its founding partners Harvard University and the Massachusetts Institute of Technology that features learning designed specifically for interactive study via the web. Based on a long history of collaboration and their shared educational missions the founders are creating a new online-learning experience. Anant Agarwal, former Director of MIT's Computer Science and Artificial Intelligence Laboratory, serves as the first president of edX. Along with offering online courses, the institutions will use edX to research how students learn and how technology can transform learning—both on-campus and worldwide. edX is based in Cambridge, Massachusetts and is governed by MIT and Harvard.
+
+
About Harvard University
+
+
Harvard University is devoted to excellence in teaching, learning and research, and to developing leaders in many disciplines who make a difference globally. Harvard Faculty are engaged with teaching and research to push the boundaries of human knowledge. The University has twelve degree-granting Schools in addition to the Radcliffe Institute for Advanced Study.
+
+
Established in 1636, Harvard is the oldest institution of higher education in the United States. The University, which is based in Cambridge and Boston, Massachusetts, has an enrollment of over 20,000 degree candidates, including undergraduate, graduate and professional students. Harvard has more than 360,000 alumni around the world.
+
+
About MIT
+
The Massachusetts Institute of Technology — a coeducational, privately endowed research university founded in 1861 — is dedicated to advancing knowledge and educating students in science, technology and other areas of scholarship that will best serve the nation and the world in the 21st century. The Institute has close to 1,000 faculty and 10,000 undergraduate and graduate students. It is organized into five Schools: Architecture and Urban Planning; Engineering; Humanities, Arts, and Social Sciences; Sloan School of Management; and Science.
+
+
MIT's commitment to innovation has led to a host of scientific breakthroughs and technological advances. Achievements of the Institute's faculty and graduates have included the first chemical synthesis of penicillin and vitamin A, the development of inertial guidance systems, modern technologies for artificial limbs and the magnetic core memory that made possible the development of digital computers. Seventy-eight alumni, faculty, researchers and staff have won Nobel Prizes.
+
+
Current areas of research and education include neuroscience and the study of the brain and mind, bioengineering, cancer, energy, the environment and sustainable development, information sciences and technology, new media, financial technology and entrepreneurship.
+
+
About the University of California, Berkeley
+
+
The University of California, Berkeley is the world's premier public university with a mission to excel in teaching, research and public service. This longstanding mission has led to the university's distinguished record of Nobel-level scholarship, constant innovation, a concern for the betterment of our world, and consistently high rankings of its schools and departments. The campus offers superior, high value education for extraordinarily talented students from all walks of life; operational excellence and a commitment to the competitiveness and prosperity of California and the nation.
+
+
The University of California was chartered in 1868 and its flagship campus in Berkeley, on San Francisco Bay, was envisioned as a “City of Learning.” Today, there are more than 1,500 fulltime and 500 part-time faculty members dispersed among more than 130 academic departments and more than 80 interdisciplinary research units. Twenty-two Nobel Prizes have been garnered by faculty and 28 by UC Berkeley alumni. There are 9 Nobel Laureates, 32 MacArthur Fellows, and 4 Pulitzer Prize winners among the current faculty.
+
+
About The University of Texas System
+
+
Educating students, providing care for patients, conducting groundbreaking research and serving the needs of Texans and the nation for more than 130 years, The University of Texas System is one of the largest public university systems in the United States, with nine academic universities and six health science centers. Student enrollment exceeded 215,000 in the 2011 academic year. The UT System confers more than one-third of the state's undergraduate degrees and educates nearly three-fourths of the state's health care professionals annually. The UT System has an annual operating budget of $13.1 billion (FY 2012) including $2.3 billion in sponsored programs funded by federal, state, local and private sources. With roughly 87,000 employees, the UT System is one of the largest employers in the state. www.utsystem.edu
Educating students, providing care for patients, conducting groundbreaking research and serving the needs of Texans and the nation for more than 130 years, The University of Texas System is one of the largest public university systems in the United States, with nine academic universities and six health science centers. Student enrollment exceeded 215,000 in the 2011 academic year. The UT System confers more than one-third of the state’s undergraduate degrees and educates nearly three-fourths of the state’s health care professionals annually. The UT System has an annual operating budget of $13.1 billion (FY 2012) including $2.3 billion in sponsored programs funded by federal, state, local and private sources. With roughly 87,000 employees, the UT System is one of the largest employers in the state.
+%block>
+
+${parent.body()}
diff --git a/lms/urls.py b/lms/urls.py
index 035db95596..89a541ab06 100644
--- a/lms/urls.py
+++ b/lms/urls.py
@@ -52,6 +52,7 @@ urlpatterns = ('',
url(r'^heartbeat$', include('heartbeat.urls')),
+ url(r'^university_profile/UTx$', 'courseware.views.static_university_profile', name="static_university_profile", kwargs={'org_id':'UTx'}),
url(r'^university_profile/(?P[^/]+)$', 'courseware.views.university_profile', name="university_profile"),
#Semi-static views (these need to be rendered and have the login bar, but don't change)
@@ -88,6 +89,8 @@ urlpatterns = ('',
{'template': 'press_releases/edX_announces_proctored_exam_testing.html'}, name="press/edX-announces-proctored-exam-testing"),
url(r'^press/elsevier-collaborates-with-edx$', 'static_template_view.views.render',
{'template': 'press_releases/Elsevier_collaborates_with_edX.html'}, name="press/elsevier-collaborates-with-edx"),
+ url(r'^press/ut-joins-edx$', 'static_template_view.views.render',
+ {'template': 'press_releases/UT_joins_edX.html'}, name="press/ut-joins-edx"),
# Should this always update to point to the latest press release?
From 516daa47107e5af664ddf9c5e37bb2ec0f6d48a1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20Andr=C3=A9s=20Rocha?=
Date: Mon, 15 Oct 2012 06:58:39 -0400
Subject: [PATCH 48/65] Converted FAQ template to unix line endings
---
lms/templates/static_templates/faq.html | 234 ++++++++++++------------
1 file changed, 117 insertions(+), 117 deletions(-)
diff --git a/lms/templates/static_templates/faq.html b/lms/templates/static_templates/faq.html
index 2a9df7c5fc..d0f2191b8f 100644
--- a/lms/templates/static_templates/faq.html
+++ b/lms/templates/static_templates/faq.html
@@ -1,117 +1,117 @@
-<%! from django.core.urlresolvers import reverse %>
-<%namespace name='static' file='../static_content.html'/>
-
-<%inherit file="../main.html" />
-
-<%block name="title">FAQ%block>
-
-
-
-
-
-
-
Organization
-
-
What is edX?
-
-
Massachusetts Institute of Technology (MIT) and Harvard University that offers online learning to on-campus students and to millions of people around the world. To do so, edX is building an open-source online learning platform and hosts an online web portal at www.edx.org for online education.
-
EdX currently offers HarvardX, MITx and BerkeleyX classes online for free. Beginning in Summer 2013, edX will also offer UTx (University of Texas) classes online for free. The University of Texas System includes nine universities and six health institutions. The edX institutions aim to extend their collective reach to build a global community of online students. Along with offering online courses, the three universities undertake research on how students learn and how technology can transform learning – both on-campus and online throughout the world.
-
-
-
What are "X Universities"?
-
Harvard, MIT and UC Berkeley, as the first universities whose courses are delivered on the edX website, are "X Universities." The three institutions will work collaboratively to establish the "X University" Consortium, whose membership will expand to include additional "X Universities" as soon as possible. Each member of the consortium will offer courses on the edX platform as an "X University." The gathering of many universities’ educational content together on one site will enable learners worldwide to access the course content of any participating university from a single website, and to use a set of online educational tools shared by all participating universities.
-
-
-
Why is UC Berkeley joining edX?
-
Like Harvard and MIT, UC Berkeley seeks to transform education in quality, efficiency and scale through technology and research, for the benefit of campus-based students and the global community of online learners.
-
UC Berkeley also shares the edX commitment to the not-for-profit and open-platform model as a way to enhance human fulfillment worldwide.
-
-
-
What will UC Berkeley's direct participation entail?
-
UC Berkeley will begin by offering two courses on edX in Fall 2012, and will collaborate on the development of the technology platform. We will explore, experiment and innovate together.
-
UC Berkeley will also serve as the inaugural chair of the "X University" Consortium for an initial 5 year period. As Chair, UC Berkeley will participate on the edX Board on behalf of the X Universities.
-
-
-
Why is The University of Texas System joining edX?
-
Joining edX not only allows UT faculty to showcase their work on a global stage, but also provides UT students the opportunity to take classes from their choice of UT institutions, as well as MIT, Harvard, UC Berkeley and future “X” Universities.
-
The UT System closely examined all the alternatives and determined that edX offered the best fit in terms of alignment of mission, platform and revenue model. The strength and reputation of the partner institutions – MIT, Harvard and UC Berkeley – was also a huge consideration. EdX is committed to both blended and online learning and to a non-profit, open source model. It is also governed by a board of academics with a commitment to excellence in learning.
-
-
-
What will The UT System’s direct participation entail?
-
The UT System will begin by offering one course on edX from The University of Texas at Austin in Summer 2013, and four courses in Fall 2013, likely at least one of those courses from one of its health institutions. The UT System is also making a $5 million investment in the edX platform. We will explore, experiment and innovate together.
-
-
-
Will edX be adding additional X Universities?
-
More than 140 institutions from around the world have expressed interest in collaborating with edX since Harvard and MIT announced its creation in May. EdX is focused above all on quality and developing the best not-for-profit model for online education. In addition to providing online courses on the edX platform, the “X University” Consortium will be a forum in which members can share experiences around online learning. Harvard, MIT, UC Berkeley and the UT System will work collaboratively to establish the “X University” Consortium, whose membership will expand to include additional “X Universities” as soon as possible. Each member of the consortium will offer courses on the edX platform as an “X University.” The gathering of many universities’ educational content together on one site will enable learners worldwide to access the course content of any participating university from a single website, and to use a set of online educational tools shared by all participating universities.
-
EdX will actively explore the addition of other institutions from around the world to the edX platform, and we look forward to adding more “X Universities” as capacity increases.
-
-
-
-
-
Students
-
-
Who can take edX courses? Will there be an admissions process?
-
EdX will be available to anyone in the world with an internet connection, and in general, there will not be an admissions process.
-
-
-
Will certificates be awarded?
-
Yes. Online learners who demonstrate mastery of subjects can earn a certificate of completion. Certificates will be issued by edX under the name of the underlying "X University" from where the course originated, i.e. HarvardX, MITx or BerkeleyX. For the courses in Fall 2012, those certificates will be free. There is a plan to charge a modest fee for certificates in the future.
-
-
-
What will the scope of the online courses be? How many? Which faculty?
-
Our goal is to offer a wide variety of courses across disciplines. There are currently seven courses offered for Fall 2012.
-
-
-
Who is the learner? Domestic or international? Age range?
-
Improving teaching and learning for students on our campuses is one of our primary goals. Beyond that, we don’t have a target group of potential learners, as the goal is to make these courses available to anyone in the world – from any demographic – who has interest in advancing their own knowledge. The only requirement is to have a computer with an internet connection. More than 150,000 students from over 160 countries registered for MITx's first course, 6.002x: Circuits and Electronics. The age range of students certified in this course was from 14 to 74 years-old.
-
-
-
Will participating universities’ standards apply to all courses offered on the edX platform?
-
Yes: the reach changes exponentially, but the rigor remains the same.
-
-
-
How do you intend to test whether this approach is improving learning?
-
Edx institutions have assembled faculty members who will collect and analyze data to assess results and the impact edX is having on learning.
-
-
-
How may I apply to study with edX?
-
Simply complete the online signup form. Enrolling will create your unique student record in the edX database, allow you to register for classes, and to receive a certificate on successful completion.
-
-
-
How may another university participate in edX?
-
If you are from a university interested in discussing edX, please email university@edx.org
-
-
-
-
-
Technology Platform
-
-
What technology will edX use?
-
The edX open-source online learning platform will feature interactive learning designed specifically for the web. Features will include: self-paced learning, online discussion groups, wiki-based collaborative learning, assessment of learning as a student progresses through a course, and online laboratories and other interactive learning tools. The platform will also serve as a laboratory from which data will be gathered to better understand how students learn. Because it is open source, the platform will be continuously improved by a worldwide community of collaborators, with new features added as needs arise.
-
The first version of the technology was used in the first MITx course, 6.002x Circuits and Electronics, which launched in Spring, 2012.
-
-
-
How is this different from what other universities are doing online?
-
EdX is a not-for-profit enterprise built upon the shared educational missions of its founding partners, Harvard University and MIT. The edX platform will be available as open source. Also, a primary goal of edX is to improve teaching and learning on campus by experimenting with blended models of learning and by supporting faculty in conducting significant research on how students learn.
Massachusetts Institute of Technology (MIT) and Harvard University that offers online learning to on-campus students and to millions of people around the world. To do so, edX is building an open-source online learning platform and hosts an online web portal at www.edx.org for online education.
+
EdX currently offers HarvardX, MITx and BerkeleyX classes online for free. Beginning in Summer 2013, edX will also offer UTx (University of Texas) classes online for free. The University of Texas System includes nine universities and six health institutions. The edX institutions aim to extend their collective reach to build a global community of online students. Along with offering online courses, the three universities undertake research on how students learn and how technology can transform learning – both on-campus and online throughout the world.
+
+
+
What are "X Universities"?
+
Harvard, MIT and UC Berkeley, as the first universities whose courses are delivered on the edX website, are "X Universities." The three institutions will work collaboratively to establish the "X University" Consortium, whose membership will expand to include additional "X Universities" as soon as possible. Each member of the consortium will offer courses on the edX platform as an "X University." The gathering of many universities’ educational content together on one site will enable learners worldwide to access the course content of any participating university from a single website, and to use a set of online educational tools shared by all participating universities.
+
+
+
Why is UC Berkeley joining edX?
+
Like Harvard and MIT, UC Berkeley seeks to transform education in quality, efficiency and scale through technology and research, for the benefit of campus-based students and the global community of online learners.
+
UC Berkeley also shares the edX commitment to the not-for-profit and open-platform model as a way to enhance human fulfillment worldwide.
+
+
+
What will UC Berkeley's direct participation entail?
+
UC Berkeley will begin by offering two courses on edX in Fall 2012, and will collaborate on the development of the technology platform. We will explore, experiment and innovate together.
+
UC Berkeley will also serve as the inaugural chair of the "X University" Consortium for an initial 5 year period. As Chair, UC Berkeley will participate on the edX Board on behalf of the X Universities.
+
+
+
Why is The University of Texas System joining edX?
+
Joining edX not only allows UT faculty to showcase their work on a global stage, but also provides UT students the opportunity to take classes from their choice of UT institutions, as well as MIT, Harvard, UC Berkeley and future “X” Universities.
+
The UT System closely examined all the alternatives and determined that edX offered the best fit in terms of alignment of mission, platform and revenue model. The strength and reputation of the partner institutions – MIT, Harvard and UC Berkeley – was also a huge consideration. EdX is committed to both blended and online learning and to a non-profit, open source model. It is also governed by a board of academics with a commitment to excellence in learning.
+
+
+
What will The UT System’s direct participation entail?
+
The UT System will begin by offering one course on edX from The University of Texas at Austin in Summer 2013, and four courses in Fall 2013, likely at least one of those courses from one of its health institutions. The UT System is also making a $5 million investment in the edX platform. We will explore, experiment and innovate together.
+
+
+
Will edX be adding additional X Universities?
+
More than 140 institutions from around the world have expressed interest in collaborating with edX since Harvard and MIT announced its creation in May. EdX is focused above all on quality and developing the best not-for-profit model for online education. In addition to providing online courses on the edX platform, the “X University” Consortium will be a forum in which members can share experiences around online learning. Harvard, MIT, UC Berkeley and the UT System will work collaboratively to establish the “X University” Consortium, whose membership will expand to include additional “X Universities” as soon as possible. Each member of the consortium will offer courses on the edX platform as an “X University.” The gathering of many universities’ educational content together on one site will enable learners worldwide to access the course content of any participating university from a single website, and to use a set of online educational tools shared by all participating universities.
+
EdX will actively explore the addition of other institutions from around the world to the edX platform, and we look forward to adding more “X Universities” as capacity increases.
+
+
+
+
+
Students
+
+
Who can take edX courses? Will there be an admissions process?
+
EdX will be available to anyone in the world with an internet connection, and in general, there will not be an admissions process.
+
+
+
Will certificates be awarded?
+
Yes. Online learners who demonstrate mastery of subjects can earn a certificate of completion. Certificates will be issued by edX under the name of the underlying "X University" from where the course originated, i.e. HarvardX, MITx or BerkeleyX. For the courses in Fall 2012, those certificates will be free. There is a plan to charge a modest fee for certificates in the future.
+
+
+
What will the scope of the online courses be? How many? Which faculty?
+
Our goal is to offer a wide variety of courses across disciplines. There are currently seven courses offered for Fall 2012.
+
+
+
Who is the learner? Domestic or international? Age range?
+
Improving teaching and learning for students on our campuses is one of our primary goals. Beyond that, we don’t have a target group of potential learners, as the goal is to make these courses available to anyone in the world – from any demographic – who has interest in advancing their own knowledge. The only requirement is to have a computer with an internet connection. More than 150,000 students from over 160 countries registered for MITx's first course, 6.002x: Circuits and Electronics. The age range of students certified in this course was from 14 to 74 years-old.
+
+
+
Will participating universities’ standards apply to all courses offered on the edX platform?
+
Yes: the reach changes exponentially, but the rigor remains the same.
+
+
+
How do you intend to test whether this approach is improving learning?
+
Edx institutions have assembled faculty members who will collect and analyze data to assess results and the impact edX is having on learning.
+
+
+
How may I apply to study with edX?
+
Simply complete the online signup form. Enrolling will create your unique student record in the edX database, allow you to register for classes, and to receive a certificate on successful completion.
+
+
+
How may another university participate in edX?
+
If you are from a university interested in discussing edX, please email university@edx.org
+
+
+
+
+
Technology Platform
+
+
What technology will edX use?
+
The edX open-source online learning platform will feature interactive learning designed specifically for the web. Features will include: self-paced learning, online discussion groups, wiki-based collaborative learning, assessment of learning as a student progresses through a course, and online laboratories and other interactive learning tools. The platform will also serve as a laboratory from which data will be gathered to better understand how students learn. Because it is open source, the platform will be continuously improved by a worldwide community of collaborators, with new features added as needs arise.
+
The first version of the technology was used in the first MITx course, 6.002x Circuits and Electronics, which launched in Spring, 2012.
+
+
+
How is this different from what other universities are doing online?
+
EdX is a not-for-profit enterprise built upon the shared educational missions of its founding partners, Harvard University and MIT. The edX platform will be available as open source. Also, a primary goal of edX is to improve teaching and learning on campus by experimenting with blended models of learning and by supporting faculty in conducting significant research on how students learn.
Massachusetts Institute of Technology (MIT) and Harvard University that offers online learning to on-campus students and to millions of people around the world. To do so, edX is building an open-source online learning platform and hosts an online web portal at www.edx.org for online education.
+
edX is a not-for-profit enterprise of its founding partners, the Massachusetts Institute of Technology (MIT) and Harvard University that offers online learning to on-campus students and to millions of people around the world. To do so, edX is building an open-source online learning platform and hosts an online web portal at www.edx.org for online education.
EdX currently offers HarvardX, MITx and BerkeleyX classes online for free. Beginning in Summer 2013, edX will also offer UTx (University of Texas) classes online for free. The University of Texas System includes nine universities and six health institutions. The edX institutions aim to extend their collective reach to build a global community of online students. Along with offering online courses, the three universities undertake research on how students learn and how technology can transform learning – both on-campus and online throughout the world.