Skip to content

Commit

Permalink
Avoid NaN impact values, order interventions desc
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeh committed Nov 22, 2022
1 parent 9ddba51 commit 00c156a
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 62 deletions.
3 changes: 3 additions & 0 deletions api/src/modules/indicator-records/indicator-record.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
Check,
Column,
Entity,
getManager,
Expand Down Expand Up @@ -39,6 +40,8 @@ export enum INDICATOR_RECORD_STATUS {
}

@Entity()
@Check(`value <> 'NaN'`)
@Check(`scaler <> 'NaN'`)
export class IndicatorRecord extends TimestampedBaseEntity {
@ApiProperty()
@PrimaryGeneratedColumn('uuid')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
Injectable,
Logger,
NotFoundException,
ServiceUnavailableException,
} from '@nestjs/common';
import { IndicatorRecordRepository } from 'modules/indicator-records/indicator-record.repository';
Expand All @@ -19,17 +18,12 @@ import {
IndicatorRecord,
} from 'modules/indicator-records/indicator-record.entity';
import { IndicatorCoefficientsDtoV2 } from 'modules/indicator-coefficients/dto/indicator-coefficients.dto';
import {
MaterialToH3,
MATERIAL_TO_H3_TYPE,
} from 'modules/materials/material-to-h3.entity';
import { MaterialToH3 } from 'modules/materials/material-to-h3.entity';
import { MissingH3DataError } from 'modules/indicator-records/errors/missing-h3-data.error';
import { IndicatorRecordCalculatedValuesDtoV2 } from 'modules/indicator-records/dto/indicator-record-calculated-values.dto';
import { MaterialsToH3sService } from 'modules/materials/materials-to-h3s.service';
import { IndicatorsService } from 'modules/indicators/indicators.service';
import { SourcingRecord } from 'modules/sourcing-records/sourcing-record.entity';
import { H3Data } from 'modules/h3-data/h3-data.entity';
import { H3DataService } from 'modules/h3-data/h3-data.service';
import { IndicatorDependencyManager } from 'modules/indicator-records/services/indicator-dependency-manager.service';

