Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
198 changes: 198 additions & 0 deletions src/abstract-interpretation/benchmarking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import fs from 'node:fs';
import type { NodeId } from '../r-bridge/lang-4.x/ast/model/processing/node-id';
import { FlowrAnalyzerBuilder } from '../project/flowr-analyzer-builder';
import { fileProtocol } from '../r-bridge/retriever';
import { BuiltInProcName } from '../dataflow/environments/built-in-proc-name';
import { VertexType } from '../dataflow/graph/vertex';
import { RType } from '../r-bridge/lang-4.x/ast/model/type';
import { IntervalExpressionSemanticsMapper } from './interval/expression-semantics';
import { Identifier } from '../dataflow/environments/identifier';
import { isNotUndefined, isUndefined } from '../util/assert';
import { PentagonExpressionSemanticsMapper } from './pentagon/expression-semantics';
import { IntervalSemanticsMaper } from './interval/condition-semantics';
import { UpperBoundsSemanticsMapper } from './pentagon/upper-bounds/upper-bounds-condition-semantics';
import { NumericIntervalInferenceVisitor } from './interval/numeric-interval-inference';
import { SourceLocation } from '../util/range';
import { NumericPentagonInferenceVisitor } from './pentagon/numeric-pentagon-inference';
import path from 'path';

if(process.argv.length < 4) {
console.error('Usage: ts-node src/abstract-interpretation/benchmarking.ts <file-to-analyze> <output-folder>');
process.exit(1);
}

const filePath = process.argv[2];
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
const outputDirectory = process.argv[3];

interface FileMetadata {
fileName: string;
intervalResultFileName: string;
pentagonResultFileName: string;
loc: number;
numOfConstants: number;
numOfRNumberConstants: number;
RNumberConstantNodeIds: NodeId[];
numOfFunctionCalls: number;
numOfSupportedExpressionFunctionCalls: number;
SupportedExpressionFunctionCallNodeIds: NodeId[];
numOfSupportedConditionFunctionCalls: number;
SupportedConditionFunctionCalls: NodeId[];
numOfConditions: number;
metadataGatheringInMs: number;
baselineInMs: number;
intervalAnalysisInMs: number;
intervalResultGatheringInMs: number;
pentagonAnalysisInMs: number;
pentagonResultGatheringInMs: number;
}

interface InferredValue {
nodeId: NodeId;
inferredValue: string;
significantFigures: string;
sourceLocation: string;
}

void async function() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think this function would be more readable if you split parts of it into separate functions :)

fs.mkdirSync(outputDirectory, { recursive: true });
const fileName = filePath.split('/').reverse()[0];
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
const metadataOutputFile = fileName.slice(0, -2) + '.csv';
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
const intervalResultFile = fileName.slice(0, -2) + '-interval.csv';
const pentagonResultFile = fileName.slice(0, -2) + '-pentagon.csv';

const baselineStart = performance.now();
const analyzer = await new FlowrAnalyzerBuilder()
Comment thread
schuler-henry marked this conversation as resolved.
.setEngine('tree-sitter')
.build();
analyzer.addRequest(fileProtocol + filePath);
const dfg = (await analyzer.dataflow()).graph;
const ast = await analyzer.normalize();

const visitorContext = {
normalizedAst: ast,
dfg: dfg,
controlFlow: await analyzer.controlflow(),
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
ctx: analyzer.inspectContext()
};
const baselineEnd = performance.now();

// Run Interval Analysis
const intervalVisitor = new NumericIntervalInferenceVisitor(visitorContext);

const intervalStart = performance.now();
intervalVisitor.start();
const intervalEnd = performance.now();

const intervalResultStart = performance.now();
const intervalResults: InferredValue[] = [];
for(const nodeId of intervalVisitor.getAbstractTrace().keys()) {
const value = intervalVisitor.getAbstractValue(nodeId);
if(isNotUndefined(value)) {
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
const node = ast.idMap.get(nodeId);
const location = node ? SourceLocation.fromNode(node) : undefined;
Comment thread
schuler-henry marked this conversation as resolved.
Outdated

intervalResults.push({
nodeId: nodeId,
Comment thread
schuler-henry marked this conversation as resolved.
inferredValue: value?.toString() ?? 'undefined',
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
significantFigures: value?.significantFigures?.toString() ?? 'unknown',
sourceLocation: isUndefined(location) ? 'unknown' : SourceLocation.getRange(location).slice(0, 4).toString(),
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
});
}
}
const intervalResultEnd = performance.now();

// Dump Interval Results
const intervalPath = path.join(outputDirectory, intervalResultFile);
if(fs.existsSync(intervalPath)) {
fs.rmSync(intervalPath, { recursive: true, force: true });
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
}
fs.writeFileSync(intervalPath, ['nodeId', 'inferredValue', 'significantFigures', 'sourceLocation'].join(',') + '\n');
for(const result of intervalResults) {
fs.appendFileSync(intervalPath, Object.values(result).map(value => '"' + value + '"').join(',') + '\n');
}
Comment thread
schuler-henry marked this conversation as resolved.
Outdated

// Run Pentagon Analysis
const pentagonVisitor = new NumericPentagonInferenceVisitor(visitorContext);

const pentagonStart = performance.now();
pentagonVisitor.start();
const pentagonEnd = performance.now();

const pentagonResultStart = performance.now();
const pentagonResults: InferredValue[] = [];
for(const nodeId of pentagonVisitor.getAbstractTrace().keys()) {
const value = pentagonVisitor.getAbstractValue(nodeId);
if(isNotUndefined(value)) {
const node = ast.idMap.get(nodeId);
const location = node ? SourceLocation.fromNode(node) : undefined;

pentagonResults.push({
nodeId: nodeId,
Comment thread
schuler-henry marked this conversation as resolved.
inferredValue: value?.toString() ?? 'undefined',
significantFigures: value?.value.interval.significantFigures?.toString() ?? 'unknown',
sourceLocation: isUndefined(location) ? 'unknown' : SourceLocation.getRange(location).slice(0, 4).toString(),
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
});
}
}
const pentagonResultEnd = performance.now();

