Search in sources :

Example 11 with CompoundModel

use of org.eclipse.scanning.api.points.models.CompoundModel in project gda-core by openGDA.

the class XanesSubmitScanSection method submitScan.

@Override
protected void submitScan() {
    final IScriptService scriptService = getService(IScriptService.class);
    final ScanRequest scanRequest = getScanRequest(getMappingBean());
    final XanesEdgeParametersSection paramsSection = getMappingView().getSection(XanesEdgeParametersSection.class);
    final XanesEdgeParameters xanesEdgeParameters = paramsSection.getScanParameters();
    if (xanesEdgeParameters.isEnforcedShape()) {
        final CompoundModel newModel = new CompoundModel(scanRequest.getCompoundModel());
        final List<IScanPointGeneratorModel> models = newModel.getModels();
        final List<IScanPointGeneratorModel> enforcedShapes = new ArrayList<>(models.size());
        for (IScanPointGeneratorModel model : models) {
            enforcedShapes.add(enforce(model));
        }
        newModel.setModels(enforcedShapes);
        scanRequest.setCompoundModel(newModel);
    }
    xanesEdgeParameters.setVisitId(InterfaceProvider.getBatonStateProvider().getBatonHolder().getVisitID());
    // Add XANES parameters as metadata to the ScanRequest, so they appear in the Nexus file
    final ScanMetadata xanesMetadata = new ScanMetadata(MetadataType.ENTRY);
    xanesMetadata.addField("tracking_method", xanesEdgeParameters.getTrackingMethod());
    xanesMetadata.addField("visit_id", xanesEdgeParameters.getVisitId());
    final LinesToTrackEntry linesToTrackEntry = xanesEdgeParameters.getLinesToTrack();
    if (linesToTrackEntry == null || linesToTrackEntry.getLine() == null || linesToTrackEntry.getLine().isEmpty()) {
        // The entry for a blank "lines to track" contains an unmodifiable Collection, which causes problems in
        // marshalling, so make sure it is set null.
        xanesEdgeParameters.setLinesToTrack(null);
        xanesMetadata.addField("line", "None");
    } else {
        xanesMetadata.addField("line", linesToTrackEntry.getLine());
        xanesMetadata.addField("file_paths", new ArrayList<String>(linesToTrackEntry.getFilePaths()));
    }
    final List<ScanMetadata> scanMetadata = new ArrayList<>(scanRequest.getScanMetadata());
    scanMetadata.add(xanesMetadata);
    scanRequest.setScanMetadata(scanMetadata);
    try {
        final IMarshallerService marshallerService = getService(IMarshallerService.class);
        scriptService.setNamedValue(VAR_NAME_SCAN_REQUEST_JSON, marshallerService.marshal(scanRequest));
        scriptService.setNamedValue(VAR_NAME_XANES_EDGE_PARAMS_JSON, marshallerService.marshal(xanesEdgeParameters));
    } catch (Exception e) {
        logger.error("Scan submission failed", e);
        MessageDialog.openError(getShell(), "Error Submitting Scan", "The scan could not be submitted. See the error log for more details.");
        return;
    }
    Async.execute(() -> runScript(scriptFilePath, "XANES scanning script"));
}
Also used : ScanMetadata(org.eclipse.scanning.api.scan.models.ScanMetadata) IMarshallerService(org.eclipse.dawnsci.analysis.api.persistence.IMarshallerService) ArrayList(java.util.ArrayList) ScanRequest(org.eclipse.scanning.api.event.scan.ScanRequest) CompoundModel(org.eclipse.scanning.api.points.models.CompoundModel) IScriptService(org.eclipse.scanning.api.script.IScriptService) XanesEdgeParameters(uk.ac.diamond.daq.mapping.api.XanesEdgeParameters) LinesToTrackEntry(uk.ac.diamond.daq.mapping.api.XanesEdgeParameters.LinesToTrackEntry) IScanPointGeneratorModel(org.eclipse.scanning.api.points.models.IScanPointGeneratorModel)

