Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add hypothetical rating change feature #91

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 71 additions & 1 deletion api/routers/contest_records.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ async def contest_records_user(
class QueryOfPredictedRating(BaseModel):
contest_name: str
users: conlist(UserKey, min_length=1, max_length=26)
hypothetical_entries: Optional[List[UserKey]] = None


class ResultOfPredictedRating(BaseModel):
Expand Down Expand Up @@ -158,7 +159,22 @@ async def predicted_rating(
)
for user in query.users
)
return await asyncio.gather(*tasks)
results = await asyncio.gather(*tasks)

if query.hypothetical_entries:
hypothetical_tasks = (
ContestRecordPredict.find_one(
ContestRecordPredict.contest_name == query.contest_name,
ContestRecordPredict.data_region == entry.data_region,
ContestRecordPredict.username == entry.username,
projection_model=ResultOfPredictedRating,
)
for entry in query.hypothetical_entries
)
hypothetical_results = await asyncio.gather(*hypothetical_tasks)
results.extend(hypothetical_results)

return results


class QueryOfRealTimeRank(BaseModel):
Expand Down Expand Up @@ -188,3 +204,57 @@ async def real_time_rank(
ContestRecordArchive.username == query.user.username,
projection_model=ResultOfRealTimeRank,
)


class HypotheticalEntry(BaseModel):
contest_name: str
username: str
data_region: str
rank: int
score: int
finish_time: datetime


class HypotheticalRatingChange(BaseModel):
old_rating: float
new_rating: float
delta_rating: float


@router.post("/hypothetical-entry")
async def hypothetical_entry(
request: Request,
entry: HypotheticalEntry,
) -> HypotheticalRatingChange:
"""
Calculate rating change based on a hypothetical entry.
:param request:
:param entry:
:return:
"""
await check_contest_name(entry.contest_name)

# Fetch the user's current rating and attended contests count
user = await User.find_one(
User.username == entry.username,
User.data_region == entry.data_region,
)

if not user:
raise HTTPException(status_code=404, detail="User not found")

old_rating = user.rating
attended_contests_count = user.attendedContestsCount

# Calculate the new rating based on the hypothetical entry
rank_array = np.array([entry.rank])
rating_array = np.array([old_rating])
k_array = np.array([attended_contests_count])
delta_rating_array = elo_delta(rank_array, rating_array, k_array)
new_rating = old_rating + delta_rating_array[0]

return HypotheticalRatingChange(
old_rating=old_rating,
new_rating=new_rating,
delta_rating=delta_rating_array[0],
)
121 changes: 120 additions & 1 deletion client/src/pages/Predicted/PredictedContests.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";

import useSWR from "swr";
Expand Down Expand Up @@ -73,6 +73,118 @@ const ContestsTable = ({ contests }) => {
);
};

const HypotheticalEntryForm = ({ titleSlug, setHypotheticalResult }) => {
const [username, setUsername] = useState("");
const [dataRegion, setDataRegion] = useState("US");
const [rank, setRank] = useState("");
const [score, setScore] = useState("");
const [finishTime, setFinishTime] = useState("");

const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch(`${baseUrl}/contest-records/hypothetical-entry`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contest_name: titleSlug,
username,
data_region: dataRegion,
rank: parseInt(rank),
score: parseInt(score),
finish_time: new Date(finishTime).toISOString(),
}),
});
const result = await response.json();
setHypotheticalResult(result);
};

return (
<form onSubmit={handleSubmit} className="container mx-auto text-center">
<div className="form-control">
<label className="input-group">
<span>Username</span>
<input
type="text"
placeholder="Username"
className="input input-bordered"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Data Region</span>
<select
className="select select-bordered"
value={dataRegion}
onChange={(e) => setDataRegion(e.target.value)}
required
>
<option value="US">US</option>
<option value="CN">CN</option>
</select>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Rank</span>
<input
type="number"
placeholder="Rank"
className="input input-bordered"
value={rank}
onChange={(e) => setRank(e.target.value)}
required
/>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Score</span>
<input
type="number"
placeholder="Score"
className="input input-bordered"
value={score}
onChange={(e) => setScore(e.target.value)}
required
/>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Finish Time</span>
<input
type="datetime-local"
className="input input-bordered"
value={finishTime}
onChange={(e) => setFinishTime(e.target.value)}
required
/>
</label>
</div>
<button className="btn btn-primary" type="submit">
Calculate Hypothetical Rating Change
</button>
</form>
);
};

