Add Weekdaypicker in AutotuneFragment and ActionRunAutotune to allow Autotune on specific days of the week

This commit is contained in:
Philoul 2022-06-05 20:30:58 +02:00
parent 72d4feffc4
commit f69fb5d64b
7 changed files with 171 additions and 53 deletions

View file

@ -29,8 +29,10 @@ import info.nightscout.androidaps.data.ProfileSealed
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.extensions.runOnUiThread
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.general.automation.elements.InputWeekDay
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.MidnightTime
@ -67,6 +69,10 @@ class AutotuneFragment : DaggerFragment() {
private lateinit var profileStore: ProfileStore
private var profileName = ""
private lateinit var profile: ATProfile
private val days get() = autotunePlugin.days
private val daysBack get() = SafeParse.stringToInt(binding.tuneDays.text)
private val calcDays get() = autotunePlugin.calcDays(daysBack)
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
@ -79,6 +85,7 @@ class AutotuneFragment : DaggerFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sp.putBoolean(R.string.key_autotune_tune_insulin_curve, false) // put to false tune insulin curve
sp.putBoolean(R.string.key_autotune_additional_log, false) // put to false additional log
autotunePlugin.lastRun = sp.getLong(R.string.key_autotune_last_run, 0)
if (autotunePlugin.lastNbDays.isEmpty())
autotunePlugin.lastNbDays = sp.getInt(R.string.key_autotune_default_tune_days, 5).toString()
@ -88,12 +95,22 @@ class AutotuneFragment : DaggerFragment() {
profileFunction.getProfile()?.let { currentProfile ->
profile = ATProfile(profileStore.getSpecificProfile(profileName)?.let { ProfileSealed.Pure(it) } ?:currentProfile, LocalInsulin(""), injector)
}
days.addToLayout(binding.selectWeekDays)
days.view?.setOnWeekdaysChangeListener { i: Int, selected: Boolean ->
if (autotunePlugin.calculationRunning)
days.view?.setSelectedDays(days.getSelectedDays())
else {
days.set(InputWeekDay.DayOfWeek.fromCalendarInt(i), selected)
resetParam()
updateGui()
}
}
binding.tuneDays.setParams(
savedInstanceState?.getDouble("tunedays")
?: defaultValue, 1.0, 30.0, 1.0, DecimalFormat("0"), false, null, textWatcher)
binding.autotuneRun.setOnClickListener {
val daysBack = SafeParse.stringToInt(binding.tuneDays.text)
autotunePlugin.calculationRunning = true
autotunePlugin.lastNbDays = daysBack.toString()
log("Run Autotune $profileName, $daysBack days")
@ -102,6 +119,13 @@ class AutotuneFragment : DaggerFragment() {
}.start()
updateGui()
}
binding.showWeekDaysCheckbox.setOnCheckedChangeListener { _, isChecked ->
run {
binding.selectWeekDays.visibility = isChecked.toVisibility()
}
}
binding.profileList.onItemClickListener = AdapterView.OnItemClickListener { _, _, _, _ ->
if (!autotunePlugin.calculationRunning)
{
@ -263,6 +287,7 @@ class AutotuneFragment : DaggerFragment() {
updateGui()
}, { fabricPrivacy.logException(it) })
checkNewDay()
binding.selectWeekDays.visibility = binding.showWeekDaysCheckbox.isChecked.toVisibility()
binding.tuneDays.value = autotunePlugin.lastNbDays.toDouble()
updateGui()
}
@ -292,6 +317,7 @@ class AutotuneFragment : DaggerFragment() {
else {
binding.profileList.setText(profileList[0], false)
}
days.view?.setSelectedDays(days.getSelectedDays())
binding.autotuneRun.visibility = View.GONE
binding.autotuneCheckInputProfile.visibility = View.GONE
binding.autotuneCopylocal.visibility = View.GONE
@ -312,11 +338,13 @@ class AutotuneFragment : DaggerFragment() {
binding.autotuneCompare.visibility = View.VISIBLE
}
else -> {
if (profile.isValid)
if (profile.isValid && calcDays > 0)
binding.autotuneRun.visibility = View.VISIBLE
binding.autotuneCheckInputProfile.visibility = View.VISIBLE
}
}
binding.calcDays.text = calcDays.toString()
binding.calcDays.visibility = (daysBack != calcDays).toVisibility()
binding.tuneLastrun.text = dateUtil.dateAndTimeString(autotunePlugin.lastRun)
showResults()
}
@ -328,6 +356,7 @@ class AutotuneFragment : DaggerFragment() {
binding.tuneWarning.text = rh.gs(R.string.autotune_warning_after_run)
} else if (!runToday || autotunePlugin.result.isEmpty()) { //if new day reinit result, default days, warning and button's visibility
resetParam(!runToday)
days.setAll(true)
}
}