// Dump Pentagon Results
const pentagonPath = path.join(outputDirectory, pentagonResultFile);
if(fs.existsSync(pentagonPath)) {
fs.rmSync(pentagonPath, { recursive: true, force: true });
}
fs.writeFileSync(pentagonPath, ['nodeId', 'inferredValue', 'significantFigures', 'sourceLocation'].join(',') + '\n');
for(const result of pentagonResults) {
fs.appendFileSync(pentagonPath, Object.values(result).map(value => '"' + value + '"').join(',') + '\n');
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
}

// Create File and Runtime Metadata
const metadataStart = performance.now();
const constants = dfg.verticesOfType(VertexType.Value).toArray();
const numberConstants = constants.filter(value => ast.idMap.get(value[0])?.type === RType.Number);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

if you filter on the ast type you have to be more careful wrt. symbols that resolve to numeric constants (which you miss this way), like NA etc. or pi

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

What woud be ur suggested solution?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you could resolve the value with alias tracking and then check on the unpacked value in case of symbols etc. but generally I'd argue this is fine 1) you do not support pi etc. yourself right now 2) the other counts are very low 3) you do not care about NA(integer) do you?

It was more a comment of something that should be noted wrt. statements made on the result.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Okay 😄


const functionCalls = dfg.verticesOfType(VertexType.FunctionCall).toArray();
Comment thread
schuler-henry marked this conversation as resolved.
const supportedExpressionFunctionCalls = functionCalls.filter(([_, dfgCall]) =>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Maybe it would also be interesting to filter these supported function calls for those calls for which you inferred anything?

isNotUndefined(IntervalExpressionSemanticsMapper().find(([id]) => Identifier.matches(id, dfgCall.name))) ||
isNotUndefined(PentagonExpressionSemanticsMapper.find(([id]) => Identifier.matches(id, dfgCall.name)))
);
const supportedConditionFunctionCalls = functionCalls.filter(([_, dfgCall]) =>
isNotUndefined(IntervalSemanticsMaper().find(([id]) => Identifier.matches(id, dfgCall.name))) ||
isNotUndefined(UpperBoundsSemanticsMapper().find(([id]) => Identifier.matches(id, dfgCall.name))) ||
['&&', '!', '||'].some(id => Identifier.matches(id, dfgCall.name))
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
);
const conditions = functionCalls.filter(([_, dfgCall]) =>
dfgCall.origin.includes(BuiltInProcName.IfThenElse) || dfgCall.origin.includes(BuiltInProcName.WhileLoop)
);//.map(([node, _]) => cfg.graph.ingoingEdges(node)?.keys().toArray()[0]);
const metadataEnd = performance.now();

Comment thread
schuler-henry marked this conversation as resolved.
const fileMetadata: FileMetadata = {
fileName: fileName,
intervalResultFileName: intervalResultFile,
pentagonResultFileName: pentagonResultFile,
loc: analyzer.inspectContext().files.getAllFiles()[0].content().toString().split('\n').length,
numOfConstants: constants.length,
numOfRNumberConstants: numberConstants.length,
RNumberConstantNodeIds: numberConstants.map(([node]) => node),
numOfFunctionCalls: functionCalls.length,
numOfSupportedExpressionFunctionCalls: supportedExpressionFunctionCalls.length,
SupportedExpressionFunctionCallNodeIds: supportedExpressionFunctionCalls.map(([node]) => node),
numOfSupportedConditionFunctionCalls: supportedConditionFunctionCalls.length,
SupportedConditionFunctionCalls: supportedConditionFunctionCalls.map(([node]) => node),
numOfConditions: conditions.length,
Comment thread
schuler-henry marked this conversation as resolved.
metadataGatheringInMs: metadataEnd - metadataStart,
Comment thread
schuler-henry marked this conversation as resolved.
baselineInMs: baselineEnd - baselineStart,
intervalAnalysisInMs: intervalEnd - intervalStart,
intervalResultGatheringInMs: intervalResultEnd - intervalResultStart,
Comment thread
schuler-henry marked this conversation as resolved.
pentagonAnalysisInMs: pentagonEnd - pentagonStart,
pentagonResultGatheringInMs: pentagonResultEnd - pentagonResultStart
};

// Dump File and Runtime Metadata
const fileMetadataPath = path.join(outputDirectory, metadataOutputFile);
if(fs.existsSync(fileMetadataPath)) {
fs.rmSync(fileMetadataPath, { recursive: true, force: true });
}
fs.writeFileSync(fileMetadataPath, Object.keys(fileMetadata).join(',') + '\n' +
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
Comment thread
schuler-henry marked this conversation as resolved.
Outdated
Object.values(fileMetadata).map(value => '"' + value + '"').join(',') + '\n');
}();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Also, for comprehensibility, giving this function a name (e.g. main or so) and calling it by name would be better

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const numericInferenceLogger = log.getSubLogger({ name: 'numeric-pentagon-infere
/**
* Maps function/operator names to the semantic functions.
*/
const PentagonExpressionSemanticsMapper = [
export const PentagonExpressionSemanticsMapper = [
[Identifier.make('+'), unaryBinaryExprOpSemantics(pentagonUnaryIdentityOp, pentagonAddOp)],
[Identifier.make('-'), unaryBinaryExprOpSemantics(pentagonNegativeOp, pentagonSubtractOp)]
] as const satisfies readonly PentagonSemanticsMapperInfo[];
Expand Down