Skip to content
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

feat: protected feature API #211

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions backend/backend/app/routers/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,57 @@ def read_sorted_features(
).order_by(desc("value"))

return paginate(session, q, page_params)


@router.get(
"/{protector_id}/protected-by",
response_model=list[schemas.ProtectedFeatureListItem],
)
def read_protected_features(
protector_id: int,
rcp: str,
protection_level: float,
session: SessionDep,
):
"""
Get all adaptation options, by feature ID and layer, for features
protected by a given protector feature.
"""

adaptation_options = select(
models.Feature.id.label("id"),
models.Feature.string_id.label("string_id"),
models.Feature.layer.label("layer"),
models.AdaptationCostBenefit.adaptation_cost.label(
"adaptation_cost"
),
models.AdaptationCostBenefit.adaptation_protection_level.label(
"adaptation_protection_level"
),
models.AdaptationCostBenefit.adaptation_name.label(
"adaptation_name"
),
models.AdaptationCostBenefit.avoided_ead_mean.label(
"avoided_ead_mean"
),
models.AdaptationCostBenefit.avoided_eael_mean.label(
"avoided_eael_mean"
),
models.AdaptationCostBenefit.rcp.label("rcp"),
models.AdaptationCostBenefit.hazard.label("hazard"),
).select_from(
models.Feature
).join(
models.FeatureLayer
).join(
models.Feature.adaptation
).filter_by(
rcp=rcp,
adaptation_protection_level=protection_level,
).where(
models.AdaptationCostBenefit.adaptation_name ==
"Flood defence around asset" # test query
# models.AdaptationCostBenefit.protector_feature_id == protector_id
)
print(adaptation_options)
return session.execute(adaptation_options)
17 changes: 17 additions & 0 deletions backend/backend/app/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,20 @@ class FeatureListItemOut(BaseModel, Generic[SortFieldT]):
AttributeT = TypeVar("AttributeT")

AttributeLookup = dict[int, AttributeT]

# Protected Features


class ProtectedFeatureListItem(BaseModel):
id: int
string_id: str
layer: str
adaptation_name: str
adaptation_protection_level: float
adaptation_cost: float
avoided_ead_mean: float
avoided_eael_mean: float
hazard: str
rcp: float

model_config = ConfigDict(from_attributes=True)
5 changes: 5 additions & 0 deletions backend/backend/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ class AdaptationCostBenefit(Base):
primary_key=True,
index=True
)
protector_feature_id = Column(
Integer,
primary_key=True,
index=True
)

hazard = Column(String(8), nullable=False, primary_key=True)
rcp = Column(String(8), nullable=False, primary_key=True)
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/app/config/views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export const VIEW_SECTIONS: Record<string, Record<string, ViewSectionConfig>> =
expanded: true,
visible: true,

