Skip to content

Commit

Permalink
front: improve simulation results performances
Browse files Browse the repository at this point in the history
  • Loading branch information
SharglutDev committed Jan 12, 2024
1 parent 6d8d32f commit 6efc220
Show file tree
Hide file tree
Showing 16 changed files with 172 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ import { store } from 'store';
import i18n from 'i18next';
import {
SimulationReport,
TimetableWithSchedulesDetails,
TrainScheduleSummary,
osrdEditoastApi,
} from 'common/api/osrdEditoastApi';
import { extractMessageFromError } from 'utils/error';
import { AllowancesSettings, Projection } from 'reducers/osrdsimulation/types';
import { ApiError } from 'common/api/baseGeneratedApis';
import { SerializedError } from '@reduxjs/toolkit';
import { differenceBy } from 'lodash';

export function selectProjection(
trainSchedules: TrainScheduleSummary[],
Expand Down Expand Up @@ -79,32 +81,36 @@ export function selectProjection(
}

/**
* Recover the time table for all the trains
* - If first load of the scenario, get all timetable trains results and update the simulation.
* - If adding/updating train(s), get these train results and update the simulation.
* - If deleting train(s) and there are still trains in the timetable, do nothing
*/
export default async function getSimulationResults(
timetable: TimetableWithSchedulesDetails,
trainSchedulesIDs: number[],
selectedProjection: Projection,
allowancesSettings?: AllowancesSettings
allowancesSettings?: AllowancesSettings,
simulation?: SimulationReport[]
) {
store.dispatch(updateIsUpdating(true));
const trainSchedulesIDs = timetable.train_schedule_summaries.map((train) => train.id);

if (trainSchedulesIDs.length > 0) {
// We use this syntax first because of the .initiate, to be able to unsubscribe from the results later
const results = store.dispatch(
osrdEditoastApi.endpoints.getTrainScheduleResults.initiate({
timetableId: timetable.id,
pathId: selectedProjection.path,
})
);
store.dispatch(updateIsUpdating(true));
try {
let simulationLocal = await store
.dispatch(
osrdEditoastApi.endpoints.postTrainScheduleResults.initiate({
body: {
path_id: selectedProjection.path,
train_ids: trainSchedulesIDs,
},
})
)
.unwrap();

const {
data: simulationLocal,
isError: isGetTrainScheduleResultsError,
error: getTrainScheduleResultsError,
} = await results;
// Means that we are adding or updating a train and we need to add it in the present simulation
if (simulation) {
const unaffectedTrains = differenceBy(simulation, simulationLocal, 'id');
simulationLocal = unaffectedTrains.concat(simulationLocal);
}

if (simulationLocal) {
const sortedSimulationLocal = [...simulationLocal].sort(
(a: SimulationReport, b: SimulationReport) => a.base.stops[0].time - b.base.stops[0].time
);
Expand All @@ -123,23 +129,19 @@ export default async function getSimulationResults(
}
});
store.dispatch(updateAllowancesSettings(newAllowancesSettings));
store.dispatch(updateIsUpdating(false));
} else if (isGetTrainScheduleResultsError && getTrainScheduleResultsError) {
} catch (e) {
store.dispatch(
setFailure({
name: i18n.t('simulation:errorMessages.unableToRetrieveTrainSchedule'),
message: extractMessageFromError(getTrainScheduleResultsError),
message: extractMessageFromError(e as ApiError | SerializedError),
})
);
console.error('trainScheduleResults error : ', e);
} finally {
store.dispatch(updateIsUpdating(false));
console.error(getTrainScheduleResultsError);
}

// Manually dispatching an RTK request with .initiate will create a subscription entry, but we need to unsubscribe from that data also manually - otherwise the data stays in the cache permanently.
results.unsubscribe();
} else {
} else if (!simulation) {
store.dispatch(updateSimulation({ trains: [] }));
store.dispatch(updateIsUpdating(false));
store.dispatch(updateSelectedTrainId(undefined));
store.dispatch(updateSelectedProjection(undefined));
}
Expand Down
23 changes: 21 additions & 2 deletions front/src/applications/operationalStudies/views/Scenario.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import getSimulationResults, {

import NavBarSNCF from 'common/BootstrapSNCF/NavBarSNCF';
import { useModal } from 'common/BootstrapSNCF/ModalSNCF';
import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
import { SimulationReport, osrdEditoastApi } from 'common/api/osrdEditoastApi';
import { useInfraID, useOsrdConfActions, useOsrdConfSelectors } from 'common/osrdContext';

import Timetable from 'modules/trainschedule/components/Timetable/Timetable';
Expand All @@ -32,6 +32,7 @@ import type { RootState } from 'reducers';
import { updateSelectedProjection, updateSimulation } from 'reducers/osrdsimulation/actions';
import {
getAllowancesSettings,
getPresentSimulation,
getSelectedProjection,
getSelectedTrainId,
} from 'reducers/osrdsimulation/selectors';
Expand All @@ -52,6 +53,7 @@ export default function Scenario() {
const [collapsedTimetable, setCollapsedTimetable] = useState(false);
const [isInfraLoaded, setIsInfraLoaded] = useState(false);
const [reloadCount, setReloadCount] = useState(1);
const [trainResultsToFetch, setTrainResultsToFetch] = useState<number[] | undefined>();
const isUpdating = useSelector((state: RootState) => state.osrdsimulation.isUpdating);

const { openModal } = useModal();
Expand All @@ -68,6 +70,7 @@ export default function Scenario() {
const selectedTrainId = useSelector(getSelectedTrainId);
const selectedProjection = useSelector(getSelectedProjection);
const allowancesSettings = useSelector(getAllowancesSettings);
const simulation = useSelector(getPresentSimulation);

const { projectId, studyId, scenarioId } = useMemo(
() => ({
Expand Down Expand Up @@ -173,7 +176,19 @@ export default function Scenario() {

useEffect(() => {
if (timetable && infra?.state === 'CACHED' && selectedProjection) {
getSimulationResults(timetable, selectedProjection, allowancesSettings);
// If trainResultsToFetch is undefined that means it's the first load of the scenario
// and we want to get all timetable trains results
if (trainResultsToFetch) {
getSimulationResults(
trainResultsToFetch,
selectedProjection,
allowancesSettings,
simulation.trains as SimulationReport[]
);
} else {
const trainScheduleIds = timetable.train_schedule_summaries.map((train) => train.id);
getSimulationResults(trainScheduleIds, selectedProjection, allowancesSettings);
}
}
}, [timetable, infra, selectedProjection]);

Expand Down Expand Up @@ -281,6 +296,7 @@ export default function Scenario() {
<TimetableManageTrainSchedule
displayTrainScheduleManagement={displayTrainScheduleManagement}
setDisplayTrainScheduleManagement={setDisplayTrainScheduleManagement}
setTrainResultsToFetch={setTrainResultsToFetch}
infraState={infra.state}
refetchTimetable={refetchTimetable}
refetchConflicts={refetchConflicts}
Expand All @@ -295,6 +311,8 @@ export default function Scenario() {
selectedTrainId={selectedTrainId}
refetchTimetable={refetchTimetable}
conflicts={conflicts}
setTrainResultsToFetch={setTrainResultsToFetch}
simulation={simulation}
/>
)}
</div>
Expand Down Expand Up @@ -347,6 +365,7 @@ export default function Scenario() {
displayTrainScheduleManagement !== MANAGE_TRAIN_SCHEDULE_TYPES.import
}
collapsedTimetable={collapsedTimetable}
setTrainResultsToFetch={setTrainResultsToFetch}
/>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
persistentUndoSimulation,
} from 'reducers/osrdsimulation/simulation';
import {
getDisplaySimulation,
getIsUpdating,
getPresentSimulation,
getSelectedTrain,
Expand All @@ -37,17 +36,18 @@ const MAP_MIN_HEIGHT = 450;
type SimulationResultsProps = {
isDisplayed: boolean;
collapsedTimetable: boolean;
setTrainResultsToFetch: (trainSchedulesIDs?: number[]) => void;
};

export default function SimulationResults({
isDisplayed,
collapsedTimetable,
setTrainResultsToFetch,
}: SimulationResultsProps) {
const { t } = useTranslation('simulation');
const dispatch = useDispatch();

// TIMELINE DISABLED // const { chart } = useSelector(getOsrdSimulation);
const displaySimulation = useSelector(getDisplaySimulation);
const selectedTrain = useSelector(getSelectedTrain);
const simulation = useSelector(getPresentSimulation);
const isUpdating = useSelector(getIsUpdating);
Expand Down Expand Up @@ -167,11 +167,12 @@ export default function SimulationResults({

<div className="osrd-simulation-container d-flex flex-grow-1 flex-shrink-1">
<div className="chart-container" style={{ height: `${heightOfSpaceTimeChart}px` }}>
{displaySimulation && (
{simulation.trains.length > 0 && (
<SpaceTimeChartIsolated
initialHeight={heightOfSpaceTimeChart}
onSetBaseHeight={setHeightOfSpaceTimeChart}
isDisplayed={isDisplayed}
setTrainResultsToFetch={setTrainResultsToFetch}
/>
)}
</div>
Expand Down
79 changes: 43 additions & 36 deletions front/src/applications/stdcm/views/StdcmRequestModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ export default function StdcmRequestModal(props: StdcmRequestModalProps) {
const dispatch = useDispatch();

const [postStdcm] = osrdEditoastApi.endpoints.postStdcm.useMutation();
const [getTrainScheduleResults] =
osrdEditoastApi.endpoints.getTrainScheduleResults.useLazyQuery();
const [postTrainScheduleResults] =
osrdEditoastApi.endpoints.postTrainScheduleResults.useMutation();

const [getTimetable] = osrdEditoastApi.endpoints.getTimetableById.useLazyQuery();

const { updateItinerary } = useOsrdConfActions();

Expand All @@ -58,11 +60,11 @@ export default function StdcmRequestModal(props: StdcmRequestModalProps) {
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController
const controller = new AbortController();

const timetableId = osrdconf.timetableID;
const { timetableID } = osrdconf;

useEffect(() => {
const payload = formatStdcmConf(dispatch, t, osrdconf as OsrdStdcmConfState);
if (payload && currentStdcmRequestStatus === STDCM_REQUEST_STATUS.pending && timetableId) {
if (payload && currentStdcmRequestStatus === STDCM_REQUEST_STATUS.pending && timetableID) {
postStdcm(payload)
.unwrap()
.then((result) => {
Expand All @@ -75,39 +77,44 @@ export default function StdcmRequestModal(props: StdcmRequestModalProps) {
id: 1500,
isStdcm: true,
};

getTrainScheduleResults({
timetableId,
pathId: result.path.id,
})
.unwrap()
.then((timetableTrains) => {
const trains: SimulationReport[] = [...timetableTrains, fakedNewTrain];
const consolidatedSimulation = createTrain(
dispatch,
CHART_AXES.SPACE_TIME,
trains as Train[], // TODO: remove Train interface
t
);
dispatch(updateConsolidatedSimulation(consolidatedSimulation));
dispatch(updateSimulation({ trains }));
dispatch(updateSelectedTrainId(fakedNewTrain.id));

dispatch(
updateSelectedProjection({
id: fakedNewTrain.id,
path: result.path.id,
})
);
getTimetable({ id: timetableID }).then(({ data: timetable }) => {
const trainIdsToFetch =
timetable?.train_schedule_summaries.map((train) => train.id) ?? [];
postTrainScheduleResults({
body: {
path_id: result.path.id,
train_ids: trainIdsToFetch,
},
})
.catch(() => {
dispatch(
setFailure({
name: t('operationalStudies/manageTrainSchedule:errorMessages.stdcmError'),
message: t('translation:common.error'),
})
);
});
.unwrap()
.then((timetableTrains) => {
const trains: SimulationReport[] = [...timetableTrains, fakedNewTrain];
const consolidatedSimulation = createTrain(
dispatch,
CHART_AXES.SPACE_TIME,
trains as Train[], // TODO: remove Train interface
t
);
dispatch(updateConsolidatedSimulation(consolidatedSimulation));
dispatch(updateSimulation({ trains }));
dispatch(updateSelectedTrainId(fakedNewTrain.id));

dispatch(
updateSelectedProjection({
id: fakedNewTrain.id,
path: result.path.id,
})
);
})
.catch(() => {
dispatch(
setFailure({
name: t('operationalStudies/manageTrainSchedule:errorMessages.stdcmError'),
message: t('translation:common.error'),
})
);
});
});
}
})
.catch((e) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export type SpaceTimeChartProps = {
onOffsetTimeByDragging?: (trains: Train[], offset: number, timePosition: Date) => void;
onSetBaseHeight?: (newHeight: number) => void;
isDisplayed?: boolean;
setTrainResultsToFetch?: (trainSchedulesIDs?: number[]) => void;
};

export default function SpaceTimeChart(props: SpaceTimeChartProps) {
Expand All @@ -85,6 +86,7 @@ export default function SpaceTimeChart(props: SpaceTimeChartProps) {
isDisplayed = true,
onOffsetTimeByDragging = noop,
onSetBaseHeight = noop,
setTrainResultsToFetch = noop,
} = props;

const [baseHeight, setBaseHeight] = useState(initialHeight);
Expand Down Expand Up @@ -122,7 +124,7 @@ export default function SpaceTimeChart(props: SpaceTimeChartProps) {
train.id === selectedTrain.id ? timeShiftTrain(train as Train, offset) : train
);
setTrainSimulations(trains as Train[]);
onOffsetTimeByDragging(trains, offset, timePosition);
onOffsetTimeByDragging(trains, offset, timePosition, setTrainResultsToFetch);
}
},
[trainSimulations, selectedTrain, onOffsetTimeByDragging]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,15 @@ function withOSRDData<T extends SpaceTimeChartProps>(
const onOffsetTimeByDragging = (
trains: SimulationReport[],
offset: number,
timePosition: Date
timePosition: Date,
setTrainResultsToFetch: (trainSchedulesIDs?: number[]) => void
) => {
dispatch(persistentUpdateSimulation({ ...simulation, trains }));

// Sets the train which needs its results to be updated
// We know it is always the selected train because when dragging one, it gets the selection
if (selectedTrain && setTrainResultsToFetch) setTrainResultsToFetch([selectedTrain.id]);

if (timePosition && offset) {
const newTimePosition = sec2datetime(datetime2sec(timePosition) + offset);
updateTimePosition(newTimePosition);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6493,7 +6493,6 @@ const ORSD_GRAPH_SAMPLE_DATA: OsrdSimulationState = {
speed_limit_tags: 'Aucune composition',
},
],
displaySimulation: true,
simulation: {
past: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export const changeTrain =
error: getTrainDetailsError,
isSuccess: isGetTrainDetailsSuccess,
} = await dispatch(osrdEditoastApi.endpoints.getTrainScheduleById.initiate({ id }));

if (isGetTrainDetailsSuccess) {
// TODO: add the other information of the trainSchedule (allowances...)
const trainSchedule: TrainSchedulePatch = {
Expand Down
Loading

0 comments on commit 6efc220

Please sign in to comment.