Build OK.

This commit is contained in:
Alexander Nozik 2018-04-28 15:10:57 +03:00
parent dae12c1b9c
commit 89a0cf7b42
36 changed files with 121 additions and 119 deletions

View File

@ -32,10 +32,10 @@ internal fun createChannel(meta: Meta): PKT8Channel {
if (meta.hasValue("coefs")) { if (meta.hasValue("coefs")) {
when (transformationType) { when (transformationType) {
"default", "hyperbolic" -> { "default", "hyperbolic" -> {
val coefs = meta.getValue("coefs").getList() val coefs = meta.getValue("coefs").list
val r0 = meta.getDouble("r0", 1000.0) val r0 = meta.getDouble("r0", 1000.0)
return PKT8Channel(meta) { r -> return PKT8Channel(meta) { r ->
coefs?.indices?.sumByDouble { coefs[it].getDouble() * Math.pow(r0 / r, it.toDouble()) } ?: -1.0 coefs.indices.sumByDouble { coefs[it].double * Math.pow(r0 / r, it.toDouble()) }
} }
} }
else -> throw RuntimeException("Unknown transformation type") else -> throw RuntimeException("Unknown transformation type")

View File

@ -21,6 +21,7 @@ import hep.dataforge.context.Context
import hep.dataforge.control.collectors.RegularPointCollector import hep.dataforge.control.collectors.RegularPointCollector
import hep.dataforge.control.connections.Roles import hep.dataforge.control.connections.Roles
import hep.dataforge.control.devices.PortSensor import hep.dataforge.control.devices.PortSensor
import hep.dataforge.control.devices.Sensor
import hep.dataforge.control.ports.GenericPortController import hep.dataforge.control.ports.GenericPortController
import hep.dataforge.control.ports.Port import hep.dataforge.control.ports.Port
import hep.dataforge.control.ports.PortFactory import hep.dataforge.control.ports.PortFactory
@ -261,7 +262,7 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor(context, meta) {
connection.also { connection.also {
it.onPhrase("[Ss]topped\\s*", this) { it.onPhrase("[Ss]topped\\s*", this) {
notifyMeasurementState(MeasurementState.STOPPED) notifyMeasurementState(Sensor.MeasurementState.STOPPED)
} }
//add weak measurement listener //add weak measurement listener
@ -275,7 +276,7 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor(context, meta) {
//send start signal //send start signal
it.send("s") it.send("s")
notifyMeasurementState(MeasurementState.IN_PROGRESS) notifyMeasurementState(Sensor.MeasurementState.IN_PROGRESS)
} }
} }
@ -286,7 +287,7 @@ class PKT8Device(context: Context, meta: Meta) : PortSensor(context, meta) {
val response = sendAndWait("p").trim() val response = sendAndWait("p").trim()
// Должно быть именно с большой буквы!!! // Должно быть именно с большой буквы!!!
if ("Stopped" == response || "stopped" == response) { if ("Stopped" == response || "stopped" == response) {
notifyMeasurementState(MeasurementState.STOPPED) notifyMeasurementState(Sensor.MeasurementState.STOPPED)
} }
} catch (ex: Exception) { } catch (ex: Exception) {
notifyError("Failed to stop measurement", ex) notifyError("Failed to stop measurement", ex)

View File

@ -120,13 +120,12 @@ class PKT8Display : DeviceDisplayFX<PKT8Device>(), PKT8ValueListener {
sortBy { it.channel } sortBy { it.channel }
} }
} }
} }
column("Sensor", PKT8Reading::channel); readonlyColumn("Sensor", PKT8Reading::channel);
column("Resistance", PKT8Reading::rawValue).cellFormat { readonlyColumn("Resistance", PKT8Reading::rawValue).cellFormat {
text = String.format("%.2f", it) text = String.format("%.2f", it)
} }
column("Temperature", PKT8Reading::temperature).cellFormat { readonlyColumn("Temperature", PKT8Reading::temperature).cellFormat {
text = String.format("%.2f", it) text = String.format("%.2f", it)
} }
} }

View File

