Skip to content

Commit

Permalink
Fix merge errors
Browse files Browse the repository at this point in the history
  • Loading branch information
toni-neurosc committed Nov 27, 2024
1 parent 6cf4516 commit 9a323a8
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 49 deletions.
16 changes: 8 additions & 8 deletions gui_dev/src/main.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
if (JSON.parse(import.meta.env.VITE_REACT_SCAN) === true) {
import("react-scan").then(({ scan }) => {
scan({
enabled: true,
log: true, // logs render info to console
});
});
}
// if (JSON.parse(import.meta.env.VITE_REACT_SCAN) === true) {
// import("react-scan").then(({ scan }) => {
// scan({
// enabled: true,
// log: true, // logs render info to console
// });
// });
// }

import { StrictMode } from "react";
import ReactDOM from "react-dom/client";
Expand Down
7 changes: 6 additions & 1 deletion gui_dev/src/pages/Settings/Settings.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ const NumberField = ({ value, onChange, label, error }) => {
const componentRegistry = {
boolean: BooleanField,
string: StringField,
int: NumberField,
float: NumberField,
number: NumberField,
};

Expand Down Expand Up @@ -166,11 +168,13 @@ const SettingsSection = ({

// Case 2: Object with component -> Don't iterate, render directly
if (isObject && Component) {
const value = "__value__" in settings ? settings.__value__ : settings;

return (
<SettingsField
Component={Component}
label={boxTitle}
value={settings}
value={value}
onChange={onChange}
path={path}
error={getFieldError(path, errors)}
Expand Down Expand Up @@ -210,6 +214,7 @@ const SettingsSection = ({

const StatusBarSettingsInfo = () => {
const validationErrors = useSettingsStore((state) => state.validationErrors);
console.log("validationErrors:", validationErrors);
const [anchorEl, setAnchorEl] = useState(null);
const open = Boolean(anchorEl);

Expand Down
23 changes: 3 additions & 20 deletions gui_dev/src/stores/settingsStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,6 @@ const INITIAL_DELAY = 3000; // wait for Flask
const RETRY_DELAY = 1000; // ms
const MAX_RETRIES = 100;

const uploadSettingsToServer = async (settings) => {
try {
const response = await fetch(getBackendURL("/api/settings"), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(settings),
});
if (!response.ok) {
throw new Error("Failed to update settings");
}
return { success: true };
} catch (error) {
console.error("Error updating settings:", error);
return { success: false, error };
}
};

export const useSettingsStore = createStore("settings", (set, get) => ({
settings: null,
lastValidSettings: null,
Expand Down Expand Up @@ -99,7 +80,9 @@ export const useSettingsStore = createStore("settings", (set, get) => ({

try {
const response = await fetch(
`/api/settings${validateOnly ? "?validate_only=true" : ""}`,
getBackendURL(
`/api/settings${validateOnly ? "?validate_only=true" : ""}`
),
{
method: "POST",
headers: {
Expand Down
3 changes: 2 additions & 1 deletion py_neuromodulation/gui/backend/app_backend.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from email import errors
import logging
import asyncio
import importlib.metadata
Expand Down Expand Up @@ -94,9 +95,9 @@ async def update_settings(data: dict, validate_only: bool = Query(False)):
# TODO: check if this works properly or needs model_validate_strings
validated_settings = NMSettings.model_validate(data)
except ValidationError as e:
self.logger.error(f"Error validating settings: {e}")
if not validate_only:
# If validation failed but we wanted to upload, return error
self.logger.error(f"Error validating settings: {e}")
raise HTTPException(
status_code=422,
detail={
Expand Down
30 changes: 25 additions & 5 deletions py_neuromodulation/stream/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
from py_neuromodulation.utils.pydantic_extensions import NMErrorList, NMField

from py_neuromodulation.processing.filter_preprocessing import FilterSettings
from py_neuromodulation.processing.normalization import FeatureNormalizationSettings, NormalizationSettings
from py_neuromodulation.processing.normalization import (
FeatureNormalizationSettings,
NormalizationSettings,
)
from py_neuromodulation.processing.resample import ResamplerSettings
from py_neuromodulation.processing.projection import ProjectionSettings

Expand Down Expand Up @@ -94,7 +97,9 @@ class NMSettings(NMBaseModel):

# Postprocessing settings
postprocessing: PostprocessingSettings = PostprocessingSettings()
feature_normalization_settings: FeatureNormalizationSettings = FeatureNormalizationSettings()
feature_normalization_settings: FeatureNormalizationSettings = (
FeatureNormalizationSettings()
)
project_cortex_settings: ProjectionSettings = ProjectionSettings(max_dist_mm=20)
project_subcortex_settings: ProjectionSettings = ProjectionSettings(max_dist_mm=5)

Expand Down Expand Up @@ -144,12 +149,27 @@ def validate_settings(self, handler: ModelWrapValidatorHandler) -> Any:
# the settings class
errors: NMErrorList = NMErrorList()

def remove_private_keys(data):
if isinstance(data, dict):
if "__value__" in data:
return data["__value__"]
else:
return {
key: remove_private_keys(value)
for key, value in data.items()
if not key.startswith("__")
}
elif isinstance(data, (list, tuple, set)):
return type(data)(remove_private_keys(item) for item in data)
else:
return data

self = remove_private_keys(self)

try:
# validate the model
self = handler(self)
self = handler(self) # validate the model
except ValidationError as e:
self = NMSettings.unvalidated(**self)
NMSettings.model_fields_set
errors.extend(NMErrorList(e.errors()))

if len(self.features.get_enabled()) == 0:
Expand Down
2 changes: 1 addition & 1 deletion py_neuromodulation/stream/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from contextlib import suppress

from py_neuromodulation.stream.data_processor import DataProcessor
from py_neuromodulation.utils.types import _PathLike, FeatureName
from py_neuromodulation.utils.types import _PathLike, FEATURE_NAME
from py_neuromodulation.utils.file_writer import MsgPackFileWriter
from py_neuromodulation.stream.settings import NMSettings
from py_neuromodulation.analysis.decode import RealTimeDecoder
Expand Down
11 changes: 6 additions & 5 deletions py_neuromodulation/utils/pydantic_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ class NMErrorList:
def __init__(
self, errors: Sequence[InitErrorDetails | ErrorDetails] | None = None
) -> None:
self.__errors: list[InitErrorDetails | ErrorDetails] = [e for e in errors or []]
if errors is None:
self.__errors: list[InitErrorDetails | ErrorDetails] = []
else:
self.__errors: list[InitErrorDetails | ErrorDetails] = [e for e in errors]

def add_error(
self,
Expand Down Expand Up @@ -160,8 +163,6 @@ def NMField(


class NMBaseModel(BaseModel):
# model_config = ConfigDict(validate_assignment=False, extra="allow")

def __init__(self, *args, **kwargs) -> None:
"""Pydantic does not support positional arguments by default.
This is a workaround to support positional arguments for models like FrequencyRange.
Expand Down Expand Up @@ -242,7 +243,7 @@ def serialize_with_metadata(self):
if isinstance(field_info, NMFieldInfo):
# Convert scalar value to dict with metadata
field_dict = {
"value": value,
"__value__": value,
# __field_type__ will be overwritte if set in custom_metadata
"__field_type__": type(value).__name__,
**{
Expand Down Expand Up @@ -342,7 +343,7 @@ def model_dump_json(self, **kwargs):
return json.dumps(self.root, **kwargs)

def serialize_with_metadata(self) -> dict[str, Any]:
result = {"__field_type__": self.__class__.__name__, "value": self.root}
result = {"__field_type__": self.__class__.__name__, "__value__": self.root}

# Add any field metadata from the root field
field_info = self.model_fields.get("root")
Expand Down
9 changes: 1 addition & 8 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,7 @@ dependencies = [

[project.optional-dependencies]
test = ["pytest>=8.0.2", "pytest-xdist"]
dev = [
"ruff",
"pytest>=8.0.2",
"pytest-cov",
"pytest-sugar",
"notebook",
"uvicorn[standard]",
]
dev = ["ruff", "pytest>=8.0.2", "pytest-cov", "pytest-sugar", "notebook"]
docs = [
"py-neuromodulation[dev]",
"sphinx",
Expand Down

0 comments on commit 9a323a8

Please sign in to comment.