Example 12 with CompoundModel

use of org.eclipse.scanning.api.points.models.CompoundModel in project gda-core by openGDA.

the class ScanRequestConverter method convertToScanRequest.

/**
 * Convert an IMappingExperimentBean to a ScanRequest so that it can be run by the
 * GDA9 scanning framework.
 * <p>
 * This will include setting the mapping scan axes with the names from the mapping axis manager.
 * <p>
 * This method is made <code>public</code> to allow testing.
 *
 * @param mappingBean
 *            the IMappingExperimentBean to be converted
 * @return the ScanRequest
 */
public ScanRequest convertToScanRequest(IMappingExperimentBean mappingBean) {
    final ScanRequest scanRequest = new ScanRequest();
    final IMappingScanRegion scanRegion = mappingBean.getScanDefinition().getMappingScanRegion();
    final IMapPathModel mapPath = getMapPathAndConfigureScanAxes(scanRegion);
    // Build the list of models for the scan
    // first get the models for any outer scannables to be included
    final List<IScanPointGeneratorModel> models = mappingBean.getScanDefinition().getOuterScannables().stream().filter(IScanModelWrapper<IScanPointGeneratorModel>::isIncludeInScan).map(IScanModelWrapper<IScanPointGeneratorModel>::getModel).filter(Objects::nonNull).collect(// use array list as we're going to add an element
    toCollection(ArrayList::new));
    // then add the actual map path model last, it's the inner most model
    models.add(mapPath);
    // Convert the list of models into a compound model
    final CompoundModel compoundModel = new CompoundModel(models);
    // Add the ROI for the mapping region
    final ScanRegion region = new ScanRegion(scanRegion.getRegion().toROI(), mapPath.getxAxisName(), mapPath.getyAxisName());
    // Convert to a List of ScanRegion<IROI> containing one item to avoid unsafe varargs warning
    compoundModel.setRegions(Arrays.asList(region));
    // Set the model on the scan request
    scanRequest.setCompoundModel(compoundModel);
    // set the scan start position (scannables not in the scan that are set to a certain value before the scan starts)
    final Map<String, Object> beamlineConfiguration = mappingBean.getBeamlineConfiguration();
    if (beamlineConfiguration != null) {
        scanRequest.setStartPosition(new MapPosition(beamlineConfiguration));
    }
    // add the required detectors to the scan
    for (IScanModelWrapper<IDetectorModel> detectorWrapper : mappingBean.getDetectorParameters()) {
        if (detectorWrapper.isIncludeInScan()) {
            IDetectorModel detectorModel = detectorWrapper.getModel();
            scanRequest.putDetector(detectorModel.getName(), detectorModel);
        }
    }
    // set the per-scan and per-point monitors according to the mapping bean
    configureMonitors(mappingBean, scanRequest);
    // set the scripts to run before and after the scan, if any
    if (mappingBean.getScriptFiles() != null) {
        final IScriptFiles scriptFiles = mappingBean.getScriptFiles();
        scanRequest.setBeforeScript(createScriptRequest(scriptFiles.getBeforeScanScript()));
        scanRequest.setAfterScript(createScriptRequest(scriptFiles.getAfterScanScript()));
        scanRequest.setAlwaysRunAfterScript(scriptFiles.isAlwaysRunAfterScript());
    }
    // add the sample metadata
    if (mappingBean.getSampleMetadata() != null) {
        setSampleMetadata(mappingBean, scanRequest);
    }
    // Add required processing
    Map<String, Collection<Object>> processingRequest = mappingBean.getProcessingRequest();
    ProcessingRequest r = new ProcessingRequest();
    r.setRequest(processingRequest);
    scanRequest.setProcessingRequest(r);
    // Add template files
    final List<TemplateFileWrapper> templateFiles = mappingBean.getTemplateFiles();
    if (templateFiles != null && !templateFiles.isEmpty()) {
        final Set<String> existingTemplateFilePaths = scanRequest.getTemplateFilePaths();
        final Set<String> allTemplateFilePaths = new TreeSet<>();
        Optional.ofNullable(existingTemplateFilePaths).ifPresent(allTemplateFilePaths::addAll);
        templateFiles.stream().filter(TemplateFileWrapper::isActive).forEach(fp -> allTemplateFilePaths.add(fp.getFilePath()));
        scanRequest.setTemplateFilePaths(allTemplateFilePaths);
    }
    // Add alternative output directory if selected and valid
    if (mappingBean.isUseAlternativeDirectory()) {
        final String outputDirString = mappingBean.getAlternativeDirectory();
        final File outputDir = new File(outputDirString);
        if (outputDir.isDirectory()) {
            scanRequest.setFilePath(outputDirString);
        } else {
            logger.warn("Cannot write output to {}: it is not a directory", outputDirString);
        }
    }
    return scanRequest;
}
Also used : ScanRegion(org.eclipse.scanning.api.points.models.ScanRegion) IMappingScanRegion(uk.ac.diamond.daq.mapping.api.IMappingScanRegion) IScriptFiles(uk.ac.diamond.daq.mapping.api.IScriptFiles) TemplateFileWrapper(uk.ac.diamond.daq.mapping.api.TemplateFileWrapper) ProcessingRequest(org.eclipse.scanning.api.event.scan.ProcessingRequest) IMappingScanRegion(uk.ac.diamond.daq.mapping.api.IMappingScanRegion) ScanRequest(org.eclipse.scanning.api.event.scan.ScanRequest) IDetectorModel(org.eclipse.scanning.api.device.models.IDetectorModel) IMapPathModel(org.eclipse.scanning.api.points.models.IMapPathModel) IScanModelWrapper(uk.ac.diamond.daq.mapping.api.IScanModelWrapper) CompoundModel(org.eclipse.scanning.api.points.models.CompoundModel) TreeSet(java.util.TreeSet) Collection(java.util.Collection) Collectors.toCollection(java.util.stream.Collectors.toCollection) IScanPointGeneratorModel(org.eclipse.scanning.api.points.models.IScanPointGeneratorModel) File(java.io.File) MapPosition(org.eclipse.scanning.api.points.MapPosition)

