Skip to content

Commit

Permalink
exit rate table and page added
Browse files Browse the repository at this point in the history
  • Loading branch information
amynickolls committed May 24, 2024
1 parent d45a670 commit c47068c
Show file tree
Hide file tree
Showing 9 changed files with 137 additions and 33 deletions.
26 changes: 21 additions & 5 deletions dm_regional_app/charts.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,12 @@ def prediction_chart(historic_data: PopulationStats, prediction: Prediction, **k
# pop start and end dates to visualise reference period
reference_start_date = kwargs.pop("reference_start_date")
reference_end_date = kwargs.pop("reference_end_date")
print(prediction.population)

# dataframe containing total children in prediction
df = prediction.population.unstack().reset_index()
print(df)

df.columns = ["from", "date", "forecast"]
print(df)
df = df[df["from"].apply(lambda x: "Not in care" in x) == False]
print(df)
df = df[["date", "forecast"]].groupby(by="date").sum().reset_index()
df["date"] = pd.to_datetime(df["date"]).dt.date

Expand Down Expand Up @@ -137,8 +134,10 @@ def transition_rate_table(data):
df["To"] = df["to"]
df["From"] = df["from"]
df.set_index(["from", "to"], inplace=True)
# df = df[df["To"].apply(lambda x: "Not in care" in x) == False]
df = df[df["To"].apply(lambda x: "Not in care" in x) == False]
df = df.round(4)
df = df.sort_values(by=["From"])
df = df[df["From"] != df["To"]]
df["From"] = df["From"].mask(df["From"].duplicated(), "")

to = df.pop("To")
Expand All @@ -149,3 +148,20 @@ def transition_rate_table(data):
df.columns = ["From", "To", "Transition rate"]

return df


def exit_rate_table(data):
df = data

df = df.reset_index()
df["From"] = df["from"]
df = df[df["to"].apply(lambda x: "Not in care" in x)]
df.set_index(["from", "to"], inplace=True)
df = df.round(4)

placement = df.pop("From")
df.insert(0, "From", placement)

df.columns = ["Placement", "Exit rate"]

return df
25 changes: 16 additions & 9 deletions dm_regional_app/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,18 +135,25 @@ def __init__(self, *args, **kwargs):
class DynamicForm(forms.Form):
def __init__(self, *args, **kwargs):
self.dataframe = kwargs.pop("dataframe", None)
super(DynamicForm, self).__init__(*args, **kwargs)
self.initialize_fields()
initial_data = kwargs.pop("initial_data", pd.Series())

rows = [Row(field, css_class="form-row") for field in self.fields]
self.helper = FormHelper()
self.helper.layout = Layout()
self.helper.layout.extend(rows)
self.helper.form_show_labels = False
super(DynamicForm, self).__init__(*args, **kwargs)
self.initialize_fields(initial_data)

def initialize_fields(self):
def initialize_fields(self, initial_data):
for index in self.dataframe.index:
self.fields[str(index)] = forms.FloatField(required=False)
field_name = str(index)
initial_value = None

# Attempt to get the initial value using the multiindex
try:
initial_value = initial_data.loc[index]
except KeyError:
initial_value = None

self.fields[field_name] = forms.FloatField(
required=False, initial=initial_value
)

def save(self):
transition = []
Expand Down
14 changes: 13 additions & 1 deletion dm_regional_app/templates/dm_regional_app/views/adjusted.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,19 @@ <h5 class="card-title">To make adjustments, you can view the table by:<br></h5>
</div>
<div class="collapse indent" id="leaving_care" data-bs-parent="#tables">
<div class="card card-body">
Leaving care chart placeholder
<div class="table-responsive">
<table id="efficiency-hub-table" class="table table-hover table-sm">
<thead>
{{ exit_rate_table | convert_data_frame_to_html_table_headers | safe}}
</thead>
<tbody>
{{exit_rate_table | convert_data_frame_to_html_table_rows | safe}}
</tbody>
</table>
<div class="d-flex bd-highlight mb-3">
<div class="ms-auto p-2 bd-highlight"><a class="btn btn-primary" href="exit_rates">Edit this table</a></div>
</div>
</div>
</div>
</div>
<div class="collapse" id="rate_change" data-bs-parent="#tables">
Expand Down
Empty file.
39 changes: 39 additions & 0 deletions dm_regional_app/templates/dm_regional_app/views/exit_rates.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{% extends "dm_regional_app/base.html" %}
{% load crispy_forms_tags %}
{% load table_tags %}


{% block content %}
<br>
<h1>Adjust transition rates</h1>
<br>
<p>You may want to edit the number of children per year entering a placement type to give a more accurate
picture of future forecasting or simply to explore what changes you may expect to see. <br><br>
Rates are applied to the daily population of children. For example, a rate of 0.5 from Fostering to Residential means
that each day, 50% of children in Fostering will move to Residential.<br>
</p>
<div class="table-responsive">
<table id="transition-rate" class="table table-hover">
<form method="post">
{% csrf_token %}
<thead>
{{ exit_rate_table | convert_data_frame_to_html_table_headers_form | safe}}
</thead>
<tbody>
{{ exit_rate_table | convert_data_frame_to_html_table_rows_form:form | safe}}
<tr>
<td colspan="2">
<div class="p-2 bd-highlight"><a class="btn btn-secondary" href="adjusted">Back</a></div>
</td>
<td>
<div class="p-2 bd-highlight"><button type="submit" class="btn btn-primary">Save</button></div>
</td>
</tr>
</tbody>
</form>
</table>
</div>

</div>

{% endblock %}
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ <h1>Adjust transition rates</h1>
{{transition_rate_table | convert_data_frame_to_html_table_rows_form:form | safe}}
<tr>
<td colspan="3">
Clear button placeholder
<div class="p-2 bd-highlight"><a class="btn btn-secondary" href="adjusted">Back</a></div>
</td>
<td>
<button type="submit" class="btn btn-primary">Save</button>
<div class="p-2 bd-highlight"><button type="submit" class="btn btn-primary">Save</button></div>
</td>
</tr>
</tbody>
Expand Down
5 changes: 2 additions & 3 deletions dm_regional_app/templatetags/table_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,19 @@ def convert_data_frame_to_html_table_headers_form(df):
html = "<tr>"
for value in df.columns:
html += f"<th><p>{value.capitalize()}</p></th>"
html += "<th><p>New rate</p></th></tr>"
html += "<th><p>Rate multiplication</p></th></tr>"
return html


def convert_data_frame_to_html_table_rows_form(df, form):
html = ""
for index, row in df.iterrows():
row_html = "<tr>"
for i, value in enumerate(row):
for value in row:
if isinstance(value, str):
row_html += f"<th><p>{value}</p></th>"
else:
row_html += f"<td><p>{value}</p></td>"
if i == 2: # Insert the input field in the fourth column
field_html = str(form[str(index)])
row_html += f"<td>{field_html}</td>"
row_html += "</tr>"
Expand Down
2 changes: 1 addition & 1 deletion dm_regional_app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@
path("router_handler", views.router_handler, name="router_handler"),
path("adjusted", views.adjusted, name="adjusted"),
path("transition_rates", views.transition_rates, name="transition_rates"),
path("edit_transition", views.edit_transition, name="edit_transition"),
path("exit_rates", views.exit_rates, name="exit_rates"),
]
55 changes: 43 additions & 12 deletions dm_regional_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from django.urls import reverse