const HypotheticalResult = ({ result }) => {
if (!result) return null;

return (
<div className="container mx-auto text-center">
<h2>Hypothetical Rating Change</h2>
<p>Old Rating: {result.old_rating.toFixed(2)}</p>
<p>New Rating: {result.new_rating.toFixed(2)}</p>
<p>Delta Rating: {result.delta_rating.toFixed(2)}</p>
</div>
);
};

const PredictedContest = () => {
useEffect(() => {
document.title = "Predicted Contests";
Expand Down Expand Up @@ -101,6 +213,8 @@ const PredictedContest = () => {
);
// console.log(`totalCount=${totalCount} pageNum=${pageNum}`);

const [hypotheticalResult, setHypotheticalResult] = useState(null);

if (!contests || isLoading)
return (
<div className="grid h-screen place-items-center ">
Expand Down Expand Up @@ -132,6 +246,11 @@ const PredictedContest = () => {
pageURL={""}
pageSize={pageSize}
/>
<HypotheticalEntryForm
titleSlug={contests[0].titleSlug}
setHypotheticalResult={setHypotheticalResult}
/>
<HypotheticalResult result={hypotheticalResult} />
</>
);
};
Expand Down
119 changes: 119 additions & 0 deletions client/src/pages/Predicted/PredictedRecords.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,118 @@ const PredictedRecordsTable = ({ predictedRecords, setUser }) => {
);
};

const HypotheticalEntryForm = ({ titleSlug, setHypotheticalResult }) => {
const [username, setUsername] = useState("");
const [dataRegion, setDataRegion] = useState("US");
const [rank, setRank] = useState("");
const [score, setScore] = useState("");
const [finishTime, setFinishTime] = useState("");

const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch(`${baseUrl}/contest-records/hypothetical-entry`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contest_name: titleSlug,
username,
data_region: dataRegion,
rank: parseInt(rank),
score: parseInt(score),
finish_time: new Date(finishTime).toISOString(),
}),
});
const result = await response.json();
setHypotheticalResult(result);
};

return (
<form onSubmit={handleSubmit} className="container mx-auto text-center">
<div className="form-control">
<label className="input-group">
<span>Username</span>
<input
type="text"
placeholder="Username"
className="input input-bordered"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Data Region</span>
<select
className="select select-bordered"
value={dataRegion}
onChange={(e) => setDataRegion(e.target.value)}
required
>
<option value="US">US</option>
<option value="CN">CN</option>
</select>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Rank</span>
<input
type="number"
placeholder="Rank"
className="input input-bordered"
value={rank}
onChange={(e) => setRank(e.target.value)}
required
/>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Score</span>
<input
type="number"
placeholder="Score"
className="input input-bordered"
value={score}
onChange={(e) => setScore(e.target.value)}
required
/>
</label>
</div>
<div className="form-control">
<label className="input-group">
<span>Finish Time</span>
<input
type="datetime-local"
className="input input-bordered"
value={finishTime}
onChange={(e) => setFinishTime(e.target.value)}
required
/>
</label>
</div>
<button className="btn btn-primary" type="submit">
Calculate Hypothetical Rating Change
</button>
</form>
);
};

const HypotheticalResult = ({ result }) => {
if (!result) return null;

return (
<div className="container mx-auto text-center">
<h2>Hypothetical Rating Change</h2>
<p>Old Rating: {result.old_rating.toFixed(2)}</p>
<p>New Rating: {result.new_rating.toFixed(2)}</p>
<p>Delta Rating: {result.delta_rating.toFixed(2)}</p>
</div>
);
};

const PredictedRecords = () => {
const pageSize = 25; // hard code `pageSize` temporarily

Expand All @@ -178,6 +290,7 @@ const PredictedRecords = () => {
const [predictedRecordsURL, setPredictedRecordsURL] = useState(null);
const [isSearching, setIsSearching] = useState(false);
const [user, setUser] = useState(null);
const [hypotheticalResult, setHypotheticalResult] = useState(null);

useEffect(() => {
document.title = `${titleSlug} 🔮`;
Expand Down Expand Up @@ -303,6 +416,12 @@ const PredictedRecords = () => {
/>
)}

<HypotheticalEntryForm
titleSlug={titleSlug}
setHypotheticalResult={setHypotheticalResult}
/>
<HypotheticalResult result={hypotheticalResult} />

<input type="checkbox" id="my-modal-4" className="modal-toggle" />
<label htmlFor="my-modal-4" className="modal cursor-pointer">
<label className="modal-box relative" htmlFor="">
Expand Down