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

Mock observations model #28

Closed
wants to merge 4 commits into from
Closed
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
1 change: 1 addition & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './ccf';
export * from './teads-aws';
export * from './teads-curve';
export * from './watt-time';
export * from './mock-observations';
81 changes: 81 additions & 0 deletions src/lib/mock-observations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Mock Observations Model
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR should be opened on official models repo

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

README should reflect the model is in official models repo


> [!NOTE]
> `Mock-observations` is a community model, not part of the IF standard library. This means the IF core team are not closely monitoring these models to keep them up to date. You should do your own research before implementing them!

## Introduction

A model for mocking observations (inputs) for testing and demo purposes

## Scope

The mode currently mocks 2 types of observation data:
- Common key-value pairs, that are generated statically and are the same for each generated observation/input (see 'helpers/CommonGenerator.ts')
- Randomly generated integer values for predefined keys (see 'helpers/RandIntGenerator.ts')


## Implementation

The model's 'config' section in the impl file determines its behaviour.
('inputs' section is ignored).
Config section will have the the following fields (see example below):
```yaml
timestamp-from
timestamp-to
duration
components
generators
```
- **timestamp-from**, **timestamp-to** and **duration** define time buckets for which to generate observations.
- **generators** define which fields to generate for each observations
- **components** define the components for which to generate observations for. The observations generated according to **timestamp-from**, **timestamp-to**, **duration** and **generators** will be duplicated for each component.
All generators implement the Generator interface, see 'interfaces/index.ts'
For more information on the models spec please refer to https://github.com/Green-Software-Foundation/if/issues/332


### Authentication

N/A

### inputs

The model's 'config' section in the impl file determines its behaviour.
'inputs' section is ignored.

### Typescript Usage
```typescript
const mock_obs_model = await new MockObservations().configure('mock-observations', {
timestamp-from: 2023-07-06T00:00
timestamp-to: 2023-07-06T00:10
duration: 60
components:
- instance-type: A1
generators:
common:
region: uk-west
});
const inputs = [{}];
const results = mock_obs_model.execute(inputs);
```

### IMPL Example
```yaml
mock-observations:
timestamp-from: 2023-07-06T00:00
timestamp-to: 2023-07-06T00:10
duration: 60
components:
- instance-type: A1
- instance-type: B1
generators:
common:
region: uk-west
common-key: common-val
randint:
cpu-util:
min: 1
max: 99
mem-util:
min: 1
max: 99
```
52 changes: 52 additions & 0 deletions src/lib/mock-observations/helpers/CommonGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {Generator} from '../interfaces';
import * as yaml from 'js-yaml';
import {ERRORS} from '../../../util/errors';
import {buildErrorMessage} from '../../../util/helpers';
const {InputValidationError} = ERRORS;

class CommonGenerator implements Generator {
private name = '';
private generateObject: {} = {};
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
errorBuilder = buildErrorMessage(CommonGenerator);
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved

initialise(name: string, config: {[key: string]: any}): void {
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
this.name = this.validateName(name);
this.generateObject = this.validateConfig(config);
}

next(_historical: Object[]): Object {

Check warning on line 17 in src/lib/mock-observations/helpers/CommonGenerator.ts

View workflow job for this annotation

GitHub Actions / build

'_historical' is defined but never used
return Object.assign({}, this.generateObject);
}

public getName(): String {
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
return this.name;
}

private validateName(name: string | null): string {
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
if (name === null || name.trim() === '') {
throw new InputValidationError(
this.errorBuilder({message: 'name is null'})
);
}
return name;
}

private validateConfig(config: {[key: string]: any}): {[key: string]: any} {
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
if (!config || Object.keys(config).length === 0) {
throw new InputValidationError(
this.errorBuilder({message: 'Config must not be null or empty'})
);
}
let ret: {[key: string]: any} = {};
try {
ret = yaml.load(JSON.stringify({...config})) as {[key: string]: any};
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
} catch (error) {
throw new InputValidationError(
this.errorBuilder({message: 'Invalid YML structure'})
);
}
return ret;
}
}

export default CommonGenerator;
62 changes: 62 additions & 0 deletions src/lib/mock-observations/helpers/RandIntGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {Generator} from '../interfaces';
import {ERRORS} from '../../../util/errors';
import {buildErrorMessage} from '../../../util/helpers';
const {InputValidationError} = ERRORS;

class RandIntGenerator implements Generator {
private static readonly MIN: string = 'min';
private static readonly MAX: string = 'max';
private fieldToPopulate = '';
private min = 0;
private max = 0;
errorBuilder = buildErrorMessage(RandIntGenerator);

initialise(fieldToPopulate: string, config: {[key: string]: any}): void {
this.fieldToPopulate = this.validateName(fieldToPopulate);
this.validateConfig(config);
this.min = config[RandIntGenerator.MIN];
this.max = config[RandIntGenerator.MAX];
}

next(_historical: Object[]): Object {

Check warning on line 21 in src/lib/mock-observations/helpers/RandIntGenerator.ts

View workflow job for this annotation

GitHub Actions / build

'_historical' is defined but never used
const retObject = {
[this.fieldToPopulate]: this.generateRandInt(),
};
return retObject;
}

private validateName(name: string | null): string {
if (name === null || name.trim() === '') {
throw new InputValidationError(
this.errorBuilder({message: 'name is empty or null'})
);
}
return name;
}

private validateConfig(config: {[key: string]: any}): void {
if (!Object.prototype.hasOwnProperty.call(config, RandIntGenerator.MIN)) {
throw new InputValidationError(
this.errorBuilder({
message: 'config is missing ' + RandIntGenerator.MIN,
})
);
}
if (!Object.prototype.hasOwnProperty.call(config, RandIntGenerator.MAX)) {
throw new InputValidationError(
this.errorBuilder({
message: 'config is missing ' + RandIntGenerator.MAX,
})
);
}
}

private generateRandInt(): number {
const randomNumber = Math.random();
const scaledNumber = randomNumber * (this.max - this.min) + this.min;
const truncatedNumber = Math.trunc(scaledNumber);
return truncatedNumber;
}
}