Example 13 with CompoundModel

use of org.eclipse.scanning.api.points.models.CompoundModel in project gda-core by openGDA.

the class PointGeneratorPathInfoCalculator method calculatePathInfo.

@Override
public PathInfo calculatePathInfo(PathInfoRequest request) throws PathInfoCalculationException {
    IScanPointGeneratorModel scanPathModel = request.getScanPathModel();
    try {
        // Invokes ScanPointGenerator to create the points
        IPointGenerator<CompoundModel> pointGenerator = getPointGeneratorService().createGenerator(scanPathModel, request.getScanRegion());
        // Initialise with sensible starting values
        int pointCount = 0;
        double smallestXStep = Double.MAX_VALUE;
        double smallestYStep = Double.MAX_VALUE;
        double smallestAbsStep = Double.MAX_VALUE;
        List<Double> xCoordinates = new ArrayList<>();
        List<Double> yCoordinates = new ArrayList<>();
        double lastX = Double.NaN;
        double lastY = Double.NaN;
        String xAxisName = getXAxisName(scanPathModel);
        String yAxisName = getYAxisName(scanPathModel);
        // - The smallest distance between two consecutive positions in 2D space
        for (IPosition point : pointGenerator) {
            pointCount++;
            if (pointCount > 1) {
                // Updates the smallest distance tracking variables if the distance
                // between this point and the last is smaller than the smallest
                // distance we've seen so far. Do this for x, y and 2D space.
                double thisXStep = Math.abs(point.getValue(xAxisName) - lastX);
                double thisYStep = Math.abs(point.getValue(yAxisName) - lastY);
                double thisAbsStep = Math.sqrt(Math.pow(thisXStep, 2) + Math.pow(thisYStep, 2));
                if (thisXStep > 0) {
                    smallestXStep = Math.min(smallestXStep, thisXStep);
                }
                if (thisYStep > 0) {
                    smallestYStep = Math.min(smallestYStep, thisYStep);
                }
                smallestAbsStep = Math.min(smallestAbsStep, thisAbsStep);
            }
            // Ensures no more than MAX_POINTS_IN_ROI points are inserted into
            // the PathInfo. Still need to iterate through the rest of the points
            // to accurately calculate step sizes and number of points.
            lastX = point.getValue(xAxisName);
            lastY = point.getValue(yAxisName);
            if (xCoordinates.size() < request.getMaxPoints()) {
                xCoordinates.add(Double.valueOf(lastX));
                yCoordinates.add(Double.valueOf(lastY));
            }
        }
        // outerAxisMultiplier is the product of the number of points
        // in each outer axis. It defaults to 1 if there are no outer axes.
        // It is multiplied by the number of points in the mapping scan
        // e.g. if the mapping scan in x and y has 25 points and is
        // also projected back through 10 points in z then there are
        // 250 points in total.
        int outerAxisMultiplier = calculateAllOuterPoints(request.getOuterScannables());
        int totalPoints = outerAxisMultiplier * pointCount;
        return PathInfo.builder().withSourceId(request.getSourceId()).withInnerPointCount(pointCount).withTotalPointCount(totalPoints).withSmallestXStep(smallestXStep).withSmallestYStep(smallestYStep).withSmallestAbsStep(smallestAbsStep).withxCoordinateList(xCoordinates).withyCoordinateList(yCoordinates).build();
    } catch (GeneratorException e) {
        throw new PathInfoCalculationException(e);
    }
}
Also used : IPosition(org.eclipse.scanning.api.points.IPosition) CompoundModel(org.eclipse.scanning.api.points.models.CompoundModel) PathInfoCalculationException(uk.ac.diamond.daq.mapping.api.PathInfoCalculationException) ArrayList(java.util.ArrayList) GeneratorException(org.eclipse.scanning.api.points.GeneratorException) IScanPointGeneratorModel(org.eclipse.scanning.api.points.models.IScanPointGeneratorModel)

