use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.
the class CounterexampleLoaderHelper method simulateCounterexample.
private void simulateCounterexample(final Counterexample cex, final int startStepIndex, final Map<String, Object> signalNameToSimStateElementMap, final AGREESimulationEngine simulationEngine, final SimulationService simulationService, final SimulationUIService simulationUIService) {
// For each frame in the counter example, step through the simulation and constrain the arguments to match those of the counter example
for (int stepIndex = startStepIndex; stepIndex < cex.getLength(); stepIndex++) {
simulationEngine.resetInputConstraints();
// Constraint simulation variables based on the counterexample
for (final Entry<String, Value> sv : cex.getStep(stepIndex).entrySet()) {
final String signalName = sv.getKey();
final Object stateElement = signalNameToSimStateElementMap.get(signalName);
// Throw exception if the state element corresponding to the signal in the counterexample was not found unless the signal corresponds to a clock or a specification statement
if (stateElement == null) {
// TODO: Cleanup
// Ignore variables that do not have state elements. Need a way to verify that they can be safely ignored. Clocks may be ignored if they aren't
// used. Variables for SpecStatements are okay to ignore but we don't have a way of getting the reference in all cases.
// In the case of a monolithic analysis, the references for all layers are not contained in the reference map
/*
final String renamedClockIdSuffix = agreeSimulationEngine.getSimulationProgram().getAgreeRenaming().forceRename(AgreeASTBuilder.clockIDSuffix);
final boolean isClock = signalName.endsWith(renamedClockIdSuffix);
final EObject ref = refMap.get(signalName);
if(!isClock && !(ref instanceof SpecStatement)) {
//throw new RuntimeException("Unable to find state element for signal '" + signalName + "'");
}
*/
} else {
// Don't include hidden variables
if (!simulationEngine.getCurrentState().isElementHidden(stateElement)) {
// Constrain the next value of the variable to match the value contained in the counter example
final InputConstraint ic = lustreValueToInputConstraint(sv.getValue());
simulationEngine.setInputConstraint(stateElement, ic);
}
}
}
simulationEngine.stepForward();
}
simulationEngine.queueNotification(notification -> {
// Check that the number of simulated frames matches the expected number. It should match the length of the counter example
if (cex.getLength() == notification.getEngineState().getNumberOfFrames()) {
simulationEngine.resetInputConstraints();
} else {
// Determine whether there are unsatisfied properties that are halting the simulation
boolean hasUnsatisfiedProperty = false;
for (final SimulationProperty simProp : simulationEngine.getSimulationProgram().getSimulationProperties()) {
if (notification.getEngineState().getPropertyStatus(simProp) == AGREEPropertyStatus.UNSATISFIED_ERROR) {
hasUnsatisfiedProperty = true;
}
}
if (hasUnsatisfiedProperty) {
Display.getDefault().syncExec(() -> {
final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
final IWorkbenchPage activePage = window.getActivePage();
if (activePage != null) {
try {
activePage.showView(UIConstants.PROPERTIES_VIEW_ID);
} catch (final PartInitException e) {
// Ignore
}
}
final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
final String errorMsg = "One or more properties could not be satisfied. Disable one or more properties from the Simulation Properties view and select Retry to continue.";
class RetryDialog extends MessageDialog {
public RetryDialog() {
super(shell, "Unable to Simulate Counterexample", null, errorMsg, MessageDialog.ERROR, new String[] { "Retry", "End Simulation" }, 0);
setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE);
setBlockOnOpen(false);
}
@Override
protected void buttonPressed(final int buttonId) {
switch(buttonId) {
case // Retry
0:
// Try to resume the simulation
simulationEngine.stepBackward();
simulateCounterexample(cex, notification.getEngineState().getNumberOfFrames() - 1, signalNameToSimStateElementMap, simulationEngine, simulationService, simulationUIService);
break;
case // End Simulation
1:
simulationService.dispose(simulationEngine);
break;
}
super.buttonPressed(buttonId);
}
}
final MessageDialog dlg = new RetryDialog();
dlg.open();
});
} else {
final StatusAdapter statusAdapter = new StatusAdapter(new Status(IStatus.WARNING, FrameworkUtil.getBundle(getClass()).getSymbolicName(), "Simulation halted before every step in the counterexample was simulated.", new RuntimeException("The number of simulated frames does not match the length of the counterexample.")));
statusAdapter.setProperty(IStatusAdapterConstants.TITLE_PROPERTY, "Unable to Simulate Counterexample");
StatusManager.getManager().handle(statusAdapter, StatusManager.SHOW);
}
}
});
}
use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.
the class VariablesView method createView.
@PostConstruct
void createView(final Composite parent) {
final Display display = parent.getDisplay();
colorManager = new DeviceResourceManager(display);
unchangedValueColor = colorManager.createColor(new RGB(192, 192, 192));
constraintErrorColor = colorManager.createColor(red);
greenImage = createColorIconImage(display, green);
redImage = createColorIconImage(display, red);
yellowImage = createColorIconImage(display, yellow);
customColorImage = createColorIconImage(display, customRgb);
// Create root composite
final Composite root = new Composite(parent, SWT.NONE);
final GridLayout rootLayout = new GridLayout(1, false);
root.setLayout(rootLayout);
// Create the variable tree viewer
treeViewer = new VariablesTreeViewer(root, SWT.FULL_SELECTION);
// Enable tooltip support
ColumnViewerToolTipSupport.enableFor(treeViewer);
treeSelectionTracker = new TreeSelectionTracker(treeViewer);
GridDataFactory.fillDefaults().grab(true, true).applyTo(treeViewer.getTree());
treeViewer.setUseHashlookup(true);
final VariableContentProvider contentProvider = new VariableContentProvider();
treeViewer.setContentProvider(contentProvider);
treeViewer.setInput(null);
treeViewer.setComparator(new ViewerComparator() {
@Override
public int compare(final Viewer viewer, final Object e1, final Object e2) {
if (contentProvider.currentState == null) {
return 0;
}
// Sort component instances before other variables
final InstanceObject io1 = contentProvider.currentState.getEngineState().getElementInstanceObject(e1);
final InstanceObject io2 = contentProvider.currentState.getEngineState().getElementInstanceObject(e2);
if (io1 instanceof ComponentInstance && !(io2 instanceof ComponentInstance)) {
return -1;
} else if (io2 instanceof ComponentInstance && !(io1 instanceof ComponentInstance)) {
return 1;
}
// Sort feature instances before the remainder
if (io1 instanceof FeatureInstance && !(io2 instanceof FeatureInstance)) {
return -1;
} else if (io2 instanceof FeatureInstance && !(io1 instanceof FeatureInstance)) {
return 1;
}
final String n1 = contentProvider.currentState.getEngineState().getElementName(e1);
final String n2 = contentProvider.currentState.getEngineState().getElementName(e2);
return getComparator().compare(n1, n2);
}
});
treeViewer.setFilters(new ViewerFilter[] { new ViewerFilter() {
@Override
public boolean select(final Viewer viewer, final Object parentElement, final Object element) {
return !contentProvider.currentState.getEngineState().isElementHidden(element);
}
} });
// Create columns
final TreeViewerColumn nameColumn = new TreeViewerColumn(treeViewer, SWT.NONE);
nameColumn.getColumn().setWidth(200);
nameColumn.getColumn().setText("Name");
nameColumn.getColumn().addControlListener(resizeListener);
nameColumn.setLabelProvider(new StyledCellLabelProvider() {
@Override
public void update(final ViewerCell cell) {
cell.setText(getText(cell.getElement()));
cell.setImage(getImage(cell.getElement()));
}
private String getText(final Object element) {
// Get the name of the frame state element
final SimulatorState state = contentProvider.getCurrentState();
if (state == null) {
return "";
}
return state.getEngineState().getElementName(element);
}
private Image getImage(final Object element) {
final SimulatorState state = contentProvider.getCurrentState();
if (state == null) {
return null;
}
final InstanceObject instanceObject = state.getEngineState().getElementInstanceObject(element);
return instanceObject == null ? null : UiUtil.getModelElementLabelProvider().getImage(instanceObject);
}
});
final TreeViewerColumn nextValueColumn = new TreeViewerColumn(treeViewer, SWT.NONE);
nextValueColumn.getColumn().setWidth(100);
nextValueColumn.getColumn().setText("Next Value");
nextValueColumn.setLabelProvider(new OwnerDrawLabelProvider() {
@Override
public void initialize(final ColumnViewer viewer, final ViewerColumn column) {
super.initialize(viewer, column, true);
}
@Override
public void update(final ViewerCell cell) {
final String constraintTxt = getConstraintText(cell.getElement());
final String txt;
final Color foreground;
if (constraintTxt == null) {
// Attempt to retrieve the value for the next frame from from the engine state.
final SimulatorState state = contentProvider.getCurrentState();
if (state == null) {
txt = "";
} else {
final SimulationEngineState engineState = state.getEngineState();
txt = ValueFormatter.formatValue(engineState.getElementValue(engineState.getNumberOfFrames(), cell.getElement()));
}
foreground = unchangedValueColor;
} else {
txt = constraintTxt;
foreground = null;
}
cell.setText(txt);
cell.setForeground(foreground);
super.update(cell);
}
private String getConstraintText(final Object element) {
// Return the invalid value if the input that was entered is not correct
final ConstraintError constraintError = elementToConstraintErrorMap.get(element);
if (constraintError != null) {
return constraintError.constraint;
}
final SimulationEngineState engineState = simulationUiService.getCurrentState().getEngineState();
if (engineState == null) {
return null;
}
final InputConstraint ic = engineState.getElementInputConstraintForNextFrame(element);
if (ic == null) {
return null;
}
return inputConstraintHelper.unparse(ic);
}
@Override
public String getToolTipText(final Object element) {
final ConstraintError constraintError = elementToConstraintErrorMap.get(element);
if (constraintError == null) {
return super.getToolTipText(element);
} else {
return constraintError.errorMessage;
}
}
@Override
protected void measure(final Event event, final Object element) {
}
@Override
protected void erase(final Event event, final Object element) {
// Color cells which contain invalid values
if (elementToConstraintErrorMap.containsKey(element)) {
final GC gc = event.gc;
final Color oldBackground = event.gc.getBackground();
gc.setBackground(constraintErrorColor);
final Rectangle bounds = event.getBounds();
gc.fillRectangle(bounds);
gc.setBackground(oldBackground);
// Ensure that selection and hover indicators are not drawn for the highlighted cell
event.detail &= ~SWT.SELECTED;
event.detail &= ~SWT.HOT;
}
// Disable drawing foreground. paint() will draw the foreground text in order to fix coloring issues when the row is selected.
event.detail &= ~SWT.FOREGROUND;
}
@Override
protected void paint(final Event event, final Object element) {
// Draw just the text with the appropriate background color
final TreeItem item = (TreeItem) event.item;
final Rectangle textBounds = item.getTextBounds(event.index);
final GC gc = event.gc;
final String txt = item.getText(event.index);
gc.setForeground(item.getForeground(event.index));
String drawTxt = txt;
// Check the width of the text and truncate it as necessary
final int maxWidth = Math.max(gc.getClipping().width - 6, textBounds.width);
if (maxWidth > 0) {
String truncatedTxt = txt;
while (gc.textExtent(drawTxt).x > maxWidth && truncatedTxt.length() > 0) {
truncatedTxt = truncatedTxt.substring(0, truncatedTxt.length() - 1);
drawTxt = truncatedTxt + "...";
}
gc.drawString(drawTxt, textBounds.x, textBounds.y, true);
}
}
});
nextValueEditingSupport = new NextValueEditingSupport(simulationUiService, treeViewer);
nextValueColumn.setEditingSupport(nextValueEditingSupport);
nextValueColumn.getColumn().addControlListener(resizeListener);
// Make headers and lines visible
final Tree tree = treeViewer.getTree();
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
createContextMenu(tree);
// Listen for tree resizing
tree.addControlListener(resizeListener);
// Create the slider
frameSlider = new Slider(root, SWT.HORIZONTAL);
frameSlider.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
if (!editingTreeViewer) {
startEditingTreeViewer();
frameScrollOffset = frameSlider.getMaximum() - frameSlider.getSelection() - frameSlider.getThumb();
update();
stopEditingTreeViewer();
}
}
});
GridDataFactory.fillDefaults().grab(true, false).applyTo(frameSlider);
// Add listener and populate UI with current state
simulationUiService.addStateChangeListener(stateListener);
stateListener.onSimulatorStateChanged(simulationUiService.getCurrentState());
}
use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.
the class InputConstraintHelper method parse.
/**
* @param str
* @return the result of parsing the input constraint string. Returns a valid result with a null input constraint if str is null or empty.
*/
public Result parse(final String str) {
if (str == null || str.trim().length() == 0) {
return new Result((InputConstraint) null);
}
final IParseResult result = parser.parse(new StringReader(str));
// Check for syntax errors
if (result.hasSyntaxErrors()) {
String errors = "Error parsing '" + str + "':";
for (final INode err : result.getSyntaxErrors()) {
errors += "\n" + err.getSyntaxErrorMessage().getMessage();
}
return new Result(errors);
}
final InputConstraint ic = (InputConstraint) result.getRootASTElement();
final Resource r = createResource();
r.getContents().add(ic);
return new Result(ic);
}
use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.
the class InputConstraintDialog method addTextExpressionMenuItem.
/**
* This function will bubble up to edit the parent if the parent is a binary or negative expression
* @param menu
* @param ref
* @param label
* @param expectedType
* @param defaultExpressionTxt used if the reference is null
*/
private void addTextExpressionMenuItem(final Menu menu, Reference ref, final String label, final ResultType expectedType, final String defaultExpressionTxt) {
// If the value is part of a binary expression, prompt the user to edit the entire containing binary expression.
while (ref.getParent() != null && (ref.getParent().get() instanceof BinaryExpression || ref.getParent().get() instanceof NegativeExpression)) {
ref = ref.getParent();
}
final Reference refToEdit = ref;
final MenuItem menuItem = new MenuItem(menu, SWT.NONE);
menuItem.setText(label);
// Disable the menu item if unable to unparse
final InputConstraint ic = (InputConstraint) refToEdit.get();
final String exprTxt = unparse(ic);
menuItem.setEnabled(exprTxt != null);
if (menuItem.isEnabled()) {
menuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
final InputDialog txtExpressionDlg = new InputDialog(dlg.getShell(), "Edit Expression", "Edit Expression", exprTxt, value -> getParseAndValidateResult(value, expectedType).getErrorMessage());
if (txtExpressionDlg.open() == Window.OK) {
refToEdit.set(getParseAndValidateResult(txtExpressionDlg.getValue(), expectedType).getInputConstraint());
dlg.refreshContraint();
}
}
});
}
}
use of edu.uah.rsesc.aadlsimulator.xtext.inputConstraint.InputConstraint in project AGREE by loonwerks.
the class InputConstraintDialog method main.
public static void main(final String[] args) {
new Display();
final com.google.inject.Injector injector = new InputConstraintStandaloneSetup().createInjectorAndDoEMFRegistration();
final InputConstraintHelper icHelper = injector.getInstance(InputConstraintHelper.class);
final TestReferenceTypeResolver resolver = new TestReferenceTypeResolver();
// Create model to provide information to the dialog.
final Model model = new Model() {
@Override
public String unparse(final InputConstraint ic) {
return icHelper.unparse(ic);
}
@Override
public InputConstraintHelper.Result parseAndValidate(final String str, final ResultType expectedType, final int numberOfPreviousSteps) {
return icHelper.parseAndValidate(str, resolver, expectedType, numberOfPreviousSteps);
}
@Override
public InputConstraintHelper.Result validate(final InputConstraint ic, final ResultType expectedType, final int numberOfPreviousSteps) {
return icHelper.validate(ic, resolver, expectedType, numberOfPreviousSteps);
}
@Override
public Stream<ElementRefExpression> getVariables() {
final Stream.Builder<ElementRefExpression> builder = Stream.builder();
builder.add(createElementRefExpression("a1", "b", "d"));
builder.add(createElementRefExpression("a1"));
builder.add(createElementRefExpression("a1", "b"));
builder.add(createElementRefExpression("a1", "b", "c"));
builder.add(createElementRefExpression("a2", "b"));
builder.add(createElementRefExpression("a2"));
return builder.build();
}
private ElementRefExpression createElementRefExpression(String... ids) {
final ElementRefExpression result = InputConstraintFactory.eINSTANCE.createElementRefExpression();
result.getIds().addAll(Arrays.asList(ids));
return result;
}
@Override
public ResultType getElementReferenceType(final ElementRefExpression reference) {
return resolver.getElementReferenceType(reference);
}
@Override
public Stream<ConstRefExpression> getConstants() {
final Stream.Builder<ConstRefExpression> builder = Stream.builder();
builder.add(createConstRefExpression("C1", "my_pkg"));
builder.add(createConstRefExpression("C2", "my_pkg", "inner_pkg"));
builder.add(createConstRefExpression("C3A", "my_pkg", "inner_pkg", "inner_inner_pkg"));
builder.add(createConstRefExpression("C3B", "my_pkg", "inner_pkg", "inner_inner_pkg"));
builder.add(createConstRefExpression("C3C", "my_pkg", "inner_pkg", "inner_inner_pkg"));
builder.add(createConstRefExpression("C3D", "my_pkg", "inner_pkg", "inner_inner_pkg"));
return builder.build();
}
private ConstRefExpression createConstRefExpression(final String constantName, final String... packageSegments) {
final ConstRefExpression result = InputConstraintFactory.eINSTANCE.createConstRefExpression();
result.setConstantName(constantName);
result.getPackageSegments().addAll(Arrays.asList(packageSegments));
return result;
}
@Override
public ResultType getConstReferenceType(final ConstRefExpression reference) {
return resolver.getConstReferenceType(reference);
}
};
// Show the dialog
final InputConstraint initialConstraint = icHelper.parse("5 + 5").getInputConstraint();
final Result result = InputConstraintDialog.show(null, model, "z", initialConstraint, ResultType.INTEGER, 1);
if (result == null) {
System.out.println("Dialog canceled");
} else {
System.out.println("Result:");
System.out.println(result.inputConstraint);
}
}
Aggregations