View file

@ -10,6 +10,7 @@ import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.automation.elements.InputWeekDay
import info.nightscout.androidaps.plugins.general.autotune.data.ATProfile
import info.nightscout.androidaps.plugins.general.autotune.data.PreppedGlucose
import info.nightscout.androidaps.plugins.general.autotune.events.EventAutotuneUpdateGui
@ -27,11 +28,10 @@ import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* adaptation from oref0 autotune started by philoul on 2020 (complete refactoring of AutotunePlugin initialised by Rumen Georgiev on 1/29/2018.)
/*
* adaptation from oref0 autotune developed by philoul on 2022 (complete refactoring of AutotunePlugin initialised by Rumen Georgiev on 1/29/2018.)
*
* TODO: replace Thread by Worker
* TODO: future version: Allow day of the week selection to tune specifics days (training days, working days, WE days)
*/
@Singleton
@ -72,9 +72,23 @@ class AutotunePlugin @Inject constructor(
@Volatile var tunedProfile: ATProfile? = null
private var preppedGlucose: PreppedGlucose? = null
private lateinit var profile: Profile
val days = InputWeekDay()
val autotuneStartHour: Int = 4
override fun aapsAutotune(daysBack: Int, autoSwitch: Boolean, profileToTune: String): String {
override fun aapsAutotune(daysBack: Int, autoSwitch: Boolean, profileToTune: String, weekDays: BooleanArray?): String {
weekDays?.let {
for (i in weekDays.indices)
days.weekdays[i] = weekDays[i]
}
val calcDays = calcDays(daysBack)
val sb = StringBuilder()
sb.append("Selected days: ")
var counter = 0
for (i in days.getSelectedDays()) {
if (counter++ > 0) sb.append(",")
sb.append(Objects.requireNonNull(InputWeekDay.DayOfWeek.fromCalendarInt(i)))
}
log(sb.toString())
tunedProfile = null
updateButtonVisibility = View.GONE
lastRunSuccess = false
@ -111,41 +125,56 @@ class AutotunePlugin @Inject constructor(
}
autotuneFS.exportPumpProfile(pumpProfile)
if (calcDays==0) {
result = rh.gs(R.string.autotune_error_more_days)
log(result)
calculationRunning = false
tunedProfile = null
autotuneFS.exportResult(result)
autotuneFS.exportLogAndZip(lastRun)
rxBus.send(EventAutotuneUpdateGui())
return result
}
var currentCalcDay = 0
for (i in 0 until daysBack) {
val from = starttime + i * 24 * 60 * 60 * 1000L // get 24 hours BG values from 4 AM to 4 AM next day
val to = from + 24 * 60 * 60 * 1000L
log("Tune day " + (i + 1) + " of " + daysBack)
tunedProfile?.let { tunedProfile ->
autotuneIob.initializeData(from, to, tunedProfile) //autotuneIob contains BG and Treatments data from history (<=> query for ns-treatments and ns-entries)
autotuneFS.exportEntries(autotuneIob) //<=> ns-entries.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine
autotuneFS.exportTreatments(autotuneIob) //<=> ns-treatments.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine (include treatments ,tempBasal and extended
preppedGlucose = autotunePrep.categorize(tunedProfile) //<=> autotune.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine
}
if (days.isSet(from)) {
currentCalcDay++
if (preppedGlucose == null || tunedProfile == null) {
result = rh.gs(R.string.autotune_error)
log(result)
calculationRunning = false
rxBus.send(EventAutotuneUpdateGui())
tunedProfile = null
autotuneFS.exportResult(result)
autotuneFS.exportLogAndZip(lastRun)
return result
log("Tune day " + (i + 1) + " of " + daysBack + " (" + currentCalcDay + " of " + calcDays + ")")
tunedProfile?.let { tunedProfile ->
autotuneIob.initializeData(from, to, tunedProfile) //autotuneIob contains BG and Treatments data from history (<=> query for ns-treatments and ns-entries)
autotuneFS.exportEntries(autotuneIob) //<=> ns-entries.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine
autotuneFS.exportTreatments(autotuneIob) //<=> ns-treatments.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine (include treatments ,tempBasal and extended
preppedGlucose = autotunePrep.categorize(tunedProfile) //<=> autotune.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine
}
if (preppedGlucose == null || tunedProfile == null) {
result = rh.gs(R.string.autotune_error)
log(result)
calculationRunning = false
rxBus.send(EventAutotuneUpdateGui())
tunedProfile = null
autotuneFS.exportResult(result)
autotuneFS.exportLogAndZip(lastRun)
return result
}
preppedGlucose?.let { preppedGlucose -> //preppedGlucose and tunedProfile should never be null here
autotuneFS.exportPreppedGlucose(preppedGlucose)
tunedProfile = autotuneCore.tuneAllTheThings(preppedGlucose, tunedProfile!!, pumpProfile)
}
// localInsulin = LocalInsulin("TunedInsulin", tunedProfile!!.peak, tunedProfile!!.dia) // Todo: Add tune Insulin option
autotuneFS.exportTunedProfile(tunedProfile!!) //<=> newprofile.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine
if (currentCalcDay < calcDays) {
log("Partial result for day ${i + 1}".trimIndent())
result = rh.gs(R.string.autotune_partial_result, currentCalcDay, calcDays)
rxBus.send(EventAutotuneUpdateGui())
}
logResult = showResults(tunedProfile, pumpProfile)
if (detailedLog)
autotuneFS.exportLog(lastRun, i + 1)
}
preppedGlucose?.let { preppedGlucose -> //preppedGlucose and tunedProfile should never be null here
autotuneFS.exportPreppedGlucose(preppedGlucose)
tunedProfile = autotuneCore.tuneAllTheThings(preppedGlucose, tunedProfile!!, pumpProfile)
}
// localInsulin = LocalInsulin("TunedInsulin", tunedProfile!!.peak, tunedProfile!!.dia) // Todo: Add tune Insulin option
autotuneFS.exportTunedProfile(tunedProfile!!) //<=> newprofile.yyyymmdd.json files exported for results compare with oref0 autotune on virtual machine
if (i < daysBack - 1) {
log("Partial result for day ${i + 1}".trimIndent())
result = rh.gs(R.string.autotune_partial_result, i + 1, daysBack)
rxBus.send(EventAutotuneUpdateGui())
}
logResult = showResults(tunedProfile, pumpProfile)
if (detailedLog)
autotuneFS.exportLog(lastRun, i + 1)
}
result = rh.gs(R.string.autotune_result, dateUtil.dateAndTimeString(lastRun))
if (!detailedLog)
@ -161,7 +190,8 @@ class AutotunePlugin @Inject constructor(
updateProfile(tunedP)
uel.log(
UserEntry.Action.STORE_PROFILE,
UserEntry.Sources.Autotune,
UserEntry.Sources.Automation,
rh.gs(R.string.autotune),
ValueWithUnit.SimpleString(tunedP.profilename)
)
updateButtonVisibility = View.GONE
@ -178,8 +208,8 @@ class AutotunePlugin @Inject constructor(
log("Profile Switch succeed ${tunedP.profilename}")
uel.log(
UserEntry.Action.PROFILE_SWITCH,
UserEntry.Sources.Autotune,
"Autotune AutoSwitch",
UserEntry.Sources.Automation,
rh.gs(R.string.autotune),
ValueWithUnit.SimpleString(tunedP.profilename))
}
rxBus.send(EventLocalProfileChanged())
@ -296,6 +326,17 @@ class AutotunePlugin @Inject constructor(
localProfilePlugin.storeSettings()
}
fun calcDays(daysBack:Int): Int {
var endTime = MidnightTime.calc(dateUtil.now()) + autotuneStartHour * 60 * 60 * 1000L
if (endTime > dateUtil.now()) endTime -= T.days(1).msecs() // Check if 4 AM is before now
val starttime = endTime - daysBack * T.days(1).msecs()
var result = 0
for (i in 0 until daysBack) {
if (days.isSet(starttime + i * T.days(1).msecs()))
result++
}
return result
}
private fun log(message: String) {
atLog("[Plugin] $message")

View file

@ -1,4 +1,5 @@
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
<androidx.core.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
@ -80,19 +81,57 @@
android:text="@string/autotune_tune_days"
android:textSize="14sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1">
<info.nightscout.androidaps.utils.ui.NumberPicker
android:id="@+id/tune_days"
<info.nightscout.androidaps.utils.ui.NumberPicker
android:id="@+id/tune_days"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:paddingStart="5dp"
android:paddingEnd="5dp"
app:customContentDescription="@string/careportal_newnstreatment_duration_label" />
<TextView
android:id="@+id/calc_days"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="start"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:text="(5)"
android:visibility="visible"
android:textSize="14sp" />
</LinearLayout>
<CheckBox
android:id="@+id/show_week_days_checkbox"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:checked="false"
android:contentDescription="@string/show_calculation"
android:drawableEnd="@drawable/ic_visibility" />
</LinearLayout>
<LinearLayout
android:id="@+id/select_week_days"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="2dp"
android:layout_weight="1"
android:paddingStart="5dp"
android:paddingEnd="5dp"
app:customContentDescription="@string/careportal_newnstreatment_duration_label" />
android:visibility="gone"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
</LinearLayout>

View file

@ -36,11 +36,12 @@
android:key="@string/key_autotune_circadian_ic_isf"
android:summary="@string/autotune_circadian_ic_isf_summary"
android:title="@string/autotune_circadian_ic_isf_title" />
<!-- Hide autotune_additional_log option
<SwitchPreference
android:defaultValue="false"
android:key="@string/key_autotune_additional_log"
android:summary="@string/autotune_additional_log_summary"
android:title="@string/autotune_additional_log_title" />
-->
</PreferenceCategory>
</androidx.preference.PreferenceScreen>

View file

@ -12,6 +12,7 @@ import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration
import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName
import info.nightscout.androidaps.plugins.general.automation.elements.InputWeekDay
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.queue.Callback
@ -28,11 +29,11 @@ class ActionRunAutotune(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var sp: SP
@Inject lateinit var uel: UserEntryLogger
var defaultValue = 0
private var inputProfileName = InputProfileName(rh, activePlugin, "", true)
private var daysBack = InputDuration(0, InputDuration.TimeUnit.DAYS)
private val days = InputWeekDay().also { it.setAll(true) }
override fun friendlyName(): Int = R.string.autotune_run
override fun shortDescription(): String = resourceHelper.gs(R.string.autotune_profile_name, inputProfileName.value)
@ -44,7 +45,7 @@ class ActionRunAutotune(injector: HasAndroidInjector) : Action(injector) {
var message = if (autoSwitch) R.string.autotune_run_with_autoswitch else R.string.autotune_run_without_autoswitch
Thread {
autotunePlugin.atLog("[Automation] Run Autotune $profileName, ${daysBack.value} days, Autoswitch $autoSwitch")
autotunePlugin.aapsAutotune(daysBack.value, autoSwitch, profileName)
autotunePlugin.aapsAutotune(daysBack.value, autoSwitch, profileName, days.weekdays)
if (!autotunePlugin.lastRunSuccess) {
message = R.string.autotune_run_with_error
aapsLogger.error(LTag.AUTOMATION, "Error during Autotune Run")
@ -61,6 +62,7 @@ class ActionRunAutotune(injector: HasAndroidInjector) : Action(injector) {
LayoutBuilder()
.add(LabelWithElement(rh, rh.gs(R.string.autotune_select_profile), "", inputProfileName))
.add(LabelWithElement(rh, rh.gs(R.string.autotune_tune_days), "", daysBack))
.add(days)
.build(root)
}
@ -70,6 +72,9 @@ class ActionRunAutotune(injector: HasAndroidInjector) : Action(injector) {
val data = JSONObject()
.put("profileToTune", inputProfileName.value)
.put("tunedays", daysBack.value)
for (i in days.weekdays.indices) {
data.put(InputWeekDay.DayOfWeek.values()[i].name, days.weekdays[i])
}
return JSONObject()
.put("type", this.javaClass.name)
.put("data", data)
@ -78,6 +83,8 @@ class ActionRunAutotune(injector: HasAndroidInjector) : Action(injector) {
override fun fromJSON(data: String): Action {
val o = JSONObject(data)
for (i in days.weekdays.indices)
days.weekdays[i] = JsonHelper.safeGetBoolean(o, InputWeekDay.DayOfWeek.values()[i].name,true)
inputProfileName.value = JsonHelper.safeGetString(o, "profileToTune", "")
defaultValue = JsonHelper.safeGetInt(o, "tunedays")
if (defaultValue == 0)

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.interfaces
interface Autotune {
fun aapsAutotune(daysBack: Int, autoSwitch: Boolean, profileToTune: String = ""): String
fun aapsAutotune(daysBack: Int, autoSwitch: Boolean, profileToTune: String = "", days: BooleanArray? = null): String
fun atLog(message: String)
var lastRunSuccess: Boolean

View file

@ -572,6 +572,7 @@
<string name="autotune_ic_warning">Autotune works with only one IC value, your profile has %1$d values. Average value is %2$.2fg/U</string>
<string name="autotune_isf_warning">Autotune works with only one ISF value, your profile has %1$d values. Average value is %2$.1f%3$s/U</string>
<string name="autotune_error">Error in input data, try to run again autotune or reduce the number of days</string>
<string name="autotune_error_more_days">Error in input data, increase the number of days</string>
<string name="autotune_warning_during_run">Autotune calculation started, please be patient</string>
<string name="autotune_warning_after_run">Check the results carefully before using it!</string>
<string name="autotune_partial_result">Partial result day %1$d / %2$d tuned</string>