Example 14 with CompoundModel

use of org.eclipse.scanning.api.points.models.CompoundModel in project gda-core by openGDA.

the class ClausesContextTest method addPathDefinitionToCompoundModelSucceedsForCompliantContext.

@Test
public void addPathDefinitionToCompoundModelSucceedsForCompliantContext() throws Exception {
    CompoundModel compoundModel = new CompoundModel();
    clausesContext.addScannable(scannable);
    clausesContext.addScannable(scannable);
    clausesContext.setRegionShape(RegionShape.CIRCLE);
    clausesContext.addParam(1);
    clausesContext.addParam(2);
    clausesContext.addParam(3);
    clausesContext.setScanpath(Scanpath.GRID_POINTS);
    clausesContext.addParam(1);
    clausesContext.addParam(2);
    clausesContext.addPathDefinitionToCompoundModel(compoundModel);
    assertThat(clausesContext.isScanPathSeen(), is(true));
    assertThat(clausesContext.isClauseProcessed(), is(true));
    assertThat(compoundModel.getModels().get(0), instanceOf(TwoAxisGridPointsModel.class));
    assertThat(((TwoAxisGridPointsModel) compoundModel.getModels().get(0)).getxAxisPoints(), is(1));
    assertThat(((TwoAxisGridPointsModel) compoundModel.getModels().get(0)).getyAxisPoints(), is(2));
    assertThat(compoundModel.getRegions().iterator().next().getRoi(), instanceOf(CircularROI.class));
    assertThat(((CircularROI) compoundModel.getRegions().iterator().next().getRoi()).getCentre()[0], is(1.0));
    assertThat(((CircularROI) compoundModel.getRegions().iterator().next().getRoi()).getCentre()[1], is(2.0));
    assertThat(((CircularROI) compoundModel.getRegions().iterator().next().getRoi()).getRadius(), is(3.0));
    assertThat(compoundModel.getMutators(), is(new ArrayList<>()));
}
Also used : TwoAxisGridPointsModel(org.eclipse.scanning.api.points.models.TwoAxisGridPointsModel) CompoundModel(org.eclipse.scanning.api.points.models.CompoundModel) CircularROI(org.eclipse.dawnsci.analysis.dataset.roi.CircularROI) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 15 with CompoundModel

