Skip to content

Implement GCD calculation and resampling resolution for time sync #1109

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions src/__tests__/if-run/builtins/time-sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -945,7 +945,7 @@ describe('builtins/time-sync:', () => {
expect(result).toStrictEqual(expectedResult);
});

it('should throw an error if the upsampling resolution is not compatible with the interval', async () => {
it('should throw an error if the upsampling resolution is not compatible with the interval (interval is bigger than upsampling).', async () => {
const basicConfig = {
'start-time': '2023-12-12T00:00:00.000Z',
'end-time': '2023-12-12T00:00:03.000Z',
Expand All @@ -970,7 +970,7 @@ describe('builtins/time-sync:', () => {
}
});

it('should throw an error if the upsampling resolution is not compatible with paddings', async () => {
it('should throw an error if the upsampling resolution is not compatible with paddings (interval is equal to upsampling).', async () => {
const basicConfig = {
'start-time': '2023-12-12T00:00:00.000Z',
'end-time': '2023-12-12T00:00:12.000Z',
Expand Down
62 changes: 59 additions & 3 deletions src/if-run/builtins/time-sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ export const TimeSync = PluginFactory<TimeNormalizerConfig>({
timeStep: number
) => {
const metrics = Object.keys(input);

return metrics.reduce((acc, metric) => {
if (metric === 'timestamp') {
acc[metric] =
Expand Down Expand Up @@ -483,15 +484,70 @@ export const TimeSync = PluginFactory<TimeNormalizerConfig>({
}, [] as PluginParams[]);

/** Implementation */
/**
* Calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.
*/
const greatestCommonDivisor = (a: number, b: number): number => {
while (b !== 0) {
[a, b] = [b, a % b];
}

return a;
};

/**
* Calculates the greatest common divisor (GCD) of an array of numbers.
*/
const calculateGCD = (numbers: number[]) =>
numbers.reduce((acc, val) => greatestCommonDivisor(acc, val));

/**
* Returns an array of unique values from the given array.
*/
const getUniqueValues = (arr: number[]) => Array.from(new Set(arr));

/**
* Finds the most efficient resampling resolution based on the given inputs and user-defined interval.
*
* This function calculates the greatest common divisor (GCD) of the combined unique values from:
* - A: All unique values of (timestamp + duration) for each input.
* - B: All unique values of (next timestamp - current timestamp + duration) for each input.
*/
const findResamplingResolution = (
inputs: PluginParams[],
userInterval: number
): number => {
const A: number[] = [];
const B: number[] = [];

for (let i = 0; i < inputs.length - 1; i++) {
const currentTimestamp = parseDate(inputs[i].timestamp).toMillis();
const nextTimestamp = parseDate(inputs[i + 1].timestamp).toMillis();

A.push(currentTimestamp + inputs[i].duration);
B.push(nextTimestamp - currentTimestamp + inputs[i].duration);
}

const uniqueA = getUniqueValues(A);
const uniqueB = getUniqueValues(B);
const combined = [...uniqueA, ...uniqueB, userInterval];

return calculateGCD(combined);
};

const upsamplingResolution =
config['upsampling-resolution'] ||
findResamplingResolution(inputs, config.interval);
console.log(`Choosen upsampling resolution is ${upsamplingResolution}\n`);

const timeParams = {
startTime: DateTime.fromISO(config['start-time'] as string),
endTime: DateTime.fromISO(config['end-time'] as string),
interval: config.interval,
allowPadding: config['allow-padding'],
upsamplingResolution: config['upsampling-resolution']
? config['upsampling-resolution']
: 1,
upsamplingResolution,
};

validateIntervalForResample(
timeParams.interval,
timeParams.upsamplingResolution,
Expand Down
3 changes: 2 additions & 1 deletion src/if-run/lib/compute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ const {
const childNames = new Set();

/**
* Traverses all child nodes based on children grouping.
* Traverses through the children nodes and computes each child node.
* It also adds the child name to the `childNames` set.
*/
const traverse = async (children: any, params: ComputeParams) => {
for (const child in children) {
Expand Down