-
Notifications
You must be signed in to change notification settings - Fork 6
Add converters for ECG and IRN data, and update exercise data parsing. #202
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
Open
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b981aa7
Remove comment
this-Aditya d0588ea
Add converters for parsing ecg and irn data
this-Aditya f076486
Update exercise converter
this-Aditya 2fb817e
Bump versions
this-Aditya 688a2fd
Handle NaN and send null insead of 0 for absent points
this-Aditya 2f2fbd4
Bump Schemas
this-Aditya 3d262aa
Resolve merge conflicts
this-Aditya File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
76 changes: 76 additions & 0 deletions
76
...kotlin/org/radarbase/googlehealth/converter/ElectrocardiogramGoogleHealthAvroConverter.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| /* | ||
| * Copyright 2026 King's College London | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.radarbase.googlehealth.converter | ||
|
|
||
| import com.fasterxml.jackson.databind.JsonNode | ||
| import org.apache.avro.specific.SpecificRecord | ||
| import org.radarbase.googlehealth.user.User | ||
| import org.radarbase.googlehealth.util.googleHealthElectrocardiogram | ||
| import java.time.Instant | ||
|
|
||
| /** | ||
| * Emits one record per ECG waveform sample. Sample i is timed at the reading start plus | ||
| * i / samplingFrequencyHertz seconds and carries the raw waveform value as reported by the | ||
| * device (an ADC count; divide by millivoltsScalingFactor for millivolts). The reading-level | ||
| * metadata (heart rate, sampling parameters, device info) is repeated on every sample's record, | ||
| * linked by the shared reading id. | ||
| */ | ||
| class ElectrocardiogramGoogleHealthAvroConverter(topic: String) : GoogleHealthAvroConverter(topic) { | ||
| override fun convertDataPoint( | ||
| point: JsonNode, | ||
| user: User, | ||
| ): List<Pair<SpecificRecord, SpecificRecord>> { | ||
| val data = point["electrocardiogram"] ?: return emptyList() | ||
| val start = data["interval"]?.get("startTime")?.asText() | ||
| ?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: return emptyList() | ||
| val id = (point["name"] ?: point["dataPointName"])?.asText()?.substringAfterLast('/') | ||
| ?: run { | ||
| logger.warn("Dropping electrocardiogram data point with no usable id for user={}", user.versionedId) | ||
| return emptyList() | ||
| } | ||
| val samples = data["waveformSamples"]?.takeIf { it.isArray } ?: return emptyList() | ||
| val frequency = data["samplingFrequencyHertz"]?.takeIf { !it.isNull }?.asInt()?.takeIf { it > 0 } | ||
| ?: return emptyList() | ||
|
|
||
| val device = data["medicalDeviceInfo"] | ||
| val beatsPerMinuteAvg = data["beatsPerMinuteAvg"]?.takeIf { !it.isNull }?.asText()?.toIntOrNull() | ||
| val scalingFactor = data["millivoltsScalingFactor"]?.takeIf { !it.isNull }?.asInt() | ||
| val leadNumber = data["leadNumber"]?.takeIf { !it.isNull }?.asInt() | ||
| val deviceModel = device?.get("deviceModel")?.asText() | ||
| val firmwareVersion = device?.get("firmwareVersion")?.asText() | ||
| val featureVersion = device?.get("featureVersion")?.asText() | ||
|
|
||
| val startSec = epochSeconds(start) | ||
| val received = nowEpochSeconds() | ||
| return samples.mapIndexed { i, sampleNode -> | ||
| val record = googleHealthElectrocardiogram { | ||
| time = startSec + i.toDouble() / frequency | ||
| timeReceived = received | ||
| this.id = id | ||
| sample = sampleNode.asInt() | ||
| this.beatsPerMinuteAvg = beatsPerMinuteAvg | ||
| this.samplingFrequencyHertz = frequency | ||
| this.millivoltsScalingFactor = scalingFactor | ||
| this.leadNumber = leadNumber | ||
| this.deviceModel = deviceModel | ||
| this.firmwareVersion = firmwareVersion | ||
| this.featureVersion = featureVersion | ||
| } | ||
| user.observationKey to record | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,8 +19,10 @@ package org.radarbase.googlehealth.converter | |
| import com.fasterxml.jackson.databind.JsonNode | ||
| import org.apache.avro.specific.SpecificRecord | ||
| import org.radarbase.googlehealth.user.User | ||
| import org.radarbase.googlehealth.util.exerciseHeartRate | ||
| import org.radarbase.googlehealth.util.activityLogRecord | ||
| import org.radarbase.googlehealth.util.googleHealthExerciseHeartRate | ||
| import org.radarbase.googlehealth.util.googleHealthExercise | ||
| import org.radarbase.googlehealth.util.googleHealthSource | ||
| import java.time.Instant | ||
|
|
||
| class ExerciseGoogleHealthAvroConverter(topic: String) : GoogleHealthAvroConverter(topic) { | ||
| override fun convertDataPoint( | ||
|
|
@@ -33,42 +35,77 @@ class ExerciseGoogleHealthAvroConverter(topic: String) : GoogleHealthAvroConvert | |
| data["interval"]?.get("startUtcOffset")?.asText(), | ||
| ) | ||
| val durationSec = (end.epochSecond - start.epochSecond).toFloat().coerceAtLeast(0.0f) | ||
| val activeDurationSec = data["activeDuration"]?.asText() | ||
| ?.let { parseDurationSeconds(it).toFloat() } ?: durationSec | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. make null |
||
| val lastModified = data["updateTime"]?.asText() | ||
| ?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: end | ||
| val metrics = data["metricsSummary"] | ||
|
|
||
| val distanceKm = metrics?.get("distanceMillimeters")?.takeIf { !it.isNull } | ||
| ?.asDouble()?.let { it.toFloat() / 1_000_000f } | ||
| val caloriesKcal = metrics?.get("caloriesKcal")?.takeIf { !it.isNull }?.asDouble() | ||
| ?.asText()?.toDoubleOrNull()?.let { it.toFloat() / 1_000_000f } | ||
|
|
||
| val caloriesKcal = metrics?.get("caloriesKcal")?.takeIf { !it.isNull }?.asText()?.toDoubleOrNull() | ||
| val energyKj = caloriesKcal?.let { (it * KCAL_TO_KJ).toFloat() } | ||
| val stepCount = metrics?.get("steps")?.takeIf { !it.isNull }?.asInt() | ||
| val avgHr = metrics?.get("averageHeartRateBeatsPerMinute")?.takeIf { !it.isNull }?.asInt() | ||
| val avgHeartRate = avgHr?.let { exerciseHeartRate { mean = it } } | ||
| val stepCount = metrics?.get("steps")?.takeIf { !it.isNull }?.asText()?.toIntOrNull() | ||
|
|
||
| val speedKmh = metrics?.get("averageSpeedMillimetersPerSecond")?.takeIf { !it.isNull } | ||
| ?.asText()?.toDoubleOrNull()?.let { it * MM_PER_S_TO_KM_PER_H } | ||
|
|
||
| val avgHr = metrics?.get("averageHeartRateBeatsPerMinute")?.takeIf { !it.isNull }?.asText()?.toIntOrNull() | ||
| val zones = metrics?.get("heartRateZoneDurations")?.takeIf { !it.isNull } | ||
| val avgHeartRate = if (avgHr != null || zones != null) { | ||
| googleHealthExerciseHeartRate { | ||
| mean = avgHr | ||
| durationLight = zones?.get("lightTime")?.asText()?.let { parseDurationSeconds(it) } | ||
| durationModerate = zones?.get("moderateTime")?.asText()?.let { parseDurationSeconds(it) } | ||
| durationVigorous = zones?.get("vigorousTime")?.asText()?.let { parseDurationSeconds(it) } | ||
| durationPeak = zones?.get("peakTime")?.asText()?.let { parseDurationSeconds(it) } | ||
| } | ||
| } else { | ||
| null | ||
| } | ||
| val exerciseType = data["exerciseType"]?.asText() | ||
| val dataSource = point["dataSource"]?.takeIf { !it.isNull } | ||
| val device = dataSource?.get("device") | ||
| val exerciseSource = dataSource?.let { | ||
| googleHealthSource { | ||
| name = device?.get("displayName")?.asText() | ||
| formFactor = device?.get("formFactor")?.asText() | ||
| manufacturer = device?.get("manufacturer")?.asText() | ||
| platform = it["platform"]?.asText() | ||
| } | ||
| } | ||
|
|
||
| val activityId = (point["name"] ?: point["dataPointName"])?.asText() | ||
| ?.substringAfterLast('/')?.toLongOrNull() | ||
| ?: run { | ||
| logger.warn("Dropping exercise data point with no usable log id for user={}", user.versionedId) | ||
| return emptyList() | ||
| } | ||
|
|
||
| val activityId = point["dataPointName"]?.asText()?.substringAfterLast('/')?.toLongOrNull() | ||
| ?: throw IllegalStateException("Exercise data point has no usable dataPointName log id: $point") | ||
| val record = activityLogRecord { | ||
| val record = googleHealthExercise { | ||
| time = epochSeconds(start) | ||
| timeReceived = nowEpochSeconds() | ||
| timeZoneOffset = offsetSeconds | ||
| timeLastModified = epochSeconds(end) | ||
| timeLastModified = epochSeconds(lastModified) | ||
| duration = durationSec | ||
| durationActive = durationSec | ||
| durationActive = activeDurationSec | ||
| id = activityId | ||
| name = data["displayName"]?.asText() ?: exerciseType | ||
| logType = point["dataSource"]?.get("recordingMethod")?.asText() | ||
| type = null | ||
| source = null | ||
| manualDataEntry = null | ||
| logType = dataSource?.get("recordingMethod")?.asText() | ||
| type = exerciseType | ||
| source = exerciseSource | ||
| energy = energyKj | ||
| levels = null | ||
| heartRate = avgHeartRate | ||
| steps = stepCount | ||
| distance = distanceKm | ||
| speed = null | ||
| speed = speedKmh | ||
| } | ||
| return listOf(user.observationKey to record) | ||
| } | ||
|
|
||
| companion object { | ||
| private const val KCAL_TO_KJ = 4.1868 | ||
| private const val MM_PER_S_TO_KM_PER_H = 0.0036 | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
.../radarbase/googlehealth/converter/IrregularRhythmNotificationGoogleHealthAvroConverter.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| /* | ||
| * Copyright 2026 King's College London | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.radarbase.googlehealth.converter | ||
|
|
||
| import com.fasterxml.jackson.databind.JsonNode | ||
| import org.apache.avro.specific.SpecificRecord | ||
| import org.radarbase.googlehealth.user.User | ||
| import org.radarbase.googlehealth.util.googleHealthIrregularRhythmNotification | ||
| import java.time.Instant | ||
|
|
||
| /** | ||
| * Emits one record per heart beat of an Irregular Rhythm Notification, flattening the API's | ||
| * session -> alertWindow -> heartBeat hierarchy. Each record carries the heart beat's own time | ||
| * plus the context of its parent window (start/end, positive) and session (start), with the | ||
| * device metadata repeated, linked by the shared notification id. | ||
| */ | ||
| class IrregularRhythmNotificationGoogleHealthAvroConverter(topic: String) : GoogleHealthAvroConverter(topic) { | ||
| override fun convertDataPoint( | ||
| point: JsonNode, | ||
| user: User, | ||
| ): List<Pair<SpecificRecord, SpecificRecord>> { | ||
| val data = point["irregularRhythmNotification"] ?: return emptyList() | ||
| val id = (point["name"] ?: point["dataPointName"])?.asText()?.substringAfterLast('/') | ||
| ?: run { | ||
| logger.warn("Dropping irregularRhythmNotification data point with no usable id for user={}", user.versionedId) | ||
| return emptyList() | ||
| } | ||
| val windows = data["alertWindows"]?.takeIf { it.isArray } ?: return emptyList() | ||
|
|
||
| val device = data["medicalDeviceInfo"] | ||
| val sessionStart = data["interval"]?.get("startTime")?.asText() | ||
| ?.let { runCatching { Instant.parse(it) }.getOrNull() } | ||
| val firmwareVersion = device?.get("firmwareVersion")?.asText() | ||
| val featureVersion = device?.get("featureVersion")?.asText() | ||
| val deviceModel = device?.get("deviceModel")?.asText() | ||
| val received = nowEpochSeconds() | ||
|
|
||
| return windows.flatMap { window -> | ||
| val windowStart = window["startTime"]?.asText() | ||
| ?.let { runCatching { Instant.parse(it) }.getOrNull() } | ||
| val windowEnd = window["endTime"]?.asText() | ||
| ?.let { runCatching { Instant.parse(it) }.getOrNull() } | ||
| if (windowStart == null || windowEnd == null) return@flatMap emptyList() | ||
| val positive = window["positive"]?.takeIf { !it.isNull }?.asBoolean() | ||
| val heartBeats = window["heartBeats"]?.takeIf { it.isArray } ?: return@flatMap emptyList() | ||
|
|
||
| heartBeats.mapNotNull { beat -> | ||
| val beatTime = (beat["physicalTime"] ?: beat["time"])?.asText() | ||
| ?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: return@mapNotNull null | ||
| val record = googleHealthIrregularRhythmNotification { | ||
| time = epochSeconds(beatTime) | ||
| timeReceived = received | ||
| this.id = id | ||
| sessionStartTime = sessionStart?.let { epochSeconds(it) } | ||
| windowStartTime = epochSeconds(windowStart) | ||
| windowEndTime = epochSeconds(windowEnd) | ||
| this.positive = positive | ||
| beatsPerMinute = beat["beatsPerMinute"]?.takeIf { !it.isNull }?.asText()?.toIntOrNull() | ||
| this.firmwareVersion = firmwareVersion | ||
| this.featureVersion = featureVersion | ||
| this.deviceModel = deviceModel | ||
| } | ||
| user.observationKey to record | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
try using parallel processing here