use of org.eclipse.scanning.api.points.models.CompoundModel in project gda-core by openGDA.

the class MScanSubmitterTest method willAllowStaticScanWithDetectorAndNoScannable.

@Test
public void willAllowStaticScanWithDetectorAndNoScannable() throws Exception {
    final int size = 5;
    Object[] arr = { Scanpath.STATIC, size, detectorRunnableDevice, EXPOSURE };
    when(resolver.resolveScanClauses()).thenReturn(Arrays.asList(Arrays.asList(new ScanpathElementProcessor(Scanpath.STATIC), new NumberElementProcessor(size)), Arrays.asList(new IRunnableDeviceDetectorElementProcessor(detectorRunnableDevice), new NumberElementProcessor(EXPOSURE))));
    builder.buildAndSubmitBlockingScanRequest(arr);
    verify(submitter).blockingSubmit(beanCaptor.capture());
    verify(eventSubscriber).addListener(any(IScanListener.class));
    ScanBean bean = beanCaptor.getValue();
    assertThat(bean.getScanRequest().getCompoundModel(), is(equalTo(new CompoundModel(new StaticModel(size)))));
    assertThat(bean.getScanRequest().getDetectors().values(), contains(detectorRunnableDevice.getModel()));
}
Also used : IScanListener(org.eclipse.scanning.api.event.scan.IScanListener) ScanBean(org.eclipse.scanning.api.event.scan.ScanBean) NumberElementProcessor(gda.mscan.processor.NumberElementProcessor) ScanpathElementProcessor(gda.mscan.processor.ScanpathElementProcessor) CompoundModel(org.eclipse.scanning.api.points.models.CompoundModel) IRunnableDeviceDetectorElementProcessor(gda.mscan.processor.IRunnableDeviceDetectorElementProcessor) StaticModel(org.eclipse.scanning.api.points.models.StaticModel) Test(org.junit.Test)

Aggregations

CompoundModel (org.eclipse.scanning.api.points.models.CompoundModel)21 Test (org.junit.Test)10 ScanpathElementProcessor (gda.mscan.processor.ScanpathElementProcessor)8 IScanListener (org.eclipse.scanning.api.event.scan.IScanListener)8 ScanBean (org.eclipse.scanning.api.event.scan.ScanBean)8 ScanRequest (org.eclipse.scanning.api.event.scan.ScanRequest)7 StaticModel (org.eclipse.scanning.api.points.models.StaticModel)7 IRunnableDeviceDetectorElementProcessor (gda.mscan.processor.IRunnableDeviceDetectorElementProcessor)6 ArrayList (java.util.ArrayList)6 IScanPointGeneratorModel (org.eclipse.scanning.api.points.models.IScanPointGeneratorModel)6 NumberElementProcessor (gda.mscan.processor.NumberElementProcessor)5 AxialStepModel (org.eclipse.scanning.api.points.models.AxialStepModel)5 IDetectorModel (org.eclipse.scanning.api.device.models.IDetectorModel)4 ScanRegion (org.eclipse.scanning.api.points.models.ScanRegion)4 ScannableElementProcessor (gda.mscan.processor.ScannableElementProcessor)3 IMapPathModel (org.eclipse.scanning.api.points.models.IMapPathModel)3 RegionShapeElementProcessor (gda.mscan.processor.RegionShapeElementProcessor)2 File (java.io.File)2 HashMap (java.util.HashMap)2 IPosition (org.eclipse.scanning.api.points.IPosition)2