from dm_regional_app.charts import (
exit_rate_table,
historic_chart,
prediction_chart,
transition_rate_table,
Expand Down Expand Up @@ -78,16 +79,13 @@ def router_handler(request):


@login_required
def edit_transition(request):
def exit_rates(request):
if "session_scenario_id" in request.session:
pk = request.session["session_scenario_id"]
session_scenario = get_object_or_404(SessionScenario, pk=pk)
# read data
datacontainer = read_data(source=settings.DATA_SOURCE)

if request.method == "POST":
something = "something"

historic_data = apply_filters(
datacontainer.enriched_view, session_scenario.historic_filters
)
Expand All @@ -97,10 +95,33 @@ def edit_transition(request):
data=historic_data, **session_scenario.prediction_parameters
)

exit_rates = exit_rate_table(prediction.transition_rates)

if request.method == "POST":
form = DynamicForm(
request.POST,
dataframe=prediction.transition_rates,
initial_data=session_scenario.adjusted_rates,
)
if form.is_valid():
data = form.save()
session_scenario.adjusted_rates = data
session_scenario.save()
return redirect("adjusted")

else:
form = DynamicForm(
initial_data=session_scenario.adjusted_rates,
dataframe=prediction.transition_rates,
)

return render(
request,
"dm_regional_app/views/edit_transition.html",
{},
"dm_regional_app/views/exit_rates.html",
{
"exit_rate_table": exit_rates,
"form": form,
},
)
else:
next_url_name = "router_handler"
Expand All @@ -126,24 +147,31 @@ def transition_rates(request):
data=historic_data, **session_scenario.prediction_parameters
)

tran_rate_table = transition_rate_table(prediction.transition_rates)
transition_rates = transition_rate_table(prediction.transition_rates)

if request.method == "POST":
form = DynamicForm(request.POST, dataframe=prediction.transition_rates)
form = DynamicForm(
request.POST,
dataframe=prediction.transition_rates,
initial_data=session_scenario.adjusted_rates,
)
if form.is_valid():
data = form.save()
session_scenario.adjusted_rates = data
session_scenario.save()
return redirect("adjusted")

else:
form = DynamicForm(dataframe=prediction.transition_rates)
form = DynamicForm(
initial_data=session_scenario.adjusted_rates,
dataframe=prediction.transition_rates,
)

return render(
request,
"dm_regional_app/views/transition_rates.html",
{
"transition_rate_table": tran_rate_table,
"transition_rate_table": transition_rates,
"form": form,
},
)
Expand Down Expand Up @@ -243,7 +271,9 @@ def adjusted(request):
stats, prediction, **session_scenario.prediction_parameters
)

tran_rate_table = transition_rate_table(prediction.transition_rates)
transition_rates = transition_rate_table(prediction.transition_rates)

exit_rates = exit_rate_table(prediction.transition_rates)

return render(
request,
Expand All @@ -253,7 +283,8 @@ def adjusted(request):
"historic_form": historic_form,
"chart": chart,
"empty_dataframe": empty_dataframe,
"transition_rate_table": tran_rate_table,
"transition_rate_table": transition_rates,
"exit_rate_table": exit_rates,
},
)
else:
Expand Down

0 comments on commit c47068c

Please sign in to comment.