-
Notifications
You must be signed in to change notification settings - Fork 2
GOATS-966 GOATS-967 GOATS-968: Implement serializers for brightness, elevation range, and exposure mode. #456
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
Merged
Merged
Changes from 2 commits
Commits
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
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 @@ | ||
Added support for unpacking user-supplied data in the `GPPTooViewSet` create method and introduced serializers for new input types. The API endpoint handles brightnesses, elevation ranges, and exposure modes. These changes bring us closer to enabling the submission of ToOs to GPP. |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
from .brightnesses import GPPBrightnessesSerializer | ||
from .elevation_range import GPPElevationRangeSerializer | ||
from .exposure_mode import GPPExposureModeSerializer | ||
|
||
__all__ = [ | ||
"GPPBrightnessesSerializer", | ||
"GPPExposureModeSerializer", | ||
"GPPElevationRangeSerializer", | ||
] |
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,108 @@ | ||
__all__ = ["GPPBrightnessesSerializer"] | ||
|
||
import re | ||
from typing import Any | ||
|
||
from gpp_client.api.enums import Band, BrightnessIntegratedUnits | ||
from rest_framework import serializers | ||
|
||
|
||
class BrightnessSerializer(serializers.Serializer): | ||
""" | ||
Serializer for individual brightness entries. | ||
Notes | ||
----- | ||
This serializer is tied to | ||
``gpp_client.api.input_types.BandNormalizedIntegratedInput.`` and will eventually | ||
eventually need to support all types of ``SourceProfileInput``. | ||
davner marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
""" | ||
|
||
band = serializers.ChoiceField(choices=[b.value for b in Band]) | ||
value = serializers.FloatField() | ||
unit = serializers.ChoiceField(choices=[u.value for u in BrightnessIntegratedUnits]) | ||
error = serializers.FloatField(required=False, allow_null=True) | ||
|
||
|
||
class GPPBrightnessesSerializer(serializers.Serializer): | ||
"""Serializer to parse and validate brightness entries from flat form data.""" | ||
|
||
brightnesses = serializers.ListField( | ||
child=BrightnessSerializer(), | ||
allow_empty=True, | ||
allow_null=True, | ||
required=False, | ||
default=None, | ||
) | ||
|
||
def to_internal_value(self, data: dict[str, Any]) -> dict[str, Any]: | ||
""" | ||
Parse flat brightness fields into structured brightnesses list. | ||
Parameters | ||
---------- | ||
data : dict[str, Any] | ||
The input data potentially containing brightness fields. | ||
Returns | ||
------- | ||
dict[str, Any] | ||
The structured brightnesses list or an error message. | ||
Raises | ||
------ | ||
serializers.ValidationError | ||
If any brightness value is invalid or required fields are missing. | ||
""" | ||
brightness_pattern = re.compile( | ||
r"brightness(ValueInput|BandSelect|UnitsSelect)(\d+)" | ||
) | ||
brightnesses_data: dict[int, dict[str, Any]] = {} | ||
|
||
# Group brightness fields by their index. | ||
for key, value in data.items(): | ||
match = brightness_pattern.match(key) | ||
if not match: | ||
continue | ||
|
||
field_type, index = match.groups() | ||
index = int(index) | ||
|
||
# Handle list values from form submissions. | ||
raw_value = value[0] if isinstance(value, list) else value | ||
raw_value = raw_value.strip() if raw_value else None | ||
|
||
# Initialize dictionary for this index if not already present. | ||
brightnesses_data.setdefault(index, {})[field_type] = raw_value | ||
|
||
# Normalize values. | ||
parsed = [] | ||
for index, entry in sorted(brightnesses_data.items()): | ||
try: | ||
value = float(entry["ValueInput"]) | ||
except (KeyError, TypeError, ValueError): | ||
raise serializers.ValidationError( | ||
"A Brightness value is not a valid number." | ||
) | ||
|
||
band = entry.get("BandSelect") | ||
unit = entry.get("UnitsSelect") | ||
|
||
# Ensure band and unit are provided. | ||
if not band or not unit: | ||
raise serializers.ValidationError( | ||
"A Brightness is missing a band or unit." | ||
) | ||
|
||
parsed.append( | ||
{ | ||
"band": band, | ||
"value": value, | ||
"unit": unit, | ||
} | ||
) | ||
|
||
# Return structured brightnesses or None if empty. | ||
if not parsed: | ||
return super().to_internal_value({"brightnesses": None}) | ||
return super().to_internal_value({"brightnesses": parsed}) |
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,82 @@ | ||
__all__ = ["GPPElevationRangeSerializer"] | ||
|
||
from typing import Any | ||
|
||
from rest_framework import serializers | ||
|
||
from .utils import normalize | ||
|
||
|
||
class GPPElevationRangeSerializer(serializers.Serializer): | ||
"""Serializer to parse and validate elevation range from flat form data.""" | ||
|
||
elevationRangeSelect = serializers.ChoiceField(choices=["Air Mass", "Hour Angle"]) | ||
airMassMinimumInput = serializers.CharField(required=False, allow_blank=True) | ||
airMassMaximumInput = serializers.CharField(required=False, allow_blank=True) | ||
haMinimumInput = serializers.CharField(required=False, allow_blank=True) | ||
haMaximumInput = serializers.CharField(required=False, allow_blank=True) | ||
|
||
def validate(self, data: dict[str, Any]) -> dict[str, Any]: | ||
""" | ||
Validate and structure elevation range input into the correct nested model | ||
shape. | ||
|
||
Returns | ||
------- | ||
dict[str, Any] | ||
The structured elevation range data. | ||
|
||
Raises | ||
------ | ||
serializers.ValidationError | ||
If required fields are missing or invalid based on the selected mode. | ||
""" | ||
|
||
mode = data["elevationRangeSelect"] | ||
|
||
# Handle Air Mass mode. | ||
if mode == "Air Mass": | ||
min_val = normalize(data.get("airMassMinimumInput")) | ||
max_val = normalize(data.get("airMassMaximumInput")) | ||
|
||
# At least one of min or max must be provided. | ||
if min_val is None and max_val is None: | ||
raise serializers.ValidationError( | ||
"Air mass range must have at least one value." | ||
) | ||
|
||
# Build and return the structured data. | ||
try: | ||
return { | ||
"airMass": { | ||
"min": float(min_val) if min_val is not None else None, | ||
"max": float(max_val) if max_val is not None else None, | ||
} | ||
} | ||
except ValueError: | ||
raise serializers.ValidationError("Air mass values must be numeric.") | ||
|
||
# Handle Hour Angle mode. | ||
elif mode == "Hour Angle": | ||
min_val = normalize(data.get("haMinimumInput")) | ||
max_val = normalize(data.get("haMaximumInput")) | ||
|
||
# At least one of min or max must be provided. | ||
if min_val is None and max_val is None: | ||
raise serializers.ValidationError( | ||
"Hour angle range must have at least one value." | ||
) | ||
|
||
# Build and return the structured data. | ||
try: | ||
return { | ||
"hourAngle": { | ||
"minHours": float(min_val) if min_val is not None else None, | ||
"maxHours": float(max_val) if max_val is not None else None, | ||
} | ||
} | ||
except ValueError: | ||
raise serializers.ValidationError("Hour angle values must be numeric.") | ||
|
||
# If mode is neither "Air Mass" nor "Hour Angle", raise an error. | ||
raise serializers.ValidationError("Invalid elevation range mode selected.") |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.