Skip to content

Commit d421cdd

Browse files
authored
Merge pull request #1197 from ccnmtl/ERD-452-sim1
Sim one refactor
2 parents 3989356 + 01c74f1 commit d421cdd

File tree

7 files changed

+89
-115
lines changed

7 files changed

+89
-115
lines changed

media/js/src/simulations/simulation1/hypothesisTest.jsx

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react';
22
import { Katex } from '../../utils/katexComponent';
33
import PropTypes from 'prop-types';
44
import { Quiz } from './quiz';
5-
import axios from 'axios';
5+
import { authedFetch } from '../../utils/utils';
66

77
export const HypothesisTest = ({
88
selectedAltHypothesis, appRvalue, tvalue, n,
@@ -28,7 +28,7 @@ export const HypothesisTest = ({
2828
hypothesisTest = 'value_right';
2929
break;
3030
case 'C':
31-
hypothesis = '\\Eta_1: {\\beta_1}~{\\lt}~0';
31+
hypothesis = '\\Eta_1: {\\beta_1}~{\\lt}~0';
3232
hypothesisTest = 'value_left';
3333
break;
3434
default:
@@ -55,12 +55,13 @@ export const HypothesisTest = ({
5555
tvalueString = '-Infinity';
5656
}
5757

58-
const response = await axios.post('/calculate_pvalue/', {
58+
const response = await authedFetch('/calculate_pvalue/', 'POST', {
5959
n,
6060
tvalue: tvalueString
6161
});
6262

63-
setPvalues(response.data);
63+
const data = await response.json();
64+
setPvalues(data);
6465
} catch (error) {
6566
console.error('Error calculating pvalue:', error);
6667
}
@@ -73,7 +74,7 @@ export const HypothesisTest = ({
7374
useEffect(() => {
7475
calculatePvalue();
7576
document.getElementById('hypothesis-test')
76-
.scrollIntoView({ behavior: 'smooth'});
77+
.scrollIntoView({ behavior: 'smooth' });
7778
if (isRedo) {
7879
setAlphaSelected(false);
7980
setLockControls(false);
@@ -108,7 +109,7 @@ export const HypothesisTest = ({
108109
<div className="katex-block border-bottom
109110
border-white">
110111
<Katex tex={
111-
// eslint-disable-next-line max-len
112+
// eslint-disable-next-line max-len
112113
`\\text{corr}(x,y) = ${appRvalue.toFixed(3)}`
113114
} />
114115
</div>
@@ -132,16 +133,16 @@ export const HypothesisTest = ({
132133
<li key={key}>
133134
<input
134135
type="radio"
135-
id={`significance${val*100}`}
136+
id={`significance${val * 100}`}
136137
name="significance"
137138
value={val}
138139
checked={alpha === val}
139140
onChange={handleAlphaChange}
140141
disabled={alphaSelected}
141142
/>
142-
<label htmlFor={`significance${val*100}`}
143+
<label htmlFor={`significance${val * 100}`}
143144
className="mx-1">
144-
{`${val*100}% (${val.toFixed(2)})`}
145+
{`${val * 100}% (${val.toFixed(2)})`}
145146
</label>
146147
</li>
147148
))}
@@ -184,7 +185,6 @@ HypothesisTest.propTypes = {
184185
selectedAltHypothesis: PropTypes.string,
185186
appRvalue: PropTypes.number.isRequired,
186187
tvalue: PropTypes.number.isRequired,
187-
coursePK: PropTypes.number,
188188
n: PropTypes.number.isRequired,
189189
completedChoices: PropTypes.array.isRequired,
190190
submissionId: PropTypes.number.isRequired,

media/js/src/simulations/simulation1/quiz.jsx

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React, { useState, useEffect } from 'react';
22
import PropTypes from 'prop-types';
3-
import axios from 'axios';
3+
import { authedFetch } from '../../utils/utils';
44
import { PvalueComponent } from './pvalueComponent.jsx';
55
import { CriticalValue } from './criticalValue.jsx';
66

@@ -20,10 +20,11 @@ export const Quiz = ({
2020
// Critical Value Logic
2121
const calculateCriticalValue = async() => {
2222
try {
23-
const response = await axios.post('/calculate_critical/',
24-
{n, alpha});
23+
const response = await authedFetch('/calculate_critical/',
24+
'POST', { n, alpha });
2525

26-
setCriticalValues(response.data);
26+
const data = await response.json();
27+
setCriticalValues(data);
2728

2829
} catch (error) {
2930
console.error('Error calculating critical value:', error);
@@ -44,14 +45,14 @@ export const Quiz = ({
4445
useEffect(() => {
4546
if (hypothesisTest1validate) {
4647
document.getElementById('criticalvalue')
47-
.scrollIntoView({ behavior: 'smooth'});
48+
.scrollIntoView({ behavior: 'smooth' });
4849
}
4950
}, [hypothesisTest1validate]);
5051

5152
useEffect(() => {
5253
calculateCriticalValue();
5354
document.getElementById('quiz')
54-
.scrollIntoView({ behavior: 'smooth'});
55+
.scrollIntoView({ behavior: 'smooth' });
5556
}, []);
5657

5758
return (
@@ -92,7 +93,7 @@ export const Quiz = ({
9293
<div className="row text-right">
9394
<div className="col-6 text-center">
9495
{!isRedo && (
95-
<button className= "btn btn-sm btn-success"
96+
<button className="btn btn-sm btn-success"
9697
id="redo"
9798
disabled={isHypothesisCompleted}
9899
onClick={handleRedo}>
@@ -101,11 +102,11 @@ export const Quiz = ({
101102
)}
102103
</div>
103104
<div className="col-6 text-left">
104-
<button className= "btn btn-sm btn-success"
105+
<button className="btn btn-sm btn-success"
105106
id="proceed"
106107
disabled={isHypothesisCompleted}
107108
onClick={handleOnComplete}>
108-
Let&rsquo;s move on &raquo;
109+
Let&rsquo;s move on &raquo;
109110
</button>
110111
</div>
111112
</div>

media/js/src/simulations/simulation1/scatterPlot.jsx

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import React, { useState, useEffect } from 'react';
22
import Plot from 'react-plotly.js';
3-
import axios from 'axios';
43
import PropTypes from 'prop-types';
5-
import { seededRandom } from '../../utils/utils';
4+
import { authedFetch, seededRandom } from '../../utils/utils';
65

76

87
export const ScatterPlot = ({ N, yCorrelation, setAppRvalue,
@@ -62,14 +61,17 @@ export const ScatterPlot = ({ N, yCorrelation, setAppRvalue,
6261

6362
if (plotType === '3d' && z_values[0]) {
6463

65-
const response = await axios.post('/calc_multi_regression/', {
66-
x1_values: x_values,
67-
x2_values: y_values,
68-
y_values: z_values,
69-
});
64+
const response = await authedFetch('/calc_multi_regression/',
65+
'POST', {
66+
x1_values: x_values,
67+
x2_values: y_values,
68+
y_values: z_values,
69+
});
70+
71+
const responseData = await response.json();
7072

7173
const { slope_x1, slope_x2, intercept,
72-
stderr, rvalue } = response.data;
74+
stderr, rvalue } = responseData;
7375
setSlopes([slope_x1, slope_x2]);
7476
setIntercept3d(intercept);
7577
setStderrs(stderr);
@@ -94,11 +96,14 @@ export const ScatterPlot = ({ N, yCorrelation, setAppRvalue,
9496
});
9597

9698
} else {
97-
const response = await axios.post('/calc_regression/', {
98-
x_values,
99-
y_values,
100-
});
101-
const { slope, intercept, stderr, rvalue } = response.data;
99+
const response = await authedFetch('/calc_regression/',
100+
'POST', {
101+
x_values,
102+
y_values,
103+
});
104+
105+
const responseData = await response.json();
106+
const { slope, intercept, stderr, rvalue } = responseData;
102107

103108
setSlope(slope);
104109
setIntercept(intercept);

media/js/src/simulations/simulation1/simulationOne.jsx

Lines changed: 26 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import React, { useState, useEffect } from 'react';
22
import { ScatterPlot } from './scatterPlot';
33
import { Katex } from '../../utils/katexComponent';
4-
import { authedFetch, fetchQuizData } from '../../utils/utils';
4+
import {
5+
fetchQuizData, createSubmission, getCoursePk
6+
} from '../../utils/utils';
57
import { SimulationOneQuiz } from './simulationOneQuiz';
68
import { SimIntro } from './simulationIntro';
79
import { GraphCoefficients } from './graphCoefficientsSection';
@@ -11,9 +13,7 @@ import { CriticalValueModal } from './modalCV';
1113
import { GlossaryModal } from './modalGlossary';
1214

1315

14-
const simContainer = document.querySelector('#react-root');
15-
const coursePk =
16-
simContainer ? Number(simContainer.dataset.course) : '';
16+
const coursePk = getCoursePk();
1717

1818
export const SimulationOne = () => {
1919
const [N, setN] = useState(50);
@@ -41,7 +41,7 @@ export const SimulationOne = () => {
4141
const [lockControls, setLockControls] = useState(false);
4242

4343

44-
const createSubmission = async() => {
44+
const handleCreateSub = async() => {
4545
// Define the data to be saved based on the plot type
4646
const data = plotType === '2d' ? {
4747
N, yCorrelation, slope, intercept, stderror, appRvalue,
@@ -52,52 +52,24 @@ export const SimulationOne = () => {
5252
appRvalue3d, intercept3d
5353
};
5454

55-
const payload = {
56-
simulation: 1,
57-
data: data,
58-
submission_id: submissionId
59-
};
55+
try {
56+
const newSubmissionId = await createSubmission(
57+
coursePk,
58+
submissionId,
59+
1,
60+
data
61+
);
6062

61-
const url = `/course/${coursePk}/api/create-sub/`;
62-
const method = submissionId ? 'PUT' : 'POST';
63+
setSubmissionId(newSubmissionId);
6364

64-
return authedFetch(url, method, payload)
65-
.then(response => {
66-
if (response.status === 201 || response.status === 200) {
67-
return response.json();
68-
} else {
69-
throw `Error (${response.status}) ${response.statusText}`;
70-
}
71-
})
72-
.then(data => {
73-
if (plotType === '2d') {
74-
setStartQuiz(true);
75-
} else {
76-
setStartQuiz2(true);
77-
}
78-
setSubmissionId(data.submission_id);
79-
return data;
80-
})
81-
.catch(error => {
82-
console.error('Error creating submission', error);
83-
throw error;
84-
});
85-
};
86-
87-
const handleCreateSub = async() => {
88-
try {
89-
if(!submissionId) {
90-
await createSubmission();
65+
if (plotType === '2d') {
66+
setStartQuiz(true);
9167
} else {
92-
if (plotType === '2d') {
93-
setStartQuiz(true);
94-
} else {
95-
setStartQuiz2(true);
96-
}
68+
setStartQuiz2(true);
9769
}
98-
await createSubmission();
9970
} catch (error) {
100-
alert('Failed to save graph and submission.', error);
71+
alert('Failed to save graph and submission.');
72+
console.error(error);
10173
}
10274
};
10375

@@ -130,7 +102,7 @@ export const SimulationOne = () => {
130102
setSelectedAltHypothesis(null);
131103
setLockControls(false);
132104
document.getElementById('learningGoal')
133-
.scrollIntoView({ behavior: 'smooth'});
105+
.scrollIntoView({ behavior: 'smooth' });
134106
};
135107

136108
let tvalue;
@@ -179,19 +151,19 @@ export const SimulationOne = () => {
179151
<div className="simulation__step-content">
180152
{plotType === '2d' && (
181153
<p>Let&rsquo;s start setting up the parameters
182-
to generate random data points for your
183-
graph.</p>
154+
to generate random data points for your
155+
graph.</p>
184156
)}
185157
{plotType === '3d' && (
186158
<p>Let&rsquo;s introduce another variable to
187-
your graph, <Katex tex={'x_2'}
188-
className="katex-inline"/> and <Katex
159+
your graph, <Katex tex={'x_2'}
160+
className="katex-inline" /> and <Katex
189161
tex={'\\text{corr}(x_1,x_2)'}
190162
className="katex-inline" />.
191-
<Katex tex={'n'} className="katex-inline"/> and
163+
<Katex tex={'n'} className="katex-inline" /> and
192164
<Katex tex={'\\text{corr}(x_1,y)'}
193165
className="katex-inline" /> are values from
194-
the previous section.</p>
166+
the previous section.</p>
195167
)}
196168
<div className="mt-4 d-flex">
197169
<label htmlFor="nSampleSize"
@@ -225,7 +197,7 @@ export const SimulationOne = () => {
225197
<div className="mt-4">
226198
<label htmlFor="correlation"
227199
className="h2 form-label">Correlation
228-
coefficient <Katex
200+
coefficient <Katex
229201
tex={'\\text{corr}(x,y)'}
230202
className="katex-inline" />:
231203
</label>

0 commit comments

Comments
 (0)