/**
Expand All @@ -46,7 +40,6 @@ export class ImpactCalculator {
private readonly materialToH3: MaterialsToH3sService,
private readonly indicatorService: IndicatorsService,
private readonly dependencyManager: IndicatorDependencyManager,
private readonly h3DataService: H3DataService,
) {}

async calculateImpactForAllSourcingRecords(
Expand All @@ -58,9 +51,9 @@ export class ImpactCalculator {
const newImpactToBeSaved: IndicatorRecord[] = [];

rawData.forEach((data: SourcingRecordsWithIndicatorRawDataDtoV2) => {
const landPerTon: number = data.harvestedArea ?? 0 / data.production ?? 0;
const landPerTon: number = data.harvestedArea / data.production || 0;
const weightedTotalCropLandArea: number =
data.weightedAllHarvest ?? 0 / data.production ?? 0;
data.weightedAllHarvest / data.production || 0;
const deforestationPerHarvestLandUse: number =
weightedTotalCropLandArea > 0
? data.rawDeforestation / weightedTotalCropLandArea
Expand Down Expand Up @@ -194,9 +187,9 @@ export class ImpactCalculator {
>();

const landPerTon: number =
rawData.harvestedArea ?? 0 / rawData.production ?? 0;
rawData.harvestedArea / rawData.production || 0;
const weightedTotalCropLandArea: number =
rawData.weightedAllHarvest ?? 0 / rawData.production ?? 0;
rawData.weightedAllHarvest / rawData.production || 0;
const deforestationPerHarvestLandUse: number =
weightedTotalCropLandArea > 0
? rawData.rawDeforestation / weightedTotalCropLandArea
Expand All @@ -209,8 +202,7 @@ export class ImpactCalculator {
const deforestation: number = deforestationPerHarvestLandUse * landUse;
const carbonLoss: number = carbonPerHarvestLandUse * landUse;
const waterUse: number = rawData.rawWater * sourcingData.tonnage;
const unsustainableWaterUse: number =
waterUse * rawData.waterStressPerct ? rawData.waterStressPerct : 0;
const unsustainableWaterUse: number = waterUse * rawData.waterStressPerct;

calculatedIndicatorRecordValues.values.set(
INDICATOR_TYPES_NEW.CLIMATE_RISK,
Expand Down Expand Up @@ -275,9 +267,8 @@ export class ImpactCalculator {
]);
return res[0];
} catch (error: any) {
console.error(error);
throw new ServiceUnavailableException(
`Could not calculate Raw Indicator values for new Scenario`,
`Could not calculate Raw Indicator values for new Scenario ` + error,
);
}
}
Expand Down Expand Up @@ -316,22 +307,22 @@ export class ImpactCalculator {
calculatedIndicatorValues.values.set(
INDICATOR_TYPES_NEW.LAND_USE,
newIndicatorCoefficients[INDICATOR_TYPES_NEW.LAND_USE] *
sourcingData.tonnage,
sourcingData.tonnage || 0,
);
calculatedIndicatorValues.values.set(
INDICATOR_TYPES_NEW.DEFORESTATION_RISK,
newIndicatorCoefficients[INDICATOR_TYPES_NEW.DEFORESTATION_RISK] *
sourcingData.tonnage,
sourcingData.tonnage || 0,
);
calculatedIndicatorValues.values.set(
INDICATOR_TYPES_NEW.CLIMATE_RISK,
newIndicatorCoefficients[INDICATOR_TYPES_NEW.CLIMATE_RISK] *
sourcingData.tonnage,
sourcingData.tonnage || 0,
);
calculatedIndicatorValues.values.set(
INDICATOR_TYPES_NEW.WATER_USE,
newIndicatorCoefficients[INDICATOR_TYPES_NEW.WATER_USE] *
sourcingData.tonnage,
sourcingData.tonnage || 0,
);

// TODO: We need to ignore satelligence indicators from being affected by a coefficient that a user can send
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export class ScenarioInterventionRepository extends Repository<ScenarioIntervent
// .leftJoin('intervention.replacedSuppliers', 'replacedSuppliers')

.where('intervention.scenarioId = :scenarioId', { scenarioId })
.orderBy('intervention.createdAt', 'DESC')
.getMany()
);
}
Expand Down
28 changes: 27 additions & 1 deletion api/test/e2e/scenarios/scenarios.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ describe('ScenariosModule (e2e)', () => {
expect(response).toHaveJSONAPIAttributes(expectedJSONAPIAttributes);
});
test(
'When I filter a Scenario by Id and I include its interventions in the query + ' +
'When I filter Interventions by Scenario Id + ' +
'Then I should receive said Interventions in the response' +
'And they should include the replaced entity information',
async () => {
Expand Down Expand Up @@ -511,4 +511,30 @@ describe('ScenariosModule (e2e)', () => {
},
);
});
test(
'When I filter Interventions by Scenario Id + ' +
'Then I should receive said Interventions in the response' +
'And they should be ordered by creation date in a DESC order',
async () => {
const interventions: ScenarioIntervention[] = [];

const scenario: Scenario = await createScenario();

for (const n of [1, 2, 3, 4, 5]) {
const intervention = await createScenarioIntervention({
scenario,
title: `inter ${n}`,
});
interventions.push(intervention);
}
const response = await request(app.getHttpServer())
.get(`/api/v1/scenarios/${scenario.id}/interventions`)
.set('Authorization', `Bearer ${jwtToken}`)
.send();

expect(
interventions.map((i: ScenarioIntervention) => i.id).reverse(),
).toEqual(response.body.data.map((i: ScenarioIntervention) => i.id));
},
);
});
Loading

0 comments on commit 00c156a

Please sign in to comment.