styles: ['type', 'damages', 'adaptation'],
styles: ['type', 'damages', 'adaptation', 'protectedFeatures'],
defaultStyle: 'adaptation',
},
drought: {
Expand Down
1 change: 0 additions & 1 deletion frontend/src/app/map/DataMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export const DataMapContainer: FC = () => {
const setViewLayersFlat = useSetRecoilState(viewLayersFlatState);
const { firstLabelId } = useBasemapStyle(background, showLabels);
const interactionGroups = useRecoilValue(interactionGroupsState);

useEffect(() => {
setViewLayersFlat(flattenConfig(viewLayers));
}, [viewLayers, setViewLayersFlat]);
Expand Down
30 changes: 28 additions & 2 deletions frontend/src/data-layers/networks/sidebar/NetworkControl.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Box } from '@mui/system';
import { Alert } from '@mui/material';
import { FC } from 'react';
import { useRecoilState, useRecoilValue } from 'recoil';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';

import { CheckboxTree } from 'lib/controls/checkbox-tree/CheckboxTree';
import { CheckboxTree, recalculateCheckboxStates } from 'lib/controls/checkbox-tree/CheckboxTree';
import { useUpdateDataParam } from 'lib/state/data-params';

import { LayerLabel } from 'lib/sidebar/ui/LayerLabel';
Expand All @@ -17,6 +17,31 @@ import { NETWORK_LAYERS_HIERARCHY } from './hierarchy';
import { NETWORKS_METADATA } from '../metadata';
import { showAdaptationsState } from '../state/layer';
import adaptationSectorLayers from '../adaptation-sector-layers.json';
import { protectedFeatureLayersState } from 'lib/state/protected-features';

/**
* Set the checkbox tree state to true for protected feature layers.
* @param checkBoxState network checkbox tree state.
*/
function useSyncProtectedFeatureLayers(checkboxState) {
const protectedFeatureLayers = useRecoilValue(protectedFeatureLayersState);
const setCheckboxState = useSetRecoilState(networkTreeCheckboxState);
protectedFeatureLayers.forEach((layer: string) => {
if (!checkboxState.checked[layer]) {
setCheckboxState((prev) => {
const newState = {
indeterminate: {},
checked: {
...prev.checked,
[layer]: true,
},
};
const resolvedTreeState = recalculateCheckboxStates(newState, networkTreeConfig);
return resolvedTreeState;
});
}
});
}

/**
* Sync adaptation parameters to the infrastructure checkbox tree, so that
Expand Down Expand Up @@ -56,6 +81,7 @@ export const NetworkControl: FC = () => {
const disableCheck = showAdaptations;

useSyncAdaptationParameters(checkboxState);
useSyncProtectedFeatureLayers(checkboxState);

return (
<>
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/data-layers/networks/sidebar/NetworksSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { DamageSourceControl } from './DamageSourceControl';
import { AdaptationControl } from './AdaptationControl';
import { NetworkControl } from './NetworkControl';
import { useSyncConfigState } from 'app/state/data-params';
import { ProtectedFeaturesControl } from './ProtectedFeaturesControl';

/**
* Sidebar controls for the `networks` layer.
Expand Down Expand Up @@ -51,6 +52,11 @@ export const NetworksSection: FC = () => {
<AdaptationControl />
</Collapse>
) : null}
{style === 'protectedFeatures' ? (
<Collapse>
<ProtectedFeaturesControl />
</Collapse>
) : null}
</TransitionGroup>
</SidebarPanelSection>
</ErrorBoundary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { FC } from 'react';
import { useRecoilState } from 'recoil';
import { FormLabel } from '@mui/material';

import { CustomNumberSlider } from 'lib/controls/CustomSlider';
import { ParamDropdown } from 'lib/controls/ParamDropdown';
import { StateEffectRoot } from 'lib/recoil/state-effects/StateEffectRoot';
import { dataParamsByGroupState } from 'lib/state/data-params';

import { InputRow } from 'lib/sidebar/ui/InputRow';
import { InputSection } from 'lib/sidebar/ui/InputSection';
import { LayerStylePanel } from 'lib/sidebar/ui/LayerStylePanel';
import { DataParam } from 'lib/sidebar/ui/params/DataParam';

import { adaptationDataParamsStateEffect, adaptationFieldState } from '../state/layer';

export const ProtectedFeaturesControl: FC = () => {
const [adaptationField, setAdaptationField] = useRecoilState(adaptationFieldState);
return (
<LayerStylePanel>
<StateEffectRoot
state={dataParamsByGroupState('adaptation')}
effect={adaptationDataParamsStateEffect}
/>
<InputSection>
<FormLabel>Adaptation for</FormLabel>
<InputRow>
<DataParam group="adaptation" id="rcp">
{({ value, onChange, options }) => (
<ParamDropdown title="RCP" value={value} onChange={onChange} options={options} />
)}
</DataParam>
</InputRow>
</InputSection>
<InputSection>
<DataParam group="adaptation" id="adaptation_protection_level">
{({ value, onChange, options }) =>
options.length > 2 ? (
<>
<FormLabel>Protection level</FormLabel>
<CustomNumberSlider
title="Protection level"
value={value}
onChange={onChange}
marks={options}
/>
</>
) : (
<ParamDropdown
title="Protection level"
value={value}
onChange={onChange}
options={options}
/>
)
}
</DataParam>
</InputSection>

<InputSection>
<ParamDropdown<typeof adaptationField>
title="Displayed variable"
value={adaptationField}
onChange={setAdaptationField}
options={[
{ value: 'avoided_ead_mean', label: 'Avoided Expected Annual Damages' },
{ value: 'avoided_eael_mean', label: 'Avoided Expected Annual Economic Losses' },
{ value: 'adaptation_cost', label: 'Adaptation Cost' },
]}
/>
</InputSection>
</LayerStylePanel>
);
};
2 changes: 2 additions & 0 deletions frontend/src/data-layers/networks/state/layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ export const networkStyleParamsState = selector<StyleParams>({
return get(damageMapStyleParamsState);
case 'adaptation':
return get(adaptationStyleParamsState);
case 'protectedFeatures':
return get(adaptationStyleParamsState);
default:
return {};
}
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/data-layers/networks/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ export const NETWORK_STYLES = makeConfig([
id: 'adaptation',
label: 'Adaptation Options',
},
{
id: 'protectedFeatures',
label: 'Protected Features',
},
]);
1 change: 1 addition & 0 deletions frontend/src/lib/api-client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type { FeatureOut } from './models/FeatureOut';
export type { HTTPValidationError } from './models/HTTPValidationError';
export type { NPVDamage } from './models/NPVDamage';
export type { Page_FeatureListItemOut_float__ } from './models/Page_FeatureListItemOut_float__';
export type { ProtectedFeatureListItem } from './models/ProtectedFeatureListItem';
export type { ReturnPeriodDamage } from './models/ReturnPeriodDamage';
export type { ValidationError } from './models/ValidationError';

Expand Down
16 changes: 16 additions & 0 deletions frontend/src/lib/api-client/models/ProtectedFeatureListItem.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */

export type ProtectedFeatureListItem = {
id: number;
string_id: string;
layer: string;
adaptation_name: string;
adaptation_protection_level: number;
adaptation_cost: number;
avoided_ead_mean: number;
avoided_eael_mean: number;
hazard: string;
rcp: number;
};
33 changes: 33 additions & 0 deletions frontend/src/lib/api-client/services/FeaturesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/* eslint-disable */
import type { FeatureOut } from '../models/FeatureOut';
import type { Page_FeatureListItemOut_float__ } from '../models/Page_FeatureListItemOut_float__';
import type { ProtectedFeatureListItem } from '../models/ProtectedFeatureListItem';

import type { CancelablePromise } from '../core/CancelablePromise';
import type { BaseHttpRequest } from '../core/BaseHttpRequest';
Expand Down Expand Up @@ -84,4 +85,36 @@ export class FeaturesService {
});
}

/**
* Read Protected Features
* Get all adaptation options, by feature ID and layer, for features
* protected by a given protector feature.
* @returns ProtectedFeatureListItem Successful Response
* @throws ApiError
*/
public featuresReadProtectedFeatures({
protectorId,
rcp,
protectionLevel,
}: {
protectorId: number,
rcp: string,
protectionLevel: number,
}): CancelablePromise<Array<ProtectedFeatureListItem>> {
return this.httpRequest.request({
method: 'GET',
url: '/features/{protector_id}/protected-by',
path: {
'protector_id': protectorId,
},
query: {
'rcp': rcp,
'protection_level': protectionLevel,
},
errors: {
422: `Validation Error`,
},
});
}

}
Loading
Loading