@ -9,7 +9,7 @@ import hep.dataforge.control.ports.VirtualPort
import hep.dataforge.meta.Meta import hep.dataforge.meta.Meta
import hep.dataforge.meta.MetaUtils import hep.dataforge.meta.MetaUtils
import hep.dataforge.meta.Metoid import hep.dataforge.meta.Metoid
import hep.dataforge.values.Value import hep.dataforge.values.asValue
import java.time.Duration import java.time.Duration
import java.util.* import java.util.*
import java.util.function.Supplier import java.util.function.Supplier
@ -29,7 +29,7 @@ class PKT8VirtualPort(private val portName: String, meta: Meta) : VirtualPort(me
"s" -> { "s" -> {
val letters = arrayOf("a", "b", "c", "d", "e", "f", "g", "h") val letters = arrayOf("a", "b", "c", "d", "e", "f", "g", "h")
for (letter in letters) { for (letter in letters) {
val channelMeta = MetaUtils.findNodeByValue(meta, "channel", "letter", Value.parseValue(letter)).orElse(Meta.empty()) val channelMeta = MetaUtils.findNodeByValue(meta, "channel", "letter", letter.asValue()).orElse(Meta.empty())
val average: Double val average: Double
val sigma: Double val sigma: Double

View File

@ -288,7 +288,7 @@ class DanteClient(val ip: String, chainLength: Int) : AutoCloseable {
val en_fil_flattop = meta.getInt("energy_filter.flat_top") val en_fil_flattop = meta.getInt("energy_filter.flat_top")
val fast_peak_time = meta.getInt("fast_filter.peaking_time") val fast_peak_time = meta.getInt("fast_filter.peaking_time")
val fast_flattop = meta.getInt("fast_filter.flat_top") val fast_flattop = meta.getInt("fast_filter.flat_top")
val recovery_time = meta.getValue("recovery_time").getLong() val recovery_time = meta.getValue("recovery_time").long
val zero_peak_rate = meta.getInt("zero_peak_rate") val zero_peak_rate = meta.getInt("zero_peak_rate")
val inverted_input = meta.getInt("inverted_input", 0) val inverted_input = meta.getInt("inverted_input", 0)

View File

@ -83,44 +83,45 @@ class LambdaMagnet(private val controller: LambdaPortController, meta: Meta) : A
val target = valueState("target") val target = valueState("target")
//output values of current and voltage //output values of current and voltage
private var outCurrent by valueState("outCurrent", getter = { s2d(controller.getParameter(address, "PC")) }) { _, value -> private var outCurrent by valueState("outCurrent", getter = { s2d(controller.getParameter(address, "PC")) }) { value ->
setCurrent(value.double) setCurrent(value.double)
return@valueState value update(value)
}.doubleDelegate }.doubleDelegate
private var outVoltage = valueState("outVoltage", getter = { s2d(controller.getParameter(address, "PV")) }) { _, value -> private var outVoltage = valueState("outVoltage", getter = { s2d(controller.getParameter(address, "PV")) }) { value ->
if (!controller.setParameter(address, "PV", value.double)) { if (!controller.setParameter(address, "PV", value.double)) {
notifyError("Can't set the target voltage") notifyError("Can't set the target voltage")
} }
return@valueState value update(value)
}.doubleDelegate }.doubleDelegate
val output = valueState("output", getter = { controller.talk(address, "OUT?") == "OK" }) { _, value -> val output = valueState("output", getter = { controller.talk(address, "OUT?") == "OK" }) {value ->
setOutputMode(value.boolean) setOutputMode(value.boolean)
if (!value.boolean) { if (!value.boolean) {
status = MagnetStatus.OFF status = MagnetStatus.OFF
} }
update(value)
} }
val monitoring = valueState("monitoring", getter = { monitorTask != null }) { _, value -> val monitoring = valueState("monitoring", getter = { monitorTask != null }) { value ->
if (value.boolean) { if (value.boolean) {
startMonitorTask() startMonitorTask()
} else { } else {
stopMonitorTask() stopMonitorTask()
} }
return@valueState value update(value)
} }
/** /**
* *
*/ */
val updating = valueState("updating", getter = { updateTask != null }) { _, value -> val updating = valueState("updating", getter = { updateTask != null }) { value ->
if (value.boolean) { if (value.boolean) {
startUpdateTask() startUpdateTask()
} else { } else {
stopUpdateTask() stopUpdateTask()
} }
return@valueState value update(value)
} }

View File

@ -16,7 +16,7 @@ import java.time.Instant
object ConsoleVac { object ConsoleVac {
private fun Sensor.read(): Double { private fun Sensor.read(): Double {
this.measure() this.measure()
return runBlocking { resultState.future.await().getDouble(RESULT_VALUE)} return runBlocking { resultState.read().getDouble(RESULT_VALUE)}
} }
@Throws(Exception::class) @Throws(Exception::class)

View File

@ -67,7 +67,7 @@ class MKSVacDevice(context: Context, meta: Meta) : PortSensor(context, meta) {
@Throws(ControlException::class) @Throws(ControlException::class)
override fun shutdown() { override fun shutdown() {
if (connected) { if (connected.booleanValue) {
power = false power = false
} }
super.shutdown() super.shutdown()

View File

@ -25,6 +25,7 @@ import hep.dataforge.storage.commons.LoaderFactory
import hep.dataforge.storage.commons.StorageConnection import hep.dataforge.storage.commons.StorageConnection
import hep.dataforge.tables.TableFormatBuilder import hep.dataforge.tables.TableFormatBuilder
import hep.dataforge.utils.DateTimeUtils import hep.dataforge.utils.DateTimeUtils
import hep.dataforge.values.Value
import hep.dataforge.values.ValueMap import hep.dataforge.values.ValueMap
import hep.dataforge.values.ValueType import hep.dataforge.values.ValueType
import hep.dataforge.values.Values import hep.dataforge.values.Values
@ -141,7 +142,7 @@ class VacCollectorDevice(context: Context, meta: Meta, val sensors: Collection<S
private fun terminator(): Values { private fun terminator(): Values {
val p = ValueMap.Builder() val p = ValueMap.Builder()
deviceNames.forEach { n -> p.putValue(n.toUnescaped(), null) } deviceNames.forEach { n -> p.putValue(n.toUnescaped(), Value.NULL) }
return p.build() return p.build()
} }

View File

@ -91,7 +91,7 @@ class VacCollectorDisplay : DeviceDisplayFX<VacCollectorDevice>() {
isSelected = false isSelected = false
LogFragment().apply { LogFragment().apply {
addLogHandler(device.logger) addLogHandler(device.logger)
bindWindow(selectedProperty()) bindWindow(this@togglebutton, selectedProperty())
} }
} }
} }

View File

@ -11,9 +11,7 @@ import java.util.stream.Collectors
* Created by darksnake on 16-May-17. * Created by darksnake on 16-May-17.
*/ */
class VacDeviceFactory : DeviceFactory { class VacDeviceFactory : DeviceFactory {
override fun getType(): String { override val type: String = "numass.vac"
return "numass.vac"
}
private fun buildSensor(context: Context, sensorConfig: Meta): Sensor { private fun buildSensor(context: Context, sensorConfig: Meta): Sensor {
return when (sensorConfig.getString("sensorType", "")) { return when (sensorConfig.getString("sensorType", "")) {

View File

@ -115,7 +115,7 @@ open class VacDisplay : DeviceDisplayFX<Sensor>() {
} }
right { right {
switch { switch {
bindBooleanToState(CONNECTED_STATE, selectedProperty()); booleanStateProperty(CONNECTED_STATE).bindBidirectional(selectedProperty())
selectedProperty().addListener { _, _, newValue -> selectedProperty().addListener { _, _, newValue ->
if (!newValue) { if (!newValue) {
value = "---" value = "---"
@ -162,7 +162,7 @@ open class VacDisplay : DeviceDisplayFX<Sensor>() {
vgrow = Priority.ALWAYS vgrow = Priority.ALWAYS
switch("Power") { switch("Power") {
alignment = Pos.CENTER alignment = Pos.CENTER
bindBooleanToState("power", selectedProperty()) booleanStateProperty("power").bindBidirectional(selectedProperty())
} }
} }
} }

View File

@ -12,6 +12,7 @@ import inr.numass.actions.TimeAnalyzerAction
import inr.numass.data.NumassDataUtils import inr.numass.data.NumassDataUtils
import inr.numass.data.api.NumassPoint import inr.numass.data.api.NumassPoint
import inr.numass.data.api.NumassSet import inr.numass.data.api.NumassSet
import inr.numass.data.api.SimpleNumassPoint
import inr.numass.data.storage.NumassStorageFactory import inr.numass.data.storage.NumassStorageFactory
/** /**
@ -48,7 +49,7 @@ new GrindShell(ctx).eval {
def builder = DataSet.builder(NumassPoint) def builder = DataSet.builder(NumassPoint)
hvs.each { hv -> hvs.each { hv ->
builder.putStatic("point_${hv as int}", new inr.numass.data.api.SimpleNumassPoint.SimpleNumassPoint(hv, all.points.filter { builder.putStatic("point_${hv as int}", new SimpleNumassPoint(hv, all.points.filter {
it.voltage == hv it.voltage == hv
}.collect())); }.collect()));
} }

View File

@ -8,6 +8,7 @@ import hep.dataforge.meta.Meta
import inr.numass.NumassPlugin import inr.numass.NumassPlugin
import inr.numass.actions.TimeAnalyzerAction import inr.numass.actions.TimeAnalyzerAction
import inr.numass.data.GeneratorKt import inr.numass.data.GeneratorKt
import inr.numass.data.api.SimpleNumassPoint
import org.apache.commons.math3.random.JDKRandomGenerator import org.apache.commons.math3.random.JDKRandomGenerator
import java.time.Instant import java.time.Instant
@ -17,7 +18,7 @@ import java.time.Instant
*/ */
Context ctx = Global.instance() Context ctx = Global.INSTANCE
ctx.getPluginManager().load(FXPlotManager) ctx.getPluginManager().load(FXPlotManager)
ctx.getPluginManager().load(NumassPlugin.class) ctx.getPluginManager().load(NumassPlugin.class)
@ -35,7 +36,7 @@ new GrindShell(ctx).eval {
GeneratorKt.generateBlock(Instant.now().plusNanos(it * length), length, chain) GeneratorKt.generateBlock(Instant.now().plusNanos(it * length), length, chain)
} }
def point = new inr.numass.data.api.SimpleNumassPoint.SimpleNumassPoint(10000, blocks) def point = new SimpleNumassPoint(10000, blocks)
def meta = Meta.empty()//Grind.buildMeta(plotHist: false) def meta = Meta.empty()//Grind.buildMeta(plotHist: false)

View File

@ -23,7 +23,7 @@ import hep.dataforge.meta.Laminate;
import hep.dataforge.meta.Meta; import hep.dataforge.meta.Meta;
import hep.dataforge.tables.ListTable; import hep.dataforge.tables.ListTable;
import hep.dataforge.tables.Table; import hep.dataforge.tables.Table;
import hep.dataforge.values.Value; import hep.dataforge.values.ValueFactory;
import hep.dataforge.values.ValueMap; import hep.dataforge.values.ValueMap;
import hep.dataforge.values.Values; import hep.dataforge.values.Values;
import inr.numass.NumassUtils; import inr.numass.NumassUtils;
@ -93,17 +93,17 @@ public class MonitorCorrectAction extends OneToOneAction<Table, Table> {
double err = Math.sqrt(corrErr * corrErr + pointErr * pointErr) * getCR(dp); double err = Math.sqrt(corrErr * corrErr + pointErr * pointErr) * getCR(dp);
if (dp.getNames().contains("Monitor")) { if (dp.getNames().contains("Monitor")) {
pb.putValue("Monitor", Value.of(dp.getValue("Monitor").getDouble() / corrFactor)); pb.putValue("Monitor", ValueFactory.of(dp.getValue("Monitor").getDouble() / corrFactor));
} else { } else {
pb.putValue("Monitor", corrFactor); pb.putValue("Monitor", corrFactor);
} }
pb.putValue(NumassAnalyzer.COUNT_RATE_KEY, Value.of(dp.getValue(NumassAnalyzer.COUNT_RATE_KEY).getDouble() / corrFactor)); pb.putValue(NumassAnalyzer.COUNT_RATE_KEY, ValueFactory.of(dp.getValue(NumassAnalyzer.COUNT_RATE_KEY).getDouble() / corrFactor));
pb.putValue(NumassAnalyzer.COUNT_RATE_ERROR_KEY, Value.of(err)); pb.putValue(NumassAnalyzer.COUNT_RATE_ERROR_KEY, ValueFactory.of(err));
} else { } else {
double corrFactor = dp.getValue(NumassAnalyzer.COUNT_RATE_KEY).getDouble() / norm; double corrFactor = dp.getValue(NumassAnalyzer.COUNT_RATE_KEY).getDouble() / norm;
if (dp.getNames().contains("Monitor")) { if (dp.getNames().contains("Monitor")) {
pb.putValue("Monitor", Value.of(dp.getValue("Monitor").getDouble() / corrFactor)); pb.putValue("Monitor", ValueFactory.of(dp.getValue("Monitor").getDouble() / corrFactor));
} else { } else {
pb.putValue("Monitor", corrFactor); pb.putValue("Monitor", corrFactor);
} }
@ -127,7 +127,7 @@ public class MonitorCorrectAction extends OneToOneAction<Table, Table> {
// } else { // } else {
// format = DataFormat.of(parnames); // format = DataFormat.of(parnames);
// } // }
Table res = new ListTable(dataList); Table res = ListTable.infer(dataList);
context.getIo().output(name, getName()).push(NumassUtils.INSTANCE.wrap(res, meta), Meta.empty()); context.getIo().output(name, getName()).push(NumassUtils.INSTANCE.wrap(res, meta), Meta.empty());
@ -192,7 +192,7 @@ public class MonitorCorrectAction extends OneToOneAction<Table, Table> {
private void printMonitorData(Context context, Meta meta) { private void printMonitorData(Context context, Meta meta) {
if (!monitorPoints.isEmpty()) { if (!monitorPoints.isEmpty()) {
String monitorFileName = meta.getString("monitorFile", "monitor"); String monitorFileName = meta.getString("monitorFile", "monitor");
ListTable data = new ListTable(monitorPoints); ListTable data = ListTable.infer(monitorPoints);
context.getIo().output(monitorFileName, getName()).push(NumassUtils.INSTANCE.wrap(data, meta), Meta.empty()); context.getIo().output(monitorFileName, getName()).push(NumassUtils.INSTANCE.wrap(data, meta), Meta.empty());
// ColumnedDataWriter.writeTable(stream, TableTransform.sort(data, "Timestamp", true), "Monitor points", monitorNames); // ColumnedDataWriter.writeTable(stream, TableTransform.sort(data, "Timestamp", true), "Monitor points", monitorNames);

View File

@ -32,13 +32,13 @@ import hep.dataforge.plots.jfreechart.JFreeChartFrame
import hep.dataforge.tables.ListTable import hep.dataforge.tables.ListTable
import hep.dataforge.tables.Table import hep.dataforge.tables.Table
import hep.dataforge.values.ValueMap import hep.dataforge.values.ValueMap
import hep.dataforge.values.ValueType
import hep.dataforge.values.Values import hep.dataforge.values.Values
import inr.numass.data.analyzers.NumassAnalyzer import inr.numass.data.analyzers.NumassAnalyzer
import inr.numass.data.api.NumassPoint import inr.numass.data.api.NumassPoint
import inr.numass.data.api.NumassSet import inr.numass.data.api.NumassSet
import inr.numass.models.FSS import inr.numass.models.FSS
import inr.numass.utils.ExpressionUtils import inr.numass.utils.ExpressionUtils
import kotlinx.coroutines.experimental.runBlocking
import org.apache.commons.math3.analysis.UnivariateFunction import org.apache.commons.math3.analysis.UnivariateFunction
import org.jfree.chart.plot.IntervalMarker import org.jfree.chart.plot.IntervalMarker
import org.jfree.chart.ui.RectangleInsets import org.jfree.chart.ui.RectangleInsets
@ -156,7 +156,9 @@ object NumassUtils {
val pointName = "point_" + point.meta.getInt("external_meta.point_index", point.hashCode()) val pointName = "point_" + point.meta.getInt("external_meta.point_index", point.hashCode())
builder.putData(pointName, point, pointMeta) builder.putData(pointName, point, pointMeta)
} }
set.hvData.ifPresent { hv -> builder.putData("hv", hv, Meta.empty()) } runBlocking {
set.hvData.await()?.let { hv -> builder.putData("hv", hv, Meta.empty()) }
}
return builder.build() return builder.build()
} }
@ -251,14 +253,7 @@ fun Values.unbox(): Map<String, Any?> {
val res = HashMap<String, Any?>() val res = HashMap<String, Any?>()
for (field in this.names) { for (field in this.names) {
val value = this.getValue(field) val value = this.getValue(field)
val obj: Any? = when (value.type) { res.put(field, value.value)
ValueType.BOOLEAN -> value.boolean
ValueType.NUMBER -> value.double
ValueType.STRING -> value.string
ValueType.TIME -> value.time
ValueType.NULL -> null
}
res.put(field, obj)
} }
return res return res
} }

View File

@ -29,8 +29,10 @@ import hep.dataforge.tables.MetaTableFormat
import hep.dataforge.tables.Table import hep.dataforge.tables.Table
import hep.dataforge.values.Value import hep.dataforge.values.Value
import hep.dataforge.values.ValueMap import hep.dataforge.values.ValueMap
import hep.dataforge.values.asValue
import inr.numass.NumassUtils import inr.numass.NumassUtils
import java.util.* import java.util.*
import kotlin.collections.ArrayList
/** /**
* @author Darksnake * @author Darksnake
@ -59,13 +61,13 @@ object SummaryAction : ManyToOneAction<FitState, Table>() {
} else { } else {
throw RuntimeException("Infering parnames not suppoerted") throw RuntimeException("Infering parnames not suppoerted")
} }
val names = arrayOfNulls<String>(2 * parNames.size + 2) val names = ArrayList<String>()
names[0] = "file" names.add("file")
for (i in parNames.indices) { parNames.forEach {
names[2 * i + 1] = parNames[i] names.add(it)
names[2 * i + 2] = parNames[i] + "Err" names.add("${it}_Err")
} }
names[names.size - 1] = "chi2" names.add("chi2")
val res = ListTable.Builder(MetaTableFormat.forNames(names)) val res = ListTable.Builder(MetaTableFormat.forNames(names))
@ -75,24 +77,24 @@ object SummaryAction : ManyToOneAction<FitState, Table>() {
Arrays.fill(av, 0.0) Arrays.fill(av, 0.0)
input.forEach { key: String, value: FitState -> input.forEach { key: String, value: FitState ->
val values = arrayOfNulls<Value>(names.size) val values = ArrayList<Value>()
values[0] = Value.parseValue(key) values.add(key.asValue())
for (i in parNames.indices) { parNames.forEachIndexed { i, it ->
val `val` = Value.of(value.parameters.getDouble(parNames[i])) val `val` = Value.of(value.parameters.getDouble(it))
values[2 * i + 1] = `val` values.add(`val`)
val err = Value.of(value.parameters.getError(parNames[i])) val err = Value.of(value.parameters.getError(it))
values[2 * i + 2] = err values.add(err)
val weight = 1.0 / err.getDouble() / err.getDouble() val weight = 1.0 / err.double / err.double
av[i] += `val`.getDouble() * weight av[i] += `val`.double * weight
weights[i] += weight weights[i] += weight
} }
values[values.size - 1] = Value.of(value.chi2) values[values.size - 1] = Value.of(value.chi2)
val point = ValueMap.of(names, *values) val point = ValueMap.of(names.toTypedArray(), values)
res.row(point) res.row(point)
} }
val averageValues = arrayOfNulls<Value>(names.size) val averageValues = arrayOfNulls<Value>(names.size)
averageValues[0] = Value.parseValue("average") averageValues[0] = "average".asValue()
averageValues[averageValues.size - 1] = Value.of(0) averageValues[averageValues.size - 1] = Value.of(0)
for (i in parNames.indices) { for (i in parNames.indices) {
@ -100,7 +102,7 @@ object SummaryAction : ManyToOneAction<FitState, Table>() {
averageValues[2 * i + 2] = Value.of(1 / Math.sqrt(weights[i])) averageValues[2 * i + 2] = Value.of(1 / Math.sqrt(weights[i]))
} }
res.row(ValueMap.of(names, *averageValues)) res.row(ValueMap.of(names.toTypedArray(), averageValues))
return res.build() return res.build()
} }

View File

@ -60,8 +60,8 @@ fun generateEvents(
val channels = DoubleArray(spectrum.size()) val channels = DoubleArray(spectrum.size())
val values = DoubleArray(spectrum.size()) val values = DoubleArray(spectrum.size())
for (i in 0 until spectrum.size()) { for (i in 0 until spectrum.size()) {
channels[i] = spectrum.get(CHANNEL_KEY, i).getDouble() channels[i] = spectrum.get(CHANNEL_KEY, i).double
values[i] = spectrum.get(COUNT_RATE_KEY, i).getDouble() values[i] = spectrum.get(COUNT_RATE_KEY, i).double
} }
val distribution = EnumeratedRealDistribution(channels, values) val distribution = EnumeratedRealDistribution(channels, values)

View File

@ -81,7 +81,7 @@ fun main(args: Array<String>) {
val res = subtractAmplitudeSpectrum(spectrum1, spectrum0) val res = subtractAmplitudeSpectrum(spectrum1, spectrum0)
val norm = res.getColumn(COUNT_RATE_KEY).stream().mapToDouble { it.getDouble() }.sum() val norm = res.getColumn(COUNT_RATE_KEY).stream().mapToDouble { it.double }.sum()
integralFrame.add(DataPlot.plot("point_$hv", AMPLITUDE_ADAPTER, spectrum0)) integralFrame.add(DataPlot.plot("point_$hv", AMPLITUDE_ADAPTER, spectrum0))

View File

@ -11,7 +11,6 @@ import inr.numass.data.api.NumassPoint
import inr.numass.data.api.NumassSet import inr.numass.data.api.NumassSet
import inr.numass.data.api.SimpleNumassPoint import inr.numass.data.api.SimpleNumassPoint
import inr.numass.data.storage.NumassStorageFactory import inr.numass.data.storage.NumassStorageFactory
import java.util.stream.Collectors
fun main(args: Array<String>) { fun main(args: Array<String>) {
@ -52,7 +51,7 @@ fun main(args: Array<String>) {
SimpleNumassPoint( SimpleNumassPoint(
all.points.filter { all.points.filter {
it.voltage == hv it.voltage == hv
}.collect(Collectors.toList()), }.toList(),
hv hv
) )
) )

View File

@ -11,14 +11,14 @@ fun main(args: Array<String>) {
val point = ProtoNumassPoint.readFile(file) val point = ProtoNumassPoint.readFile(file)
point.plotAmplitudeSpectrum() point.plotAmplitudeSpectrum()
point.blocks.filter { it.channel == 0 }.findFirst().ifPresent { point.blocks.filter { it.channel == 0 }.firstOrNull()?.let {
it.plotAmplitudeSpectrum(plotName = "0") { it.plotAmplitudeSpectrum(plotName = "0") {
"title" to "pixel 0" "title" to "pixel 0"
"binning" to 50 "binning" to 50
} }
} }
point.blocks.filter { it.channel == 4 }.findFirst().ifPresent { point.blocks.filter { it.channel == 4 }.firstOrNull()?.let {
it.plotAmplitudeSpectrum(plotName = "4") { it.plotAmplitudeSpectrum(plotName = "4") {
"title" to "pixel 4" "title" to "pixel 4"
"binning" to 50 "binning" to 50

View File

@ -35,7 +35,7 @@ fun main(args: Array<String>) {
} }
} }
val point: NumassPoint = set.points.filter { it.index == 18 }.findFirst().get() val point: NumassPoint = set.points.first { it.index == 18 }
(0..99).forEach { bin -> (0..99).forEach { bin ->
val times = point.events.filter { it.amp > 0 }.map { it.timeOffset }.toList() val times = point.events.filter { it.amp > 0 }.map { it.timeOffset }.toList()
val count = times.filter { it > bin.toDouble() / 10 * 1e9 && it < (bin + 1).toDouble() / 10 * 1e9 }.count() val count = times.filter { it > bin.toDouble() / 10 * 1e9 && it < (bin + 1).toDouble() / 10 * 1e9 }.count()

View File

@ -97,7 +97,7 @@ object Threshold {
private fun norm(spectrum: Table, xLow: Int, upper: Int): Double { private fun norm(spectrum: Table, xLow: Int, upper: Int): Double {
return spectrum.rows.filter { row -> return spectrum.rows.filter { row ->
row.getInt(CHANNEL_KEY) in (xLow + 1)..(upper - 1) row.getInt(CHANNEL_KEY) in (xLow + 1)..(upper - 1)
}.mapToDouble { it.getValue(COUNT_RATE_KEY).getDouble() }.sum() }.mapToDouble { it.getValue(COUNT_RATE_KEY).double }.sum()
} }
private val expPointNames = arrayOf("U", "amp", "expConst", "correction"); private val expPointNames = arrayOf("U", "amp", "expConst", "correction");

View File

@ -60,7 +60,7 @@ object NumassFitScanSummaryTask : AbstractTask<Table>() {
} }
builder.row( builder.row(
Math.sqrt(pars.getValue("msterile2").getDouble()), Math.sqrt(pars.getValue("msterile2").double),
pars.getValue("U2"), pars.getValue("U2"),
pars.getError("U2"), pars.getError("U2"),
limit, limit,

View File

@ -14,9 +14,9 @@ import hep.dataforge.stat.fit.FitResult
import hep.dataforge.tables.Table import hep.dataforge.tables.Table
import hep.dataforge.values.ListValue import hep.dataforge.values.ListValue
import hep.dataforge.values.Value import hep.dataforge.values.Value
import hep.dataforge.values.asValue
import hep.dataforge.workspace.tasks.AbstractTask import hep.dataforge.workspace.tasks.AbstractTask
import hep.dataforge.workspace.tasks.TaskModel import hep.dataforge.workspace.tasks.TaskModel
import java.util.stream.Collectors
/** /**
* @author Alexander Nozik * @author Alexander Nozik
@ -30,12 +30,11 @@ object NumassFitScanTask : AbstractTask<FitResult>() {
val scanValues: Value = if (config.hasValue("masses")) { val scanValues: Value = if (config.hasValue("masses")) {
ListValue(config.getValue("masses") ListValue(config.getValue("masses")
.list.stream() .list
.map { it -> Math.pow(it.double * 1000, 2.0) } .map { it -> Math.pow(it.double * 1000, 2.0).asValue() }
.collect(Collectors.toList<Any>())
) )
} else { } else {
config.getValue("hep/dataforge/values", Value.parseValue("[2.5e5, 1e6, 2.25e6, 4e6, 6.25e6, 9e6]")) config.getValue("hep/dataforge/values", listOf(2.5e5, 1e6, 2.25e6, 4e6, 6.25e6, 9e6))
} }
val action = FitAction() val action = FitAction()

View File

@ -64,7 +64,7 @@ val monitorTableTask = task("monitor") {
val res = ListTable.Builder("timestamp", "count", "cr", "crErr") val res = ListTable.Builder("timestamp", "count", "cr", "crErr")
.rows( .rows(
data.values.stream().parallel() data.values.stream().parallel()
.flatMap { it.points } .flatMap { it.points.stream() }
.filter { it.voltage == monitorVoltage } .filter { it.voltage == monitorVoltage }
.map { it -> analyzer.analyzePoint(it, analyzerMeta) } .map { it -> analyzer.analyzePoint(it, analyzerMeta) }
).build() ).build()
@ -259,7 +259,7 @@ val plotFitTask = task("plotFit") {
// ensuring all data points are calculated explicitly // ensuring all data points are calculated explicitly
StreamSupport.stream<Values>(data.spliterator(), false) StreamSupport.stream<Values>(data.spliterator(), false)
.map { dp -> Adapters.getXValue(adapter, dp).getDouble() }.sorted().forEach { fit.calculateIn(it) } .map { dp -> Adapters.getXValue(adapter, dp).double }.sorted().forEach { fit.calculateIn(it) }
frame.add(DataPlot.plot("data", adapter, data)) frame.add(DataPlot.plot("data", adapter, data))

View File

@ -6,6 +6,7 @@
package inr.numass.server; package inr.numass.server;
import freemarker.template.Template; import freemarker.template.Template;
import hep.dataforge.io.JSONMetaWriter;
import hep.dataforge.server.ServerManager; import hep.dataforge.server.ServerManager;
import hep.dataforge.server.ServletUtils; import hep.dataforge.server.ServletUtils;
import hep.dataforge.storage.api.Loader; import hep.dataforge.storage.api.Loader;
@ -27,7 +28,7 @@ import static inr.numass.server.HandlerUtils.renderStates;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class NumassRootHandler implements Handler { public class NumassRootHandler implements Handler {
private final JSONMetaWriter writer = new JSONMetaWriter(); private final JSONMetaWriter writer = JSONMetaWriter.INSTANCE;
NumassServer server; NumassServer server;
ServerManager manager; ServerManager manager;

View File

@ -26,6 +26,7 @@ import hep.dataforge.storage.api.StateLoader;
import hep.dataforge.storage.api.Storage; import hep.dataforge.storage.api.Storage;
import hep.dataforge.storage.commons.LoaderFactory; import hep.dataforge.storage.commons.LoaderFactory;
import hep.dataforge.values.Value; import hep.dataforge.values.Value;
import hep.dataforge.values.ValueFactory;
import inr.numass.data.storage.NumassStorage; import inr.numass.data.storage.NumassStorage;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -86,7 +87,7 @@ public class NumassRun implements Metoid, Responder {
} }
public void setState(String name, Object value) throws StorageException { public void setState(String name, Object value) throws StorageException {
states.push(name, Value.of(value)); states.push(name, ValueFactory.of(value));
} }
public boolean hasState(String name) { public boolean hasState(String name) {

View File

@ -15,13 +15,11 @@
*/ */
package inr.numass.scripts package inr.numass.scripts
import hep.dataforge.io.MetaStreamWriter
import hep.dataforge.storage.commons.StorageManager import hep.dataforge.storage.commons.StorageManager
new StorageManager().startGlobal(); new StorageManager().startGlobal();
MetaStreamWriter parser = new JSONMetaWriter();
println "Starting Numass test client..." println "Starting Numass test client..."
String line = ""; String line = "";

View File

@ -6,6 +6,7 @@
package inr.numass.scripts package inr.numass.scripts
import hep.dataforge.io.JSONMetaWriter
import hep.dataforge.io.MetaStreamWriter import hep.dataforge.io.MetaStreamWriter
import hep.dataforge.meta.Meta import hep.dataforge.meta.Meta
import hep.dataforge.storage.commons.StorageManager import hep.dataforge.storage.commons.StorageManager
@ -15,21 +16,21 @@ new StorageManager().startGlobal();
new NumassClient("127.0.0.1",8335).withCloseable{ new NumassClient("127.0.0.1",8335).withCloseable{
MetaStreamWriter parser = new JSONMetaWriter(); MetaStreamWriter writer = JSONMetaWriter.INSTANCE
Meta startRun = it.startRun("test") Meta startRun = it.startRun("test")
println parser.writeString(startRun); println writer.writeString(startRun);
Meta run = it.getCurrentRun(); Meta run = it.getCurrentRun();
println parser.writeString(run); println writer.writeString(run);
Meta response = it.sendNumassData("C:\\Users\\darksnake\\Dropbox\\PlayGround\\data-test\\zip\\20150703143643_1.nm.zip"); Meta response = it.sendNumassData("C:\\Users\\darksnake\\Dropbox\\PlayGround\\data-test\\zip\\20150703143643_1.nm.zip");
println parser.writeString(response); println writer.writeString(response);
response = it.sendNumassData("C:\\Users\\darksnake\\Dropbox\\PlayGround\\data-test\\20150703144707_2"); response = it.sendNumassData("C:\\Users\\darksnake\\Dropbox\\PlayGround\\data-test\\20150703144707_2");
println parser.writeString(response); println writer.writeString(response);
} }

View File

@ -6,12 +6,9 @@
package inr.numass.scripts package inr.numass.scripts
import hep.dataforge.io.MetaStreamWriter
import hep.dataforge.storage.commons.StorageManager import hep.dataforge.storage.commons.StorageManager
import inr.numass.client.NumassClient import inr.numass.client.NumassClient
new StorageManager().startGlobal(); new StorageManager().startGlobal();
MetaStreamWriter parser = new JSONMetaWriter();
NumassClient.runComand("127.0.0.1", 8336, "addNote", "This is my note with <strong>html</strong>"); NumassClient.runComand("127.0.0.1", 8336, "addNote", "This is my note with <strong>html</strong>");

View File

@ -15,15 +15,11 @@
*/ */
package inr.numass.scripts package inr.numass.scripts
import hep.dataforge.io.MetaStreamWriter
import hep.dataforge.storage.commons.StorageManager import hep.dataforge.storage.commons.StorageManager
import inr.numass.client.NumassClient import inr.numass.client.NumassClient
new StorageManager().startGlobal(); new StorageManager().startGlobal();
MetaStreamWriter parser = new JSONMetaWriter();
println "Starting Numass test client..." println "Starting Numass test client..."

View File

@ -6,6 +6,7 @@
package inr.numass.scripts package inr.numass.scripts
import hep.dataforge.io.JSONMetaWriter
import hep.dataforge.io.MetaStreamWriter import hep.dataforge.io.MetaStreamWriter
import hep.dataforge.meta.Meta import hep.dataforge.meta.Meta
import hep.dataforge.storage.commons.StorageManager import hep.dataforge.storage.commons.StorageManager
@ -15,15 +16,15 @@ new StorageManager().startGlobal();
new NumassClient("127.0.0.1",8335).withCloseable{ new NumassClient("127.0.0.1",8335).withCloseable{
MetaStreamWriter parser = new JSONMetaWriter(); MetaStreamWriter writer = JSONMetaWriter.INSTANCE
Meta startRun = it.startRun("test") Meta startRun = it.startRun("test")
println parser.writeString(startRun); println writer.writeString(startRun);
Meta set1 = it.setState("myState", 112); Meta set1 = it.setState("myState", 112);
println parser.writeString(set1); println writer.writeString(set1);
Meta set2 = it.setState("otherState.property", ["a", "b", "c"]) Meta set2 = it.setState("otherState.property", ["a", "b", "c"])

View File

@ -6,6 +6,7 @@
package inr.numass.scripts package inr.numass.scripts
import hep.dataforge.io.JSONMetaWriter
import hep.dataforge.io.MetaStreamWriter import hep.dataforge.io.MetaStreamWriter
import hep.dataforge.io.envelopes.Envelope import hep.dataforge.io.envelopes.Envelope
import hep.dataforge.meta.Meta import hep.dataforge.meta.Meta
@ -19,11 +20,11 @@ new StorageManager().startGlobal();
new NumassClient("127.0.0.1",8335).withCloseable{ new NumassClient("127.0.0.1",8335).withCloseable{
MetaStreamWriter parser = new JSONMetaWriter(); MetaStreamWriter writer = JSONMetaWriter.INSTANCE
Meta startRun = it.startRun("test") Meta startRun = it.startRun("test")
println parser.writeString(startRun); println writer.writeString(startRun);
MetaBuilder target = new MetaBuilder("target") MetaBuilder target = new MetaBuilder("target")
@ -50,6 +51,6 @@ new NumassClient("127.0.0.1",8335).withCloseable{
def response = it.respond(bin); def response = it.respond(bin);
println parser.writeString(response.getMeta()); println writer.writeString(response.getMeta());
} }

View File

@ -1,11 +1,13 @@
package inr.numass.server package inr.numass.server
import hep.dataforge.control.DeviceManager import hep.dataforge.control.DeviceManager
import hep.dataforge.io.JSONMetaWriter
import hep.dataforge.kodex.KMetaBuilder
import hep.dataforge.kodex.buildMeta
import hep.dataforge.meta.Meta
import hep.dataforge.providers.Path import hep.dataforge.providers.Path
import hep.dataforge.server.InterceptorFactory import hep.dataforge.server.InterceptorFactory
import hep.dataforge.server.ServerInterceptor import hep.dataforge.server.ServerInterceptor
import hep.dataforge.server.asJson
import hep.dataforge.server.jsonObject
import hep.dataforge.storage.api.TableLoader import hep.dataforge.storage.api.TableLoader
import hep.dataforge.storage.commons.StorageManager import hep.dataforge.storage.commons.StorageManager
import hep.dataforge.values.Value import hep.dataforge.values.Value
@ -16,19 +18,26 @@ import io.ktor.response.respondText
import io.ktor.routing.get import io.ktor.routing.get
private fun Meta.render() = JSONMetaWriter.writeString(this)
private suspend fun ApplicationCall.error(type: String, message: String) { private suspend fun ApplicationCall.error(type: String, message: String) {
this.respondText(ContentType("application", "json")) { this.respondText(ContentType("application", "json")) {
jsonObject { buildMeta {
add("status", "ERROR") "status" to "ERROR"
add("type", type) "type" to type
add("message", message) "message" to message
}.render() }.render()
} }
} }
private suspend fun ApplicationCall.json(json: suspend JsonObjectBuilder.() -> Unit) { private suspend fun ApplicationCall.json(json: suspend KMetaBuilder.() -> Unit) {
this.respondText(ContentType("application", "json")) { this.respondText(ContentType("application", "json")) {
jsonObject(json).add("status", "OK").render() buildMeta {
run {
json.invoke(this)
}
"status" to "OK"
}.render()
} }
} }
@ -92,7 +101,7 @@ val deviceInterceptor = InterceptorFactory { context, meta ->
get("listDevices") { get("listDevices") {
call.json { call.json {
val devices = jsonArray(); val devices = jsonArray();
for (name in deviceManager.getDeviceNames()) { for (name in deviceManager.deviceNames) {
val device = deviceManager.optDevice(name).get(); val device = deviceManager.optDevice(name).get();
devices.add(jsonObject { devices.add(jsonObject {
add("name", name.toUnescaped()) add("name", name.toUnescaped())
@ -116,7 +125,7 @@ val deviceInterceptor = InterceptorFactory { context, meta ->
add("getMeta", device.meta.asJson()) add("getMeta", device.meta.asJson())
add("state", jsonObject { add("state", jsonObject {
device.states.forEach { device.states.forEach {
add(it.name,it.toString()) add(it.name, it.toString())
} }
}) })
} }

View File

@ -14,7 +14,7 @@ include ":numass-core"
include ":numass-client" include ":numass-client"
include ":numass-server" include ":numass-server"
include ":numass-server" include ":numass-server"
include ":numass-web" //include ":numass-web"
include ":numass-test" include ":numass-test"
// //
include ":numass-viewer" include ":numass-viewer"