diff --git a/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8Device.java b/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8Device.java index f15bf6c9..b7af8c82 100644 --- a/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8Device.java +++ b/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8Device.java @@ -17,8 +17,6 @@ package inr.numass.cryotemp; import hep.dataforge.context.Context; import hep.dataforge.control.collectors.RegularPointCollector; -import hep.dataforge.control.connections.Connection; -import hep.dataforge.control.connections.LoaderConnection; import hep.dataforge.control.connections.Roles; import hep.dataforge.control.connections.StorageConnection; import hep.dataforge.control.devices.PortSensor; @@ -36,10 +34,10 @@ import hep.dataforge.storage.api.PointLoader; import hep.dataforge.storage.api.Storage; import hep.dataforge.storage.commons.LoaderFactory; import hep.dataforge.tables.DataPoint; -import hep.dataforge.tables.PointListener; import hep.dataforge.tables.TableFormat; import hep.dataforge.tables.TableFormatBuilder; import hep.dataforge.utils.DateTimeUtils; +import inr.numass.control.StorageHelper; import java.time.Duration; import java.util.Collection; @@ -52,7 +50,6 @@ import java.util.Map; * @author Alexander Nozik */ @RoleDef(name = Roles.STORAGE_ROLE) -@RoleDef(name = Roles.POINT_LISTENER_ROLE) @RoleDef(name = Roles.VIEW_ROLE, objectType = PKT8View.class) @ValueDef(name = "port", def = "virtual", info = "The name of the port for this PKT8") public class PKT8Device extends PortSensor { @@ -67,6 +64,7 @@ public class PKT8Device extends PortSensor { */ private final Map channels = new HashMap<>(); private RegularPointCollector collector; + private StorageHelper storageHelper; /** * Cached values @@ -82,6 +80,18 @@ public class PKT8Device extends PortSensor { setMetaBase(meta); } + private PointLoader buildLoader(StorageConnection connection) { + Storage storage = connection.getStorage(); + String suffix = DateTimeUtils.fileSuffix(); + + try { + return LoaderFactory.buildPointLoder(storage, + "cryotemp_" + suffix, "", "timestamp", getTableFormat()); + } catch (StorageException e) { + throw new RuntimeException("Failed to build loader from storage", e); + } + } + @Override public void init() throws ControlException { @@ -104,7 +114,7 @@ public class PKT8Device extends PortSensor { //update parameters from meta if (meta().hasValue("pga")) { getLogger().info("Setting dynamic range to " + meta().getInt("pga")); - String response = getHandler().sendAndWait("g" + meta().getInt("pga"), null, 400).trim(); + String response = getHandler().sendAndWait("g" + meta().getInt("pga"), 400, null).trim(); if (response.contains("=")) { updateState(PGA, Integer.parseInt(response.substring(4))); } else { @@ -116,12 +126,11 @@ public class PKT8Device extends PortSensor { setBUF(meta().getInt("abuf", 100)); // setting up the collector + storageHelper = new StorageHelper(this, this::buildLoader); Duration duration = Duration.parse(meta().getString("averagingDuration", "PT30S")); collector = new RegularPointCollector((DataPoint dp) -> { - forEachConnection(Roles.POINT_LISTENER_ROLE, PointListener.class, listener -> { - getLogger().debug("Point measurement complete. Pushing..."); - listener.accept(dp); - }); + getLogger().debug("Point measurement complete. Pushing..."); + storageHelper.push(dp); }, duration, channels.values().stream().map(PKT8Channel::getName).toArray(String[]::new)); } @@ -140,26 +149,9 @@ public class PKT8Device extends PortSensor { return format; } - @Override - public synchronized void connect(Connection connection, String... roles) { - super.connect(connection, roles); - if (connection instanceof StorageConnection) { - //TODO add loader cache to remove loaders on disconnect - Storage storage = ((StorageConnection) connection).getStorage(); - String suffix = DateTimeUtils.fileSuffix(); - - try { - PointLoader pointLoader = LoaderFactory.buildPointLoder(storage, - "cryotemp_" + suffix, "", "timestamp", getTableFormat()); - this.connect(new LoaderConnection(pointLoader), Roles.POINT_LISTENER_ROLE); - } catch (StorageException e) { - getLogger().error("Failed to build loader from storage {}", storage.getName()); - } - } - } - @Override public void shutdown() throws ControlException { + storageHelper.close(); if (collector != null) { collector.clear(); collector = null; @@ -190,7 +182,7 @@ public class PKT8Device extends PortSensor { getLogger().info("Setting avaraging buffer size to " + buf); String response; try { - response = getHandler().sendAndWait("b" + buf, null, 400).trim(); + response = getHandler().sendAndWait("b" + buf, 400, null).trim(); } catch (Exception ex) { response = ex.getMessage(); } @@ -279,7 +271,7 @@ public class PKT8Device extends PortSensor { getLogger().info("Setting sampling rate to " + spsToStr(sps)); String response; try { - response = getHandler().sendAndWait("v" + sps, null, 400).trim(); + response = getHandler().sendAndWait("v" + sps, 400, null).trim(); } catch (Exception ex) { response = ex.getMessage(); } @@ -333,6 +325,8 @@ public class PKT8Device extends PortSensor { return super.startMeasurement(); } + + public class PKT8Measurement extends AbstractMeasurement implements PortHandler.PortController { final PortHandler handler; diff --git a/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8View.java b/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8View.java index de3b24f8..e3d7240d 100644 --- a/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8View.java +++ b/numass-control/cryotemp/src/main/java/inr/numass/cryotemp/PKT8View.java @@ -24,6 +24,7 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.net.URL; import java.time.Instant; +import java.util.Comparator; import java.util.ResourceBundle; /** @@ -98,7 +99,7 @@ public class PKT8View extends DeviceViewConnection implements Initia lastUpdateLabel.setText(time.toString()); table.getItems().removeIf(it -> it.channel.equals(result.channel)); table.getItems().add(result); - table.getItems().sort((o1, o2) -> o1.channel.compareTo(o2.channel)); + table.getItems().sort(Comparator.comparing(o -> o.channel)); }); } @@ -131,7 +132,7 @@ public class PKT8View extends DeviceViewConnection implements Initia stopMeasurement(); } } catch (ControlException ex) { - evaluateDeviceException(getDevice(), "Failed to start or stop device", ex); + getDevice().getLogger().error("Failed to start or stop device", ex); } } } diff --git a/numass-control/magnet/src/main/java/inr/numass/control/magnet/MagnetController.java b/numass-control/magnet/src/main/java/inr/numass/control/magnet/MagnetController.java index db2e01b5..59d4d0e7 100644 --- a/numass-control/magnet/src/main/java/inr/numass/control/magnet/MagnetController.java +++ b/numass-control/magnet/src/main/java/inr/numass/control/magnet/MagnetController.java @@ -122,11 +122,11 @@ public class MagnetController implements PortHandler.PortController { private String talk(String request) throws PortException { try { - return port.sendAndWait(request + "\r", null, timeout).trim(); + return port.sendAndWait(request + "\r", timeout, null).trim(); } catch (PortTimeoutException tex) { //Single retry on timeout LoggerFactory.getLogger(getClass()).warn("A timeout exception for request '" + request + "'. Making another atempt."); - return port.sendAndWait(request + "\r", null, timeout).trim(); + return port.sendAndWait(request + "\r", timeout, null).trim(); } } diff --git a/numass-control/magnet/src/main/java/inr/numass/control/magnet/Talk.java b/numass-control/magnet/src/main/java/inr/numass/control/magnet/Talk.java index b400a144..28b60c17 100644 --- a/numass-control/magnet/src/main/java/inr/numass/control/magnet/Talk.java +++ b/numass-control/magnet/src/main/java/inr/numass/control/magnet/Talk.java @@ -60,7 +60,7 @@ public class Talk { while (!"exit".equals(nextString)) { try { Instant start = DateTimeUtils.now(); - String answer = handler.sendAndWait(nextString + "\r", null, 1000); + String answer = handler.sendAndWait(nextString + "\r", 1000, null); //String answer = controller.request(nextString); System.out.printf("ANSWER (latency = %s): %s;%n", Duration.between(start, DateTimeUtils.now()), answer.trim()); } catch (PortException ex) { diff --git a/numass-control/msp/src/main/java/inr/numass/control/msp/MspDevice.java b/numass-control/msp/src/main/java/inr/numass/control/msp/MspDevice.java index 27d307b2..932f3408 100644 --- a/numass-control/msp/src/main/java/inr/numass/control/msp/MspDevice.java +++ b/numass-control/msp/src/main/java/inr/numass/control/msp/MspDevice.java @@ -39,6 +39,7 @@ import hep.dataforge.tables.TableFormat; import hep.dataforge.tables.TableFormatBuilder; import hep.dataforge.utils.DateTimeUtils; import hep.dataforge.values.Value; +import inr.numass.control.StorageHelper; import java.time.Instant; import java.util.*; @@ -259,8 +260,7 @@ public class MspDevice extends SingleMeasurementDevice implements PortHandler.Po String response = getHandler().sendAndWait( request, - (String str) -> str.trim().startsWith(commandName), - TIMEOUT + TIMEOUT, (String str) -> str.trim().startsWith(commandName) ); return new MspResponse(response); } @@ -404,8 +404,7 @@ public class MspDevice extends SingleMeasurementDevice implements PortHandler.Po private class PeakJumpMeasurement extends AbstractMeasurement { private final Map measurement = new ConcurrentSkipListMap<>(); - private final Map loaderMap = new HashMap<>(); - // private List loaders = new ArrayList<>(); + private StorageHelper helper = new StorageHelper(MspDevice.this,this::makeLoader); private final Meta meta; private Map peakMap; private double zero = 0; @@ -481,13 +480,7 @@ public class MspDevice extends SingleMeasurementDevice implements PortHandler.Po boolean stop = sendAndWait("ScanStop").isOK(); afterStop(); responseDelegate = null; - loaderMap.values().forEach(loader -> { - try { - loader.close(); - } catch (Exception ex) { - getLogger().error("Failed to close Loader", ex); - } - }); + helper.close(); return stop; } catch (PortException ex) { throw new MeasurementException(ex); @@ -520,24 +513,15 @@ public class MspDevice extends SingleMeasurementDevice implements PortHandler.Po MapPoint.Builder point = new MapPoint.Builder(); point.putValue("timestamp", time); - measurement.entrySet().forEach((entry) -> { - double val = entry.getValue(); - point.putValue(peakMap.get(entry.getKey()), val); + measurement.forEach((key, value1) -> { + double val = value1; + point.putValue(peakMap.get(key), val); }); mspListener.acceptScan(measurement); - - if (getState("storing").booleanValue()) { - forEachConnection(Roles.STORAGE_ROLE, StorageConnection.class, (StorageConnection connection) -> { - PointLoader pl = loaderMap.computeIfAbsent(connection, this::makeLoader); - try { - pl.push(point.build()); - } catch (StorageException ex) { - getLogger().error("Push to loader failed", ex); - } - }); - } + //pushing data to storage + helper.push(point.build()); } measurement.clear(); diff --git a/numass-control/src/main/java/inr/numass/control/StorageHelper.java b/numass-control/src/main/java/inr/numass/control/StorageHelper.java new file mode 100644 index 00000000..23fb2be6 --- /dev/null +++ b/numass-control/src/main/java/inr/numass/control/StorageHelper.java @@ -0,0 +1,51 @@ +package inr.numass.control; + +import hep.dataforge.control.connections.StorageConnection; +import hep.dataforge.control.devices.AbstractDevice; +import hep.dataforge.exceptions.StorageException; +import hep.dataforge.storage.api.PointLoader; +import hep.dataforge.tables.DataPoint; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +/** + * A helper to store points in multiple loaders + * Created by darksnake on 16-May-17. + */ +public class StorageHelper implements AutoCloseable { + private final AbstractDevice device; + private final Map loaderMap = new HashMap<>(); + private final Function loaderFactory; + + public StorageHelper(AbstractDevice device, Function loaderFactory) { + this.device = device; + this.loaderFactory = loaderFactory; + } + + public void push(DataPoint point) { + if (!device.hasState("storing") || device.getState("storing").booleanValue()) { + device.forEachConnection("storage", StorageConnection.class, connection -> { + PointLoader pl = loaderMap.computeIfAbsent(connection, loaderFactory); + try { + pl.push(point); + } catch (StorageException ex) { + device.getLogger().error("Push to loader failed", ex); + } + }); + } + } + + + @Override + public void close() { + loaderMap.values().forEach(it -> { + try { + it.close(); + } catch (Exception ex) { + device.getLogger().error("Failed to close Loader", ex); + } + }); + } +} diff --git a/numass-control/vac/build.gradle b/numass-control/vac/build.gradle index ec890e7c..8d310c32 100644 --- a/numass-control/vac/build.gradle +++ b/numass-control/vac/build.gradle @@ -1,10 +1,10 @@ apply plugin: 'application' -version = "0.4.2" +version = "0.5.0" if (!hasProperty('mainClass')) { //ext.mainClass = 'inr.numass.readvac.app.ConsoleVac' - ext.mainClass = 'inr.numass.readvac.app.ReadVac' + ext.mainClass = 'inr.numass.readvac.fx.ReadVac' } mainClassName = mainClass diff --git a/numass-control/vac/src/main/java/inr/numass/readvac/VITVacDevice.java b/numass-control/vac/src/main/java/inr/numass/readvac/MeradatVacDevice.java similarity index 65% rename from numass-control/vac/src/main/java/inr/numass/readvac/VITVacDevice.java rename to numass-control/vac/src/main/java/inr/numass/readvac/MeradatVacDevice.java index b1654c42..a575da2b 100644 --- a/numass-control/vac/src/main/java/inr/numass/readvac/VITVacDevice.java +++ b/numass-control/vac/src/main/java/inr/numass/readvac/MeradatVacDevice.java @@ -10,6 +10,7 @@ import hep.dataforge.control.devices.PortSensor; import hep.dataforge.control.measurements.Measurement; import hep.dataforge.control.measurements.SimpleMeasurement; import hep.dataforge.control.ports.PortHandler; +import hep.dataforge.description.ValueDef; import hep.dataforge.exceptions.ControlException; import hep.dataforge.meta.Meta; @@ -21,12 +22,13 @@ import java.util.regex.Pattern; /** * @author Alexander Nozik */ -public class VITVacDevice extends PortSensor { +@ValueDef(name = "address", type = "NUMBER", def = "1", info = "A modbus address") +public class MeradatVacDevice extends PortSensor { - public VITVacDevice() { + public MeradatVacDevice() { } - public VITVacDevice(Context context, Meta meta) { + public MeradatVacDevice(Context context, Meta meta) { setContext(context); setMetaBase(meta); } @@ -40,7 +42,7 @@ public class VITVacDevice extends PortSensor { @Override protected Measurement createMeasurement() { - return new CMVacMeasurement(); + return new MeradatMeasurement(meta().getInt("adress", 1)); } @Override @@ -48,41 +50,31 @@ public class VITVacDevice extends PortSensor { return meta().getString("type", "Vit vacuumeter"); } - @Override - protected Object computeState(String stateName) throws ControlException { - if (getHandler() == null) { - notifyError("No port connection", null); - return null; + private class MeradatMeasurement extends SimpleMeasurement { + +// private static final String VIT_QUERY = ":010300000002FA\r\n"; + + private final String query; + private final Pattern response; + private final String base; + + public MeradatMeasurement(int address) { + base = String.format(":%02d", address); + query = base + "0300000002FA\r\n"; + response = Pattern.compile(base + "0304(\\w{4})(\\w{4})..\r\n"); } - notifyError("State not found: " + stateName, null); - return null; - //TODO add connection check here -// switch (stateName) { -// case "connection": -// return !talk("T?").isEmpty(); -// default: -// notifyError("State not found: " + stateName, null); -// return null; -// } - } - - - private class CMVacMeasurement extends SimpleMeasurement { - - private static final String VIT_QUERY = ":010300000002FA\r\n"; - @Override protected synchronized Double doMeasure() throws Exception { - String answer = getHandler().sendAndWait(VIT_QUERY, timeout()); + String answer = getHandler().sendAndWait(query, timeout(), phrase -> phrase.startsWith(base)); if (answer.isEmpty()) { this.progressUpdate("No signal"); updateState("connection", false); return null; } else { - Matcher match = Pattern.compile(":010304(\\w{4})(\\w{4})..\r\n").matcher(answer); + Matcher match = response.matcher(answer); if (match.matches()) { double base = (double) (Integer.parseInt(match.group(1), 16)) / 10d; @@ -95,7 +87,8 @@ public class VITVacDevice extends PortSensor { this.progressUpdate("OK"); updateState("connection", true); return res.doubleValue(); - } else { + } + else { this.progressUpdate("Wrong answer: " + answer); updateState("connection", false); return null; diff --git a/numass-control/vac/src/main/java/inr/numass/readvac/VacCollectorDevice.java b/numass-control/vac/src/main/java/inr/numass/readvac/VacCollectorDevice.java index c696493b..c81b79ca 100644 --- a/numass-control/vac/src/main/java/inr/numass/readvac/VacCollectorDevice.java +++ b/numass-control/vac/src/main/java/inr/numass/readvac/VacCollectorDevice.java @@ -8,21 +8,28 @@ package inr.numass.readvac; import hep.dataforge.control.collectors.PointCollector; import hep.dataforge.control.collectors.ValueCollector; import hep.dataforge.control.connections.Roles; +import hep.dataforge.control.connections.StorageConnection; import hep.dataforge.control.devices.annotations.RoleDef; +import hep.dataforge.control.devices.annotations.StateDef; import hep.dataforge.control.measurements.AbstractMeasurement; import hep.dataforge.control.measurements.Measurement; import hep.dataforge.control.measurements.Sensor; import hep.dataforge.exceptions.ControlException; import hep.dataforge.exceptions.MeasurementException; +import hep.dataforge.storage.api.PointLoader; +import hep.dataforge.storage.commons.LoaderFactory; import hep.dataforge.tables.DataPoint; import hep.dataforge.tables.MapPoint; import hep.dataforge.tables.PointListener; +import hep.dataforge.tables.TableFormatBuilder; import hep.dataforge.utils.DateTimeUtils; import hep.dataforge.values.Value; +import hep.dataforge.values.ValueType; +import inr.numass.control.StorageHelper; import java.time.Instant; +import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.Executors; @@ -31,25 +38,30 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** - * * @author Alexander Nozik */ @RoleDef(name = Roles.STORAGE_ROLE, objectType = PointListener.class, info = "Storage for acquired points") +@StateDef(name = "storing", writable = true, info = "Define if this device is currently writes to storage") public class VacCollectorDevice extends Sensor { - private Map sensorMap = new HashMap<>(); + private Map> sensorMap = new LinkedHashMap<>(); - public void setSensors(Sensor... sensors) { - sensorMap = new LinkedHashMap<>(sensors.length); - for (Sensor sensor : sensors) { + public void setSensors(Iterable> sensors) { + sensorMap = new LinkedHashMap<>(); + for (Sensor sensor : sensors) { sensorMap.put(sensor.getName(), sensor); } } + @SuppressWarnings("unchecked") + public void setSensors(Sensor... sensors) { + setSensors(Arrays.asList(sensors)); + } + @Override public void init() throws ControlException { super.init(); - for (Sensor s : sensorMap.values()) { + for (Sensor s : sensorMap.values()) { s.init(); } } @@ -87,39 +99,34 @@ public class VacCollectorDevice extends Sensor { } } - public Collection getSensors() { + public Collection> getSensors() { return sensorMap.values(); } - public void setSensors(Iterable sensors) { - sensorMap = new LinkedHashMap<>(); - for (Sensor sensor : sensors) { - sensorMap.put(sensor.getName(), sensor); - } - } - private class VacuumMeasurement extends AbstractMeasurement { private final ValueCollector collector = new PointCollector(this::result, sensorMap.keySet()); private ScheduledExecutorService executor; private ScheduledFuture currentTask; + private StorageHelper helper; @Override public void start() { + helper = new StorageHelper(VacCollectorDevice.this, this::buildLoader); executor = Executors .newSingleThreadScheduledExecutor((Runnable r) -> new Thread(r, "VacuumMeasurement thread")); currentTask = executor.scheduleWithFixedDelay(() -> { - sensorMap.entrySet().stream().parallel().forEach((entry) -> { + sensorMap.values().forEach((sensor) -> { try { Object value; - if (entry.getValue().meta().getBoolean("disabled", false)) { + if(sensor.optBooleanState("disabled").orElse(false)){ value = null; } else { - value = entry.getValue().read(); + value = sensor.read(); } - collector.put(entry.getKey(), value); + collector.put(sensor.getName(), value); } catch (Exception ex) { - collector.put(entry.getKey(), Value.NULL); + collector.put(sensor.getName(), Value.NULL); } }); }, 0, meta().getInt("delay", 5000), TimeUnit.MILLISECONDS); @@ -133,10 +140,19 @@ public class VacCollectorDevice extends Sensor { }); } + private PointLoader buildLoader(StorageConnection connection) { + TableFormatBuilder format = new TableFormatBuilder().setType("timestamp", ValueType.TIME); + getSensors().forEach((s) -> { + format.setType(s.getName(), ValueType.NUMBER); + }); + + return LoaderFactory.buildPointLoder(connection.getStorage(), "vactms", "", "timestamp", format.build()); + } + private DataPoint terminator() { MapPoint.Builder p = new MapPoint.Builder(); p.putValue("timestamp", DateTimeUtils.now()); - sensorMap.keySet().stream().forEach((n) -> { + sensorMap.keySet().forEach((n) -> { p.putValue(n, null); }); return p.build(); @@ -151,6 +167,7 @@ public class VacCollectorDevice extends Sensor { currentTask.cancel(force); executor.shutdown(); currentTask = null; + helper.close(); afterStop(); } return isRunning; diff --git a/numass-control/vac/src/main/java/inr/numass/readvac/VacDeviceFactory.java b/numass-control/vac/src/main/java/inr/numass/readvac/VacDeviceFactory.java new file mode 100644 index 00000000..fe8bf54d --- /dev/null +++ b/numass-control/vac/src/main/java/inr/numass/readvac/VacDeviceFactory.java @@ -0,0 +1,46 @@ +package inr.numass.readvac; + +import hep.dataforge.context.Context; +import hep.dataforge.control.devices.DeviceFactory; +import hep.dataforge.control.measurements.Sensor; +import hep.dataforge.meta.Meta; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * A factory for vacuum measurements collector + * Created by darksnake on 16-May-17. + */ +public class VacDeviceFactory implements DeviceFactory { + @Override + public String getType() { + return "numass:vac"; + } + + public Sensor buildSensor(Context context, Meta sensorConfig) { + switch (sensorConfig.getString("sensorType", "")) { + case "mks": + return new MKSVacDevice(context, sensorConfig); + case "CM32": + return new CM32Device(context, sensorConfig); + case "meradat": + return new MeradatVacDevice(context, sensorConfig); + case "baratron": + return new MKSBaratronDevice(context, sensorConfig); + default: + throw new RuntimeException("Unknown vacuum sensor type"); + } + } + + @Override + public VacCollectorDevice build(Context context, Meta config) { + List> sensors = config.getMetaList("sensor").stream() + .map(sensorConfig -> buildSensor(context, sensorConfig)).collect(Collectors.toList()); + + VacCollectorDevice collector = new VacCollectorDevice(); + collector.configure(config); + collector.setSensors(sensors); + return collector; + } +} diff --git a/numass-control/vac/src/main/java/inr/numass/readvac/fx/ReadVac.java b/numass-control/vac/src/main/java/inr/numass/readvac/fx/ReadVac.java index 383d67b2..42860faf 100644 --- a/numass-control/vac/src/main/java/inr/numass/readvac/fx/ReadVac.java +++ b/numass-control/vac/src/main/java/inr/numass/readvac/fx/ReadVac.java @@ -5,78 +5,90 @@ */ package inr.numass.readvac.fx; -import ch.qos.logback.classic.Level; -import hep.dataforge.context.Context; -import hep.dataforge.control.connections.DeviceConnection; -import hep.dataforge.control.connections.Roles; -import hep.dataforge.exceptions.ControlException; +import hep.dataforge.control.devices.DeviceFactory; import hep.dataforge.meta.Meta; import inr.numass.control.DeviceViewConnection; -import inr.numass.control.NumassControlUtils; +import inr.numass.control.NumassControlApplication; import inr.numass.readvac.VacCollectorDevice; -import javafx.application.Application; -import javafx.application.Platform; -import javafx.scene.Scene; +import inr.numass.readvac.VacDeviceFactory; import javafx.stage.Stage; -import org.slf4j.LoggerFactory; -import java.util.Locale; +import java.util.Objects; /** * @author Alexander Nozik */ -public class ReadVac extends Application { - private VacCollectorDevice device; - +public class ReadVac extends NumassControlApplication { @Override - public void start(Stage primaryStage) throws Exception { - Locale.setDefault(Locale.US);// чтобы отделение десятичных знаков было точкой - ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); - rootLogger.setLevel(Level.INFO); - - DeviceViewConnection controller = buildView(); - - Scene scene = new Scene(controller.getPane()); - - primaryStage.setScene(scene); - primaryStage.show(); - - device = setupDevice(controller); - primaryStage.setTitle("Numass vacuum measurements"); - } - - - private VacCollectorDevice setupDevice(DeviceConnection controller) { - Meta config = NumassControlUtils.getConfig(this) - .orElseGet(() -> NumassControlUtils.readResourceMeta("/config/devices.xml")); - - Context ctx = NumassControlUtils.setupContext(config); - Meta mspConfig = NumassControlUtils.findDeviceMeta(config, this::acceptDevice) - .orElseThrow(() -> new RuntimeException("Device configuration not found")); - - - try { - D d = getDeviceFactory().build(ctx, mspConfig); - d.init(); - NumassControlUtils.connectStorage(d, config); - Platform.runLater(() -> { - d.connect(controller, Roles.VIEW_ROLE, Roles.DEVICE_LISTENER_ROLE); - }); - return d; - } catch (ControlException e) { - throw new RuntimeException("Failed to build device", e); - } + protected DeviceViewConnection buildView() { + return VacCollectorView.build(); } @Override - public void stop() throws Exception { - super.stop(); - if (device != null) { - device.shutdown(); - device.getContext().close(); - } + protected DeviceFactory getDeviceFactory() { + return new VacDeviceFactory(); } + @Override + protected void setupStage(Stage stage, VacCollectorDevice device) { + stage.setTitle("Numass vacuum measurements"); + } + + @Override + protected boolean acceptDevice(Meta meta) { + return Objects.equals(meta.getString("type", ""), "numass:vac"); + } +// private VacCollectorDevice device; +// +// @Override +// public void start(Stage primaryStage) throws Exception { +// Locale.setDefault(Locale.US);// чтобы отделение десятичных знаков было точкой +// ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); +// rootLogger.setLevel(Level.INFO); +// +// DeviceViewConnection controller = buildView(); +// +// Scene scene = new Scene(controller.getPane()); +// +// primaryStage.setScene(scene); +// primaryStage.show(); +// +// device = setupDevice(controller); +// primaryStage.setTitle("Numass vacuum measurements"); +// } +// +// +// private VacCollectorDevice setupDevice(DeviceConnection controller) { +// Meta config = NumassControlUtils.getConfig(this) +// .orElseGet(() -> NumassControlUtils.readResourceMeta("/config/devices.xml")); +// +// Context ctx = NumassControlUtils.setupContext(config); +// Meta mspConfig = NumassControlUtils.findDeviceMeta(config, this::acceptDevice) +// .orElseThrow(() -> new RuntimeException("Device configuration not found")); +// +// +// try { +// D d = getDeviceFactory().build(ctx, mspConfig); +// d.init(); +// NumassControlUtils.connectStorage(d, config); +// Platform.runLater(() -> { +// d.connect(controller, Roles.VIEW_ROLE, Roles.DEVICE_LISTENER_ROLE); +// }); +// return d; +// } catch (ControlException e) { +// throw new RuntimeException("Failed to build device", e); +// } +// } +// +// @Override +// public void stop() throws Exception { +// super.stop(); +// if (device != null) { +// device.shutdown(); +// device.getContext().close(); +// } +// } + // VacCollectorView controller; // Logger logger = LoggerFactory.getLogger("ReadVac"); @@ -92,7 +104,7 @@ public class ReadVac extends Application { // public void start(Stage primaryStage) throws Exception { // String configFileName = getParameters().getNamed().get("config"); // if (configFileName == null) { -// configFileName = "vac-config.xml"; +// configFileName = "devices.xml"; // } // File configFile = new File(configFileName); // Meta config; @@ -104,54 +116,7 @@ public class ReadVac extends Application { // // Context context = Global.instance(); // -// Meta p1Meta = config.getMeta("p1", -// new MetaBuilder("p1") -// .setValue("port", "com::/dev/ttyUSB0") -// .setValue("name", "P1") -// .build() -// ); -// -// Sensor p1 = new MKSVacDevice(context, p1Meta); -// -// Meta p2Meta = config.getMeta("p2", -// new MetaBuilder("p2") -// .setValue("port", "tcp::192.168.111.32:4002") -// .setValue("name", "P2") -// .build() -// ); -// -// Sensor p2 = new CM32Device(context,p2Meta); -// -// Meta p3Meta = config.getMeta("p3", -// new MetaBuilder("p3") -// .setValue("port", "tcp::192.168.111.32:4003") -// .setValue("name", "P3") -// .build() -// ); -// -// Sensor p3 = new CM32Device(context, p3Meta); -// -// Meta pxMeta = config.getMeta("px", -// new MetaBuilder("px") -// .setValue("port", "tcp::192.168.111.32:4003") -// .setValue("name", "Px") -// .build() -// ); -// -// Sensor px = new VITVacDevice(context,pxMeta); -// -// Meta baratronMeta = config.getMeta("baratron", -// new MetaBuilder("baratron") -// .setValue("port", "tcp::192.168.111.33:4004") -// .setValue("name", "Baratron") -// .build() -// ); -// -// Sensor baratron = new MKSBaratronDevice(context,baratronMeta); -// -// VacCollectorDevice collector = new VacCollectorDevice(); -// collector.configure(config); -// collector.setSensors(p1, p2, p3, px, baratron); + // collector.init(); // // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/VacCollector.fxml")); diff --git a/numass-control/vac/src/main/java/inr/numass/readvac/fx/TestVac.java b/numass-control/vac/src/main/java/inr/numass/readvac/fx/TestVac.java index 6fbd0ede..6770b1d3 100644 --- a/numass-control/vac/src/main/java/inr/numass/readvac/fx/TestVac.java +++ b/numass-control/vac/src/main/java/inr/numass/readvac/fx/TestVac.java @@ -5,6 +5,7 @@ */ package inr.numass.readvac.fx; +import hep.dataforge.control.connections.Roles; import hep.dataforge.control.measurements.Sensor; import hep.dataforge.control.virtual.Virtual; import inr.numass.readvac.VacCollectorDevice; @@ -60,7 +61,7 @@ public class TestVac extends Application { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/VacCollector.fxml")); loader.load(); controller = loader.getController(); - controller.setDevice(collector); + collector.connect(controller, Roles.VIEW_ROLE); Scene scene = new Scene(loader.getRoot(), 800, 600); diff --git a/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacCollectorView.java b/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacCollectorView.java index c19d6f8a..21c4ed3a 100644 --- a/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacCollectorView.java +++ b/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacCollectorView.java @@ -5,10 +5,8 @@ */ package inr.numass.readvac.fx; -import hep.dataforge.control.connections.LoaderConnection; import hep.dataforge.control.connections.Roles; import hep.dataforge.control.devices.Device; -import hep.dataforge.control.devices.DeviceListener; import hep.dataforge.control.measurements.Measurement; import hep.dataforge.control.measurements.MeasurementListener; import hep.dataforge.control.measurements.Sensor; @@ -23,33 +21,29 @@ import hep.dataforge.plots.data.TimePlottableGroup; import hep.dataforge.plots.fx.FXPlotFrame; import hep.dataforge.plots.fx.PlotContainer; import hep.dataforge.plots.jfreechart.JFreeChartFrame; -import hep.dataforge.storage.api.PointLoader; -import hep.dataforge.storage.api.Storage; -import hep.dataforge.storage.commons.LoaderFactory; -import hep.dataforge.storage.commons.StorageManager; import hep.dataforge.tables.DataPoint; -import hep.dataforge.tables.TableFormatBuilder; import hep.dataforge.values.Value; -import hep.dataforge.values.ValueType; +import inr.numass.control.DeviceViewConnection; import inr.numass.readvac.VacCollectorDevice; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; +import javafx.scene.Node; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.ToggleButton; import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; -import javafx.stage.DirectoryChooser; import javafx.util.Duration; import org.controlsfx.control.Notifications; -import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; +import java.io.IOException; import java.net.URL; import java.time.Instant; import java.time.LocalDateTime; @@ -58,24 +52,33 @@ import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; -import java.util.function.BiFunction; /** - * FXML Controller class + * A view controller for Vac collector * * @author Alexander Nozik */ -public class VacCollectorView implements Initializable, DeviceListener, MeasurementListener { +public class VacCollectorView extends DeviceViewConnection implements Initializable, MeasurementListener { + + public static VacCollectorView build() { + try { + FXMLLoader loader = new FXMLLoader(VacCollectorView.class.getResource("/fxml/VacCollector.fxml")); + loader.load(); + return loader.getController(); + } catch (IOException e) { + throw new Error(e); + } + } private final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + private final String[] intervalNames = {"1 sec", "5 sec", "10 sec", "30 sec", "1 min"}; private final int[] intervals = {1000, 5000, 10000, 30000, 60000}; private final List views = new ArrayList<>(); -// private LoaderConnection storageConnection; - private VacCollectorDevice device; private TimePlottableGroup plottables; -// private BiFunction loaderFactory; + @FXML + private BorderPane root; @FXML private AnchorPane plotHolder; @FXML @@ -91,6 +94,12 @@ public class VacCollectorView implements Initializable, DeviceListener, Measurem @FXML private ToggleButton logButton; + + @Override + public Node getFXNode() { + return root; + } + /** * Initializes the controller class. */ @@ -118,24 +127,19 @@ public class VacCollectorView implements Initializable, DeviceListener, Measurem Notifications.create().darkStyle().hideAfter(Duration.seconds(2d)).text(message).showError(); } - public VacCollectorDevice getDevice() { - return device; - } - - public void setDevice(VacCollectorDevice device) { - this.device = device; + @Override + public void open(VacCollectorDevice device) throws Exception { + super.open(device); device.getSensors().stream().map((sensor) -> { - VacuumeterView controller; - if (sensor.meta().getBoolean("powerButton", false)) { - controller = new PoweredVacuumeterView(); + VacuumeterView view; + if (sensor.hasState("power")) { + view = new PoweredVacuumeterView(); } else { - controller = new VacuumeterView(); + view = new VacuumeterView(); } - sensor.connect(controller, Roles.DEVICE_LISTENER_ROLE, Roles.MEASUREMENT_CONSUMER_ROLE); - return controller; - }).forEach((controller) -> { - views.add(controller); - }); + sensor.connect(view, Roles.VIEW_ROLE, Roles.DEVICE_LISTENER_ROLE, Roles.MEASUREMENT_CONSUMER_ROLE); + return view; + }).forEach(views::add); setupView(); } @@ -153,13 +157,6 @@ public class VacCollectorView implements Initializable, DeviceListener, Measurem public void onMeasurementResult(Measurement measurement, DataPoint result, Instant time) { if (plottables != null) { plottables.put(result); - //workaround to fix autorange problem -// for (String n : result.names()) { -// Value val = result.getValue(n); -// if (val.doubleValue() > 0) { -// plottables.put(n, val); -// } -// } } Platform.runLater(() -> timeLabel.setText(TIME_FORMAT.format(LocalDateTime.ofInstant(time, ZoneOffset.UTC)))); } @@ -167,11 +164,11 @@ public class VacCollectorView implements Initializable, DeviceListener, Measurem private void setupView() { vacBoxHolder.getChildren().clear(); plottables = new TimePlottableGroup(); - views.forEach((controller) -> { - vacBoxHolder.getChildren().add(controller.getComponent()); - TimePlottable plot = new TimePlottable(controller.getTitle(), - controller.getName()); - plot.configure(controller.meta()); + views.forEach((view) -> { + vacBoxHolder.getChildren().add(view.getComponent()); + TimePlottable plot = new TimePlottable(view.getTitle(), + view.getDevice().getName()); + plot.configure(view.getDevice().meta()); plottables.add(plot); }); plottables.setValue("thickness", 3); @@ -208,10 +205,6 @@ public class VacCollectorView implements Initializable, DeviceListener, Measurem } } - public void setLoaderFactory(BiFunction loaderFactory) { - this.loaderFactory = loaderFactory; - } - @FXML private void onStartStopToggle(ActionEvent event) { if (startStopButton.isSelected() != getDevice().isMeasuring()) { @@ -221,7 +214,7 @@ public class VacCollectorView implements Initializable, DeviceListener, Measurem try { startMeasurement(); } catch (ControlException ex) { - getLogger().error("Failed to start measurement", ex); + getDevice().getLogger().error("Failed to start measurement", ex); startStopButton.setSelected(false); } } else { @@ -233,56 +226,51 @@ public class VacCollectorView implements Initializable, DeviceListener, Measurem @FXML private void onStoreToggle(ActionEvent event) { - if (storeButton.isSelected()) { - //creating storage on UI thread - if (!device.meta().hasMeta("storage")) { - getLogger().info("Storage not defined. Starting storage selection dialog"); - DirectoryChooser chooser = new DirectoryChooser(); - File storageDir = chooser.showDialog(plotHolder.getScene().getWindow()); - if (storageDir == null) { - storeButton.setSelected(false); - throw new RuntimeException("User canceled directory selection"); - } - device.getConfig().putNode(new MetaBuilder("storage") - .putValue("path", storageDir.getAbsolutePath())); - } - Meta storageConfig = device.meta().getMeta("storage"); - Storage localStorage = StorageManager.buildFrom(device.getContext()) - .buildStorage(storageConfig); - //Start storage creation on non-UI thread - new Thread(() -> { - try { - - PointLoader loader; - - if (loaderFactory != null) { - loader = loaderFactory.apply(device, localStorage); - } else { - TableFormatBuilder format = new TableFormatBuilder().setType("timestamp", ValueType.TIME); - device.getSensors().forEach((s) -> { - format.setType(s.getName(), ValueType.NUMBER); - }); - - loader = LoaderFactory.buildPointLoder(localStorage, "vactms", - device.meta().getString("storage.shelf", ""), "timestamp", format.build()); - } - storageConnection = new LoaderConnection(loader); - device.connect(storageConnection, Roles.STORAGE_ROLE); - } catch (Exception ex) { - getLogger().error("Failed to start data storing", ex); - storeButton.setSelected(false); - } - }).start(); - } else if (storageConnection != null) { - device.disconnect(storageConnection); - } + getDevice().setState("storing", storeButton.isSelected()); +// if (storeButton.isSelected()) { +// //creating storage on UI thread +// if (!device.meta().hasMeta("storage")) { +// getLogger().info("Storage not defined. Starting storage selection dialog"); +// DirectoryChooser chooser = new DirectoryChooser(); +// File storageDir = chooser.showDialog(plotHolder.getScene().getWindow()); +// if (storageDir == null) { +// storeButton.setSelected(false); +// throw new RuntimeException("User canceled directory selection"); +// } +// device.getConfig().putNode(new MetaBuilder("storage") +// .putValue("path", storageDir.getAbsolutePath())); +// } +// Meta storageConfig = device.meta().getMeta("storage"); +// Storage localStorage = StorageManager.buildFrom(device.getContext()) +// .buildStorage(storageConfig); +// //Start storage creation on non-UI thread +// new Thread(() -> { +// try { +// +// PointLoader loader; +// +// if (loaderFactory != null) { +// loader = loaderFactory.apply(device, localStorage); +// } else { +// TableFormatBuilder format = new TableFormatBuilder().setType("timestamp", ValueType.TIME); +// device.getSensors().forEach((s) -> { +// format.setType(s.getName(), ValueType.NUMBER); +// }); +// +// loader = LoaderFactory.buildPointLoder(localStorage, "vactms", +// device.meta().getString("storage.shelf", ""), "timestamp", format.build()); +// } +// storageConnection = new LoaderConnection(loader); +// device.connect(storageConnection, Roles.STORAGE_ROLE); +// } catch (Exception ex) { +// getLogger().error("Failed to start data storing", ex); +// storeButton.setSelected(false); +// } +// }).start(); +// } else if (storageConnection != null) { +// device.disconnect(storageConnection); +// } } - /** - * @return the logger - */ - private Logger getLogger() { - return device.getLogger(); - } } diff --git a/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacuumeterView.java b/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacuumeterView.java index 54692bee..db656c63 100644 --- a/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacuumeterView.java +++ b/numass-control/vac/src/main/java/inr/numass/readvac/fx/VacuumeterView.java @@ -5,16 +5,13 @@ */ package inr.numass.readvac.fx; -import hep.dataforge.control.connections.DeviceConnection; import hep.dataforge.control.connections.MeasurementConsumer; import hep.dataforge.control.devices.Device; -import hep.dataforge.control.devices.DeviceListener; import hep.dataforge.control.measurements.Measurement; import hep.dataforge.control.measurements.MeasurementListener; -import hep.dataforge.meta.Meta; -import hep.dataforge.meta.Metoid; -import hep.dataforge.names.Named; +import hep.dataforge.control.measurements.Sensor; import hep.dataforge.values.Value; +import inr.numass.control.DeviceViewConnection; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; @@ -22,6 +19,7 @@ import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Label; +import javafx.scene.layout.BorderPane; import javafx.scene.paint.Color; import org.controlsfx.control.ToggleSwitch; @@ -37,7 +35,7 @@ import java.util.ResourceBundle; /** * @author Alexander Nozik */ -public class VacuumeterView extends DeviceConnection implements DeviceListener, MeasurementConsumer, MeasurementListener, Initializable, Named, Metoid { +public class VacuumeterView extends DeviceViewConnection> implements MeasurementConsumer, MeasurementListener, Initializable { private static final DecimalFormat FORMAT = new DecimalFormat("0.###E0"); private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ISO_LOCAL_TIME; @@ -45,27 +43,24 @@ public class VacuumeterView extends DeviceConnection implements DeviceListener, protected Node node; @FXML - Label deviceNameLabel; - + private BorderPane root; @FXML - Label unitLabel; - + protected Label deviceNameLabel; @FXML - Label valueLabel; - + protected Label unitLabel; @FXML - Label status; - + private Label valueLabel; @FXML - ToggleSwitch disableButton; + private Label status; + @FXML + private ToggleSwitch disableButton; @Override @SuppressWarnings("unchecked") public void accept(Device device, String measurementName, Measurement measurement) { measurement.addListener(this); - if (device.meta().hasValue("color")) { - valueLabel.setTextFill(Color.valueOf(device.meta().getString("color"))); - } + getDevice().meta().optValue("color").ifPresent(colorValue ->valueLabel.setTextFill(Color.valueOf(colorValue.stringValue()))); + } @Override @@ -91,9 +86,9 @@ public class VacuumeterView extends DeviceConnection implements DeviceListener, Platform.runLater(() -> { unitLabel.setText(getDevice().meta().getString("units", "mbar")); deviceNameLabel.setText(getDevice().getName()); - disableButton.setSelected(!getDevice().meta().getBoolean("disabled", false)); + disableButton.setSelected(!getDevice().optBooleanState("disabled").orElse(false)); disableButton.selectedProperty().addListener((ObservableValue observable, Boolean oldValue, Boolean newValue) -> { - getDevice().getConfig().setValue("disabled", !newValue); + getDevice().setState("disabled",!newValue); if (!newValue) { valueLabel.setText("---"); } @@ -137,17 +132,13 @@ public class VacuumeterView extends DeviceConnection implements DeviceListener, }); } - @Override - public String getName() { - return getDevice().getName(); - } - - @Override - public Meta meta() { - return getDevice().meta(); - } public String getTitle() { - return meta().getString("title", getName()); + return getDevice().meta().getString("title", getDevice().getName()); + } + + @Override + public Node getFXNode() { + return root; } } diff --git a/numass-control/vac/src/main/resources/config/devices.xml b/numass-control/vac/src/main/resources/config/devices.xml new file mode 100644 index 00000000..9f50f237 --- /dev/null +++ b/numass-control/vac/src/main/resources/config/devices.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/numass-control/vac/src/main/resources/fxml/VacBox.fxml b/numass-control/vac/src/main/resources/fxml/VacBox.fxml index bc84e30e..4b7a4d23 100644 --- a/numass-control/vac/src/main/resources/fxml/VacBox.fxml +++ b/numass-control/vac/src/main/resources/fxml/VacBox.fxml @@ -1,63 +1,59 @@ - - - + - - - - - - - - + - - - - - + + +
+ - - + - - - - - - - - - - + + + + + + + + + + - - - - - - - - + + + + + + + - - - +
+
diff --git a/numass-control/vac/src/main/resources/fxml/VacCollector.fxml b/numass-control/vac/src/main/resources/fxml/VacCollector.fxml index 85ff92e9..d4d6154f 100644 --- a/numass-control/vac/src/main/resources/fxml/VacCollector.fxml +++ b/numass-control/vac/src/main/resources/fxml/VacCollector.fxml @@ -5,51 +5,48 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + +
+ + + + + + + + + + + + + + + + + + + - - +
+
diff --git a/numass-control/vac/src/main/resources/inr/numass/readvac/testConfig.xml b/numass-control/vac/src/main/resources/inr/numass/readvac/testConfig.xml deleted file mode 100644 index dd1227fb..00000000 --- a/numass-control/vac/src/main/resources/inr/numass/readvac/testConfig.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - 12_2015.test - diff --git a/numass-control/vac/src/main/resources/inr/numass/readvac/vac-config.xml b/numass-control/vac/src/main/resources/inr/numass/readvac/vac-config.xml deleted file mode 100644 index 5526b9fd..00000000 --- a/numass-control/vac/src/main/resources/inr/numass/readvac/vac-config.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/numass-main/src/main/groovy/inr/numass/scripts/Underflow.groovy b/numass-main/src/main/groovy/inr/numass/scripts/Underflow.groovy index 1824a7bd..1097c0e0 100644 --- a/numass-main/src/main/groovy/inr/numass/scripts/Underflow.groovy +++ b/numass-main/src/main/groovy/inr/numass/scripts/Underflow.groovy @@ -10,6 +10,7 @@ import hep.dataforge.io.ColumnedDataWriter import hep.dataforge.storage.commons.StorageUtils import hep.dataforge.tables.Table import inr.numass.data.NMPoint +import inr.numass.data.NumassData import inr.numass.data.NumassDataUtils import inr.numass.storage.NumassStorage import inr.numass.utils.UnderflowCorrection @@ -26,7 +27,7 @@ Collection data = NumassDataUtils.joinSpectra( .map { println "loading ${it.key}" it.value - } + }.map { (NumassData) it } ) data = NumassDataUtils.substractReferencePoint(data, 18600d); @@ -62,8 +63,8 @@ def printPoint(Iterable data, List us, int binning = 20, normalize = tr points.eachWithIndex { it, index -> print "\t${it.voltage}" it.getMap(binning, normalize).each { k, v -> - spectra[k].add(v) - } + spectra[k].add(v) + } } println() diff --git a/numass-main/src/main/java/inr/numass/tasks/NumassFitScanTask.java b/numass-main/src/main/java/inr/numass/tasks/NumassFitScanTask.java index 29e41882..f7d8d7eb 100644 --- a/numass-main/src/main/java/inr/numass/tasks/NumassFitScanTask.java +++ b/numass-main/src/main/java/inr/numass/tasks/NumassFitScanTask.java @@ -84,7 +84,7 @@ public class NumassFitScanTask extends AbstractTask { if (model.meta().hasMeta("filter")) { model.dependsOn("filter", metaBuilder.build(), "prepare"); } else if (model.meta().hasMeta("empty")) { - model.dependsOn("substractEmpty", metaBuilder.build(), "prepare"); + model.dependsOn("subtractEmpty", metaBuilder.build(), "prepare"); } else { model.dependsOn("prepare", metaBuilder.build(), "prepare"); } diff --git a/numass-main/src/main/java/inr/numass/tasks/NumassFitTask.java b/numass-main/src/main/java/inr/numass/tasks/NumassFitTask.java index 50613e75..93b2424e 100644 --- a/numass-main/src/main/java/inr/numass/tasks/NumassFitTask.java +++ b/numass-main/src/main/java/inr/numass/tasks/NumassFitTask.java @@ -72,7 +72,7 @@ public class NumassFitTask extends SingleActionTask { if (model.meta().hasMeta("filter")) { model.dependsOn("filter", metaBuilder.build(), "prepare"); } else if (model.meta().hasMeta("empty")) { - model.dependsOn("substractEmpty", metaBuilder.build(), "prepare"); + model.dependsOn("subtractEmpty", metaBuilder.build(), "prepare"); } else { model.dependsOn("prepare", metaBuilder.build(), "prepare"); } diff --git a/numass-main/src/main/java/inr/numass/tasks/NumassSubstractEmptySourceTask.java b/numass-main/src/main/java/inr/numass/tasks/NumassSubstractEmptySourceTask.java index d539c670..b0fa80be 100644 --- a/numass-main/src/main/java/inr/numass/tasks/NumassSubstractEmptySourceTask.java +++ b/numass-main/src/main/java/inr/numass/tasks/NumassSubstractEmptySourceTask.java @@ -41,7 +41,7 @@ import java.util.function.BiFunction; public class NumassSubstractEmptySourceTask extends AbstractTask { @Override public String getName() { - return "substractEmpty"; + return "subtractEmpty"; } @Override @@ -50,7 +50,7 @@ public class NumassSubstractEmptySourceTask extends AbstractTask
{ DataNode
rootNode = data.getCheckedNode("prepare", Table.class); Data emptySource = data.getCheckedNode("empty", Table.class).getData(); rootNode.forEachDataWithType(Table.class, input -> { - Data res = subtractBackground(input, emptySource); + Data res = subtract(input, emptySource); res.getGoal().onComplete((r, err) -> { if (r != null) { OutputStream out = model.getContext().io().out("merge", input.getName() + ".subtract"); @@ -77,11 +77,11 @@ public class NumassSubstractEmptySourceTask extends AbstractTask
{ } - private Data subtractBackground(Data mergeData, Data emptyData) { - return DataUtils.combine(mergeData, emptyData, Table.class, mergeData.meta(), (BiFunction) this::subtractBackground); + private Data subtract(Data mergeData, Data emptyData) { + return DataUtils.combine(mergeData, emptyData, Table.class, mergeData.meta(), (BiFunction) this::subtract); } - private Table subtractBackground(Table merge, Table empty) { + private Table subtract(Table merge, Table empty) { ListTable.Builder builder = new ListTable.Builder(merge.getFormat()); merge.stream().forEach(point -> { MapPoint.Builder pointBuilder = new MapPoint.Builder(point);