-
Notifications
You must be signed in to change notification settings - Fork 19
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
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
# Mock Observations Model | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[]> { | ||
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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