export default RandIntGenerator;
146 changes: 146 additions & 0 deletions src/lib/mock-observations/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import {ERRORS} from '../../util/errors';
import {buildErrorMessage} from '../../util/helpers';
import {ModelParams} from '../../types/common';
import {ModelPluginInterface} from '../../interfaces';
import * as dayjs from 'dayjs';
import CommonGenerator from './helpers/CommonGenerator';
import RandIntGenerator from './helpers/RandIntGenerator';
import Generator from './interfaces/index';
const {InputValidationError} = ERRORS;

export class MockObservations implements ModelPluginInterface {
private errorBuilder = buildErrorMessage(MockObservations);
private duration = 0;
private timeBuckets: dayjs.Dayjs[] = [];
private components: Record<string, Record<string, string>> = {};
private generators: Generator[] = [];

async execute(_inputs: ModelParams[]): Promise<any[]> {

Check warning on line 18 in src/lib/mock-observations/index.ts

View workflow job for this annotation

GitHub Actions / build

'_inputs' is defined but never used
const observations: ModelParams[] = [];
const generatorToHistory = new Map<Generator, number[]>();
this.generators.forEach(generator => {
generatorToHistory.set(generator, []);
});
for (const componentKey in this.components) {
if (Object.prototype.hasOwnProperty.call(this.components, componentKey)) {
const component = this.components[componentKey];
for (const timeBucket of this.timeBuckets) {
const observation = this.createObservation(
component,
timeBucket,
generatorToHistory
);
observations.push(observation);
}
}
}
return observations;
}

async configure(
staticParams: object | undefined
): Promise<ModelPluginInterface> {
if (staticParams === undefined) {
throw new InputValidationError(
this.errorBuilder({message: 'Input data is missing'})
);
}
const timestampFrom: dayjs.Dayjs = dayjs(
this.getValidatedParam(
'timestamp-from',
staticParams
) as unknown as string
);
const timestampTo: dayjs.Dayjs = dayjs(
this.getValidatedParam('timestamp-to', staticParams) as unknown as string
);
const duration = this.getValidatedParam(
'duration',
staticParams
) as unknown as number;
this.timeBuckets = this.createTimeBuckets(
timestampFrom,
timestampTo,
duration
);
this.components = this.getValidatedParam(
'components',
staticParams
) as Record<string, Record<string, string>>;
this.generators = this.createGenerators(
this.getValidatedParam('generators', staticParams)
);
return this;
}

private getValidatedParam(
attributeName: string,
params: {[key: string]: any}
): object {
if (attributeName in params) {
return params[attributeName];
} else {
throw new InputValidationError(
this.errorBuilder({message: attributeName + ' missing from params'})
);
}
}

private createTimeBuckets(
timestampFrom: dayjs.Dayjs,
timestampTo: dayjs.Dayjs,
duration: number
): dayjs.Dayjs[] {
const timeBuckets: dayjs.Dayjs[] = [];
let currTimestamp: dayjs.Dayjs = timestampFrom;
while (
currTimestamp.isBefore(timestampTo) ||
currTimestamp.isSame(timestampTo, 'second')
) {
timeBuckets.push(currTimestamp);
currTimestamp = currTimestamp.add(duration, 'second');
}
return timeBuckets;
}

private createGenerators(generatorsConfig: object): Generator[] {
const generators: Generator[] = [];
Object.entries(generatorsConfig).forEach(([key, value]) => {
if ('common' === key) {
const commonGenerator = new CommonGenerator();
commonGenerator.initialise('common-generator', value);
generators.push(commonGenerator);
}
if ('randint' === key) {
for (const fieldToPopulate in value) {
const randIntGenerator = new RandIntGenerator();
randIntGenerator.initialise(fieldToPopulate, value[fieldToPopulate]);
generators.push(randIntGenerator);
}
}
});
return generators;
}

private createObservation(
component: Record<string, string>,
timeBucket: dayjs.Dayjs,
generatorToHistory: Map<Generator, number[]>
): ModelParams {
const observation: ModelParams = {
timestamp: timeBucket.format('YYYY-MM-DD HH:mm:ss'),
duration: this.duration,
};
Object.assign(observation, component);
for (const generator of this.generators) {
const generated: Record<string, any> = generator.next(
generatorToHistory.get(generator)
);
generatorToHistory.get(generator)?.push(generated.value);
Object.assign(observation, generated);
}
return observation;
}
}

export default MockObservations;
11 changes: 11 additions & 0 deletions src/lib/mock-observations/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export interface Generator {
/**
* initialise the generator with the given name and config.
*/
initialise(name: String, config: {[key: string]: any}): void;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check with Asim if we can replace this with a plain ctor

pazbardanl marked this conversation as resolved.
Show resolved Hide resolved
/**
* generate the next value, optionally based on historical values
*/
next(historical: Object[] | undefined): Object;
}
export default Generator;
pazbardanl marked this conversation as resolved.
Show resolved Hide resolved