Merged kodex into core

This commit is contained in:
Alexander Nozik 2018-01-09 20:04:19 +03:00
parent 804221c859
commit 8fa0c651ff
15 changed files with 183 additions and 122 deletions

View File

@ -18,19 +18,14 @@ package inr.numass.control.cryotemp
import hep.dataforge.context.Context
import hep.dataforge.control.RoleDef
import hep.dataforge.control.RoleDefs
import hep.dataforge.control.collectors.RegularPointCollector
import hep.dataforge.control.connections.Roles
import hep.dataforge.control.devices.Device
import hep.dataforge.control.devices.PortSensor
import hep.dataforge.control.devices.Sensor
import hep.dataforge.control.devices.StateDef
import hep.dataforge.control.measurements.AbstractMeasurement
import hep.dataforge.control.measurements.Measurement
import hep.dataforge.control.ports.GenericPortController
import hep.dataforge.control.devices.stringState
import hep.dataforge.control.ports.Port
import hep.dataforge.description.ValueDef
import hep.dataforge.exceptions.ControlException
import hep.dataforge.exceptions.MeasurementException
import hep.dataforge.exceptions.StorageException
import hep.dataforge.meta.Meta
import hep.dataforge.storage.api.TableLoader
@ -39,12 +34,10 @@ import hep.dataforge.storage.commons.StorageConnection
import hep.dataforge.tables.TableFormat
import hep.dataforge.tables.TableFormatBuilder
import hep.dataforge.utils.DateTimeUtils
import hep.dataforge.values.Values
import inr.numass.control.DeviceView
import inr.numass.control.StorageHelper
import java.time.Duration
import java.util.*
import java.util.function.BiConsumer
/**
@ -83,14 +76,11 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
tableFormatBuilder.build()
}
val sps: String
get() = getState(SPS).stringValue()
val sps: String by stringState(SPS)
val pga: String
get() = getState(PGA).stringValue()
val pga: String by stringState(PGA)
val abuf: String
get() = getState(ABUF).stringValue()
val abuf: String by stringState(ABUF)
private val duration = Duration.parse(getMeta().getString("averagingDuration", "PT30S"))
@ -137,8 +127,8 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
}
setSPS(getMeta().getInt("sps", 0))
setBUF(getMeta().getInt("abuf", 100))
setSPS(meta.getInt("sps", 0))
setBUF(meta.getInt("abuf", 100))
// setting up the collector
storageHelper = StorageHelper(this) { connection: StorageConnection -> this.buildLoader(connection) }
@ -146,11 +136,11 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
@Throws(ControlException::class)
override fun shutdown() {
measurement?.stop(true)
storageHelper?.close()
super.shutdown()
}
@Throws(ControlException::class)
override fun buildPort(portName: String): Port {
//setup connection
@ -184,7 +174,7 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
@Throws(ControlException::class)
fun changeParameters(sps: Int, abuf: Int) {
stopMeasurement(false)
stopCurrentMeasurement()
//setting sps
setSPS(sps)
//setting buffer
@ -233,72 +223,14 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
}
}
private fun setSPS(sps: Int) {
logger.info("Setting sampling rate to " + spsToStr(sps))
val response: String = try {
sendAndWait("v" + sps).trim { it <= ' ' }
} catch (ex: Exception) {
ex.message ?: ""
}
if (response.contains("=")) {
updateLogicalState(SPS, Integer.parseInt(response.substring(4)))
} else {
logger.error("Setting sps failed with message: " + response)
}
}
@Throws(MeasurementException::class)
override fun createMeasurement(): Measurement<PKT8Result> {
return if (this.measurement != null) {
this.measurement
} else {
try {
PKT8Measurement(connection)
} catch (e: ControlException) {
throw MeasurementException(e)
}
}
}
@Throws(MeasurementException::class)
override fun startMeasurement(): Measurement<PKT8Result> {
//clearing PKT queue
try {
send("p")
sendAndWait("p")
} catch (e: ControlException) {
logger.error("Failed to clear PKT8 port")
// throw new MeasurementException(e);
}
return super.startMeasurement()
}
inner class PKT8Measurement(private val controller: GenericPortController) : AbstractMeasurement<PKT8Result>() {
override fun getDevice(): Device = this@PKT8Device
private var collector: RegularPointCollector = RegularPointCollector(duration, channels.values.map { it.name }) { dp: Values ->
logger.debug("Point measurement complete. Pushing...")
storageHelper?.push(dp)
}
var errorListener: BiConsumer<String, Throwable>? = null
var stopListener: GenericPortController.PhraseListener? = null;
var valueListener: GenericPortController.PhraseListener? = null;
override fun start() {
if (isStarted) {
override fun startMeasurement(oldMeta: Meta, newMeta: Meta) {
if (!oldMeta.isEmpty) {
logger.warn("Trying to start measurement which is already started")
}
try {
logger.info("Starting measurement")
//add weak error listener
errorListener = controller.onError(this::onError)
//add weak stop listener
stopListener = controller.onPhrase("[Ss]topped\\s*") {
@ -329,11 +261,9 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
} catch (ex: ControlException) {
onError("Failed to start measurement", ex)
}
}
}
@Throws(MeasurementException::class)
override fun stop(force: Boolean): Boolean {
override fun stopMeasurement(meta: Meta) {
if (isFinished) {
logger.warn("Trying to stop measurement which is already stopped")
return true
@ -356,9 +286,134 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor<PKT8Result>(context,
logger.debug("Collector stopped")
}
}
}
private fun setSPS(sps: Int) {
logger.info("Setting sampling rate to " + spsToStr(sps))
val response: String = try {
sendAndWait("v" + sps).trim { it <= ' ' }
} catch (ex: Exception) {
ex.message ?: ""
}
if (response.contains("=")) {
updateLogicalState(SPS, Integer.parseInt(response.substring(4)))
} else {
logger.error("Setting sps failed with message: " + response)
}
}
// @Throws(MeasurementException::class)
// override fun createMeasurement(): Measurement<PKT8Result> {
// return if (this.measurement != null) {
// this.measurement
// } else {
// try {
// PKT8Measurement(connection)
// } catch (e: ControlException) {
// throw MeasurementException(e)
// }
//
// }
// }
//
// @Throws(MeasurementException::class)
// override fun startMeasurement(): Measurement<PKT8Result> {
// //clearing PKT queue
// try {
// send("p")
// sendAndWait("p")
// } catch (e: ControlException) {
// logger.error("Failed to clear PKT8 port")
// // throw new MeasurementException(e);
// }
//
// return super.startMeasurement()
// }
// inner class PKT8Measurement(private val controller: GenericPortController) : AbstractMeasurement<PKT8Result>() {
//
// override fun getDevice(): Device = this@PKT8Device
//
// private var collector: RegularPointCollector = RegularPointCollector(duration, channels.values.map { it.name }) { dp: Values ->
// logger.debug("Point measurement complete. Pushing...")
// storageHelper?.push(dp)
// }
//
// var errorListener: BiConsumer<String, Throwable>? = null
// var stopListener: GenericPortController.PhraseListener? = null;
// var valueListener: GenericPortController.PhraseListener? = null;
//
// override fun start() {
// if (isStarted) {
// logger.warn("Trying to start measurement which is already started")
// }
//
// try {
// logger.info("Starting measurement")
// //add weak error listener
// errorListener = controller.onError(this::onError)
//
// //add weak stop listener
// stopListener = controller.onPhrase("[Ss]topped\\s*") {
// afterPause()
// updateLogicalState(Sensor.MEASURING_STATE, false)
// }
//
// //add weak measurement listener
// valueListener = controller.onPhrase("[a-f].*") {
// val trimmed = it.trim()
// val designation = trimmed.substring(0, 1)
// val rawValue = java.lang.Double.parseDouble(trimmed.substring(1)) / 100
//
// val channel = this@PKT8Device.channels[designation]
//
// if (channel != null) {
// result(channel.evaluate(rawValue))
// collector.put(channel.name, channel.getTemperature(rawValue))
// } else {
// result(PKT8Result(designation, rawValue, -1.0))
// }
// }
//
// //send start signal
// controller.send("s")
//
// afterStart()
// } catch (ex: ControlException) {
// onError("Failed to start measurement", ex)
// }
//
// }
//
// @Throws(MeasurementException::class)
// override fun stop(force: Boolean): Boolean {
// if (isFinished) {
// logger.warn("Trying to stop measurement which is already stopped")
// return true
// } else {
//
// try {
// logger.info("Stopping measurement")
// val response = sendAndWait("p").trim()
// // Должно быть именно с большой буквы!!!
// return "Stopped" == response || "stopped" == response
// } catch (ex: Exception) {
// onError("Failed to stop measurement", ex)
// return false
// } finally {
// afterStop()
// errorListener?.let { controller.removeErrorListener(it) }
// stopListener?.let { controller.removePhraseListener(it) }
// valueListener?.let { controller.removePhraseListener(it) }
// collector.stop()
// logger.debug("Collector stopped")
// }
// }
// }
// }
//
companion object {
val PKT8_DEVICE_TYPE = "numass.pkt8"

View File

@ -35,7 +35,7 @@ class LambdaHub(context: Context, meta: Meta) : DeviceHub, AbstractDevice(contex
return if(portName.startsWith("virtual")){
VirtualLambdaPort(meta)
} else{
PortFactory.getPort(portName);
PortFactory.build(portName);
}
}

View File

@ -16,11 +16,8 @@
package inr.numass.control.magnet
import hep.dataforge.context.Context
import hep.dataforge.control.devices.AbstractDevice
import hep.dataforge.control.devices.StateDef
import hep.dataforge.control.devices.StateDefs
import hep.dataforge.control.devices.*
import hep.dataforge.control.ports.PortFactory
import hep.dataforge.control.ports.PortTimeoutException
import hep.dataforge.description.ValueDef
import hep.dataforge.exceptions.ControlException
import hep.dataforge.exceptions.PortException
@ -28,9 +25,6 @@ import hep.dataforge.meta.Meta
import hep.dataforge.utils.DateTimeUtils
import hep.dataforge.values.Value
import hep.dataforge.values.ValueType.*
import hep.dataforge.control.devices.booleanState
import hep.dataforge.control.devices.doubleState
import hep.dataforge.control.devices.timeState
import org.slf4j.LoggerFactory
import java.text.DecimalFormat
import java.time.Duration
@ -97,7 +91,7 @@ open class LambdaMagnet(context: Context, meta: Meta, private val controller: La
* @throws ControlException
*/
@Throws(ControlException::class)
constructor(context: Context, meta: Meta) : this(context, meta, LambdaPortController(context, PortFactory.getPort(meta.getString("port")))) {
constructor(context: Context, meta: Meta) : this(context, meta, LambdaPortController(context, PortFactory.build(meta.getString("port")))) {
closePortOnShutDown = true
}

View File

@ -56,7 +56,7 @@ object Talk {
portName = args[0]
}
val handler: Port
handler = PortFactory.getPort(portName)
handler = PortFactory.build(portName)
handler.setPhraseCondition { str: String -> str.endsWith("\r") }
// LambdaMagnet controller = new LambdaMagnet(handler, 1);

View File

@ -131,7 +131,7 @@ class MspDevice(context: Context, meta: Meta) : PortSensor<Values>(context, meta
@Throws(ControlException::class)
override fun shutdown() {
super.stopMeasurement(true)
if (isConnected) {
if (connected) {
setFilamentOn(false)
setConnected(false)
}
@ -183,7 +183,7 @@ class MspDevice(context: Context, meta: Meta) : PortSensor<Values>(context, meta
@Throws(ControlException::class)
private fun setConnected(connected: Boolean): Boolean {
val sensorName: String
if (isConnected != connected) {
if (this.connected != connected) {
if (connected) {
connection.open()
var response = commandAndWait("Sensors")

View File

@ -7,6 +7,7 @@ import hep.dataforge.control.devices.DeviceListener
import hep.dataforge.control.devices.PortSensor
import hep.dataforge.control.devices.Sensor
import hep.dataforge.fx.bindWindow
import hep.dataforge.meta.Meta
import hep.dataforge.values.Value
import javafx.beans.binding.BooleanBinding
import javafx.beans.binding.ObjectBinding
@ -48,6 +49,7 @@ fun Device.getDisplay(): DeviceDisplay<*> {
abstract class DeviceDisplay<D : Device> : Component(), Connection, DeviceListener {
private val bindings = HashMap<String, ObjectBinding<Value>>()
private val metaBindings = HashMap<String, ObjectBinding<Meta>>()
private val deviceProperty = SimpleObjectProperty<D>(this, "device", null)
val device: D by deviceProperty
@ -99,6 +101,20 @@ abstract class DeviceDisplay<D : Device> : Component(), Connection, DeviceListen
}
}
fun getMetaStateBinding(state: String): ObjectBinding<Meta> {
return metaBindings.computeIfAbsent(state) { stateName ->
object : ObjectBinding<Meta>() {
override fun computeValue(): Meta {
return if (isOpen) {
device.getMetaState(stateName)
} else {
Meta.empty()
}
}
}
}
}
fun getBooleanStateBinding(state: String): BooleanBinding =
getStateBinding(state).booleanBinding { it?.booleanValue() ?: false }
@ -131,6 +147,10 @@ abstract class DeviceDisplay<D : Device> : Component(), Connection, DeviceListen
bindings[name]?.invalidate()
}
override fun notifyDeviceStateChanged(device: Device, name: String, state: Meta) {
metaBindings[name]?.invalidate()
}
open fun getBoardView(): Parent {
return HBox().apply {
alignment = Pos.CENTER_LEFT

View File

@ -72,7 +72,7 @@ class Indicator(radius: Double = 10.0) : Circle(radius, Color.GRAY) {
}
}
fun EventTarget.indicator(radius: Double = 10.0, op: (Indicator.() -> Unit)? = null) = opcr(this, Indicator(radius), op)
fun EventTarget.indicator(radius: Double = 10.0, op: (Indicator.() -> Unit) = {}): Indicator = opcr(this, Indicator(radius), op)
fun Indicator.bind(connection: DeviceDisplay<*>, state: String, transform: ((Value) -> Paint)? = null) {
tooltip(state)
@ -130,7 +130,7 @@ fun Node.deviceStateToggle(connection: DeviceDisplay<*>, state: String, title: S
}
}
fun EventTarget.switch(text: String = "", op: (ToggleSwitch.() -> Unit)? = null): ToggleSwitch {
fun EventTarget.switch(text: String = "", op: (ToggleSwitch.() -> Unit) = {}): ToggleSwitch {
val switch = ToggleSwitch(text)
return opcr(this, switch, op)
}

View File

@ -44,7 +44,7 @@ fun connectStorage(device: Device, config: Meta) {
device.context.logger.info("Creating storage for device with getMeta: {}", node)
//building storage in a separate thread
Thread {
var storage = StorageFactory.buildStorage(device.context, node)
var storage = StorageManager.buildStorage(device.context, node)
if (!numassRun.isEmpty()) {
try {
storage = storage.buildShelf(numassRun, Meta.empty())

View File

@ -30,7 +30,7 @@ class CM32Device(context: Context, meta: Meta) : PortSensor<Double>(context, met
if (portName.startsWith("com")) {
new = ComPort(portName, 2400, 8, 1, 0)
} else {
new = PortFactory.getPort(portName)
new = PortFactory.build(portName)
}
new.setDelimiter("T--\r")
return new

View File

@ -87,7 +87,7 @@ class MKSVacDevice(context: Context, meta: Meta) : PortSensor<Double>(context, m
@Throws(ControlException::class)
override fun shutdown() {
if (isConnected) {
if (connected) {
setState("power", false)
}
super.shutdown()

View File

@ -3,7 +3,6 @@ package inr.numass.control.readvac
import hep.dataforge.context.Context
import hep.dataforge.control.devices.DeviceFactory
import hep.dataforge.control.devices.Sensor
import hep.dataforge.control.virtual.VirtualDevice
import hep.dataforge.meta.Meta
import java.util.stream.Collectors

View File

@ -14,7 +14,6 @@ description = "A bse package with minimal dependencies for numass"
dependencies {
compile "hep.dataforge:dataforge-storage" //project(':dataforge-storage')
compile "hep.dataforge:kodex"
compile 'com.google.protobuf:protobuf-java:3.5.0'
// https://mvnrepository.com/artifact/com.github.robtimus/sftp-fs

View File

@ -32,7 +32,6 @@ dependencies {
compile project(':numass-core')
compile "hep.dataforge:dataforge-minuit" //project(':dataforge-stat:dataforge-minuit')
compile "hep.dataforge:grind-terminal" //project(':dataforge-grind:grind-terminal')
compile "hep.dataforge:kmath"
compile "hep.dataforge:dataforge-gui"
// https://mvnrepository.com/artifact/org.ehcache/ehcache

View File

@ -62,7 +62,7 @@ public class SpectrumGenerator implements Generator {
}
public SpectrumGenerator(XYModel source, ParamSet params) {
this(source, params, getDefaultRandomGenerator());
this(source, params, INSTANCE.getDefaultRandomGenerator());
}
@Override

View File

@ -121,9 +121,9 @@ class NumassBeta : AbstractParametricBiFunction(list) {
val ve = pe / eTot
val yfactor = 2.0 * 2.0 * 1.0 / 137.039 * Math.PI
val y = yfactor / ve
val Fn = y / abs(1.0 - exp(-y))
val Fermi = Fn * (1.002037 - 0.001427 * ve)
val res = Fermi * pe * eTot
val fn = y / abs(1.0 - exp(-y))
val fermi = fn * (1.002037 - 0.001427 * ve)
val res = fermi * pe * eTot
return K * res
}
@ -141,22 +141,17 @@ class NumassBeta : AbstractParametricBiFunction(list) {
*/
private fun root(E0: Double, mnu2: Double, E: Double): Double {
//bare beta-spectrum
val delta = E0 - E//E0-E
val res: Double
val delta = E0 - E
val bare = factor(E) * delta * sqrt(Math.max(delta * delta - mnu2, 0.0))
if (delta == 0.0) {
return 0.0
}
if (mnu2 >= 0) {
res = Math.max(bare, 0.0)
} else {
if (delta + 0.812 * sqrt(-mnu2) <= 0) {
return 0.0 //sqrt(0.66)
return when {
mnu2 >= 0 -> Math.max(bare, 0.0)
delta == 0.0 -> 0.0
delta + 0.812 * sqrt(-mnu2) <= 0 -> 0.0 //sqrt(0.66)
else -> {
val aux = sqrt(-mnu2 * 0.66) / delta
Math.max(bare * (1 + aux * exp(-1 - 1 / aux)), 0.0)
}
val aux = sqrt(-mnu2 * 0.66) / delta
res = Math.max(bare * (1 + aux * exp(-1 - 1 / aux)), 0.0)
}
return res
}
/**
@ -181,9 +176,9 @@ class NumassBeta : AbstractParametricBiFunction(list) {
}
override fun getDefaultParameter(name: String): Double {
when (name) {
"mnu2", "U2", "msterile2" -> return 0.0
else -> return super.getDefaultParameter(name)
return when (name) {
"mnu2", "U2", "msterile2" -> 0.0
else -> super.getDefaultParameter(name)
}
}